repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
maxeler/eclipse | eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test47/out/A.java | 55 | package p;
public class A{
public static int F= B.i;
} | epl-1.0 |
maxeler/eclipse | eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test11_in.java | 95 | package p;
class A{
int m(int y){
do{
int x= 1 + 2;
} while(y==0);
return 1 + 2;
}
} | epl-1.0 |
jandsu/ironjacamar | api/src/main/java/javax/resource/spi/security/GenericCredential.java | 4794 | /*
* IronJacamar, a Java EE Connector Architecture implementation
* Copyright 2013, Red Hat Inc, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the Eclipse Public License 1.0 as
* published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Eclipse
* Public License for more details.
*
* You should have received a copy of the Eclipse Public License
* along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package javax.resource.spi.security;
import javax.resource.spi.SecurityException;
/** The interface <code>javax.resource.spi.security.GenericCredential</code>
* defines a security mechanism independent interface for accessing
* security credential of a resource principal.
*
* <p>The <code>GenericCredential</code> interface provides a Java
* wrapper over an underlying mechanism specific representation of
* a security credential. For example, the <code>GenericCredential</code>
* interface can be used to wrap Kerberos credentials.
*
* <p>The connector architecture does not define any standard format
* and requirements for security mechanism specific credentials. For
* example, a security credential wrapped by a GenericCredential
* interface can have a native representation specific to an operating
* system.
*
* <p>The GenericCredential interface enables a resource adapter to
* extract information about a security credential. The resource adapter
* can then manage EIS sign-on for a resource principal by either:
* <UL>
* <LI>using the credentials in an EIS specific manner if the underlying
* EIS supports the security mechanism type represented by the
* GenericCredential instance, or,
* <LI>using GSS-API if the resource adapter and underlying EIS
* instance support GSS-API.
* </UL>
*
* @author Rahul Sharma
* @version 0.7
* @since 0.7
* @see javax.security.auth.Subject
* @see java.security.Principal
* @deprecated The preferred way to represent generic credential information
* is via the <code>org.ietf.jgss.GSSCredential</code> interface in
* J2SE Version 1.4, which provides similar functionality.
*/
@Deprecated
public interface GenericCredential
{
/** Returns the name of the resource principal associated
* with a GenericCredential instance.
*
* @return Name of the principal
**/
public String getName();
/** Returns the mechanism type for the GenericCredential instance.
* The mechanism type definition for GenericCredential should be
* consistent with the Object Identifier (OID) based representation
* specified in the GSS specification. In the GenericCredential
* interface, the mechanism type is returned as a stringified
* representation of the OID specification.
*
* @return mechanism type
**/
public String getMechType();
/** Gets security data for a specific security mechanism represented
* by the GenericCredential. An example is authentication data required
* for establishing a secure association with an EIS instance on
* behalf of the associated resource principal.
*
* <p>The getCredentialData method returns the credential
* representation as an array of bytes. Note that the connector
* architecture does not define any standard format for the returned
* credential data.
*
* @return credential representation as an array of bytes.
* @throws SecurityException
* Failed operation due to security related
* error condition
**/
public byte[] getCredentialData() throws SecurityException;
/** Tests if this GenericCredential instance refers to the same entity
* as the supplied object. The two credentials must be acquired over
* the same mechanisms and must refer to the same principal.
*
* Returns true if the two GenericCredentials refer to the same entity;
* false otherwise.
* @param another The other object
* @return True if equal; otherwise false
**/
public boolean equals(Object another);
/** Returns the hash code for this GenericCredential
*
* @return hash code for this GenericCredential
**/
public int hashCode();
}
| epl-1.0 |
sguan-actuate/birt | testsuites/org.eclipse.birt.tests.data/src/org/eclipse/birt/tests/data/engine/api/MultiPassTest.java | 2134 |
package org.eclipse.birt.tests.data.engine.api;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.OdaDataSetDesign;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import testutil.APITestCase;
import testutil.ConfigText;
public class MultiPassTest extends APITestCase
{
protected DataSourceInfo getDataSourceInfo( )
{
return new DataSourceInfo( ConfigText
.getString( "Api.TestData.TableName" ), ConfigText
.getString( "Api.TestData.TableSQL" ), ConfigText
.getString( "Api.TestData.TestDataFileName" ) );
}
/**
* Test feature of aggregation expression
*/
public void test_RunningAggregationExpression( ) throws Exception
{
// Test a SQL with duplicate column name (quite common with join data
// sets)
String testSQL = "select COUNTRY, AMOUNT from " + getTestTableName( );
( (OdaDataSetDesign) this.dataSet ).setQueryText( testSQL );
IBaseExpression[] bindingExprGroup = new IBaseExpression[]{
new ScriptExpression( "dataSetRow.COUNTRY", 0 ),
new ScriptExpression(
"Total.Sum( dataSetRow.AMOUNT,null,1 )",
2 )};
String names[] = {"group_COUNTRY", "group_AMOUNT"};
GroupDefinition[] groupDefn = new GroupDefinition[]{
new GroupDefinition( "G1" ), new GroupDefinition( "G2" )};
groupDefn[0].setKeyExpression( "row.group_COUNTRY" );
groupDefn[1].setKeyExpression( "row.group_AMOUNT" );
String[] bindingNameRow = new String[3];
bindingNameRow[0] = "country";
bindingNameRow[1] = "amount";
bindingNameRow[2] = "binding3";
IBaseExpression[] bindingExprRow = new IBaseExpression[3];
bindingExprRow[0] = new ScriptExpression( "dataSetRow.COUNTRY" );
bindingExprRow[1] = new ScriptExpression( "dataSetRow.AMOUNT" );
bindingExprRow[2] = new ScriptExpression(
"Total.sum( dataSetRow.AMOUNT,null,1)" );
createAndRunQuery(
names,
bindingExprGroup,
groupDefn,
null,
null,
null,
null,
null,
null,
bindingNameRow,
bindingExprRow );
checkOutputFile( );
}
} | epl-1.0 |
Charling-Huang/birt | model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/api/ScriptDataSourceHandle.java | 2729 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.model.api;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.core.DesignElement;
import org.eclipse.birt.report.model.core.Module;
import org.eclipse.birt.report.model.elements.interfaces.IScriptDataSourceModel;
/**
* Represents a script data source. Script data source is one that is defined in
* JavaScript. The application is responsible for implementing two operations:
* <ul>
* <li>Open: connect to the external system. Report an error if the connection
* fails.
* <li>Close: drop the connection to the external system.
* </ul>
*
*
* @see org.eclipse.birt.report.model.elements.ScriptDataSource
*/
public class ScriptDataSourceHandle extends DataSourceHandle
implements
IScriptDataSourceModel
{
/**
* Constructs a handle for script data source.
*
* @param module
* the module
* @param element
* the script data source element
*/
public ScriptDataSourceHandle( Module module, DesignElement element )
{
super( module, element );
}
/**
* Sets the script for opening data connection.
*
* @param value
* the script to set.
* @throws SemanticException
* if the property is locked.
*/
public void setOpen( String value ) throws SemanticException
{
setProperty( IScriptDataSourceModel.OPEN_METHOD, value );
}
/**
* Returns the script name for opening data connection.
*
* @return the script name for opening data connection.
*/
public String getOpen( )
{
return getStringProperty( IScriptDataSourceModel.OPEN_METHOD );
}
/**
* Sets the script name for closing data connection.
*
* @param value
* the script name to set.
* @throws SemanticException
* if the property is locked.
*/
public void setClose( String value ) throws SemanticException
{
setProperty( IScriptDataSourceModel.CLOSE_METHOD, value );
}
/**
* Returns the script name for closing data connection.
*
* @return the script name for closing data connection.
*/
public String getClose( )
{
return getStringProperty( IScriptDataSourceModel.CLOSE_METHOD );
}
} | epl-1.0 |
akervern/che | selenium/che-selenium-test/src/test/java/org/eclipse/che/selenium/debugger/PhpProjectDebuggingTest.java | 8888 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.selenium.debugger;
import static org.eclipse.che.selenium.core.constant.TestProjectExplorerContextMenuConstants.ContextMenuCommandGoals.COMMON_GOAL;
import com.google.inject.Inject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Paths;
import org.eclipse.che.selenium.core.client.TestProjectServiceClient;
import org.eclipse.che.selenium.core.constant.TestMenuCommandsConstants;
import org.eclipse.che.selenium.core.project.ProjectTemplates;
import org.eclipse.che.selenium.core.utils.WaitUtils;
import org.eclipse.che.selenium.core.workspace.InjectTestWorkspace;
import org.eclipse.che.selenium.core.workspace.TestWorkspace;
import org.eclipse.che.selenium.core.workspace.WorkspaceTemplate;
import org.eclipse.che.selenium.pageobject.CodenvyEditor;
import org.eclipse.che.selenium.pageobject.Consoles;
import org.eclipse.che.selenium.pageobject.Ide;
import org.eclipse.che.selenium.pageobject.Loader;
import org.eclipse.che.selenium.pageobject.Menu;
import org.eclipse.che.selenium.pageobject.NotificationsPopupPanel;
import org.eclipse.che.selenium.pageobject.ProjectExplorer;
import org.eclipse.che.selenium.pageobject.debug.DebugPanel;
import org.eclipse.che.selenium.pageobject.debug.PhpDebugConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/** @author Dmytro Nochevnov */
public class PhpProjectDebuggingTest {
private static final Logger LOG = LoggerFactory.getLogger(PhpProjectDebuggingTest.class);
protected static final String PROJECT = "php-tests";
private static final String PATH_TO_INDEX_PHP = PROJECT + "/index.php";
private static final String PATH_TO_LIB_PHP = PROJECT + "/lib.php";
private static final String DEBUG_PHP_SCRIPT_COMMAND_NAME = "debug php script";
private static final int NON_DEFAULT_DEBUG_PORT = 10140;
private static final String START_DEBUG_PARAMETERS =
"?start_debug=1&debug_host=localhost&debug_port=" + NON_DEFAULT_DEBUG_PORT;
@InjectTestWorkspace(template = WorkspaceTemplate.ECLIPSE_PHP)
private TestWorkspace ws;
@Inject private Ide ide;
@Inject protected ProjectExplorer projectExplorer;
@Inject private Loader loader;
@Inject private DebugPanel debugPanel;
@Inject private PhpDebugConfig debugConfig;
@Inject private NotificationsPopupPanel notificationPopup;
@Inject private Menu menu;
@Inject private CodenvyEditor editor;
@Inject private Consoles consoles;
@Inject private TestProjectServiceClient testProjectServiceClient;
@BeforeClass
public void setup() throws Exception {
URL resource = getClass().getResource("/projects/plugins/DebuggerPlugin/php-tests");
testProjectServiceClient.importProject(
ws.getId(), Paths.get(resource.toURI()), PROJECT, ProjectTemplates.PHP);
// open IDE
ide.open(ws);
loader.waitOnClosed();
projectExplorer.waitItem(PROJECT);
notificationPopup.waitProgressPopupPanelClose();
// open project tree
projectExplorer.quickExpandWithJavaScript();
}
@BeforeMethod
public void startDebug() {
// goto root item in the Project Explorer to have proper value of ${current.project.path} when
// executing maven command.
projectExplorer.waitAndSelectItem(PROJECT);
}
@AfterMethod
public void stopDebug() {
debugPanel.removeAllBreakpoints();
menu.runCommand(
TestMenuCommandsConstants.Run.RUN_MENU, TestMenuCommandsConstants.Run.END_DEBUG_SESSION);
invokeStopCommandWithContextMenu();
// remove debug configuration
menu.runCommand(
TestMenuCommandsConstants.Run.RUN_MENU,
TestMenuCommandsConstants.Run.EDIT_DEBUG_CONFIGURATION);
debugConfig.removeConfig(PROJECT);
}
@Test
public void shouldDebugCliPhpScriptFromFirstLine() {
// when
menu.runCommand(
TestMenuCommandsConstants.Run.RUN_MENU,
TestMenuCommandsConstants.Run.EDIT_DEBUG_CONFIGURATION);
debugConfig.createConfig(PROJECT);
menu.runCommandByXpath(
TestMenuCommandsConstants.Run.RUN_MENU,
TestMenuCommandsConstants.Run.DEBUG,
getXpathForDebugConfigurationMenuItem());
notificationPopup.waitExpectedMessageOnProgressPanelAndClose("Remote debugger connected");
projectExplorer.openItemByPath(PATH_TO_LIB_PHP);
editor.setBreakpoint(14);
editor.closeAllTabs();
projectExplorer.openItemByPath(PATH_TO_INDEX_PHP);
projectExplorer.invokeCommandWithContextMenu(
COMMON_GOAL, PROJECT, DEBUG_PHP_SCRIPT_COMMAND_NAME);
debugPanel.openDebugPanel();
// then
debugPanel.waitDebugHighlightedText("<?php include 'lib.php';?>");
debugPanel.waitTextInVariablesPanel("$_GET=array [0]");
// when
debugPanel.clickOnButton(DebugPanel.DebuggerActionButtons.RESUME_BTN_ID);
// then
editor.waitTabFileWithSavedStatus("lib.php");
editor.waitActiveBreakpoint(14);
debugPanel.waitDebugHighlightedText("return \"Hello, $name\"");
debugPanel.waitTextInVariablesPanel("$name=\"man\"");
// when
debugPanel.clickOnButton(DebugPanel.DebuggerActionButtons.STEP_OUT);
// then
editor.waitTabFileWithSavedStatus("index.php");
debugPanel.waitDebugHighlightedText("echo sayHello(\"man\");");
debugPanel.waitTextInVariablesPanel("$_GET=array [0]");
}
@Test(priority = 1)
public void shouldDebugWebPhpScriptFromNonDefaultPortAndNotFromFirstLine() {
// when
menu.runCommand(
TestMenuCommandsConstants.Run.RUN_MENU,
TestMenuCommandsConstants.Run.EDIT_DEBUG_CONFIGURATION);
debugConfig.createConfig(PROJECT, false, NON_DEFAULT_DEBUG_PORT);
menu.runCommandByXpath(
TestMenuCommandsConstants.Run.RUN_MENU,
TestMenuCommandsConstants.Run.DEBUG,
getXpathForDebugConfigurationMenuItem());
notificationPopup.waitExpectedMessageOnProgressPanelAndClose(
String.format(
"Remote debugger connected\nConnected to: Zend Debugger, port: %s.",
NON_DEFAULT_DEBUG_PORT));
projectExplorer.openItemByPath(PATH_TO_LIB_PHP);
editor.setBreakpoint(14);
editor.closeAllTabs();
projectExplorer.openItemByPath(PATH_TO_INDEX_PHP);
invokeStartCommandWithContextMenu();
startWebPhpScriptInDebugMode();
debugPanel.openDebugPanel();
// then
editor.waitTabFileWithSavedStatus("lib.php");
editor.waitActiveBreakpoint(14);
debugPanel.waitDebugHighlightedText("return \"Hello, $name\"");
debugPanel.waitTextInVariablesPanel("$name=\"man\"");
// when
debugPanel.clickOnButton(DebugPanel.DebuggerActionButtons.STEP_OUT);
// then
editor.waitTabFileWithSavedStatus("index.php");
debugPanel.waitDebugHighlightedText("echo sayHello(\"man\");");
debugPanel.waitTextInVariablesPanel("$_GET=array [3]");
}
/**
* Start Web PHP Application in debug mode by making HTTP GET request to this application
* asynchronously on preview url displayed in console + start debug parameters
*/
private void startWebPhpScriptInDebugMode() {
final String previewUrl = consoles.getPreviewUrl() + START_DEBUG_PARAMETERS;
// it needs when the test is running on the che6-ocp platform
if (previewUrl.contains("route")) {
WaitUtils.sleepQuietly(10);
}
new Thread(
() -> {
try {
URL connectionUrl = new URL(previewUrl);
HttpURLConnection connection = (HttpURLConnection) connectionUrl.openConnection();
connection.setRequestMethod("GET");
connection.getResponseCode();
} catch (IOException e) {
LOG.error(
String.format(
"There was a problem with connecting to PHP-application for debug on URL '%s'",
previewUrl),
e);
}
})
.start();
}
private String getXpathForDebugConfigurationMenuItem() {
return String.format(
"//*[@id=\"%1$s/%2$s\" or @id=\"topmenu/Run/Debug/Debug '%2$s'\"]",
TestMenuCommandsConstants.Run.DEBUG, PROJECT);
}
protected void invokeStartCommandWithContextMenu() {
projectExplorer.invokeCommandWithContextMenu(COMMON_GOAL, PROJECT, "start apache");
}
protected void invokeStopCommandWithContextMenu() {
projectExplorer.invokeCommandWithContextMenu(COMMON_GOAL, PROJECT, "stop apache");
}
}
| epl-1.0 |
bmaggi/Papyrus-SysML11 | plugins/diagram/org.eclipse.papyrus.sysml.diagram.common/src-gen/org/eclipse/papyrus/sysml/diagram/common/factory/BlockPropertyCompositeClassifierViewFactory.java | 2938 | /*****************************************************************************
* Copyright (c) 2011 CEA LIST.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*
* CEA LIST - Initial API and implementation
*
*****************************************************************************/
package org.eclipse.papyrus.sysml.diagram.common.factory;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.papyrus.gmf.diagram.common.factory.ShapeViewFactory;
import org.eclipse.papyrus.sysml.diagram.common.utils.SysMLGraphicalTypes;
import org.eclipse.papyrus.uml.diagram.common.utils.UMLGraphicalTypes;
public class BlockPropertyCompositeClassifierViewFactory extends ShapeViewFactory {
/**
* Creates BlockPropertyComposite view and add Label and Compartment nodes
*/
@Override
protected void decorateView(View containerView, View view, IAdaptable element, String semanticHint, int index, boolean persisted) {
getViewService().createNode(element, view, UMLGraphicalTypes.LABEL_UML_PROPERTY_LABEL_ID, ViewUtil.APPEND, persisted, getPreferencesHint());
getViewService().createNode(element, view, SysMLGraphicalTypes.COMPARTMENT_SYSML_BLOCKPROPERTY_STRUCTURE_ID, ViewUtil.APPEND, persisted, getPreferencesHint());
// this action needs to be done after the compartments creation
super.decorateView(containerView, view, element, semanticHint, index, persisted);
}
// Start of user code preferences
@Override
protected void initializeFromPreferences(View view) {
super.initializeFromPreferences(view);
org.eclipse.jface.preference.IPreferenceStore store = (org.eclipse.jface.preference.IPreferenceStore) getPreferencesHint().getPreferenceStore();
if (store == null) {
return;
}
// Get default size from preferences use set view size.
String preferenceConstantWitdh = org.eclipse.papyrus.uml.diagram.common.helper.PreferenceInitializerForElementHelper.getpreferenceKey(view, view.getType(), org.eclipse.papyrus.infra.gmfdiag.common.preferences.PreferencesConstantsHelper.WIDTH);
String preferenceConstantHeight = org.eclipse.papyrus.uml.diagram.common.helper.PreferenceInitializerForElementHelper.getpreferenceKey(view, view.getType(), org.eclipse.papyrus.infra.gmfdiag.common.preferences.PreferencesConstantsHelper.HEIGHT);
ViewUtil.setStructuralFeatureValue(view, org.eclipse.gmf.runtime.notation.NotationPackage.eINSTANCE.getSize_Width(), store.getInt(preferenceConstantWitdh));
ViewUtil.setStructuralFeatureValue(view, org.eclipse.gmf.runtime.notation.NotationPackage.eINSTANCE.getSize_Height(), store.getInt(preferenceConstantHeight));
}
// End of user code
}
| epl-1.0 |
boniatillo-com/PhaserEditor | source/thirdparty/jsdt/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/SourceView.java | 16208 | /*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.jsdt.internal.ui.infoviews;
import java.io.IOException;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.wst.jsdt.core.ICodeAssist;
import org.eclipse.wst.jsdt.core.IJavaScriptElement;
import org.eclipse.wst.jsdt.core.IJavaScriptProject;
import org.eclipse.wst.jsdt.core.ISourceRange;
import org.eclipse.wst.jsdt.core.ISourceReference;
import org.eclipse.wst.jsdt.core.JavaScriptModelException;
import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.wst.jsdt.internal.corext.util.Strings;
import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
import org.eclipse.wst.jsdt.internal.ui.text.JavaCodeReader;
import org.eclipse.wst.jsdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.wst.jsdt.ui.actions.JdtActionConstants;
import org.eclipse.wst.jsdt.ui.actions.OpenAction;
import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
/**
* View which shows source for a given Java element.
*
*
*/
public class SourceView extends AbstractInfoView implements IMenuListener {
/** Symbolic Java editor font name. */
private static final String SYMBOLIC_FONT_NAME= "org.eclipse.wst.jsdt.ui.editors.textfont"; //$NON-NLS-1$
/**
* Internal property change listener for handling changes in the editor's preferences.
*
*
*/
class PropertyChangeListener implements IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
if (fViewerConfiguration.affectsTextPresentation(event)) {
fViewerConfiguration.handlePropertyChangeEvent(event);
fViewer.invalidateTextPresentation();
}
}
}
/**
* Internal property change listener for handling workbench font changes.
*/
class FontPropertyChangeListener implements IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
String property= event.getProperty();
if (SYMBOLIC_FONT_NAME.equals(property))
setViewerFont();
}
}
/**
* The Javadoc view's select all action.
*/
private static class SelectAllAction extends Action {
private TextViewer fTextViewer;
/**
* Creates the action.
*
* @param textViewer the text viewer
*/
public SelectAllAction(TextViewer textViewer) {
super("selectAll"); //$NON-NLS-1$
Assert.isNotNull(textViewer);
fTextViewer= textViewer;
setText(InfoViewMessages.SelectAllAction_label);
setToolTipText(InfoViewMessages.SelectAllAction_tooltip);
setDescription(InfoViewMessages.SelectAllAction_description);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IAbstractTextEditorHelpContextIds.SELECT_ALL_ACTION);
}
/**
* Selects all in the viewer.
*/
public void run() {
fTextViewer.doOperation(ITextOperationTarget.SELECT_ALL);
}
}
/** This view's source viewer */
private SourceViewer fViewer;
/** The viewers configuration */
private JavaScriptSourceViewerConfiguration fViewerConfiguration;
/** The viewer's font properties change listener. */
private IPropertyChangeListener fFontPropertyChangeListener= new FontPropertyChangeListener();
/**
* The editor's property change listener.
*
*/
private IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
/** The open action */
private OpenAction fOpen;
/** The number of removed leading comment lines. */
private int fCommentLineCount;
/** The select all action. */
private SelectAllAction fSelectAllAction;
/** Element opened by the open action. */
private IJavaScriptElement fLastOpenedElement;
/*
* @see AbstractInfoView#internalCreatePartControl(Composite)
*/
protected void internalCreatePartControl(Composite parent) {
IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
fViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL, store);
fViewerConfiguration= new SimpleJavaSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, IJavaScriptPartitions.JAVA_PARTITIONING, false);
fViewer.configure(fViewerConfiguration);
fViewer.setEditable(false);
setViewerFont();
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
store.addPropertyChangeListener(fPropertyChangeListener);
getViewSite().setSelectionProvider(fViewer);
}
/*
* @see AbstractInfoView#internalCreatePartControl(Composite)
*/
protected void createActions() {
super.createActions();
fSelectAllAction= new SelectAllAction(fViewer);
// Setup OpenAction
fOpen= new OpenAction(getViewSite()) {
/*
* @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#getSelection()
*/
public ISelection getSelection() {
return convertToJavaElementSelection(fViewer.getSelection());
}
/*
* @see org.eclipse.wst.jsdt.ui.actions.OpenAction#run(IStructuredSelection)
*/
public void run(IStructuredSelection selection) {
if (selection.isEmpty()) {
getShell().getDisplay().beep();
return;
}
super.run(selection);
}
/*
* @see org.eclipse.wst.jsdt.ui.actions.OpenAction#getElementToOpen(Object)
*/
public Object getElementToOpen(Object object) throws JavaScriptModelException {
if (object instanceof IJavaScriptElement)
fLastOpenedElement= (IJavaScriptElement)object;
else
fLastOpenedElement= null;
return super.getElementToOpen(object);
}
/*
* @see org.eclipse.wst.jsdt.ui.actions.OpenAction#run(Object[])
*/
public void run(Object[] elements) {
stopListeningForSelectionChanges();
super.run(elements);
startListeningForSelectionChanges();
}
};
}
/*
* @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getSelectAllAction()
*
*/
protected IAction getSelectAllAction() {
return fSelectAllAction;
}
/*
* @see AbstractInfoView#fillActionBars(IActionBars)
*/
protected void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
actionBars.setGlobalActionHandler(JdtActionConstants.OPEN, fOpen);
fOpen.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_EDITOR);
}
/*
* @see AbstractInfoView#getControl()
*/
protected Control getControl() {
return fViewer.getControl();
}
/*
* @see AbstractInfoView#menuAboutToShow(IMenuManager)
*/
public void menuAboutToShow(IMenuManager menu) {
super.menuAboutToShow(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen);
}
/*
* @see AbstractInfoView#setForeground(Color)
*/
protected void setForeground(Color color) {
fViewer.getTextWidget().setForeground(color);
}
/*
* @see AbstractInfoView#setBackground(Color)
*/
protected void setBackground(Color color) {
fViewer.getTextWidget().setBackground(color);
}
/*
* @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getBackgroundColorKey()
*
*/
protected String getBackgroundColorKey() {
return "org.eclipse.wst.jsdt.ui.DeclarationView.backgroundColor"; //$NON-NLS-1$
}
/**
* Converts the given selection to a structured selection
* containing Java elements.
*
* @param selection the selection
* @return a structured selection with Java elements
*/
private IStructuredSelection convertToJavaElementSelection(ISelection selection) {
if (!(selection instanceof ITextSelection && fCurrentViewInput instanceof ISourceReference))
return StructuredSelection.EMPTY;
ITextSelection textSelection= (ITextSelection)selection;
Object codeAssist= fCurrentViewInput.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
if (codeAssist == null)
codeAssist= fCurrentViewInput.getAncestor(IJavaScriptElement.CLASS_FILE);
if (codeAssist instanceof ICodeAssist) {
IJavaScriptElement[] elements= null;
try {
ISourceRange range= ((ISourceReference)fCurrentViewInput).getSourceRange();
elements= ((ICodeAssist)codeAssist).codeSelect(range.getOffset() + getOffsetInUnclippedDocument(textSelection), textSelection.getLength());
} catch (JavaScriptModelException e) {
return StructuredSelection.EMPTY;
}
if (elements != null && elements.length > 0) {
return new StructuredSelection(elements[0]);
} else
return StructuredSelection.EMPTY;
}
return StructuredSelection.EMPTY;
}
/**
* Computes and returns the offset in the unclipped document
* based on the given text selection from the clipped
* document.
*
* @param textSelection
* @return the offest in the unclipped document or <code>-1</code> if the offset cannot be computed
*/
private int getOffsetInUnclippedDocument(ITextSelection textSelection) {
IDocument unclippedDocument= null;
try {
unclippedDocument= new Document(((ISourceReference)fCurrentViewInput).getSource());
} catch (JavaScriptModelException e) {
return -1;
}
IDocument clippedDoc= (IDocument)fViewer.getInput();
try {
IRegion unclippedLineInfo= unclippedDocument.getLineInformation(fCommentLineCount + textSelection.getStartLine());
IRegion clippedLineInfo= clippedDoc.getLineInformation(textSelection.getStartLine());
int removedIndentation= unclippedLineInfo.getLength() - clippedLineInfo.getLength();
int relativeLineOffset= textSelection.getOffset() - clippedLineInfo.getOffset();
return unclippedLineInfo.getOffset() + removedIndentation + relativeLineOffset ;
} catch (BadLocationException ex) {
return -1;
}
}
/*
* @see AbstractInfoView#internalDispose()
*/
protected void internalDispose() {
fViewer= null;
fViewerConfiguration= null;
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
JavaScriptPlugin.getDefault().getCombinedPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
}
/*
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTextWidget().setFocus();
}
/*
* @see AbstractInfoView#computeInput(Object)
*/
protected Object computeInput(Object input) {
if (fViewer == null || !(input instanceof ISourceReference))
return null;
ISourceReference sourceRef= (ISourceReference)input;
if (fLastOpenedElement != null && input instanceof IJavaScriptElement && ((IJavaScriptElement)input).getHandleIdentifier().equals(fLastOpenedElement.getHandleIdentifier())) {
fLastOpenedElement= null;
return null;
} else {
fLastOpenedElement= null;
}
String source;
try {
source= sourceRef.getSource();
} catch (JavaScriptModelException ex) {
return ""; //$NON-NLS-1$
}
if (source == null)
return ""; //$NON-NLS-1$
source= removeLeadingComments(source);
String delim= StubUtility.getLineDelimiterUsed((IJavaScriptElement) input);
String[] sourceLines= Strings.convertIntoLines(source);
if (sourceLines == null || sourceLines.length == 0)
return ""; //$NON-NLS-1$
String firstLine= sourceLines[0];
boolean firstCharNotWhitespace= firstLine != null && firstLine.length() > 0 && !Character.isWhitespace(firstLine.charAt(0));
if (firstCharNotWhitespace)
sourceLines[0]= ""; //$NON-NLS-1$
IJavaScriptProject project;
if (input instanceof IJavaScriptElement)
project= ((IJavaScriptElement) input).getJavaScriptProject();
else
project= null;
Strings.trimIndentation(sourceLines, project);
if (firstCharNotWhitespace)
sourceLines[0]= firstLine;
return Strings.concatenate(sourceLines, delim);
}
/*
* @see AbstractInfoView#setInput(Object)
*/
protected void setInput(Object input) {
if (input instanceof IDocument)
fViewer.setInput(input);
else if (input == null)
fViewer.setInput(new Document("")); //$NON-NLS-1$
else {
IDocument document= new Document(input.toString());
JavaScriptPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
fViewer.setInput(document);
}
}
/**
* Removes the leading comments from the given source.
*
* @param source the string with the source
* @return the source without leading comments
*/
private String removeLeadingComments(String source) {
JavaCodeReader reader= new JavaCodeReader();
IDocument document= new Document(source);
int i;
try {
reader.configureForwardReader(document, 0, document.getLength(), true, false);
int c= reader.read();
while (c != -1 && (c == '\r' || c == '\n' || c == '\t')) {
c= reader.read();
}
i= reader.getOffset();
reader.close();
} catch (IOException ex) {
i= 0;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ex) {
JavaScriptPlugin.log(ex);
}
}
try {
fCommentLineCount= document.getLineOfOffset(i);
} catch (BadLocationException e) {
fCommentLineCount= 0;
}
if (i < 0)
return source;
return source.substring(i);
}
/**
* Sets the font for this viewer sustaining selection and scroll position.
*/
private void setViewerFont() {
Font font= JFaceResources.getFont(SYMBOLIC_FONT_NAME);
if (fViewer.getDocument() != null) {
Point selection= fViewer.getSelectedRange();
int topIndex= fViewer.getTopIndex();
StyledText styledText= fViewer.getTextWidget();
Control parent= fViewer.getControl();
parent.setRedraw(false);
styledText.setFont(font);
fViewer.setSelectedRange(selection.x , selection.y);
fViewer.setTopIndex(topIndex);
if (parent instanceof Composite) {
Composite composite= (Composite) parent;
composite.layout(true);
}
parent.setRedraw(true);
} else {
StyledText styledText= fViewer.getTextWidget();
styledText.setFont(font);
}
}
/*
* @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getHelpContextId()
*
*/
protected String getHelpContextId() {
return IJavaHelpContextIds.SOURCE_VIEW;
}
}
| epl-1.0 |
unverbraucht/kura | kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/net/route/RouteConfig4.java | 650 | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
*******************************************************************************/
package org.eclipse.kura.net.route;
/**
* Marker interface for IPv4 route configs
*/
public interface RouteConfig4 extends RouteConfig {
}
| epl-1.0 |
bmaggi/Papyrus-SysML11 | plugins/org.eclipse.papyrus.sysml.edit/src/org/eclipse/papyrus/sysml/activities/provider/ProbabilityItemProvider.java | 6076 | /*****************************************************************************
* Copyright (c) 2009 CEA LIST.
*
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Yann Tanguy (CEA LIST) yann.tanguy@cea.fr - Initial API and implementation
*
*****************************************************************************/
package org.eclipse.papyrus.sysml.activities.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.papyrus.sysml.activities.ActivitiesPackage;
import org.eclipse.papyrus.sysml.provider.SysmlEditPlugin;
/**
* This is the item provider adapter for a {@link org.eclipse.papyrus.sysml.activities.Probability} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public class ProbabilityItemProvider extends ItemProviderAdapter implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource
{
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public ProbabilityItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addBase_ActivityEdgePropertyDescriptor(object);
addBase_ParameterSetPropertyDescriptor(object);
addProbabilityPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Base Activity Edge feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected void addBase_ActivityEdgePropertyDescriptor(Object object) {
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Probability_base_ActivityEdge_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Probability_base_ActivityEdge_feature", "_UI_Probability_type"), ActivitiesPackage.Literals.PROBABILITY__BASE_ACTIVITY_EDGE, true, false, true, null, null, null));
}
/**
* This adds a property descriptor for the Base Parameter Set feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected void addBase_ParameterSetPropertyDescriptor(Object object) {
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Probability_base_ParameterSet_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Probability_base_ParameterSet_feature", "_UI_Probability_type"), ActivitiesPackage.Literals.PROBABILITY__BASE_PARAMETER_SET, true, false, true, null, null, null));
}
/**
* This adds a property descriptor for the Probability feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected void addProbabilityPropertyDescriptor(Object object) {
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Probability_probability_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Probability_probability_feature", "_UI_Probability_type"), ActivitiesPackage.Literals.PROBABILITY__PROBABILITY, true, false, true, null, null, null));
}
/**
* This returns Probability.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/Probability"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getText(Object object) {
return getString("_UI_Probability_type");
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return SysmlEditPlugin.INSTANCE;
}
}
| epl-1.0 |
majianxiong/vulcan | vulcan-core/source/main/java/net/sourceforge/vulcan/exception/DuplicatePluginIdException.java | 1055 | /*
* Vulcan Build Manager
* Copyright (C) 2005-2012 Chris Eldredge
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package net.sourceforge.vulcan.exception;
public class DuplicatePluginIdException extends StoreException {
final String id;
public DuplicatePluginIdException(String id) {
super(id, null);
this.id = id;
}
public String getId() {
return id;
}
}
| gpl-2.0 |
georgenicoll/esper | esper/src/main/java/com/espertech/esper/epl/enummethod/dot/ExprDotEvalEnumMethodBase.java | 15362 | /*
* *************************************************************************************
* Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. *
* http://www.espertech.com/esper *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.epl.enummethod.dot;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.EventType;
import com.espertech.esper.core.service.ExpressionResultCacheEntry;
import com.espertech.esper.core.service.ExpressionResultCacheStackEntry;
import com.espertech.esper.epl.core.MethodResolutionService;
import com.espertech.esper.epl.core.StreamTypeService;
import com.espertech.esper.epl.core.StreamTypeServiceImpl;
import com.espertech.esper.epl.enummethod.eval.EnumEval;
import com.espertech.esper.epl.expression.core.*;
import com.espertech.esper.epl.expression.dot.ExprDotEvalVisitor;
import com.espertech.esper.epl.expression.visitor.ExprNodeIdentifierCollectVisitor;
import com.espertech.esper.epl.methodbase.*;
import com.espertech.esper.epl.rettype.EPType;
import com.espertech.esper.epl.rettype.EPTypeHelper;
import com.espertech.esper.event.EventAdapterService;
import com.espertech.esper.event.EventBeanUtility;
import com.espertech.esper.util.CollectionUtil;
import com.espertech.esper.util.JavaClassHelper;
import java.util.*;
public abstract class ExprDotEvalEnumMethodBase implements ExprDotEvalEnumMethod, ExpressionResultCacheStackEntry {
private EnumMethodEnum enumMethodEnum;
private String enumMethodUsedName;
private int streamCountIncoming;
private EnumEval enumEval;
private int enumEvalNumRequiredEvents;
private EPType typeInfo;
private boolean cache;
private long contextNumber = 0;
protected ExprDotEvalEnumMethodBase() {
}
public abstract EventType[] getAddStreamTypes(String enumMethodUsedName, List<String> goesToNames, EventType inputEventType, Class collectionComponentType, List<ExprDotEvalParam> bodiesAndParameters, EventAdapterService eventAdapterService);
public abstract EnumEval getEnumEval(MethodResolutionService methodResolutionService, EventAdapterService eventAdapterService, StreamTypeService streamTypeService, String statementId, String enumMethodUsedName, List<ExprDotEvalParam> bodiesAndParameters, EventType inputEventType, Class collectionComponentType, int numStreamsIncoming, boolean disablePropertyExpressionEventCollCache) throws ExprValidationException;
public EnumMethodEnum getEnumMethodEnum() {
return enumMethodEnum;
}
public void visit(ExprDotEvalVisitor visitor) {
visitor.visitEnumeration(enumMethodEnum.getNameCamel());
}
public void init(Integer streamOfProviderIfApplicable, EnumMethodEnum enumMethodEnum, String enumMethodUsedName, EPType typeInfo, List<ExprNode> parameters, ExprValidationContext validationContext) throws ExprValidationException {
final EventType eventTypeColl = EPTypeHelper.getEventTypeMultiValued(typeInfo);
final EventType eventTypeBean = EPTypeHelper.getEventTypeSingleValued(typeInfo);
final Class collectionComponentType = EPTypeHelper.getClassMultiValued(typeInfo);
this.enumMethodEnum = enumMethodEnum;
this.enumMethodUsedName = enumMethodUsedName;
this.streamCountIncoming = validationContext.getStreamTypeService().getEventTypes().length;
if (eventTypeColl == null && collectionComponentType == null && eventTypeBean == null) {
throw new ExprValidationException("Invalid input for built-in enumeration method '" + enumMethodUsedName + "', expecting collection of event-type or scalar values as input, received " + EPTypeHelper.toTypeDescriptive(typeInfo));
}
// compile parameter abstract for validation against available footprints
DotMethodFPProvided footprintProvided = DotMethodUtil.getProvidedFootprint(parameters);
// validate parameters
DotMethodInputTypeMatcher inputTypeMatcher = new DotMethodInputTypeMatcher() {
public boolean matches(DotMethodFP footprint) {
if (footprint.getInput() == DotMethodFPInputEnum.EVENTCOLL && eventTypeBean == null && eventTypeColl == null) {
return false;
}
if (footprint.getInput() == DotMethodFPInputEnum.SCALAR_ANY && collectionComponentType == null) {
return false;
}
return true;
}
};
DotMethodFP footprint = DotMethodUtil.validateParametersDetermineFootprint(enumMethodEnum.getFootprints(), DotMethodTypeEnum.ENUM, enumMethodUsedName, footprintProvided, inputTypeMatcher);
// validate input criteria met for this footprint
if (footprint.getInput() != DotMethodFPInputEnum.ANY) {
String message = "Invalid input for built-in enumeration method '" + enumMethodUsedName + "' and " + footprint.getParameters().length + "-parameter footprint, expecting collection of ";
String received = " as input, received " + EPTypeHelper.toTypeDescriptive(typeInfo);
if (footprint.getInput() == DotMethodFPInputEnum.EVENTCOLL && eventTypeColl == null) {
throw new ExprValidationException(message + "events" + received);
}
if (footprint.getInput().isScalar() && collectionComponentType == null) {
throw new ExprValidationException(message + "values (typically scalar values)" + received);
}
if (footprint.getInput() == DotMethodFPInputEnum.SCALAR_NUMERIC && !JavaClassHelper.isNumeric(collectionComponentType)) {
throw new ExprValidationException(message + "numeric values" + received);
}
}
// manage context of this lambda-expression in regards to outer lambda-expression that may call this one.
validationContext.getExprEvaluatorContext().getExpressionResultCacheService().pushStack(this);
List<ExprDotEvalParam> bodiesAndParameters = new ArrayList<ExprDotEvalParam>();
int count = 0;
EventType inputEventType = eventTypeBean == null ? eventTypeColl : eventTypeBean;
for (ExprNode node : parameters) {
ExprDotEvalParam bodyAndParameter = getBodyAndParameter(enumMethodUsedName, count++, node, inputEventType, collectionComponentType, validationContext, bodiesAndParameters, footprint);
bodiesAndParameters.add(bodyAndParameter);
}
this.enumEval = getEnumEval(validationContext.getMethodResolutionService(), validationContext.getEventAdapterService(), validationContext.getStreamTypeService(), validationContext.getStatementId(), enumMethodUsedName, bodiesAndParameters, inputEventType, collectionComponentType, streamCountIncoming, validationContext.isDisablePropertyExpressionEventCollCache());
this.enumEvalNumRequiredEvents = enumEval.getStreamNumSize();
// determine the stream ids of event properties asked for in the evaluator(s)
HashSet<Integer> streamsRequired = new HashSet<Integer>();
ExprNodeIdentifierCollectVisitor visitor = new ExprNodeIdentifierCollectVisitor();
for (ExprDotEvalParam desc : bodiesAndParameters) {
desc.getBody().accept(visitor);
for (ExprIdentNode ident : visitor.getExprProperties()) {
streamsRequired.add(ident.getStreamId());
}
}
if (streamOfProviderIfApplicable != null) {
streamsRequired.add(streamOfProviderIfApplicable);
}
// We turn on caching if the stack is not empty (we are an inner lambda) and the dependency does not include the stream.
boolean isInner = !validationContext.getExprEvaluatorContext().getExpressionResultCacheService().popLambda();
if (isInner) {
// If none of the properties that the current lambda uses comes from the ultimate parent(s) or subsequent streams, then cache.
Deque<ExpressionResultCacheStackEntry> parents = validationContext.getExprEvaluatorContext().getExpressionResultCacheService().getStack();
boolean found = false;
for (int req : streamsRequired) {
ExprDotEvalEnumMethodBase first = (ExprDotEvalEnumMethodBase) parents.getFirst();
int parentIncoming = first.streamCountIncoming - 1;
int selfAdded = streamCountIncoming; // the one we use ourselfs
if (req > parentIncoming && req < selfAdded) {
found = true;
}
}
cache = !found;
}
}
public void setTypeInfo(EPType typeInfo) {
this.typeInfo = typeInfo;
}
public EPType getTypeInfo() {
return typeInfo;
}
public Object evaluate(Object target, EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) {
if (target instanceof EventBean) {
target = Collections.singletonList((EventBean) target);
}
if (cache) {
ExpressionResultCacheEntry<Long[], Object> cacheValue = exprEvaluatorContext.getExpressionResultCacheService().getEnumerationMethodLastValue(this);
if (cacheValue != null) {
return cacheValue.getResult();
}
Collection coll = (Collection) target;
if (coll == null) {
return null;
}
EventBean[] eventsLambda = allocateCopyEventLambda(eventsPerStream);
Object result = enumEval.evaluateEnumMethod(eventsLambda, coll, isNewData, exprEvaluatorContext);
exprEvaluatorContext.getExpressionResultCacheService().saveEnumerationMethodLastValue(this, result);
return result;
}
contextNumber++;
try {
exprEvaluatorContext.getExpressionResultCacheService().pushContext(contextNumber);
Collection coll = (Collection) target;
if (coll == null) {
return null;
}
EventBean[] eventsLambda = allocateCopyEventLambda(eventsPerStream);
return enumEval.evaluateEnumMethod(eventsLambda, coll, isNewData, exprEvaluatorContext);
}
finally {
exprEvaluatorContext.getExpressionResultCacheService().popContext();
}
}
private EventBean[] allocateCopyEventLambda(EventBean[] eventsPerStream) {
EventBean[] eventsLambda = new EventBean[enumEvalNumRequiredEvents];
EventBeanUtility.safeArrayCopy(eventsPerStream, eventsLambda);
return eventsLambda;
}
private ExprDotEvalParam getBodyAndParameter(String enumMethodUsedName,
int parameterNum,
ExprNode parameterNode,
EventType inputEventType,
Class collectionComponentType,
ExprValidationContext validationContext,
List<ExprDotEvalParam> priorParameters,
DotMethodFP footprint) throws ExprValidationException {
// handle an expression that is a constant or other (not =>)
if (!(parameterNode instanceof ExprLambdaGoesNode)) {
// no node subtree validation is required here, the chain parameter validation has taken place in ExprDotNode.validate
// validation of parameter types has taken place in footprint matching
return new ExprDotEvalParamExpr(parameterNum, parameterNode, parameterNode.getExprEvaluator());
}
ExprLambdaGoesNode goesNode = (ExprLambdaGoesNode) parameterNode;
// Get secondary
EventType[] additionalTypes = getAddStreamTypes(enumMethodUsedName, goesNode.getGoesToNames(), inputEventType, collectionComponentType, priorParameters, validationContext.getEventAdapterService());
String[] additionalStreamNames = goesNode.getGoesToNames().toArray(new String[goesNode.getGoesToNames().size()]);
validateDuplicateStreamNames(validationContext.getStreamTypeService().getStreamNames(), additionalStreamNames);
// add name and type to list of known types
EventType[] addTypes = (EventType[]) CollectionUtil.arrayExpandAddElements(validationContext.getStreamTypeService().getEventTypes(), additionalTypes);
String[] addNames = (String[]) CollectionUtil.arrayExpandAddElements(validationContext.getStreamTypeService().getStreamNames(), additionalStreamNames);
StreamTypeServiceImpl types = new StreamTypeServiceImpl(addTypes, addNames, new boolean[addTypes.length], null, false);
// validate expression body
ExprNode filter = goesNode.getChildNodes()[0];
try {
ExprValidationContext filterValidationContext = new ExprValidationContext(types, validationContext);
filter = ExprNodeUtility.getValidatedSubtree(ExprNodeOrigin.DECLAREDEXPRBODY, filter, filterValidationContext);
}
catch (ExprValidationException ex) {
throw new ExprValidationException("Error validating enumeration method '" + enumMethodUsedName + "' parameter " + parameterNum + ": " + ex.getMessage(), ex);
}
ExprEvaluator filterEvaluator = filter.getExprEvaluator();
DotMethodFPParamTypeEnum expectedType = footprint.getParameters()[parameterNum].getType();
// Lambda-methods don't use a specific expected return-type, so passing null for type is fine.
DotMethodUtil.validateSpecificType(enumMethodUsedName, DotMethodTypeEnum.ENUM, expectedType, null, filterEvaluator.getType(), parameterNum, filter);
int numStreamsIncoming = validationContext.getStreamTypeService().getEventTypes().length;
return new ExprDotEvalParamLambda(parameterNum, filter, filterEvaluator,
numStreamsIncoming, goesNode.getGoesToNames(), additionalTypes);
}
private void validateDuplicateStreamNames(String[] streamNames, String[] additionalStreamNames) throws ExprValidationException {
for (int added = 0; added < additionalStreamNames.length; added++) {
for (int exist = 0; exist < streamNames.length; exist++) {
if (streamNames[exist] != null && streamNames[exist].equalsIgnoreCase(additionalStreamNames[added])) {
String message = "Error validating enumeration method '" + enumMethodUsedName + "', the lambda-parameter name '" + additionalStreamNames[added] + "' has already been declared in this context";
throw new ExprValidationException(message);
}
}
}
}
public String toString() {
return this.getClass().getSimpleName() +
" lambda=" + enumMethodEnum;
}
}
| gpl-2.0 |
md-5/jdk10 | test/jdk/java/lang/invoke/VarargsArrayTest.java | 10292 | /*
* Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import sun.invoke.util.Wrapper;
import test.java.lang.invoke.lib.CodeCacheOverflowProcessor;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleHelper;
import java.lang.invoke.MethodType;
import java.util.Arrays;
import java.util.Collections;
/* @test
* @summary unit tests for varargs array methods: MethodHandleInfo.varargsArray(int),
* MethodHandleInfo.varargsArray(Class,int) & MethodHandleInfo.varargsList(int)
* @modules java.base/sun.invoke.util
* @library /test/lib /java/lang/invoke/common
* @compile/module=java.base java/lang/invoke/MethodHandleHelper.java
* @run main/bootclasspath VarargsArrayTest
* @run main/bootclasspath/othervm -DVarargsArrayTest.MAX_ARITY=255 -DVarargsArrayTest.START_ARITY=250
* VarargsArrayTest
*/
/* This might take a while and burn lots of metadata:
* @run main/bootclasspath -DVarargsArrayTest.MAX_ARITY=255 -DVarargsArrayTest.EXHAUSTIVE=true VarargsArrayTest
*/
public class VarargsArrayTest {
private static final Class<?> CLASS = VarargsArrayTest.class;
private static final int MAX_ARITY = Integer.getInteger(
CLASS.getSimpleName()+".MAX_ARITY", 40);
private static final int START_ARITY = Integer.getInteger(
CLASS.getSimpleName()+".START_ARITY", 0);
private static final boolean EXHAUSTIVE = Boolean.getBoolean(
CLASS.getSimpleName()+".EXHAUSTIVE");
public static void main(String[] args) throws Throwable {
CodeCacheOverflowProcessor.runMHTest(VarargsArrayTest::test);
}
public static void test() throws Throwable {
testVarargsArray();
testVarargsReferenceArray();
testVarargsPrimitiveArray();
}
public static void testVarargsArray() throws Throwable {
final int MIN = START_ARITY;
final int MAX = MAX_ARITY-2; // 253+1 would cause parameter overflow with 'this' added
for (int nargs = MIN; nargs <= MAX; nargs = nextArgCount(nargs, 17, MAX)) {
MethodHandle target = MethodHandleHelper.varargsArray(nargs);
Object[] args = new Object[nargs];
for (int i = 0; i < nargs; i++)
args[i] = "#"+i;
Object res = target.invokeWithArguments(args);
assertArrayEquals(args, (Object[])res);
}
}
public static void testVarargsReferenceArray() throws Throwable {
testTypedVarargsArray(Object[].class);
testTypedVarargsArray(String[].class);
testTypedVarargsArray(Number[].class);
}
public static void testVarargsPrimitiveArray() throws Throwable {
testTypedVarargsArray(int[].class);
testTypedVarargsArray(long[].class);
testTypedVarargsArray(byte[].class);
testTypedVarargsArray(boolean[].class);
testTypedVarargsArray(short[].class);
testTypedVarargsArray(char[].class);
testTypedVarargsArray(float[].class);
testTypedVarargsArray(double[].class);
}
private static int nextArgCount(int nargs, int density, int MAX) {
if (EXHAUSTIVE) return nargs + 1;
if (nargs >= MAX) return Integer.MAX_VALUE;
int BOT = 20, TOP = MAX-5;
if (density < 10) { BOT = 10; MAX = TOP-2; }
if (nargs <= BOT || nargs >= TOP) {
++nargs;
} else {
int bump = Math.max(1, 100 / density);
nargs += bump;
if (nargs > TOP) nargs = TOP;
}
return nargs;
}
private static void testTypedVarargsArray(Class<?> arrayType) throws Throwable {
Class<?> elemType = arrayType.getComponentType();
int MIN = START_ARITY;
int MAX = MAX_ARITY-2; // 253+1 would cause parameter overflow with 'this' added
int density = 3;
if (elemType == int.class || elemType == long.class) density = 7;
if (elemType == long.class || elemType == double.class) { MAX /= 2; MIN /= 2; }
for (int nargs = MIN; nargs <= MAX; nargs = nextArgCount(nargs, density, MAX)) {
Object[] args = makeTestArray(elemType, nargs);
MethodHandle varargsArray = MethodHandleHelper.varargsArray(arrayType, nargs);
MethodType vaType = varargsArray.type();
assertEquals(arrayType, vaType.returnType());
if (nargs != 0) {
assertEquals(elemType, vaType.parameterType(0));
assertEquals(elemType, vaType.parameterType(vaType.parameterCount()-1));
}
assertEquals(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType)),
vaType);
Object res = varargsArray.invokeWithArguments(args);
assertEquals(res.getClass(), arrayType);
String resString = toArrayString(res);
assertEquals(Arrays.toString(args), resString);
MethodHandle spreader = varargsArray.asSpreader(arrayType, nargs);
MethodType stype = spreader.type();
assert(stype == MethodType.methodType(arrayType, arrayType));
if (nargs <= 5) {
// invoke target as a spreader also:
@SuppressWarnings("cast")
Object res2 = spreader.invokeWithArguments((Object)res);
String res2String = toArrayString(res2);
assertEquals(Arrays.toString(args), res2String);
// invoke the spreader on a generic Object[] array; check for error
try {
Object res3 = spreader.invokeWithArguments((Object)args);
String res3String = toArrayString(res3);
assertTrue(arrayType.getName(), arrayType.isAssignableFrom(Object[].class));
assertEquals(Arrays.toString(args), res3String);
} catch (ClassCastException ex) {
assertFalse(arrayType.getName(), arrayType.isAssignableFrom(Object[].class));
}
}
if (nargs == 0) {
// invoke spreader on null arglist
Object res3 = spreader.invokeWithArguments((Object)null);
String res3String = toArrayString(res3);
assertEquals(Arrays.toString(args), res3String);
}
}
}
private static Object[] makeTestArray(Class<?> elemType, int len) {
Wrapper elem = null;
if (elemType.isPrimitive())
elem = Wrapper.forPrimitiveType(elemType);
else if (Wrapper.isWrapperType(elemType))
elem = Wrapper.forWrapperType(elemType);
Object[] args = new Object[len];
for (int i = 0; i < len; i++) {
Object arg = i * 100;
if (elem == null) {
if (elemType == String.class)
arg = "#"+arg;
arg = elemType.cast(arg); // just to make sure
} else {
switch (elem) {
case BOOLEAN: arg = (i % 3 == 0); break;
case CHAR: arg = 'a' + i; break;
case LONG: arg = (long)i * 1000_000_000; break;
case FLOAT: arg = (float)i / 100; break;
case DOUBLE: arg = (double)i / 1000_000; break;
}
arg = elem.cast(arg, elemType);
}
args[i] = arg;
}
return args;
}
private static String toArrayString(Object a) {
if (a == null) return "null";
Class<?> elemType = a.getClass().getComponentType();
if (elemType == null) return a.toString();
if (elemType.isPrimitive()) {
switch (Wrapper.forPrimitiveType(elemType)) {
case INT: return Arrays.toString((int[])a);
case BYTE: return Arrays.toString((byte[])a);
case BOOLEAN: return Arrays.toString((boolean[])a);
case SHORT: return Arrays.toString((short[])a);
case CHAR: return Arrays.toString((char[])a);
case FLOAT: return Arrays.toString((float[])a);
case LONG: return Arrays.toString((long[])a);
case DOUBLE: return Arrays.toString((double[])a);
}
}
return Arrays.toString((Object[])a);
}
public static void assertArrayEquals(Object[] arr1, Object[] arr2) {
if (arr1 == null && arr2 == null) return;
if (arr1 != null && arr2 != null && arr1.length == arr2.length) {
for (int i = 0; i < arr1.length; i++) {
assertEquals(arr1[i], arr2[i]);
}
return;
}
throw new AssertionError(Arrays.deepToString(arr1)
+ " != " + Arrays.deepToString(arr2));
}
public static void assertEquals(Object o1, Object o2) {
if (o1 == null && o2 == null) return;
if (o1 != null && o1.equals(o2)) return;
throw new AssertionError(o1 + " != " + o2);
}
public static void assertTrue(String msg, boolean b) {
if (!b) {
throw new AssertionError(msg);
}
}
public static void assertFalse(String msg, boolean b) {
assertTrue(msg, !b);
}
}
| gpl-2.0 |
severinh/java-gnome | src/bindings/org/gnome/gtk/Dialog.java | 14192 | /*
* java-gnome, a UI library for writing GTK and GNOME programs from Java!
*
* Copyright © 2007-2011 Operational Dynamics Consulting, Pty Ltd and Others
*
* The code in this file, and the program it is a part of, is made available
* to you by its authors as open source software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License version
* 2 ("GPL") as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details.
*
* You should have received a copy of the GPL along with this program. If not,
* see http://www.gnu.org/licenses/. The authors of this program may be
* contacted through http://java-gnome.sourceforge.net/.
*
* Linking this library statically or dynamically with other modules is making
* a combined work based on this library. Thus, the terms and conditions of
* the GPL cover the whole combination. As a special exception (the
* "Classpath Exception"), the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library. If
* you modify this library, you may extend the Classpath Exception to your
* version of the library, but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version.
*/
package org.gnome.gtk;
/**
* A Dialog is a special Window which is used to display information for the
* user or to get response from her. While a normal Window usually is used to
* represent the whole application and to offer sometimes many interactions
* for the user, a Dialog should only be opened if a special situation has
* occurred.
*
* <p>
* A Dialog is a composite Window which contains a {@link VBox}. This box is
* split by an HSeparator into two areas:
*
* <ul>
* <li>
* <p>
* The <var>main area</var> consists of the VBox itself above the separator.
* It is used to pack Widgets such as Labels or Icons which will display the
* descriptive part of your Dialog. The easiest way to add Widget(s) to the
* top area is to simply call the {@link Dialog#add(Widget) add()} method. It
* is a good technique to first add your own Container such as an {@link HBox}
* to the top area and pack all other Widgets to it if you need more refined
* layout control, although this is not compulsory.
*
* <li>
* <p>
* The bottom <var>action area</var> (actually an HButtonBox) is used to pack
* buttons to the Dialog which may perform actions such as "Ok" or "Cancel".
* You should only add Buttons to the <var>action area</var> using one of the
* {@link Dialog#addButton(String, ResponseType) addButton()} methods allowing
* you to specify a ResponseType constant to be emitted if the Button is
* clicked.
* </ul>
*
* <p>
* To open the Dialog as a normal non-blocking Window you use the
* {@link Window#present() present()} method after you have packed the various
* child elements into it. On the other hand, for occasions where you are
* using a Dialog to get information required for the further progress of the
* main application, the {@link Dialog#run() run()} method can be used to open
* the Dialog. This method blocks the application and waits for response from
* the user.
*
* <p>
* Like any Window that you are finished with, you have to
* {@link Window#hide() hide()} when you receive a
* <code>Dialog.Response</code> callback, or after {@link Dialog#run() run()}
* returns.
*
* <p>
* GTK comes with a number of standard Dialogs which can be used for typical
* situations such as {@link MessageDialog MessageDialog} to present urgent
* information to the user, and {@link FileChooserDialog FileChooserDialog}
* which provides the familiar behaviour of popping up a Dialog to select a
* file.
*
* @author Thomas Schmitz
* @author Vreixo Formoso
* @author Andrew Cowie
* @since 4.0.5
*/
public class Dialog extends Window
{
protected Dialog(long pointer) {
super(pointer);
}
/**
* Creates a new Dialog box with both <var>main area</var> and an empty
* <var>action area</var>, separated by an HSeparator. You'll need to do
* the rest of the Dialog setup manually yourself, including calling
* {@link Window#setTransientFor(Window) setTransientFor()} and
* {@link Window#setTitle(String) setTitle()}.
*
* @since 4.0.5
*/
public Dialog() {
super(GtkDialog.createDialog());
}
/**
* Create a new Dialog. This is a convenience constructor with the same
* effect as:
*
* <pre>
* d = new Dialog();
* d.setTitle(title);
* d.setModal(modal);
* d.setTransientFor(parent);
* </pre>
*
* @param title
* Title of the new Dialog.
* @param parent
* Transient parent of the dialog, or <code>null</code>. If a
* parent is provided, the window manager will keep the Dialog
* on top of it. If the Dialog is modal, it is highly
* recommended that you provide a parent Window, otherwise the
* user could be trying to interact with the main Window while
* the Dialog is blocking it, but hidden under other Window. In
* that case, the user experience is really bad, as it is not
* easy to figure out the real case of the blocking.
* @param modal
* Whether the dialog is to be modal or not. A modal Dialog
* blocks interaction with the other parts of the application.
* Note that you can also get a similar behaviour using the
* {@link #run() run()} method.
* @since 4.0.5
*/
public Dialog(String title, Window parent, boolean modal) {
super(GtkDialog.createDialogWithButtons(title, parent, modal ? DialogFlags.MODAL
: DialogFlags.NONE, null));
}
/**
* Add a Widget to the <var>main area</var> of the Dialog.
*
* @since 4.0.5
*/
public void add(Widget widget) {
final Box box;
box = (Box) this.getChild();
box.add(widget);
}
/**
* Adds an action {@link Button} with the given text as its label to the
* end of the Dialog's <var>action area</var>. The given ResponseType will
* be returned back in the Dialog's {@link Dialog.Response} signal when
* the Button added as a result of this call is clicked.
*
* @return the added Button. This is a convenience allowing you to hook up
* further handlers to the Button if necessary.
* @since 4.0.5
*/
public Button addButton(String text, ResponseType response) {
return (Button) GtkDialog.addButton(this, text, response.getResponseId());
}
/**
* Add a Button whose icon and label are taken from a given Stock. It is,
* as ever, recommended to use a Stock Button for common actions. See
* {@link #addButton(String, ResponseType) addButton()}.
*
* @since 4.0.5
*/
public Button addButton(Stock stock, ResponseType response) {
return (Button) GtkDialog.addButton(this, stock.getStockId(), response.getResponseId());
}
/**
* Add a Button Widget you've already constructed to the action area of
* this Dialog.
*
* <p>
* It is, as ever, recommended to use a Stock Button for common actions.
* See {@link #addButton(String, ResponseType) addButton()}.
*
* <p>
* <i>You can pass any Activatable as the <code>widget</code>
* parameter.</i>
*
* @since 4.0.14
*/
public Button addButton(Widget widget, ResponseType response) {
GtkDialog.addActionWidget(this, widget, response.getResponseId());
/*
* The other addButton() signature returns Button, though the native
* code here actually takes a GtkActivatable. So workaround in this
* overload by returning Button if possible.
*/
if (widget instanceof Button) {
return (Button) widget;
} else {
return null;
}
}
/**
* Block the rest of the application by running in a recursive main loop
* until a {@link Dialog.Response} signal arises on the Dialog as a result
* of the user activating one of the <var>action area</var> Buttons. This
* is known as a 'modal' Dialog. While this loop is running the user is
* prevented from interacting with the rest of the application.
*
* <pre>
* response = dialog.run();
*
* dialog.hide();
* if (response == ResponseType.CANCEL) {
* return;
* }
* // take action!
* </pre>
*
* If you don't care about the response, just go ahead and
* <code>hide()</code> right away as soon as <code>run()</code> returns.
*
* <pre>
* dialog = new AboutDialog();
* dialog.run();
* dialog.hide();
* </pre>
*
* <p>
* While there are legitimate uses of modal Dialogs, it is a feature that
* tends to be badly abused. Therefore, before you call this method,
* please consider carefully if it is wise to prevent the rest of the user
* interface from being used.
*
* <p>
* A common bug is for people to neglect to {@link Widget#hide() hide()}
* the Dialog after this method returns. If you don't, then the Dialog
* will remain on screen despite repeated clicking of (for example) the
* "Close" Button [the Window is not hidden automatically because of cases
* like "Apply" in preferences Dialogs and "Open" in FileChoosers when a
* folder is selected and activation will change directory rather than
* finishing the Dialog].
*
* <p>
* While <code>run()</code> can be very useful in callbacks when popping
* up a quick question, you may find hooking up to the
* {@link Dialog.Response} signal more flexible.
*
* <p>
* <b>Warning</b><br>
* <i>Using this method will prevent other threads that use GTK from
* running. That's a bug as far as we're concerned, but if the goal is to
* display a dialog without blocking other threads that use GTK, it is
* better (for now) to call Window's</i> {@link Window#present()
* present()} <i>and the</i> {@link #connect(Response) connect()} <i>to
* the </i> {@link Dialog.Response} <i>signal.</i>
*
* <pre>
* dialog.connect(new Dialog.Response() {
* public void onResponse(Dialog source, ResponseType response) {
* dialog.hide();
* if (response == ResponseType.CLOSE) {
* return;
* }
* // take action!
* }
* });
*
* dialog.present();
* </pre>
*
* @return the emitted response constant. If asking a question, you should
* check this against the various constants in the ResponseType
* class. Don't forget to <code>hide()</code> afterwards.
* @since 4.0.5
* @see <a href="https://bugzilla.gnome.org/show_bug.cgi?id=606796">the
* bug report</a>
*/
public ResponseType run() {
final int value;
final ResponseType response;
value = GtkDialog.run(this);
response = ResponseType.constantFor(value);
return response;
}
/**
* This signal arises when a user activates one of the Widgets laid out in
* the <var>action area</var> of the Dialog.
*
* @author Thomas Schmitz
* @author Vreixo Formoso
* @since 4.0.5
*/
public interface Response
{
void onResponse(Dialog source, ResponseType response);
}
/**
* Hook up a <code>Dialog.Response</code> handler.
*/
public void connect(Dialog.Response handler) {
GtkDialog.connect(this, new ResponseHandler(handler), false);
}
/*
* Needed for emit the Dialog.Response signal with a type-safe
* ResponseType instead of the underlying int ordinal.
*/
private static class ResponseHandler implements GtkDialog.ResponseSignal
{
private Dialog.Response handler;
private ResponseHandler(Dialog.Response handler) {
this.handler = handler;
}
public void onResponse(Dialog source, int responseId) {
final ResponseType response;
response = ResponseType.constantFor(responseId);
handler.onResponse(source, response);
}
}
/**
* Cause a <code>Dialog.Response</code> signal with the specified
* ResponseType to be emitted by this Dialog.
*
* @since 4.0.9
*/
public void emitResponse(ResponseType response) {
GtkDialog.response(this, response.getResponseId());
}
/**
* Tell the Dialog which Button (which ResponseType) is to be activated
* when the user presses <b><code>Enter</code></b>.
*
* <p>
* If you're calling this because you've created a custom Button with
* {@link #addButton(Widget, ResponseType) addButton()}, you'll probably
* need to call Widget's {@link Widget#setCanDefault(boolean)
* setCanDefault()} on that Button first, before using this.
*
* <p>
* Note that calling Widget's {@link Widget#grabDefault() grabDefault()}
* is insufficient; Dialogs have some fairly tricky internal wiring, and
* you need to use this method instead.
*
* @since 4.0.17
*/
public void setDefaultResponse(ResponseType response) {
GtkDialog.setDefaultResponse(this, response.getResponseId());
}
}
| gpl-2.0 |
166MMX/openjdk.java.net-openjfx-8u40-rt | modules/controls/src/test/java/com/sun/javafx/scene/control/test/RT_22463_Person.java | 2162 | /*
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.javafx.scene.control.test;
public class RT_22463_Person {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override public String toString() {
return getName();
}
@Override public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final RT_22463_Person other = (RT_22463_Person) obj;
if (this.id != other.id) {
return false;
}
return true;
}
@Override public int hashCode() {
int hash = 7;
hash = 89 * hash + (int) (this.id ^ (this.id >>> 32));
return hash;
}
}
| gpl-2.0 |
JrmyDev/CodenameOne | CodenameOne/src/com/codename1/db/Database.java | 8950 | /*
* Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Codename One designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Codename One through http://www.codenameone.com/ if you
* need additional information or have any questions.
*/
package com.codename1.db;
import com.codename1.ui.Display;
import java.io.IOException;
/**
* <p>Allows access to SQLite specifically connecting to a database and executing sql queries on the data.
* There is more thorough coverage of the {@link com.codename1.db Database API here}.</p>
*
* <p>The Database class abstracts the underlying SQLite of the device if
* available.<br>
*
* Notice that this might not be supported on all platforms in which case the {@code Database} will be null.</p>
*
* <p>SQLite should be used for very large data handling, for small storage
* refer to {@link com.codename1.io.Storage} which is more portable.</p>
*
* <p>The sample code below presents a Database Explorer tool that allows executing arbitrary SQL and
* viewing the tabular results:</p>
* <script src="https://gist.github.com/codenameone/282b02c20e7bd067f1f0.js"></script>
* <img src="https://www.codenameone.com/img/developer-guide/sql-table.png" alt="Querying the temp demo generated by the SQLDemo application">
* <img src="https://www.codenameone.com/img/developer-guide/sql-entry.png" alt="Issuing a query">
*
* @author Chen
*/
public abstract class Database {
/**
* Opens a database or create one if not exists
*
* @param databaseName the name of the database
* @return Database Object or null if not supported on the platform
*
* @throws IOException if database cannot be created
*/
public static Database openOrCreate(String databaseName) throws IOException{
return Display.getInstance().openOrCreate(databaseName);
}
/**
* Indicates weather a database exists
*
* <p><strong>NOTE:</strong> Not supported in the Javascript port. Will always return false.</p>
*
* @param databaseName the name of the database
* @return true if database exists
*/
public static boolean exists(String databaseName){
return Display.getInstance().exists(databaseName);
}
/**
* Deletes database
*
* <p><strong>NOTE:</strong> This method is not supported in the Javascript port. Will silently fail.</p>
*
* @param databaseName the name of the database
* @throws IOException if database cannot be deleted
*/
public static void delete(String databaseName) throws IOException{
Display.getInstance().delete(databaseName);
}
/**
* Returns the file path of the Database if exists and if supported on
* the platform.
*
* <p><strong>NOTE:</strong> This method will return null in the Javascript port.</p>
* @return the file path of the database
*/
public static String getDatabasePath(String databaseName){
return Display.getInstance().getDatabasePath(databaseName);
}
/**
* Starts a transaction
*
* <p><strong>NOTE:</strong> Not supported in Javascript port. This method will do nothing when running in Javascript.</p>
* @throws IOException if database is not opened
*/
public abstract void beginTransaction() throws IOException;
/**
* Commits current transaction
*
* <p><strong>NOTE:</strong> Not supported in Javascript port. This method will do nothing when running in Javascript.</p>
*
* @throws IOException if database is not opened or transaction was not started
*/
public abstract void commitTransaction() throws IOException;
/**
* Rolls back current transaction
*
* <p><strong>NOTE:</strong> Not supported in Javascript port. This method will do nothing when running in Javascript.</p>
*
* @throws IOException if database is not opened or transaction was not started
*/
public abstract void rollbackTransaction() throws IOException;
/**
* Closes the database
*
* @throws IOException
*/
public abstract void close() throws IOException;
/**
* Execute an update query.
* Used for INSERT, UPDATE, DELETE and similar sql statements.
*
* @param sql the sql to execute
*
* @throws IOException
*/
public abstract void execute(String sql) throws IOException;
/**
* Execute an update query with params.
* Used for INSERT, UPDATE, DELETE and similar sql statements.
* The sql can be constructed with '?' and the params will be binded to the
* query
*
* @param sql the sql to execute
* @param params to bind to the query where the '?' exists
*
* @throws IOException
*/
public abstract void execute(String sql, String [] params) throws IOException;
/**
* Execute an update query with params.
* Used for INSERT, UPDATE, DELETE and similar sql statements.
* The sql can be constructed with '?' and the params will be binded to the
* query
*
* @param sql the sql to execute
* @param params to bind to the query where the '?' exists, supported object
* types are String, byte[], Double, Long and null
*
* @throws IOException
*/
public void execute(String sql, Object... params) throws IOException{
if ( params == null) {
execute(sql);
} else {
//throw new RuntimeException("not implemented");
int len = params.length;
String[] strParams = new String[len];
for ( int i=0; i<len; i++) {
if (params[i] instanceof byte[]) {
throw new RuntimeException("Blobs aren't supported on this platform");
}
if (params[i] == null) {
strParams[i] = null;
} else {
strParams[i] = params[i].toString();
}
}
execute(sql, strParams);
}
}
/**
* This method should be called with SELECT type statements that return
* row set.
*
* @param sql the sql to execute
* @param params to bind to the query where the '?' exists
* @return a cursor to iterate over the results
*
* @throws IOException
*/
public abstract Cursor executeQuery(String sql, String [] params) throws IOException;
/**
* This method should be called with SELECT type statements that return
* row set it accepts object with params.
*
* @param sql the sql to execute
* @param params to bind to the query where the '?' exists, supported object
* types are String, byte[], Double, Long and null
* @return a cursor to iterate over the results
*
* @throws IOException
*/
public Cursor executeQuery(String sql, Object... params) throws IOException{
if ( params == null || params.length == 0) {
return executeQuery(sql);
} else {
int len = params.length;
String[] strParams = new String[len];
for ( int i=0; i<len; i++) {
if (params[i] instanceof byte[]) {
throw new RuntimeException("Blobs aren't supported on this platform");
}
if (params[i] == null) {
strParams[i] = null;
} else {
strParams[i] = params[i].toString();
}
}
return executeQuery(sql, strParams);
}
}
/**
* This method should be called with SELECT type statements that return
* row set.
*
* @param sql the sql to execute
* @return a cursor to iterate over the results
*
* @throws IOException
*/
public abstract Cursor executeQuery(String sql) throws IOException;
}
| gpl-2.0 |
intfloat/CoreNLP | src/edu/stanford/nlp/parser/lexparser/ArabicTreebankParserParams.java | 40364 | package edu.stanford.nlp.parser.lexparser;
import edu.stanford.nlp.util.logging.Redwood;
import java.util.*;
import java.util.regex.*;
import edu.stanford.nlp.international.arabic.ArabicMorphoFeatureSpecification;
import edu.stanford.nlp.international.morph.MorphoFeatureSpecification;
import edu.stanford.nlp.international.morph.MorphoFeatureSpecification.MorphoFeatureType;
import edu.stanford.nlp.international.morph.MorphoFeatures;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.ling.SentenceUtils;
import edu.stanford.nlp.process.SerializableFunction;
import edu.stanford.nlp.trees.*;
import edu.stanford.nlp.trees.international.arabic.*;
import edu.stanford.nlp.trees.tregex.*;
import java.util.function.Function;
import edu.stanford.nlp.util.Generics;
import edu.stanford.nlp.util.Index;
import edu.stanford.nlp.util.Pair;
/**
* A {@link TreebankLangParserParams} implementing class for
* the Penn Arabic Treebank. The baseline feature set works with either
* UTF-8 or Buckwalter input, although the behavior of some unused features depends
* on the input encoding.
*
* @author Roger Levy
* @author Christopher Manning
* @author Spence Green
*/
public class ArabicTreebankParserParams extends AbstractTreebankParserParams {
/** A logger for this class */
private static Redwood.RedwoodChannels log = Redwood.channels(ArabicTreebankParserParams.class);
private static final long serialVersionUID = 8853426784197984653L;
private final StringBuilder optionsString;
private boolean retainNPTmp = false;
private boolean retainNPSbj = false;
private boolean retainPRD = false;
private boolean retainPPClr = false;
private boolean changeNoLabels = false;
private boolean collinizerRetainsPunctuation = false;
private boolean discardX = false;
private HeadFinder headFinder;
private final Map<String,Pair<TregexPattern,Function<TregexMatcher,String>>> annotationPatterns;
private final List<Pair<TregexPattern,Function<TregexMatcher,String>>> activeAnnotations;
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private MorphoFeatureSpecification morphoSpec = null;
public ArabicTreebankParserParams() {
super(new ArabicTreebankLanguagePack());
optionsString = new StringBuilder();
optionsString.append("ArabicTreebankParserParams\n");
annotationPatterns = Generics.newHashMap();
activeAnnotations = new ArrayList<>();
//Initialize the headFinder here
headFinder = headFinder();
initializeAnnotationPatterns();
}
/**
* Creates an {@link ArabicTreeReaderFactory} with parameters set
* via options passed in from the command line.
*
* @return An {@link ArabicTreeReaderFactory}
*/
public TreeReaderFactory treeReaderFactory() {
return new ArabicTreeReaderFactory(retainNPTmp, retainPRD,
changeNoLabels, discardX,
retainNPSbj, false, retainPPClr);
}
//NOTE (WSG): This method is called by main() to load the test treebank
@Override
public MemoryTreebank memoryTreebank() {
return new MemoryTreebank(treeReaderFactory(), inputEncoding);
}
//NOTE (WSG): This method is called to load the training treebank
@Override
public DiskTreebank diskTreebank() {
return new DiskTreebank(treeReaderFactory(), inputEncoding);
}
@Override
public HeadFinder headFinder() {
if(headFinder == null)
headFinder = new ArabicHeadFinder(treebankLanguagePack());
return headFinder;
}
@Override
public HeadFinder typedDependencyHeadFinder() {
return headFinder();
}
/**
* Returns a lexicon for Arabic. At the moment this is just a BaseLexicon.
*
* @param op Lexicon options
* @return A Lexicon
*/
@Override
public Lexicon lex(Options op, Index<String> wordIndex, Index<String> tagIndex) {
if(op.lexOptions.uwModelTrainer == null) {
op.lexOptions.uwModelTrainer = "edu.stanford.nlp.parser.lexparser.ArabicUnknownWordModelTrainer";
}
if(morphoSpec != null) {
return new FactoredLexicon(op, morphoSpec, wordIndex, tagIndex);
}
return new BaseLexicon(op, wordIndex, tagIndex);
}
/**
* Return a default sentence for the language (for testing).
* The example is in UTF-8.
*/
public List<? extends HasWord> defaultTestSentence() {
String[] sent = {"هو","استنكر","الحكومة","يوم","امس","."};
return SentenceUtils.toWordList(sent);
}
protected class ArabicSubcategoryStripper implements TreeTransformer {
protected final TreeFactory tf = new LabeledScoredTreeFactory();
public Tree transformTree(Tree tree) {
Label lab = tree.label();
String s = lab.value();
if (tree.isLeaf()) {
Tree leaf = tf.newLeaf(lab);
leaf.setScore(tree.score());
return leaf;
} else if(tree.isPhrasal()) {
if(retainNPTmp && s.startsWith("NP-TMP")) {
s = "NP-TMP";
} else if(retainNPSbj && s.startsWith("NP-SBJ")) {
s = "NP-SBJ";
} else if(retainPRD && s.matches("VB[^P].*PRD.*")) {
s = tlp.basicCategory(s);
s += "-PRD";
} else {
s = tlp.basicCategory(s);
}
} else if(tree.isPreTerminal()) {
s = tlp.basicCategory(s);
} else {
System.err.printf("Encountered a non-leaf/phrasal/pre-terminal node %s\n",s);
//Normalize by default
s = tlp.basicCategory(s);
}
// Recursively process children depth-first
List<Tree> children = new ArrayList<>(tree.numChildren());
for (Tree child : tree.getChildrenAsList()) {
Tree newChild = transformTree(child);
children.add(newChild);
}
// Make the new parent label
Tree node = tf.newTreeNode(lab, children);
node.setValue(s);
node.setScore(tree.score());
if(node.label() instanceof HasTag)
((HasTag) node.label()).setTag(s);
return node;
}
}
/**
* Returns a TreeTransformer that retains categories
* according to the following options supported by setOptionFlag:
* <p>
* <code>-retainNPTmp</code> Retain temporal NP marking on NPs.
* <code>-retainNPSbj</code> Retain NP subject function tags
* <code>-markPRDverbs</code> Retain PRD verbs.
* </p>
*/
//NOTE (WSG): This is applied to both the best parse by getBestParse()
//and to the gold eval tree by testOnTreebank()
@Override
public TreeTransformer subcategoryStripper() {
return new ArabicSubcategoryStripper();
}
/**
* The collinizer eliminates punctuation
*/
@Override
public TreeTransformer collinizer() {
return new TreeCollinizer(tlp, !collinizerRetainsPunctuation, false);
}
/**
* Stand-in collinizer does nothing to the tree.
*/
@Override
public TreeTransformer collinizerEvalb() {
return collinizer();
}
@Override
public String[] sisterSplitters() {
return EMPTY_STRING_ARRAY;
}
// WSGDEBUG -- Annotate POS tags with nominal (grammatical) gender
private static final MorphoFeatureSpecification tagSpec = new ArabicMorphoFeatureSpecification();
static {
tagSpec.activate(MorphoFeatureType.NGEN);
}
@Override
public Tree transformTree(Tree t, Tree root) {
String baseCat = t.value();
StringBuilder newCategory = new StringBuilder();
//Add manual state splits
for (Pair<TregexPattern,Function<TregexMatcher,String>> e : activeAnnotations) {
TregexMatcher m = e.first().matcher(root);
if (m.matchesAt(t))
newCategory.append(e.second().apply(m));
}
// WSGDEBUG
//Add morphosyntactic features if this is a POS tag
if(t.isPreTerminal() && tagSpec != null) {
if( !(t.firstChild().label() instanceof CoreLabel) || ((CoreLabel) t.firstChild().label()).originalText() == null )
throw new RuntimeException(String.format("%s: Term lacks morpho analysis: %s",this.getClass().getName(),t.toString()));
String morphoStr = ((CoreLabel) t.firstChild().label()).originalText();
MorphoFeatures feats = tagSpec.strToFeatures(morphoStr);
baseCat = feats.getTag(baseCat);
}
//Update the label(s)
String newCat = baseCat + newCategory.toString();
t.setValue(newCat);
if (t.isPreTerminal() && t.label() instanceof HasTag)
((HasTag) t.label()).setTag(newCat);
return t;
}
/**
* These are the annotations included when the user selects the -arabicFactored option.
*/
private final List<String> baselineFeatures = new ArrayList<>();
{
baselineFeatures.add("-markNounNPargTakers");
baselineFeatures.add("-genitiveMark");
baselineFeatures.add("-splitPUNC");
baselineFeatures.add("-markContainsVerb");
baselineFeatures.add("-markStrictBaseNP");
baselineFeatures.add("-markOneLevelIdafa");
baselineFeatures.add("-splitIN");
baselineFeatures.add("-markMasdarVP");
baselineFeatures.add("-containsSVO");
baselineFeatures.add("-splitCC");
baselineFeatures.add("-markFem");
// Added for MWE experiments
baselineFeatures.add("-mwe");
baselineFeatures.add("-mweContainsVerb");
}
private final List<String> additionalFeatures = new ArrayList<>();
private void initializeAnnotationPatterns() {
//This doesn't/can't really pick out genitives, but just any NP following an NN head.
//wsg2011: In particular, it doesn't select NP complements of PPs, which are also genitive.
final String genitiveNodeTregexString = "@NP > @NP $- /^N/";
TregexPatternCompiler tregexPatternCompiler =
new TregexPatternCompiler(headFinder());
try {
// ******************
// Baseline features
// ******************
annotationPatterns.put("-genitiveMark", new Pair<>(TregexPattern.compile(genitiveNodeTregexString), new SimpleStringFunction("-genitive")));
annotationPatterns.put("-markStrictBaseNP", new Pair<>(tregexPatternCompiler.compile("@NP !< (__ < (__ < __))"), new SimpleStringFunction("-base"))); // NP with no phrasal node in it
annotationPatterns.put("-markOneLevelIdafa", new Pair<>(tregexPatternCompiler.compile("@NP < (@NP < (__ < __)) !< (/^[^N]/ < (__ < __)) !< (__ < (__ < (__ < __)))"), new SimpleStringFunction("-idafa1")));
annotationPatterns.put("-markNounNPargTakers", new Pair<>(tregexPatternCompiler.compile("@NN|NNS|NNP|NNPS|DTNN|DTNNS|DTNNP|DTNNPS ># (@NP < @NP)"), new SimpleStringFunction("-NounNParg")));
annotationPatterns.put("-markContainsVerb", new Pair<>(tregexPatternCompiler.compile("__ << (/^[CIP]?V/ < (__ !< __))"), new SimpleStringFunction("-withV")));
annotationPatterns.put("-splitIN", new Pair<>(tregexPatternCompiler.compile("@IN < __=word"), new AddRelativeNodeFunction("-", "word", false)));
annotationPatterns.put("-splitPUNC", new Pair<>(tregexPatternCompiler.compile("@PUNC < __=" + AnnotatePunctuationFunction2.key), new AnnotatePunctuationFunction2()));
annotationPatterns.put("-markMasdarVP", new Pair<>(tregexPatternCompiler.compile("@VP|MWVP < /VBG|VN/"), new SimpleStringFunction("-masdar")));
annotationPatterns.put("-containsSVO", new Pair<>(tregexPatternCompiler.compile("__ << (@S < (@NP . @VP|MWVP))"), new SimpleStringFunction("-hasSVO")));
annotationPatterns.put("-splitCC", new Pair<>(tregexPatternCompiler.compile("@CC|CONJ . __=term , __"), new AddEquivalencedConjNode("-", "term")));
annotationPatterns.put("-markFem", new Pair<>(tregexPatternCompiler.compile("__ < /ة$/"), new SimpleStringFunction("-fem")));
// Added for MWE experiments
annotationPatterns.put("-mwe", new Pair<>(tregexPatternCompiler.compile("__ > /MW/=tag"), new AddRelativeNodeFunction("-", "tag", true)));
annotationPatterns.put("-mweContainsVerb", new Pair<>(tregexPatternCompiler.compile("__ << @MWVP"), new SimpleStringFunction("-withV")));
//This version, which uses the PTB equivalence classing, results in slightly lower labeled F1
//than the splitPUNC feature above, which was included in the COLING2010 evaluation
annotationPatterns.put("-splitPUNC2", new Pair<>(tregexPatternCompiler.compile("@PUNC < __=punc"), new AnnotatePunctuationFunction("-", "punc")));
// Label each POS with its parent
annotationPatterns.put("-tagPAar", new Pair<>(tregexPatternCompiler.compile("!@PUNC < (__ !< __) > __=parent"), new AddRelativeNodeFunction("-", "parent", true)));
//Didn't work
annotationPatterns.put("-splitCC1", new Pair<>(tregexPatternCompiler.compile("@CC|CONJ < __=term"), new AddRelativeNodeRegexFunction("-", "term", "-*([^-].*)")));
annotationPatterns.put("-splitCC2", new Pair<>(tregexPatternCompiler.compile("@CC . __=term , __"), new AddRelativeNodeFunction("-", "term", true)));
annotationPatterns.put("-idafaJJ1", new Pair<>(tregexPatternCompiler.compile("@NP <, (@NN $+ @NP) <+(@NP) @ADJP"), new SimpleStringFunction("-idafaJJ")));
annotationPatterns.put("-idafaJJ2", new Pair<>(tregexPatternCompiler.compile("@NP <, (@NN $+ @NP) <+(@NP) @ADJP !<< @SBAR"), new SimpleStringFunction("-idafaJJ")));
annotationPatterns.put("-properBaseNP", new Pair<>(tregexPatternCompiler.compile("@NP !<< @NP < /NNP/ !< @PUNC|CD"), new SimpleStringFunction("-prop")));
annotationPatterns.put("-interrog", new Pair<>(tregexPatternCompiler.compile("__ << هل|ماذا|لماذا|اين|متى"), new SimpleStringFunction("-inter")));
annotationPatterns.put("-splitPseudo", new Pair<>(tregexPatternCompiler.compile("@NN < مع|بعد|بين"), new SimpleStringFunction("-pseudo")));
annotationPatterns.put("-nPseudo", new Pair<>(tregexPatternCompiler.compile("@NP < (@NN < مع|بعد|بين)"), new SimpleStringFunction("-npseudo")));
annotationPatterns.put("-pseudoArg", new Pair<>(tregexPatternCompiler.compile("@NP < @NP $, (@NN < مع|بعد|بين)"), new SimpleStringFunction("-pseudoArg")));
annotationPatterns.put("-eqL1", new Pair<>(tregexPatternCompiler.compile("__ < (@S !< @VP|S)"), new SimpleStringFunction("-haseq")));
annotationPatterns.put("-eqL1L2", new Pair<>(tregexPatternCompiler.compile("__ < (__ < (@S !< @VP|S)) | < (@S !< @VP|S)"), new SimpleStringFunction("-haseq")));
annotationPatterns.put("-fullQuote", new Pair<>(tregexPatternCompiler.compile("__ < ((@PUNC < \") $ (@PUNC < \"))"), new SimpleStringFunction("-fq")));
annotationPatterns.put("-brokeQuote", new Pair<>(tregexPatternCompiler.compile("__ < ((@PUNC < \") !$ (@PUNC < \"))"), new SimpleStringFunction("-bq")));
annotationPatterns.put("-splitVP", new Pair<>(tregexPatternCompiler.compile("@VP <# __=term1"), new AddRelativeNodeFunction("-", "term1", true)));
annotationPatterns.put("-markFemP", new Pair<>(tregexPatternCompiler.compile("@NP|ADJP < (__ < /ة$/)"), new SimpleStringFunction("-femP")));
annotationPatterns.put("-embedSBAR", new Pair<>(tregexPatternCompiler.compile("@NP|PP <+(@NP|PP) @SBAR"), new SimpleStringFunction("-embedSBAR")));
annotationPatterns.put("-complexVP", new Pair<>(tregexPatternCompiler.compile("__ << (@VP < (@NP $ @NP)) > __"), new SimpleStringFunction("-complexVP")));
annotationPatterns.put("-containsJJ", new Pair<>(tregexPatternCompiler.compile("@NP <+(@NP) /JJ/"), new SimpleStringFunction("-hasJJ")));
annotationPatterns.put("-markMasdarVP2", new Pair<>(tregexPatternCompiler.compile("__ << @VN|VBG"), new SimpleStringFunction("-masdar")));
annotationPatterns.put("-coordNP", new Pair<>(tregexPatternCompiler.compile("@NP|ADJP <+(@NP|ADJP) (@CC|PUNC $- __ $+ __)"), new SimpleStringFunction("-coordNP")));
annotationPatterns.put("-coordWa", new Pair<>(tregexPatternCompiler.compile("__ << (@CC , __ < و-)"), new SimpleStringFunction("-coordWA")));
annotationPatterns.put("-NPhasADJP", new Pair<>(tregexPatternCompiler.compile("@NP <+(@NP) @ADJP"), new SimpleStringFunction("-NPhasADJP")));
annotationPatterns.put("-NPADJP", new Pair<>(tregexPatternCompiler.compile("@NP < @ADJP"), new SimpleStringFunction("-npadj")));
annotationPatterns.put("-NPJJ", new Pair<>(tregexPatternCompiler.compile("@NP < /JJ/"), new SimpleStringFunction("-npjj")));
annotationPatterns.put("-NPCC", new Pair<>(tregexPatternCompiler.compile("@NP <+(@NP) @CC"), new SimpleStringFunction("-npcc")));
annotationPatterns.put("-NPCD", new Pair<>(tregexPatternCompiler.compile("@NP < @CD"), new SimpleStringFunction("-npcd")));
annotationPatterns.put("-NPNNP", new Pair<>(tregexPatternCompiler.compile("@NP < /NNP/"), new SimpleStringFunction("-npnnp")));
annotationPatterns.put("-SVO", new Pair<>(tregexPatternCompiler.compile("@S < (@NP . @VP)"), new SimpleStringFunction("-svo")));
annotationPatterns.put("-containsSBAR", new Pair<>(tregexPatternCompiler.compile("__ << @SBAR"), new SimpleStringFunction("-hasSBAR")));
//WSGDEBUG - Template
//annotationPatterns.put("", new Pair<TregexPattern,Function<TregexMatcher,String>>(tregexPatternCompiler.compile(""), new SimpleStringFunction("")));
// ************
// Old and unused features (in various states of repair)
// *************
annotationPatterns.put("-markGappedVP", new Pair<>(TregexPattern.compile("@VP > @VP $- __ $ /^(?:CC|CONJ)/ !< /^V/"), new SimpleStringFunction("-gappedVP")));
annotationPatterns.put("-markGappedVPConjoiners", new Pair<>(TregexPattern.compile("/^(?:CC|CONJ)/ $ (@VP > @VP $- __ !< /^V/)"), new SimpleStringFunction("-gappedVP")));
annotationPatterns.put("-markGenitiveParent", new Pair<>(TregexPattern.compile("@NP < (" + genitiveNodeTregexString + ')'), new SimpleStringFunction("-genitiveParent")));
// maSdr: this pattern is just a heuristic classification, which matches on
// various common maSdr pattterns, but probably also matches on a lot of other
// stuff. It marks NPs with possible maSdr.
// Roger's old pattern:
annotationPatterns.put("-maSdrMark", new Pair<>(tregexPatternCompiler.compile("/^N/ <<# (/^[t\\u062a].+[y\\u064a].$/ > @NN|NOUN|DTNN)"), new SimpleStringFunction("-maSdr")));
// chris' attempt
annotationPatterns.put("-maSdrMark2", new Pair<>(tregexPatternCompiler.compile("/^N/ <<# (/^(?:[t\\u062a].+[y\\u064a].|<.{3,}|A.{3,})$/ > @NN|NOUN|DTNN)"), new SimpleStringFunction("-maSdr")));
annotationPatterns.put("-maSdrMark3", new Pair<>(tregexPatternCompiler.compile("/^N/ <<# (/^(?:[t\\u062a<A].{3,})$/ > @NN|NOUN|DTNN)"), new SimpleStringFunction("-maSdr")));
annotationPatterns.put("-maSdrMark4", new Pair<>(tregexPatternCompiler.compile("/^N/ <<# (/^(?:[t\\u062a<A].{3,})$/ > (@NN|NOUN|DTNN > (@NP < @NP)))"), new SimpleStringFunction("-maSdr")));
annotationPatterns.put("-maSdrMark5", new Pair<>(tregexPatternCompiler.compile("/^N/ <<# (__ > (@NN|NOUN|DTNN > (@NP < @NP)))"), new SimpleStringFunction("-maSdr")));
annotationPatterns.put("-mjjMark", new Pair<>(tregexPatternCompiler.compile("@JJ|DTJJ < /^m/ $+ @PP ># @ADJP "), new SimpleStringFunction("-mjj")));
//annotationPatterns.put(markPRDverbString,new Pair<TregexPattern,Function<TregexMatcher,String>>(TregexPattern.compile("/^V[^P]/ > VP $ /-PRD$/"),new SimpleStringFunction("-PRDverb"))); // don't need this pattern anymore, the functionality has been moved to ArabicTreeNormalizer
// PUNC is PUNC in either raw or Bies POS encoding
annotationPatterns.put("-markNPwithSdescendant", new Pair<>(tregexPatternCompiler.compile("__ !< @S << @S [ >> @NP | == @NP ]"), new SimpleStringFunction("-inNPdominatesS")));
annotationPatterns.put("-markRightRecursiveNP", new Pair<>(tregexPatternCompiler.compile("__ <<- @NP [>>- @NP | == @NP]"), new SimpleStringFunction("-rrNP")));
annotationPatterns.put("-markBaseNP", new Pair<>(tregexPatternCompiler.compile("@NP !< @NP !< @VP !< @SBAR !< @ADJP !< @ADVP !< @S !< @QP !< @UCP !< @PP"), new SimpleStringFunction("-base")));
// allow only a single level of idafa as Base NP; this version works!
annotationPatterns.put("-markBaseNPplusIdafa", new Pair<>(tregexPatternCompiler.compile("@NP !< (/^[^N]/ < (__ < __)) !< (__ < (__ < (__ < __)))"), new SimpleStringFunction("-base")));
annotationPatterns.put("-markTwoLevelIdafa", new Pair<>(tregexPatternCompiler.compile("@NP < (@NP < (@NP < (__ < __)) !< (/^[^N]/ < (__ < __))) !< (/^[^N]/ < (__ < __)) !< (__ < (__ < (__ < (__ < __))))"), new SimpleStringFunction("-idafa2")));
annotationPatterns.put("-markDefiniteIdafa", new Pair<>(tregexPatternCompiler.compile("@NP < (/^(?:NN|NOUN)/ !$,, /^[^AP]/) <+(/^NP/) (@NP < /^DT/)"), new SimpleStringFunction("-defIdafa")));
annotationPatterns.put("-markDefiniteIdafa1", new Pair<>(tregexPatternCompiler.compile("@NP < (/^(?:NN|NOUN)/ !$,, /^[^AP]/) < (@NP < /^DT/) !< (/^[^N]/ < (__ < __)) !< (__ < (__ < (__ < __)))"), new SimpleStringFunction("-defIdafa1")));
annotationPatterns.put("-markContainsSBAR", new Pair<>(tregexPatternCompiler.compile("__ << @SBAR"), new SimpleStringFunction("-withSBAR")));
annotationPatterns.put("-markPhrasalNodesDominatedBySBAR", new Pair<>(tregexPatternCompiler.compile("__ < (__ < __) >> @SBAR"), new SimpleStringFunction("-domBySBAR")));
annotationPatterns.put("-markCoordinateNPs", new Pair<>(tregexPatternCompiler.compile("@NP < @CC|CONJ"), new SimpleStringFunction("-coord")));
//annotationPatterns.put("-markCopularVerbTags",new Pair<TregexPattern,Function<TregexMatcher,String>>(tregexPatternCompiler.compile("/^V/ < " + copularVerbForms),new SimpleStringFunction("-copular")));
//annotationPatterns.put("-markSBARVerbTags",new Pair<TregexPattern,Function<TregexMatcher,String>>(tregexPatternCompiler.compile("/^V/ < " + sbarVerbForms),new SimpleStringFunction("-SBARverb")));
annotationPatterns.put("-markNounAdjVPheads", new Pair<>(tregexPatternCompiler.compile("@NN|NNS|NNP|NNPS|JJ|DTJJ|DTNN|DTNNS|DTNNP|DTNNPS ># @VP"), new SimpleStringFunction("-VHead")));
// a better version of the below might only mark clitic pronouns, but
// since most pronouns are clitics, let's try this first....
annotationPatterns.put("-markPronominalNP", new Pair<>(tregexPatternCompiler.compile("@NP < @PRP"), new SimpleStringFunction("-PRP")));
// try doing coordination parallelism -- there's a lot of that in Arabic (usually the same, sometimes different CC)
annotationPatterns.put("-markMultiCC", new Pair<>(tregexPatternCompiler.compile("__ < (@CC $.. @CC)"), new SimpleStringFunction("-multiCC"))); // this unfortunately didn't seem helpful for capturing CC parallelism; should try again
annotationPatterns.put("-markHasCCdaughter", new Pair<>(tregexPatternCompiler.compile("__ < @CC"), new SimpleStringFunction("-CCdtr")));
annotationPatterns.put("-markAcronymNP", new Pair<>(tregexPatternCompiler.compile("@NP !< (__ < (__ < __)) < (/^NN/ < /^.$/ $ (/^NN/ < /^.$/)) !< (__ < /../)"), new SimpleStringFunction("-acro")));
annotationPatterns.put("-markAcronymNN", new Pair<>(tregexPatternCompiler.compile("/^NN/ < /^.$/ $ (/^NN/ < /^.$/) > (@NP !< (__ < (__ < __)) !< (__ < /../))"), new SimpleStringFunction("-acro")));
//PP Specific patterns
annotationPatterns.put("-markPPwithPPdescendant", new Pair<>(tregexPatternCompiler.compile("__ !< @PP << @PP [ >> @PP | == @PP ]"), new SimpleStringFunction("-inPPdominatesPP")));
annotationPatterns.put("-gpAnnotatePrepositions", new Pair<>(TregexPattern.compile("/^(?:IN|PREP)$/ > (__ > __=gp)"), new AddRelativeNodeFunction("^^", "gp", false)));
annotationPatterns.put("-gpEquivalencePrepositions", new Pair<>(TregexPattern.compile("/^(?:IN|PREP)$/ > (@PP >+(/^PP/) __=gp)"), new AddEquivalencedNodeFunction("^^", "gp")));
annotationPatterns.put("-gpEquivalencePrepositionsVar", new Pair<>(TregexPattern.compile("/^(?:IN|PREP)$/ > (@PP >+(/^PP/) __=gp)"), new AddEquivalencedNodeFunctionVar("^^", "gp")));
annotationPatterns.put("-markPPParent", new Pair<>(tregexPatternCompiler.compile("@PP=max !< @PP"), new AddRelativeNodeRegexFunction("^^", "max", "^(\\w)")));
annotationPatterns.put("-whPP", new Pair<>(tregexPatternCompiler.compile("@PP <- (@SBAR <, /^WH/)"), new SimpleStringFunction("-whPP")));
// annotationPatterns.put("-markTmpPP", new Pair<TregexPattern,Function<TregexMatcher,String>>(tregexPatternCompiler.compile("@PP !<+(__) @PP"),new LexicalCategoryFunction("-TMP",temporalNouns)));
annotationPatterns.put("-deflateMin", new Pair<>(tregexPatternCompiler.compile("__ < (__ < من)"), new SimpleStringFunction("-min")));
annotationPatterns.put("-v2MarkovIN", new Pair<>(tregexPatternCompiler.compile("@IN > (@__=p1 > @__=p2)"), new AddRelativeNodeFunction("^", "p1", "p2", false)));
annotationPatterns.put("-pleonasticMin", new Pair<>(tregexPatternCompiler.compile("@PP <, (IN < من) > @S"), new SimpleStringFunction("-pleo")));
annotationPatterns.put("-v2MarkovPP", new Pair<>(tregexPatternCompiler.compile("@PP > (@__=p1 > @__=p2)"), new AddRelativeNodeFunction("^", "p1", "p2", false)));
} catch (TregexParseException e) {
int nth = annotationPatterns.size() + 1;
String nthStr = (nth == 1) ? "1st": ((nth == 2) ? "2nd": nth + "th");
log.info("Parse exception on " + nthStr + " annotation pattern initialization:" + e);
throw e;
}
}
private static class SimpleStringFunction implements SerializableFunction<TregexMatcher,String> {
public SimpleStringFunction(String result) {
this.result = result;
}
private String result;
public String apply(TregexMatcher tregexMatcher) {
return result;
}
@Override
public String toString() { return "SimpleStringFunction[" + result + ']'; }
private static final long serialVersionUID = 1L;
}
private static class AddRelativeNodeFunction implements SerializableFunction<TregexMatcher,String> {
private String annotationMark;
private String key;
private String key2;
private boolean doBasicCat = false;
private static final TreebankLanguagePack tlp = new ArabicTreebankLanguagePack();
public AddRelativeNodeFunction(String annotationMark, String key, boolean basicCategory) {
this.annotationMark = annotationMark;
this.key = key;
this.key2 = null;
doBasicCat = basicCategory;
}
public AddRelativeNodeFunction(String annotationMark, String key1, String key2, boolean basicCategory) {
this(annotationMark,key1,basicCategory);
this.key2 = key2;
}
public String apply(TregexMatcher m) {
if(key2 == null)
return annotationMark + ((doBasicCat) ? tlp.basicCategory(m.getNode(key).label().value()) : m.getNode(key).label().value());
else {
String annot1 = (doBasicCat) ? tlp.basicCategory(m.getNode(key).label().value()) : m.getNode(key).label().value();
String annot2 = (doBasicCat) ? tlp.basicCategory(m.getNode(key2).label().value()) : m.getNode(key2).label().value();
return annotationMark + annot1 + annotationMark + annot2;
}
}
@Override
public String toString() {
if(key2 == null)
return "AddRelativeNodeFunction[" + annotationMark + ',' + key + ']';
else
return "AddRelativeNodeFunction[" + annotationMark + ',' + key + ',' + key2 + ']';
}
private static final long serialVersionUID = 1L;
}
private static class AddRelativeNodeRegexFunction implements SerializableFunction<TregexMatcher,String> {
private String annotationMark;
private String key;
private Pattern pattern;
private String key2 = null;
private Pattern pattern2;
public AddRelativeNodeRegexFunction(String annotationMark, String key, String regex) {
this.annotationMark = annotationMark;
this.key = key;
try {
this.pattern = Pattern.compile(regex);
} catch (PatternSyntaxException pse) {
log.info("Bad pattern: " + regex);
pattern = null;
throw new IllegalArgumentException(pse);
}
}
public String apply(TregexMatcher m) {
String val = m.getNode(key).label().value();
if (pattern != null) {
Matcher mat = pattern.matcher(val);
if (mat.find()) {
val = mat.group(1);
}
}
if(key2 != null && pattern2 != null) {
String val2 = m.getNode(key2).label().value();
Matcher mat2 = pattern2.matcher(val2);
if(mat2.find()) {
val = val + annotationMark + mat2.group(1);
} else {
val = val + annotationMark + val2;
}
}
return annotationMark + val;
}
@Override
public String toString() { return "AddRelativeNodeRegexFunction[" + annotationMark + ',' + key + ',' + pattern + ']'; }
private static final long serialVersionUID = 1L;
}
/** This one only distinguishes VP, S and Other (mainly nominal) contexts.
* These seem the crucial distinctions for Arabic true prepositions,
* based on raw counts in data.
*/
private static class AddEquivalencedNodeFunction implements SerializableFunction<TregexMatcher,String> {
private String annotationMark;
private String key;
public AddEquivalencedNodeFunction(String annotationMark, String key) {
this.annotationMark = annotationMark;
this.key = key;
}
public String apply(TregexMatcher m) {
String node = m.getNode(key).label().value();
if (node.startsWith("S")) {
return annotationMark + 'S';
} else if (node.startsWith("V")) {
return annotationMark + 'V';
} else {
return "";
}
}
@Override
public String toString() { return "AddEquivalencedNodeFunction[" + annotationMark + ',' + key + ']'; }
private static final long serialVersionUID = 1L;
}
/** This one only distinguishes VP, S*, A* versus other (mainly nominal) contexts. */
private static class AddEquivalencedNodeFunctionVar implements SerializableFunction<TregexMatcher,String> {
private String annotationMark;
private String key;
public AddEquivalencedNodeFunctionVar(String annotationMark, String key) {
this.annotationMark = annotationMark;
this.key = key;
}
public String apply(TregexMatcher m) {
String node = m.getNode(key).label().value();
// We also tried if (node.startsWith("V")) [var2] and if (node.startsWith("V") || node.startsWith("S")) [var3]. Both seemed markedly worse than the basic function or this var form (which seems a bit better than the basic equiv option).
if (node.startsWith("S") || node.startsWith("V") || node.startsWith("A")) {
return annotationMark + "VSA";
} else {
return "";
}
}
@Override
public String toString() { return "AddEquivalencedNodeFunctionVar[" + annotationMark + ',' + key + ']'; }
private static final long serialVersionUID = 1L;
}
private static class AnnotatePunctuationFunction2 implements SerializableFunction<TregexMatcher,String> {
static final String key = "term";
private static final Pattern quote = Pattern.compile("^\"$");
public String apply(TregexMatcher m) {
final String punc = m.getNode(key).value();
if (punc.equals("."))
return "-fs";
else if (punc.equals("?"))
return "-quest";
else if (punc.equals(","))
return "-comma";
else if (punc.equals(":") || punc.equals(";"))
return "-colon";
else if (punc.equals("-LRB-"))
return "-lrb";
else if (punc.equals("-RRB-"))
return "-rrb";
else if (punc.equals("-PLUS-"))
return "-plus";
else if (punc.equals("-"))
return "-dash";
else if (quote.matcher(punc).matches())
return "-quote";
// else if(punc.equals("/"))
// return "-slash";
// else if(punc.equals("%"))
// return "-perc";
// else if(punc.contains(".."))
// return "-ellipses";
return "";
}
@Override
public String toString() { return "AnnotatePunctuationFunction2"; }
private static final long serialVersionUID = 1L;
}
private static class AddEquivalencedConjNode implements SerializableFunction<TregexMatcher,String> {
private String annotationMark;
private String key;
private static final String nnTags = "DTNN DTNNP DTNNPS DTNNS NN NNP NNS NNPS";
private static final Set<String> nnTagClass = Collections.unmodifiableSet(Generics.newHashSet(Arrays.asList(nnTags.split("\\s+"))));
private static final String jjTags = "ADJ_NUM DTJJ DTJJR JJ JJR";
private static final Set<String> jjTagClass = Collections.unmodifiableSet(Generics.newHashSet(Arrays.asList(jjTags.split("\\s+"))));
private static final String vbTags = "VBD VBP";
private static final Set<String> vbTagClass = Collections.unmodifiableSet(Generics.newHashSet(Arrays.asList(vbTags.split("\\s+"))));
private static final TreebankLanguagePack tlp = new ArabicTreebankLanguagePack();
public AddEquivalencedConjNode(String annotationMark, String key) {
this.annotationMark = annotationMark;
this.key = key;
}
public String apply(TregexMatcher m) {
String node = m.getNode(key).value();
String eqClass = tlp.basicCategory(node);
if(nnTagClass.contains(eqClass))
eqClass = "noun";
else if(jjTagClass.contains(eqClass))
eqClass = "adj";
else if(vbTagClass.contains(eqClass))
eqClass = "vb";
return annotationMark + eqClass;
}
@Override
public String toString() { return "AddEquivalencedConjNode[" + annotationMark + ',' + key + ']'; }
private static final long serialVersionUID = 1L;
}
/**
* Reconfigures active features after a change in the default headfinder.
*
* @param hf
*/
private void setHeadFinder(HeadFinder hf) {
if(hf == null)
throw new IllegalArgumentException();
headFinder = hf;
// Need to re-initialize all patterns due to the new headFinder
initializeAnnotationPatterns();
activeAnnotations.clear();
for(String key : baselineFeatures) {
Pair<TregexPattern,Function<TregexMatcher,String>> p = annotationPatterns.get(key);
activeAnnotations.add(p);
}
for(String key : additionalFeatures) {
Pair<TregexPattern,Function<TregexMatcher,String>> p = annotationPatterns.get(key);
activeAnnotations.add(p);
}
}
/**
* Configures morpho-syntactic annotations for POS tags.
*
* @param activeFeats A comma-separated list of feature values with names according
* to MorphoFeatureType.
*
*/
private String setupMorphoFeatures(String activeFeats) {
String[] feats = activeFeats.split(",");
morphoSpec = tlp.morphFeatureSpec();
for(String feat : feats) {
MorphoFeatureType fType = MorphoFeatureType.valueOf(feat.trim());
morphoSpec.activate(fType);
}
return morphoSpec.toString();
}
private void removeBaselineFeature(String featName) {
if(baselineFeatures.contains(featName)) {
baselineFeatures.remove(featName);
Pair<TregexPattern,Function<TregexMatcher,String>> p = annotationPatterns.get(featName);
activeAnnotations.remove(p);
}
}
@Override
public void display() {
log.info(optionsString.toString());
}
/** Some options for setOptionFlag:
*
* <p>
* <code>-retainNPTmp</code> Retain temporal NP marking on NPs.
* <code>-retainNPSbj</code> Retain NP subject function tags
* <code>-markGappedVP</code> marked gapped VPs.
* <code>-collinizerRetainsPunctuation</code> does what it says.
* </p>
*
* @param args flag arguments (usually from commmand line
* @param i index at which to begin argument processing
* @return Index in args array after the last processed index for option
*/
@Override
public int setOptionFlag(String[] args, int i) {
//log.info("Setting option flag: " + args[i]);
//lang. specific options
boolean didSomething = false;
if (annotationPatterns.keySet().contains(args[i])) {
if(!baselineFeatures.contains(args[i])) additionalFeatures.add(args[i]);
Pair<TregexPattern,Function<TregexMatcher,String>> p = annotationPatterns.get(args[i]);
activeAnnotations.add(p);
optionsString.append("Option " + args[i] + " added annotation pattern " + p.first() + " with annotation " + p.second() + '\n');
didSomething = true;
} else if (args[i].equals("-retainNPTmp")) {
optionsString.append("Retaining NP-TMP marking.\n");
retainNPTmp = true;
didSomething = true;
} else if (args[i].equals("-retainNPSbj")) {
optionsString.append("Retaining NP-SBJ dash tag.\n");
retainNPSbj = true;
didSomething = true;
} else if (args[i].equals("-retainPPClr")) {
optionsString.append("Retaining PP-CLR dash tag.\n");
retainPPClr = true;
didSomething = true;
} else if (args[i].equals("-discardX")) {
optionsString.append("Discarding X trees.\n");
discardX = true;
didSomething = true;
} else if (args[i].equals("-changeNoLabels")) {
optionsString.append("Change no labels.\n");
changeNoLabels = true;
didSomething = true;
} else if (args[i].equals("-markPRDverbs")) {
optionsString.append("Mark PRD.\n");
retainPRD = true;
didSomething = true;
} else if (args[i].equals("-collinizerRetainsPunctuation")) {
optionsString.append("Collinizer retains punctuation.\n");
collinizerRetainsPunctuation = true;
didSomething = true;
} else if (args[i].equals("-arabicFactored")) {
for(String annotation : baselineFeatures) {
String[] a = {annotation};
setOptionFlag(a,0);
}
didSomething = true;
} else if (args[i].equalsIgnoreCase("-headFinder") && (i + 1 < args.length)) {
try {
HeadFinder hf = (HeadFinder) Class.forName(args[i + 1]).newInstance();
setHeadFinder(hf);
optionsString.append("HeadFinder: " + args[i + 1] + "\n");
} catch (Exception e) {
log.info(e);
log.info(this.getClass().getName() +
": Could not load head finder " + args[i + 1]);
}
i++;
didSomething = true;
} else if(args[i].equals("-factlex") && (i + 1 < args.length)) {
String activeFeats = setupMorphoFeatures(args[++i]);
optionsString.append("Factored Lexicon: active features: ").append(activeFeats);
//
// removeBaselineFeature("-markFem");
// optionsString.append(" (removed -markFem)\n");
didSomething = true;
} else if(args[i].equals("-noFeatures")) {
activeAnnotations.clear();
optionsString.append("Removed all manual features.\n");
didSomething = true;
}
//wsg2010: The segmenter does not work, but keep this to remember how it was instantiated.
// else if (args[i].equals("-arabicTokenizerModel")) {
// String modelFile = args[i+1];
// try {
// WordSegmenter aSeg = (WordSegmenter) Class.forName("edu.stanford.nlp.wordseg.ArabicSegmenter").newInstance();
// aSeg.loadSegmenter(modelFile);
// System.out.println("aSeg=" + aSeg);
// TokenizerFactory<Word> aTF = WordSegmentingTokenizer.factory(aSeg);
// ((ArabicTreebankLanguagePack) treebankLanguagePack()).setTokenizerFactory(aTF);
// } catch (RuntimeIOException ex) {
// log.info("Couldn't load ArabicSegmenter " + modelFile);
// ex.printStackTrace();
// } catch (Exception e) {
// log.info("Couldn't instantiate segmenter: edu.stanford.nlp.wordseg.ArabicSegmenter");
// e.printStackTrace();
// }
// i++; // 2 args
// didSomething = true;
// }
if (didSomething) i++;
return i;
}
/**
*
* @param args
*/
public static void main(String[] args) {
if(args.length != 1) {
System.exit(-1);
}
ArabicTreebankParserParams tlpp = new ArabicTreebankParserParams();
String[] options = {"-arabicFactored"};
tlpp.setOptionFlag(options, 0);
DiskTreebank tb = tlpp.diskTreebank();
tb.loadPath(args[0], "txt", false);
for(Tree t : tb) {
for(Tree subtree : t) {
tlpp.transformTree(subtree, t);
}
System.out.println(t.toString());
}
}
}
| gpl-2.0 |
rupenp/CoreNLP | src/edu/stanford/nlp/ie/crf/CRFLogConditionalObjectiveFloatFunction.java | 19880 | package edu.stanford.nlp.ie.crf;
import edu.stanford.nlp.util.logging.Redwood;
import edu.stanford.nlp.math.ArrayMath;
import edu.stanford.nlp.optimization.AbstractCachingDiffFloatFunction;
import edu.stanford.nlp.util.Index;
import java.util.Arrays;
import java.util.List;
/**
* @author Jenny Finkel
*/
public class CRFLogConditionalObjectiveFloatFunction extends AbstractCachingDiffFloatFunction implements HasCliquePotentialFunction {
/** A logger for this class */
private static Redwood.RedwoodChannels log = Redwood.channels(CRFLogConditionalObjectiveFloatFunction.class);
public static final int NO_PRIOR = 0;
public static final int QUADRATIC_PRIOR = 1;
/* Use a Huber robust regression penalty (L1 except very near 0) not L2 */
public static final int HUBER_PRIOR = 2;
public static final int QUARTIC_PRIOR = 3;
protected int prior;
protected float sigma;
protected float epsilon;
List<Index<CRFLabel>> labelIndices;
Index<String> classIndex;
float[][] Ehat; // empirical counts of all the features [feature][class]
int window;
int numClasses;
int[] map;
int[][][][] data;
int[][] labels;
int domainDimension = -1;
String backgroundSymbol;
public static boolean VERBOSE = false;
CRFLogConditionalObjectiveFloatFunction(int[][][][] data, int[][] labels, int window, Index<String> classIndex, List<Index<CRFLabel>> labelIndices, int[] map, String backgroundSymbol) {
this(data, labels, window, classIndex, labelIndices, map, QUADRATIC_PRIOR, backgroundSymbol);
}
CRFLogConditionalObjectiveFloatFunction(int[][][][] data, int[][] labels, int window, Index<String> classIndex, List<Index<CRFLabel>> labelIndices, int[] map, String backgroundSymbol, double sigma) {
this(data, labels, window, classIndex, labelIndices, map, QUADRATIC_PRIOR, backgroundSymbol, sigma);
}
CRFLogConditionalObjectiveFloatFunction(int[][][][] data, int[][] labels, int window, Index<String> classIndex, List<Index<CRFLabel>> labelIndices, int[] map, int prior, String backgroundSymbol) {
this(data, labels, window, classIndex, labelIndices, map, prior, backgroundSymbol, 1.0f);
}
CRFLogConditionalObjectiveFloatFunction(int[][][][] data, int[][] labels, int window, Index<String> classIndex, List<Index<CRFLabel>> labelIndices, int[] map, int prior, String backgroundSymbol, double sigma) {
this.window = window;
this.classIndex = classIndex;
this.numClasses = classIndex.size();
this.labelIndices = labelIndices;
this.map = map;
this.data = data;
this.labels = labels;
this.prior = prior;
this.backgroundSymbol = backgroundSymbol;
this.sigma = (float) sigma;
empiricalCounts(data, labels);
}
@Override
public int domainDimension() {
if (domainDimension < 0) {
domainDimension = 0;
for (int aMap : map) {
domainDimension += labelIndices.get(aMap).size();
}
}
return domainDimension;
}
@Override
public CliquePotentialFunction getCliquePotentialFunction(double[] x) {
throw new UnsupportedOperationException("CRFLogConditionalObjectiveFloatFunction is not clique potential compatible yet");
}
public float[][] to2D(float[] weights) {
float[][] newWeights = new float[map.length][];
int index = 0;
for (int i = 0; i < map.length; i++) {
newWeights[i] = new float[labelIndices.get(map[i]).size()];
System.arraycopy(weights, index, newWeights[i], 0, labelIndices.get(map[i]).size());
index += labelIndices.get(map[i]).size();
}
return newWeights;
}
public float[] to1D(float[][] weights) {
float[] newWeights = new float[domainDimension()];
int index = 0;
for (float[] weight : weights) {
System.arraycopy(weight, 0, newWeights, index, weight.length);
index += weight.length;
}
return newWeights;
}
public float[][] empty2D() {
float[][] d = new float[map.length][];
// int index = 0;
for (int i = 0; i < map.length; i++) {
d[i] = new float[labelIndices.get(map[i]).size()];
// Arrays.fill(d[i], 0); // not needed; Java arrays zero initialized
// index += labelIndices.get(map[i]).size();
}
return d;
}
private void empiricalCounts(int[][][][] data, int[][] labels) {
Ehat = empty2D();
for (int m = 0; m < data.length; m++) {
int[][][] dataDoc = data[m];
int[] labelsDoc = labels[m];
int[] label = new int[window];
//Arrays.fill(label, classIndex.indexOf("O"));
Arrays.fill(label, classIndex.indexOf(backgroundSymbol));
for (int i = 0; i < dataDoc.length; i++) {
System.arraycopy(label, 1, label, 0, window - 1);
label[window - 1] = labelsDoc[i];
for (int j = 0; j < dataDoc[i].length; j++) {
int[] cliqueLabel = new int[j + 1];
System.arraycopy(label, window - 1 - j, cliqueLabel, 0, j + 1);
CRFLabel crfLabel = new CRFLabel(cliqueLabel);
int labelIndex = labelIndices.get(j).indexOf(crfLabel);
//log.info(crfLabel + " " + labelIndex);
for (int k = 0; k < dataDoc[i][j].length; k++) {
Ehat[dataDoc[i][j][k]][labelIndex]++;
}
}
}
}
}
public static FloatFactorTable getFloatFactorTable(float[][] weights, int[][] data, List<Index<CRFLabel>> labelIndices, int numClasses) {
FloatFactorTable factorTable = null;
for (int j = 0; j < labelIndices.size(); j++) {
Index<CRFLabel> labelIndex = labelIndices.get(j);
FloatFactorTable ft = new FloatFactorTable(numClasses, j + 1);
// ...and each possible labeling for that clique
for (int k = 0; k < labelIndex.size(); k++) {
int[] label = labelIndex.get(k).getLabel();
float weight = 0.0f;
for (int m = 0; m < data[j].length; m++) {
//log.info("**"+weights[data[j][m]][k]);
weight += weights[data[j][m]][k];
}
ft.setValue(label, weight);
//log.info(">>"+ft);
}
//log.info("::"+ft);
if (j > 0) {
ft.multiplyInEnd(factorTable);
}
//log.info("::"+ft);
factorTable = ft;
}
return factorTable;
}
public static FloatFactorTable[] getCalibratedCliqueTree(float[][] weights, int[][][] data, List<Index<CRFLabel>> labelIndices, int numClasses) {
// for (int i = 0; i < weights.length; i++) {
// for (int j = 0; j < weights[i].length; j++) {
// log.info(i+" "+j+": "+weights[i][j]);
// }
// }
//log.info("calibrating clique tree");
FloatFactorTable[] factorTables = new FloatFactorTable[data.length];
FloatFactorTable[] messages = new FloatFactorTable[data.length - 1];
for (int i = 0; i < data.length; i++) {
factorTables[i] = getFloatFactorTable(weights, data[i], labelIndices, numClasses);
if (VERBOSE) {
log.info(i + ": " + factorTables[i]);
}
if (i > 0) {
messages[i - 1] = factorTables[i - 1].sumOutFront();
if (VERBOSE) {
log.info(messages[i - 1]);
}
factorTables[i].multiplyInFront(messages[i - 1]);
if (VERBOSE) {
log.info(factorTables[i]);
if (i == data.length - 1) {
log.info(i + ": " + factorTables[i].toProbString());
}
}
}
}
for (int i = factorTables.length - 2; i >= 0; i--) {
FloatFactorTable summedOut = factorTables[i + 1].sumOutEnd();
if (VERBOSE) {
log.info((i + 1) + "-->" + i + ": " + summedOut);
}
summedOut.divideBy(messages[i]);
if (VERBOSE) {
log.info((i + 1) + "-->" + i + ": " + summedOut);
}
factorTables[i].multiplyInEnd(summedOut);
if (VERBOSE) {
log.info(i + ": " + factorTables[i]);
log.info(i + ": " + factorTables[i].toProbString());
}
}
return factorTables;
}
@Override
public void calculate(float[] x) {
// if (crfType.equalsIgnoreCase("weird")) {
// calculateWeird(x);
// return;
// }
float[][] weights = to2D(x);
float prob = 0;
float[][] E = empty2D();
for (int m = 0; m < data.length; m++) {
FloatFactorTable[] factorTables = getCalibratedCliqueTree(weights, data[m], labelIndices, numClasses);
// log.info("calibrated:");
// for (int i = 0; i < factorTables.length; i++) {
// System.out.println(factorTables[i]);
// System.out.println("+++++++++++++++++++++++++++++");
// }
// System.exit(0);
float z = factorTables[0].totalMass();
int[] given = new int[window - 1];
Arrays.fill(given, classIndex.indexOf(backgroundSymbol));
for (int i = 0; i < data[m].length; i++) {
float p = factorTables[i].conditionalLogProb(given, labels[m][i]);
if (VERBOSE) {
log.info("P(" + labels[m][i] + "|" + Arrays.toString(given) + ")=" + p);
}
prob += p;
System.arraycopy(given, 1, given, 0, given.length - 1);
given[given.length - 1] = labels[m][i];
}
// get predicted count
for (int i = 0; i < data[m].length; i++) {
// go through each clique...
for (int j = 0; j < data[m][i].length; j++) {
Index<CRFLabel> labelIndex = labelIndices.get(j);
// ...and each possible labeling for that clique
for (int k = 0; k < labelIndex.size(); k++) {
int[] label = labelIndex.get(k).getLabel();
// float p = Math.pow(Math.E, factorTables[i].logProbEnd(label));
float p = (float) Math.exp(factorTables[i].unnormalizedLogProbEnd(label) - z);
for (int n = 0; n < data[m][i][j].length; n++) {
E[data[m][i][j][n]][k] += p;
}
}
}
}
}
if (Float.isNaN(prob)) {
System.exit(0);
}
value = -prob;
// compute the partial derivative for each feature
int index = 0;
for (int i = 0; i < E.length; i++) {
for (int j = 0; j < E[i].length; j++) {
derivative[index++] = (E[i][j] - Ehat[i][j]);
if (VERBOSE) {
log.info("deriv(" + i + "," + j + ") = " + E[i][j] + " - " + Ehat[i][j] + " = " + derivative[index - 1]);
}
}
}
// priors
if (prior == QUADRATIC_PRIOR) {
float sigmaSq = sigma * sigma;
for (int i = 0; i < x.length; i++) {
float k = 1.0f;
float w = x[i];
value += k * w * w / 2.0 / sigmaSq;
derivative[i] += k * w / sigmaSq;
}
} else if (prior == HUBER_PRIOR) {
float sigmaSq = sigma * sigma;
for (int i = 0; i < x.length; i++) {
float w = x[i];
float wabs = Math.abs(w);
if (wabs < epsilon) {
value += w * w / 2.0 / epsilon / sigmaSq;
derivative[i] += w / epsilon / sigmaSq;
} else {
value += (wabs - epsilon / 2) / sigmaSq;
derivative[i] += ((w < 0.0) ? -1.0 : 1.0) / sigmaSq;
}
}
} else if (prior == QUARTIC_PRIOR) {
float sigmaQu = sigma * sigma * sigma * sigma;
for (int i = 0; i < x.length; i++) {
float k = 1.0f;
float w = x[i];
value += k * w * w * w * w / 2.0 / sigmaQu;
derivative[i] += k * w / sigmaQu;
}
}
}
public void calculateWeird1(float[] x) {
float[][] weights = to2D(x);
float[][] E = empty2D();
value = 0.0f;
Arrays.fill(derivative, 0.0f);
float[][] sums = new float[labelIndices.size()][];
float[][] probs = new float[labelIndices.size()][];
float[][] counts = new float[labelIndices.size()][];
for (int i = 0; i < sums.length; i++) {
int size = labelIndices.get(i).size();
sums[i] = new float[size];
probs[i] = new float[size];
counts[i] = new float[size];
// Arrays.fill(counts[i], 0.0f); // not needed; Java arrays zero initialized
}
for (int d = 0; d < data.length; d++) {
int[] llabels = labels[d];
for (int e = 0; e < data[d].length; e++) {
int[][] ddata = this.data[d][e];
for (int cl = 0; cl < ddata.length; cl++) {
int[] features = ddata[cl];
// activation
Arrays.fill(sums[cl], 0.0f);
int numClasses = labelIndices.get(cl).size();
for (int c = 0; c < numClasses; c++) {
for (int feature : features) {
sums[cl][c] += weights[feature][c];
}
}
}
for (int cl = 0; cl < ddata.length; cl++) {
int[] label = new int[cl + 1];
//Arrays.fill(label, classIndex.indexOf("O"));
Arrays.fill(label, classIndex.indexOf(backgroundSymbol));
int index1 = label.length - 1;
for (int pos = e; pos >= 0 && index1 >= 0; pos--) {
//log.info(index1+" "+pos);
label[index1--] = llabels[pos];
}
CRFLabel crfLabel = new CRFLabel(label);
int labelIndex = labelIndices.get(cl).indexOf(crfLabel);
float total = ArrayMath.logSum(sums[cl]);
// int[] features = ddata[cl];
int numClasses = labelIndices.get(cl).size();
for (int c = 0; c < numClasses; c++) {
probs[cl][c] = (float) Math.exp(sums[cl][c] - total);
}
// for (int f=0; f<features.length; f++) {
// for (int c=0; c<numClasses; c++) {
// //probs[cl][c] = Math.exp(sums[cl][c]-total);
// derivative[index] += probs[cl][c];
// if (c == labelIndex) {
// derivative[index]--;
// }
// index++;
// }
// }
value -= sums[cl][labelIndex] - total;
// // observed
// for (int f=0; f<features.length; f++) {
// //int i = indexOf(features[f], labels[d]);
// derivative[index+labelIndex] -= 1.0;
// }
}
// go through each clique...
for (int j = 0; j < data[d][e].length; j++) {
Index<CRFLabel> labelIndex = labelIndices.get(j);
// ...and each possible labeling for that clique
for (int k = 0; k < labelIndex.size(); k++) {
//int[] label = ((CRFLabel) labelIndex.get(k)).getLabel();
// float p = Math.pow(Math.E, factorTables[i].logProbEnd(label));
float p = probs[j][k];
for (int n = 0; n < data[d][e][j].length; n++) {
E[data[d][e][j][n]][k] += p;
}
}
}
}
}
// compute the partial derivative for each feature
int index = 0;
for (int i = 0; i < E.length; i++) {
for (int j = 0; j < E[i].length; j++) {
derivative[index++] = (E[i][j] - Ehat[i][j]);
}
}
// observed
// int index = 0;
// for (int i = 0; i < Ehat.length; i++) {
// for (int j = 0; j < Ehat[i].length; j++) {
// derivative[index++] -= Ehat[i][j];
// }
// }
// priors
if (prior == QUADRATIC_PRIOR) {
float sigmaSq = sigma * sigma;
for (int i = 0; i < x.length; i++) {
float k = 1.0f;
float w = x[i];
value += k * w * w / 2.0 / sigmaSq;
derivative[i] += k * w / sigmaSq;
}
} else if (prior == HUBER_PRIOR) {
float sigmaSq = sigma * sigma;
for (int i = 0; i < x.length; i++) {
float w = x[i];
float wabs = Math.abs(w);
if (wabs < epsilon) {
value += w * w / 2.0 / epsilon / sigmaSq;
derivative[i] += w / epsilon / sigmaSq;
} else {
value += (wabs - epsilon / 2) / sigmaSq;
derivative[i] += ((w < 0.0) ? -1.0 : 1.0) / sigmaSq;
}
}
} else if (prior == QUARTIC_PRIOR) {
float sigmaQu = sigma * sigma * sigma * sigma;
for (int i = 0; i < x.length; i++) {
float k = 1.0f;
float w = x[i];
value += k * w * w * w * w / 2.0 / sigmaQu;
derivative[i] += k * w / sigmaQu;
}
}
}
/*
// TODO(mengqiu) verify this is useless and remove
public void calculateWeird(float[] x) {
float[][] weights = to2D(x);
float[][] E = empty2D();
value = 0.0f;
Arrays.fill(derivative, 0.0f);
int size = labelIndices.get(labelIndices.size() - 1).size();
float[] sums = new float[size];
float[] probs = new float[size];
Index labelIndex = labelIndices.get(labelIndices.size() - 1);
for (int d = 0; d < data.length; d++) {
int[] llabels = labels[d];
int[] label = new int[window];
//Arrays.fill(label, classIndex.indexOf("O"));
Arrays.fill(label, classIndex.indexOf(backgroundSymbol));
for (int e = 0; e < data[d].length; e++) {
Arrays.fill(sums, 0.0f);
System.arraycopy(label, 1, label, 0, window - 1);
label[window - 1] = llabels[e];
CRFLabel crfLabel = new CRFLabel(label);
int maxCliqueLabelIndex = labelIndex.indexOf(crfLabel);
int[][] ddata = this.data[d][e];
//Iterator labelIter = labelIndices.get(labelIndices.size()-1).iterator();
//while (labelIter.hasNext()) {
for (int i = 0; i < labelIndex.size(); i++) {
CRFLabel c = (CRFLabel) labelIndex.get(i);
for (int cl = 0; cl < ddata.length; cl++) {
CRFLabel cliqueLabel = c.getSmallerLabel(cl + 1);
int clIndex = labelIndices.get(cl).indexOf(cliqueLabel);
int[] features = ddata[cl];
for (int f = 0; f < features.length; f++) {
sums[i] += weights[features[f]][clIndex];
}
}
}
float total = ArrayMath.logSum(sums);
for (int i = 0; i < probs.length; i++) {
probs[i] = (float) Math.exp(sums[i] - total);
}
value -= sums[maxCliqueLabelIndex] - total;
for (int i = 0; i < labelIndex.size(); i++) {
CRFLabel c = (CRFLabel) labelIndex.get(i);
for (int cl = 0; cl < ddata.length; cl++) {
CRFLabel cliqueLabel = c.getSmallerLabel(cl + 1);
int clIndex = labelIndices.get(cl).indexOf(cliqueLabel);
int[] features = ddata[cl];
for (int f = 0; f < features.length; f++) {
E[features[f]][clIndex] += probs[i];
if (i == maxCliqueLabelIndex) {
E[features[f]][clIndex] -= 1.0f;
}
//sums[i] += weights[features[f]][cl];
}
}
}
}
}
// compute the partial derivative for each feature
int index = 0;
for (int i = 0; i < E.length; i++) {
for (int j = 0; j < E[i].length; j++) {
//derivative[index++] = (E[i][j] - Ehat[i][j]);
derivative[index++] = E[i][j];
}
}
// priors
if (prior == QUADRATIC_PRIOR) {
float sigmaSq = sigma * sigma;
for (int i = 0; i < x.length; i++) {
float k = 1.0f;
float w = x[i];
value += k * w * w / 2.0 / sigmaSq;
derivative[i] += k * w / sigmaSq;
}
} else if (prior == HUBER_PRIOR) {
float sigmaSq = sigma * sigma;
for (int i = 0; i < x.length; i++) {
float w = x[i];
float wabs = Math.abs(w);
if (wabs < epsilon) {
value += w * w / 2.0 / epsilon / sigmaSq;
derivative[i] += w / epsilon / sigmaSq;
} else {
value += (wabs - epsilon / 2) / sigmaSq;
derivative[i] += ((w < 0.0f ? -1.0f : 1.0f) / sigmaSq);
}
}
} else if (prior == QUARTIC_PRIOR) {
float sigmaQu = sigma * sigma * sigma * sigma;
for (int i = 0; i < x.length; i++) {
float k = 1.0f;
float w = x[i];
value += k * w * w * w * w / 2.0 / sigmaQu;
derivative[i] += k * w / sigmaQu;
}
}
}
*/
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | external/jmonkeyengine/engine/src/core/com/jme3/audio/AudioStream.java | 5990 | /*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.audio;
import com.jme3.util.NativeObject;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <code>AudioStream</code> is an implementation of AudioData that
* acquires the audio from an InputStream. Audio can be streamed
* from network, hard drive etc. It is assumed the data coming
* from the input stream is uncompressed.
*
* @author Kirill Vainer
*/
public class AudioStream extends AudioData implements Closeable{
private final static Logger logger = Logger.getLogger(AudioStream.class.getName());
protected InputStream in;
protected float duration = -1f;
protected boolean open = false;
protected int[] ids;
public AudioStream(){
super();
}
protected AudioStream(int[] ids){
// Pass some dummy ID so handle
// doesn't get created.
super(-1);
// This is what gets destroyed in reality
this.ids = ids;
}
public void updateData(InputStream in, float duration){
if (id != -1 || this.in != null)
throw new IllegalStateException("Data already set!");
this.in = in;
this.duration = duration;
open = true;
}
/**
* Reads samples from the stream. The format of the data
* depends on the getSampleRate(), getChannels(), getBitsPerSample()
* values.
*
* @param buf Buffer where to read the samples
* @param offset The offset in the buffer where to read samples
* @param length The length inside the buffer where to read samples
* @return number of bytes read.
*/
public int readSamples(byte[] buf, int offset, int length){
if (!open)
return -1;
try{
return in.read(buf, offset, length);
}catch (IOException ex){
return -1;
}
}
/**
* Reads samples from the stream.
*
* @see AudioStream#readSamples(byte[], int, int)
* @param buf Buffer where to read the samples
* @return number of bytes read.
*/
public int readSamples(byte[] buf){
return readSamples(buf, 0, buf.length);
}
public float getDuration(){
return duration;
}
@Override
public int getId(){
throw new RuntimeException("Don't use getId() on streams");
}
@Override
public void setId(int id){
throw new RuntimeException("Don't use setId() on streams");
}
public void initIds(int count){
ids = new int[count];
}
public int getId(int index){
return ids[index];
}
public void setId(int index, int id){
ids[index] = id;
}
public int[] getIds(){
return ids;
}
public void setIds(int[] ids){
this.ids = ids;
}
@Override
public DataType getDataType() {
return DataType.Stream;
}
@Override
public void resetObject() {
id = -1;
ids = null;
setUpdateNeeded();
}
@Override
public void deleteObject(Object rendererObject) {
// It seems that the audio renderer is already doing a good
// job at deleting audio streams when they finish playing.
// ((AudioRenderer)rendererObject).deleteAudioData(this);
}
@Override
public NativeObject createDestructableClone() {
return new AudioStream(ids);
}
/**
* @return Whether the stream is open or not. Reading from a closed
* stream will always return eof.
*/
public boolean isOpen(){
return open;
}
/**
* Closes the stream, releasing all data relating to it. Reading
* from the stream will return eof.
* @throws IOException
*/
public void close() {
if (in != null && open){
try{
in.close();
}catch (IOException ex){
}
open = false;
}else{
throw new RuntimeException("AudioStream is already closed!");
}
}
public void setTime(float time){
if(in instanceof SeekableStream){
((SeekableStream)in).setTime(time);
}else{
logger.log(Level.WARNING,"Cannot use setTime on a stream that is not seekable. You must load the file with the streamCache option set to true");
}
}
}
| gpl-2.0 |
CA-IRIS/mn-iris | src/us/mn/state/dot/tms/client/proxy/ProxyColumn.java | 3164 | /*
* IRIS -- Intelligent Roadway Information System
* Copyright (C) 2009-2013 Minnesota Department of Transportation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package us.mn.state.dot.tms.client.proxy;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import us.mn.state.dot.sonar.SonarObject;
import us.mn.state.dot.tms.utils.I18N;
import static us.mn.state.dot.tms.client.widget.Widgets.UI;
/**
* A column in the proxy table model.
*
* @author Douglas Lau
* @author Michael Darter
*/
abstract public class ProxyColumn<T extends SonarObject> {
/** Column header */
protected final String header;
/** Column class */
protected final Class c_class;
/** Column width (pixels) */
protected final int width;
/** Create a new proxy column.
* @param tid Text ID for column header.
* @param w Width in pixels.
* @param c Column class. */
public ProxyColumn(String tid, int w, Class c) {
header = I18N.get(tid);
width = UI.scaled(w);
c_class = c;
}
/** Create a new proxy column */
public ProxyColumn(String tid, int w) {
this(tid, w, String.class);
}
/** Create a new proxy column */
public ProxyColumn(String tid) {
this(tid, 0, String.class);
}
/** Add a column to the table column model */
public void addColumn(TableColumnModel m, int col) {
TableColumn tc = createTableColumn(col);
tc.setHeaderValue(header);
tc.setCellRenderer(createCellRenderer());
tc.setCellEditor(createCellEditor());
m.addColumn(tc);
}
/** Create a table column */
protected TableColumn createTableColumn(int col) {
if(width > 0)
return new TableColumn(col, width);
else
return new TableColumn(col);
}
/** Get the column class */
public Class getColumnClass() {
return c_class;
}
/** Create the table cell renderer */
protected TableCellRenderer createCellRenderer() {
return null;
}
/** Create the table cell editor */
protected TableCellEditor createCellEditor() {
return null;
}
/** Get the value of the column for the given row */
public Object getValueAt(int row) {
return null;
}
/** Get the value of the column for the given proxy */
abstract public Object getValueAt(T proxy);
/** Test if the column for the given proxy is editable */
public boolean isEditable(T proxy) {
return false;
}
/** Set the value of the column for the given proxy */
public void setValueAt(T proxy, int row, Object value) {
setValueAt(proxy, value);
}
/** Set the value of the column for the given proxy */
public void setValueAt(T proxy, Object value) {
// Subclasses must override for editable columns
}
}
| gpl-2.0 |
geneos/adempiere | base/src/org/compiere/model/X_C_Dunning.java | 5778 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.KeyNamePair;
/** Generated Model for C_Dunning
* @author Adempiere (generated)
* @version Release 3.7.0LTS - $Id$ */
public class X_C_Dunning extends PO implements I_C_Dunning, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20110831L;
/** Standard Constructor */
public X_C_Dunning (Properties ctx, int C_Dunning_ID, String trxName)
{
super (ctx, C_Dunning_ID, trxName);
/** if (C_Dunning_ID == 0)
{
setC_Dunning_ID (0);
setCreateLevelsSequentially (false);
setIsDefault (false);
setName (null);
setSendDunningLetter (false);
} */
}
/** Load Constructor */
public X_C_Dunning (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_Dunning[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Dunning.
@param C_Dunning_ID
Dunning Rules for overdue invoices
*/
public void setC_Dunning_ID (int C_Dunning_ID)
{
if (C_Dunning_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Dunning_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Dunning_ID, Integer.valueOf(C_Dunning_ID));
}
/** Get Dunning.
@return Dunning Rules for overdue invoices
*/
public int getC_Dunning_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Dunning_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Create levels sequentially.
@param CreateLevelsSequentially
Create Dunning Letter by level sequentially
*/
public void setCreateLevelsSequentially (boolean CreateLevelsSequentially)
{
set_Value (COLUMNNAME_CreateLevelsSequentially, Boolean.valueOf(CreateLevelsSequentially));
}
/** Get Create levels sequentially.
@return Create Dunning Letter by level sequentially
*/
public boolean isCreateLevelsSequentially ()
{
Object oo = get_Value(COLUMNNAME_CreateLevelsSequentially);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Send dunning letters.
@param SendDunningLetter
Indicates if dunning letters will be sent
*/
public void setSendDunningLetter (boolean SendDunningLetter)
{
set_Value (COLUMNNAME_SendDunningLetter, Boolean.valueOf(SendDunningLetter));
}
/** Get Send dunning letters.
@return Indicates if dunning letters will be sent
*/
public boolean isSendDunningLetter ()
{
Object oo = get_Value(COLUMNNAME_SendDunningLetter);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | gpl-2.0 |
KomeijiLogi/BlueToothSeekingForProject | zxing-android-embedded-master/sample/src/main/java/example/zxing/ToolbarCaptureActivity.java | 2001 | package example.zxing;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
/**
* Sample Activity extending from ActionBarActivity to display a Toolbar.
*/
public class ToolbarCaptureActivity extends AppCompatActivity {
private CaptureManager capture;
private DecoratedBarcodeView barcodeScannerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.capture_appcompat);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setTitle("Scan Barcode");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
barcodeScannerView = (DecoratedBarcodeView)findViewById(R.id.zxing_barcode_scanner);
capture = new CaptureManager(this, barcodeScannerView);
capture.initializeFromIntent(getIntent(), savedInstanceState);
capture.decode();
}
@Override
protected void onResume() {
super.onResume();
capture.onResume();
}
@Override
protected void onPause() {
super.onPause();
capture.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
capture.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
capture.onSaveInstanceState(outState);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeScannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
}
| gpl-2.0 |
geneos/adempiere | base/src/org/compiere/model/I_AD_InfoColumn.java | 7769 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.compiere.util.KeyNamePair;
/** Generated Interface for AD_InfoColumn
* @author Adempiere (generated)
* @version Release 3.7.0LTS
*/
public interface I_AD_InfoColumn
{
/** TableName=AD_InfoColumn */
public static final String Table_Name = "AD_InfoColumn";
/** AD_Table_ID=897 */
public static final int Table_ID = MTable.getTable_ID(Table_Name);
KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 4 - System
*/
BigDecimal accessLevel = BigDecimal.valueOf(4);
/** Load Meta Data */
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/** Get Client.
* Client/Tenant for this installation.
*/
public int getAD_Client_ID();
/** Column name AD_Element_ID */
public static final String COLUMNNAME_AD_Element_ID = "AD_Element_ID";
/** Set System Element.
* System Element enables the central maintenance of column description and help.
*/
public void setAD_Element_ID (int AD_Element_ID);
/** Get System Element.
* System Element enables the central maintenance of column description and help.
*/
public int getAD_Element_ID();
public org.compiere.model.I_AD_Element getAD_Element() throws RuntimeException;
/** Column name AD_InfoColumn_ID */
public static final String COLUMNNAME_AD_InfoColumn_ID = "AD_InfoColumn_ID";
/** Set Info Column.
* Info Window Column
*/
public void setAD_InfoColumn_ID (int AD_InfoColumn_ID);
/** Get Info Column.
* Info Window Column
*/
public int getAD_InfoColumn_ID();
/** Column name AD_InfoWindow_ID */
public static final String COLUMNNAME_AD_InfoWindow_ID = "AD_InfoWindow_ID";
/** Set Info Window.
* Info and search/select Window
*/
public void setAD_InfoWindow_ID (int AD_InfoWindow_ID);
/** Get Info Window.
* Info and search/select Window
*/
public int getAD_InfoWindow_ID();
public org.compiere.model.I_AD_InfoWindow getAD_InfoWindow() throws RuntimeException;
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/** Set Organization.
* Organizational entity within client
*/
public void setAD_Org_ID (int AD_Org_ID);
/** Get Organization.
* Organizational entity within client
*/
public int getAD_Org_ID();
/** Column name AD_Reference_ID */
public static final String COLUMNNAME_AD_Reference_ID = "AD_Reference_ID";
/** Set Reference.
* System Reference and Validation
*/
public void setAD_Reference_ID (int AD_Reference_ID);
/** Get Reference.
* System Reference and Validation
*/
public int getAD_Reference_ID();
public org.compiere.model.I_AD_Reference getAD_Reference() throws RuntimeException;
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/** Get Created.
* Date this record was created
*/
public Timestamp getCreated();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/** Get Created By.
* User who created this records
*/
public int getCreatedBy();
/** Column name Description */
public static final String COLUMNNAME_Description = "Description";
/** Set Description.
* Optional short description of the record
*/
public void setDescription (String Description);
/** Get Description.
* Optional short description of the record
*/
public String getDescription();
/** Column name EntityType */
public static final String COLUMNNAME_EntityType = "EntityType";
/** Set Entity Type.
* Dictionary Entity Type;
Determines ownership and synchronization
*/
public void setEntityType (String EntityType);
/** Get Entity Type.
* Dictionary Entity Type;
Determines ownership and synchronization
*/
public String getEntityType();
/** Column name Help */
public static final String COLUMNNAME_Help = "Help";
/** Set Comment/Help.
* Comment or Hint
*/
public void setHelp (String Help);
/** Get Comment/Help.
* Comment or Hint
*/
public String getHelp();
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/** Set Active.
* The record is active in the system
*/
public void setIsActive (boolean IsActive);
/** Get Active.
* The record is active in the system
*/
public boolean isActive();
/** Column name IsDisplayed */
public static final String COLUMNNAME_IsDisplayed = "IsDisplayed";
/** Set Displayed.
* Determines, if this field is displayed
*/
public void setIsDisplayed (boolean IsDisplayed);
/** Get Displayed.
* Determines, if this field is displayed
*/
public boolean isDisplayed();
/** Column name IsQueryCriteria */
public static final String COLUMNNAME_IsQueryCriteria = "IsQueryCriteria";
/** Set Query Criteria.
* The column is also used as a query criteria
*/
public void setIsQueryCriteria (boolean IsQueryCriteria);
/** Get Query Criteria.
* The column is also used as a query criteria
*/
public boolean isQueryCriteria();
/** Column name Name */
public static final String COLUMNNAME_Name = "Name";
/** Set Name.
* Alphanumeric identifier of the entity
*/
public void setName (String Name);
/** Get Name.
* Alphanumeric identifier of the entity
*/
public String getName();
/** Column name SelectClause */
public static final String COLUMNNAME_SelectClause = "SelectClause";
/** Set Sql SELECT.
* SQL SELECT clause
*/
public void setSelectClause (String SelectClause);
/** Get Sql SELECT.
* SQL SELECT clause
*/
public String getSelectClause();
/** Column name SeqNo */
public static final String COLUMNNAME_SeqNo = "SeqNo";
/** Set Sequence.
* Method of ordering records;
lowest number comes first
*/
public void setSeqNo (int SeqNo);
/** Get Sequence.
* Method of ordering records;
lowest number comes first
*/
public int getSeqNo();
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/** Get Updated.
* Date this record was updated
*/
public Timestamp getUpdated();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/** Get Updated By.
* User who updated this records
*/
public int getUpdatedBy();
}
| gpl-2.0 |
elijah513/ice | java/src/Ice/src/main/java/IceInternal/Functional_TwowayCallbackBool.java | 1560 | // **********************************************************************
//
// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
package IceInternal;
public abstract class Functional_TwowayCallbackBool extends Functional_TwowayCallback implements Ice.TwowayCallbackBool
{
public Functional_TwowayCallbackBool(Functional_BoolCallback responseCb,
Functional_GenericCallback1<Ice.Exception> exceptionCb,
Functional_BoolCallback sentCb)
{
super(responseCb != null, exceptionCb, sentCb);
this.__responseCb = responseCb;
}
protected Functional_TwowayCallbackBool(boolean userExceptionCb,
Functional_BoolCallback responseCb,
Functional_GenericCallback1<Ice.Exception> exceptionCb,
Functional_BoolCallback sentCb)
{
super(exceptionCb, sentCb);
CallbackBase.check(responseCb != null || (userExceptionCb && exceptionCb != null));
this.__responseCb = responseCb;
}
@Override
public void response(boolean arg)
{
if(__responseCb != null)
{
__responseCb.apply(arg);
}
}
final private Functional_BoolCallback __responseCb;
}
| gpl-2.0 |
superzadeh/processdash | src/net/sourceforge/processdash/ui/lib/JLinkLabel.java | 3816 | // Copyright (C) 2008-2011 Tuma Solutions, LLC
// Process Dashboard - Data Automation Tool for high-maturity processes
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// Additional permissions also apply; see the README-license.txt
// file in the project root directory for more information.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
// The author(s) may be contacted at:
// processdash@tuma-solutions.com
// processdash-devel@lists.sourceforge.net
package net.sourceforge.processdash.ui.lib;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JLinkLabel extends JPanel {
public JLinkLabel(String label) {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
while (label.length() > 0) {
Matcher m = LINK_PAT.matcher(label);
if (m.lookingAt()) {
String preText = m.group(1);
String attrs = m.group(2);
String linkText = m.group(3);
if (preText.length() > 0)
add(new JLabel(preText));
add(new Link(linkText, getHref(attrs)));
label = label.substring(m.end());
} else {
add(new JLabel(label));
label = "";
}
}
}
public JLinkLabel(String label, ActionListener handler) {
this(label);
addActionListener(handler);
}
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
public void removeActionListener(ActionListener l) {
listenerList.remove(ActionListener.class, l);
}
protected void fireActionPerformed(ActionEvent e) {
for (ActionListener l : listenerList.getListeners(ActionListener.class))
l.actionPerformed(e);
}
private class Link extends JLabel {
public Link(String text, final String href) {
super("<html><a href='#'>" + text + "</a></html>");
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setForeground(Color.blue);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
fireActionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, href));
}
});
}
@Override
public Dimension getMaximumSize() {
return super.getPreferredSize();
}
}
private static final String getHref(String tagContents) {
Matcher m = HREF_PAT.matcher(tagContents);
if (m.find())
return m.group(1);
else
return null;
}
private static final Pattern LINK_PAT = Pattern.compile(
"([^<]*)<a([^>]*)>([^<]+)</a>", Pattern.CASE_INSENSITIVE);
private static final Pattern HREF_PAT = Pattern.compile(
"href=['\"]([^'\"]+)['\"]", Pattern.CASE_INSENSITIVE);
}
| gpl-3.0 |
scribblemaniac/AwakenDreamsClient | mcp/temp/src/minecraft/net/minecraft/util/IJsonSerializable.java | 179 | package net.minecraft.util;
import com.google.gson.JsonElement;
public interface IJsonSerializable {
void func_152753_a(JsonElement var1);
JsonElement func_151003_a();
}
| gpl-3.0 |
Bbalusa/Dat2 | src/main/java/tudu/web/mvc/BackupController.java | 1140 | package tudu.web.mvc;
import org.jdom.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceView;
import tudu.domain.TodoList;
import tudu.service.TodoListsService;
import javax.servlet.http.HttpSession;
/**
* Backup a Todo List.
*
* @author Julien Dubois
*/
@Controller
public class BackupController {
@Autowired
private TodoListsService todoListsService;
/**
* Backup a Todo List.
*/
@RequestMapping("/backup")
public ModelAndView backup(@RequestParam String listId, HttpSession session)
throws Exception {
Document doc = todoListsService.backupTodoList(listId);
session.setAttribute("todoListDocument", doc);
ModelAndView mv = new ModelAndView();
mv.setView(new InternalResourceView("/servlet/tudu_lists_backup.xml"));
return mv;
}
}
| gpl-3.0 |
FAIMS/faims-android | faimsandroidapp/src/main/java/au/org/intersect/faims/android/ui/map/LegacyQueryBuilder.java | 941 | package au.org.intersect.faims.android.ui.map;
import org.json.JSONException;
import org.json.JSONObject;
public class LegacyQueryBuilder extends QueryBuilder {
private String dbPath;
private String tableName;
public LegacyQueryBuilder() {
super();
}
public LegacyQueryBuilder(String sql) {
super(sql);
}
public String getDbPath() {
return dbPath;
}
public void setDbPath(String dbPath) {
this.dbPath = dbPath;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
@Override
public void saveToJSON(JSONObject json) throws JSONException {
super.saveToJSON(json);
json.put("dbPath", dbPath);
json.put("tableName", tableName);
}
@Override
public void loadFromJSON(JSONObject json) throws JSONException {
super.loadFromJSON(json);
dbPath = json.getString("dbPath");
tableName = json.getString("tableName");
}
}
| gpl-3.0 |
windrobin/atlasmapper | src/main/java/au/gov/aims/atlasmapperserver/jsonWrappers/server/UsersConfigWrapper.java | 1823 | /*
* This file is part of AtlasMapper server and clients.
*
* Copyright (C) 2012 Australian Institute of Marine Science
*
* Contact: Gael Lafond <g.lafond@aims.org.au>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.gov.aims.atlasmapperserver.jsonWrappers.server;
import au.gov.aims.atlasmapperserver.jsonWrappers.AbstractWrapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class UsersConfigWrapper extends AbstractWrapper {
public UsersConfigWrapper() { super(); }
public UsersConfigWrapper(JSONObject json) { super(json); }
public Double getVersion() {
return this.getVersion(null);
}
public Double getVersion(Double defaultValue) {
if (this.json.isNull("version")) {
return defaultValue;
}
return this.json.optDouble("version");
}
public void setVersion(Double version) throws JSONException {
if (version == null && !this.json.isNull("version")) {
this.json.remove("version");
} else {
this.json.put("version", version);
}
}
public JSONArray getUsers() {
return this.json.optJSONArray("users");
}
public void setUsers(JSONArray users) throws JSONException {
this.json.put("users", users);
}
}
| gpl-3.0 |
dmike16/gestioneRisorseAziendali | ProjectWorkGio/src/domain/RicercaScelta.java | 463 | package domain;
public class RicercaScelta {
private String nome;
private String cognome;
private String scelta;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getScelta() {
return scelta;
}
public void setScelta(String scelta) {
this.scelta = scelta;
}
} | gpl-3.0 |
thomashaw/SecGen | modules/utilities/unix/audit_tools/ghidra/files/release/Ghidra/Features/Base/ghidra_scripts/SearchGuiSingle.java | 4867 | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//The script will use the first instructions in a selection and build a combined mask/value buffer.
//Memory is then searched looking for this combined value buffer that represents the selected instructions.
//This automates the process of searching through memory for a particular ordering of instructions by hand.
//@category Search.InstructionPattern
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import docking.widgets.checkbox.GCheckBox;
import docking.widgets.label.GDLabel;
public class SearchGuiSingle extends SearchBaseExtended {
private JButton searchButton;
private JCheckBox mnemonicCheckBox;
private JCheckBox opOneCheckBox;
private JCheckBox opTwoCheckBox;
private JCheckBox constCheckBox;
private JLabel jLabel1;
private JPanel jPanel1;
private JFrame frame;
@Override
public void run() throws Exception {
initComponents();
}
private void initComponents() {
frame = new JFrame();
jPanel1 = new JPanel();
mnemonicCheckBox = new GCheckBox("Mnemonics", true);
opOneCheckBox = new GCheckBox("Operand 1", false);
opTwoCheckBox = new GCheckBox("Operand 2", false);
constCheckBox = new GCheckBox("Constants", false);
searchButton = new JButton();
jLabel1 = new GDLabel();
GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 100,
Short.MAX_VALUE));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 100,
Short.MAX_VALUE));
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
searchButton.setText("Search");
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Search Parameters ...");
GroupLayout layout = new GroupLayout(frame.getContentPane());
frame.getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) //
.addGroup(layout.createSequentialGroup() //
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) //
.addGroup(layout.createSequentialGroup() //
.addContainerGap() //
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) //
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING) //
.addComponent(opTwoCheckBox) //
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) //
.addComponent(mnemonicCheckBox) //
.addComponent(opOneCheckBox) //
) //
) //
.addComponent(constCheckBox) //
.addComponent(jLabel1) //
) //
) //
.addGroup(layout.createSequentialGroup() //
.addGap(32, 32, 32) //
.addComponent(searchButton) //
) //
) //
.addContainerGap(12, Short.MAX_VALUE) //
) //
);
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) //
.addGroup(layout.createSequentialGroup() //
.addContainerGap() //
.addComponent(jLabel1) //
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) //
.addComponent(mnemonicCheckBox) //
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) //
.addComponent(opOneCheckBox) //
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) //
.addComponent(opTwoCheckBox) //
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) //
.addComponent(constCheckBox) //
.addGap(18, 18, 18).addComponent(searchButton) //
.addContainerGap(27, Short.MAX_VALUE) //
) //
);
frame.pack();
frame.setVisible(true);
}
private void jButton1ActionPerformed(ActionEvent evt) {
SLMaskControl control = new SLMaskControl();
this.clearResults();
if (mnemonicCheckBox.isSelected()) {
control.useMnemonic = true;
}
if (opOneCheckBox.isSelected()) {
control.useOp1 = true;
}
if (opTwoCheckBox.isSelected()) {
control.useOp2 = true;
}
if (constCheckBox.isSelected()) {
control.useConst = true;
}
setState(control);
loadSelectedInstructions();
executeSearch();
frame.dispose();
}
}
| gpl-3.0 |
octopus-platform/bjoern | projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/structures/StridedInterval.java | 17120 | package bjoern.plugins.vsa.structures;
import java.math.BigInteger;
public class StridedInterval
{
protected final long stride;
protected final long lowerBound;
protected final long upperBound;
protected final DataWidth dataWidth;
protected StridedInterval(long stride, long lower, long upper, DataWidth dataWidth)
{
// Strided intervals must be immutable
lower = dataWidth.effectiveValue(lower);
upper = dataWidth.effectiveValue(upper);
if (stride < 0)
{
throw new IllegalArgumentException("Invalid strided interval: stride must not be negative");
} else if (stride == 0 && lower != upper)
{
throw new IllegalArgumentException("Invalid strided interval: stride must not be zero");
} else if ((lower > upper) && (stride != 1 || lower != 1 || upper != 0))
{
throw new IllegalArgumentException("Invalid strided interval: lower bound must not be larger than upper "
+ "bound.");
} else if (stride > 0 &&
BigInteger.valueOf(upper).subtract(BigInteger.valueOf(lower)).mod(BigInteger.valueOf(stride))
.longValue() != 0)
{
throw new IllegalArgumentException("Invalid strided interval: upper bound must be tight.");
}
this.stride = stride;
this.lowerBound = lower;
this.upperBound = upper;
this.dataWidth = dataWidth;
}
public static StridedInterval getTop(DataWidth dataWidth)
{
switch (dataWidth.getWidth())
{
case 1:
return StridedInterval1Bit.TOP;
case 64:
return StridedInterval64Bit.TOP;
default:
return getInterval(dataWidth.getMinimumValue(), dataWidth.getMaximumValue(), dataWidth);
}
}
public static StridedInterval getBottom(DataWidth dataWidth)
{
// the bottom element (empty set) is always represented by a stride equal to 1, minimum value equal to 1, and
// maximum value equal to 0.
switch (dataWidth.getWidth())
{
case 1:
return StridedInterval1Bit.BOTTOM;
case 64:
return StridedInterval64Bit.BOTTOM;
default:
return getStridedInterval(1, 1, 0, dataWidth);
}
}
public static StridedInterval getSingletonSet(long number, DataWidth dataWidth)
{
// singleton sets have a stride equal to 0
return getStridedInterval(0, number, number, dataWidth);
}
public static StridedInterval getInterval(long lower, long upper, DataWidth dataWidth)
{
return getStridedInterval(1, lower, upper, dataWidth);
}
public static StridedInterval getStridedInterval(long stride, long lower, long upper, DataWidth dataWidth)
{
switch (dataWidth.getWidth())
{
case 1:
return new StridedInterval1Bit(stride, lower, upper);
case 64:
return new StridedInterval64Bit(stride, lower, upper);
default:
return new StridedInterval(stride, lower, upper, dataWidth);
}
}
@Override
public String toString()
{
if (isSingletonSet())
{
return "{" + lowerBound + "}";
} else if (isBottom())
{
return "{}"; //empty set
} else if (isInterval())
{
return "[" + lowerBound + ", " + upperBound + "]";
} else
{
return stride + "[" + lowerBound + ", " + upperBound + "]";
}
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof StridedInterval))
{
return false;
}
StridedInterval other = (StridedInterval) o;
return this.stride == other.stride && this.lowerBound == other.lowerBound
&& this.upperBound == other.upperBound;
}
@Override
public int hashCode()
{
int result = 17;
result = 31 * result + (int) (stride ^ (stride >>> 32));
result = 31 * result + (int) (lowerBound ^ (lowerBound >>> 32));
result = 31 * result + (int) (upperBound ^ (upperBound >>> 32));
return result;
}
public DataWidth getDataWidth()
{
return dataWidth;
}
public boolean isSingletonSet()
{
return stride == 0; // this implies that lowerBound == upperBound
}
public boolean isTop()
{
return this.equals(getTop(dataWidth));
}
public boolean isBottom()
{
return this.equals(getBottom(dataWidth));
}
public boolean isZero()
{
return isSingletonSet() && lowerBound == 0;
}
public boolean isOne()
{
return isSingletonSet() && lowerBound == 1;
}
public boolean isInterval()
{
return stride == 1;
}
public boolean contains(long number)
{
return !(lowerBound > number || upperBound < number) && (isSingletonSet() && lowerBound == number
|| ((number - lowerBound) % stride) == 0);
}
public boolean contains(StridedInterval si)
{
if (isBottom())
{
return false;
} else if (si.isBottom())
{
return true;
} else if (isSingletonSet())
{
return equals(si);
} else if (si.isSingletonSet())
{
return contains(si.lowerBound);
} else
{
return si.stride % this.stride == 0
&& si.lowerBound >= this.lowerBound && si.lowerBound <= this.upperBound
&& si.upperBound >= this.lowerBound && si.upperBound <= this.upperBound
&& this.contains(si.lowerBound);
}
}
protected boolean isLowerBoundMinimal()
{
return this.lowerBound == dataWidth.getMinimumValue();
}
protected boolean isUpperBoundMaximal()
{
return this.upperBound == dataWidth.getMaximumValue();
}
protected long sharedSuffixMask()
{
if (isSingletonSet())
{
return 0xffffffffffffffffL;
}
int t = Long.numberOfTrailingZeros(stride);
return (0x1 << t) - 1;
}
protected long sharedPrefixMask()
{
if (isSingletonSet())
{
return 0xffffffffffffffffL;
}
long l = Long.numberOfLeadingZeros(lowerBound ^ upperBound);
if (l == 0)
{
return 0x0000000000000000L;
}
return 0x8000000000000000L >> (l - 1);
}
public StridedInterval add(long c)
{
return this.add(getSingletonSet(c, dataWidth));
}
public StridedInterval add(StridedInterval si)
{
if (dataWidth.compareTo(si.dataWidth) < 0)
{
return si.add(this);
} else if (dataWidth.compareTo(si.dataWidth) > 0)
{
return add(si.signExtend(dataWidth));
}
long stride = gcd(this.stride, si.stride);
long lower = this.lowerBound + si.lowerBound;
long upper = this.upperBound + si.upperBound;
long u = this.lowerBound & si.lowerBound & ~lower & ~(this.upperBound & si.upperBound & ~upper);
long v = ((this.lowerBound ^ si.lowerBound) | ~(this.lowerBound ^ lower)) & (~this.upperBound & ~si.upperBound
& upper);
u = dataWidth.effectiveValue(u);
v = dataWidth.effectiveValue(v);
if ((u | v) < 0)
{
return getTop(dataWidth);
} else
{
return getStridedInterval(stride, dataWidth.effectiveValue(lower), dataWidth.effectiveValue(upper),
dataWidth);
}
}
public StridedInterval sub(long c)
{
return this.add(-c);
}
public StridedInterval sub(StridedInterval si)
{
return this.add(si.negate());
}
public StridedInterval inc()
{
return this.add(1);
}
public StridedInterval dec()
{
return this.sub(1);
}
public StridedInterval union(StridedInterval si)
{
// handle inverted cases
if (this.upperBound > si.upperBound)
{
return si.union(this);
}
// bounds are simple
long lowerBound = Math.min(this.lowerBound, si.lowerBound);
long upperBound = Math.max(this.upperBound, si.upperBound);
long delta;
if (this.upperBound <= si.lowerBound)
{
// non-overlapping intervals
delta = si.lowerBound - this.upperBound;
} else if (this.lowerBound < si.lowerBound && this.upperBound < si.upperBound)
{
// partly overlapping intervals
delta = this.upperBound - si.lowerBound;
} else //if (this.lowerBound >= si.lowerBound && this.upperBound <= si.upperBound)
{
// fully contained interval
delta = this.lowerBound - si.lowerBound;
}
long gcd = gcd(gcd(this.stride, si.stride), delta);
long stride = gcd < 0 ? -gcd : gcd;
return getStridedInterval(stride, lowerBound, upperBound, DataWidth.maximum(dataWidth, si.dataWidth));
}
public StridedInterval intersect(StridedInterval si)
{
if (this.upperBound > si.upperBound)
{
return si.intersect(this);
}
if (this.upperBound <= si.lowerBound)
{
// non-overlapping intervals
return getBottom(dataWidth);
} else
{
// partly overlapping intervals
long[] ans = extended_gcd(si.stride, this.stride);
long gcd = ans[0];
long u = ans[1];
long v = ans[2];
long difference = this.upperBound - si.lowerBound;
long answerStride = (this.stride * si.stride) / gcd;
// check if there can be any common elements
if ((difference % gcd) != 0)
{
return getBottom(dataWidth);
}
// find one solution (let's call it the anchor) to
// si.lowerBound + i0 * si.stride == this.upperbound - j0 * this.stride
// Starting at the anchor we can jump to common points that reside in the bound of both intervals
// by adding the stride of the answer strided interval
long i0 = (difference / gcd) * u;
long j0 = (difference / gcd) * v;
long anchor = si.lowerBound + (i0 * si.stride);
assert anchor == (this.upperBound - (j0 * this.stride)) : "Anchor is invalid";
long t = (Math.max(this.lowerBound, si.lowerBound) - anchor) / answerStride;
if (t >= 0 && ((Math.max(this.lowerBound, si.lowerBound) - anchor) % answerStride) != 0)
{
t++;
}
long answerLowerBound = anchor + (t * answerStride);
if (answerLowerBound > Math.min(this.upperBound, si.upperBound))
{
return getBottom(dataWidth);
} else if (Math.min(this.upperBound, si.upperBound) - answerLowerBound < answerStride)
{
return getSingletonSet(answerLowerBound, dataWidth);
} else
{
long answerSize = (Math.min(this.upperBound, si.upperBound) - answerLowerBound) / answerStride + 1;
return getStridedInterval(answerStride, answerLowerBound,
answerLowerBound + (answerSize - 1) * answerStride, dataWidth);
}
}
}
public StridedInterval removeLowerBound()
{
if (lowerBound == dataWidth.getMinimumValue())
{
return this;
} else if (isSingletonSet())
{
return getStridedInterval(1, dataWidth.getMinimumValue(), upperBound, dataWidth);
} else
{
long lowerBound = dataWidth.getMinimumValue();
long delta = BigInteger.valueOf(upperBound).subtract(BigInteger.valueOf(lowerBound))
.mod(BigInteger.valueOf(stride)).longValue();
lowerBound += delta;
return getStridedInterval(stride, lowerBound, upperBound, dataWidth);
}
}
public StridedInterval removeUpperBound()
{
if (upperBound == dataWidth.getMaximumValue())
{
return this;
} else if (isSingletonSet())
{
return getStridedInterval(1, lowerBound, dataWidth.getMaximumValue(), dataWidth);
} else
{
long upperBound = dataWidth.getMaximumValue();
long delta = BigInteger.valueOf(upperBound).subtract(BigInteger.valueOf(lowerBound))
.mod(BigInteger.valueOf(stride)).longValue();
upperBound -= delta;
return getStridedInterval(stride, lowerBound, upperBound, dataWidth);
}
}
public StridedInterval negate()
{
if (isSingletonSet() && isLowerBoundMinimal())
{
return this;
} else if (!isLowerBoundMinimal())
{
return getStridedInterval(stride, -upperBound, -lowerBound, dataWidth);
} else
{
return getTop(dataWidth);
}
}
public StridedInterval or(StridedInterval si)
{
if (dataWidth.compareTo(si.dataWidth) < 0)
{
return extend(si.dataWidth).or(si);
} else if (dataWidth.compareTo(si.dataWidth) > 0)
{
return or(si.extend(dataWidth));
}
long suffixMask1 = this.sharedSuffixMask();
long suffixMask2 = si.sharedSuffixMask();
long suffixBits1 = suffixMask1 & this.lowerBound;
long suffixBits2 = suffixMask2 & si.lowerBound;
long suffixBits = suffixBits1 | suffixBits2;
long t = Long.min(Long.numberOfTrailingZeros(this.stride), Long.numberOfTrailingZeros(si.stride));
long mask = (0x1L << t) - 1;
long answerStride = 0x1L << t;
long answerSharedSuffix = (this.lowerBound & mask) | (si.lowerBound & mask);
// zero out suffix bits
long answerLowerBound =
minOrSigned((this.lowerBound & ~mask), (this.upperBound & ~mask), (si.lowerBound & ~mask), (
si.upperBound & ~mask));
long answerUpperBound =
maxOrSigned((this.lowerBound & ~mask), (this.upperBound & ~mask), (si.lowerBound & ~mask), (
si.upperBound & ~mask));
answerLowerBound = (answerLowerBound & ~mask) | answerSharedSuffix;
answerUpperBound = (answerUpperBound & ~mask) | answerSharedSuffix;
while ((answerLowerBound & suffixBits) != suffixBits) answerLowerBound++;
while ((answerUpperBound & suffixBits) != suffixBits) answerUpperBound--;
return getStridedInterval(answerStride, answerLowerBound, answerUpperBound, dataWidth);
}
public StridedInterval not()
{
return getStridedInterval(stride, ~upperBound, ~lowerBound, dataWidth);
}
public StridedInterval and(StridedInterval si)
{
return not().or(si.not()).not();
}
public StridedInterval xor(StridedInterval si)
{
return not().or(si).not().or(or(si.not()).not());
}
public Bool3 compare(StridedInterval si)
{
if (equals(si))
{
return Bool3.TRUE;
} else
{
if (intersect(si).isBottom())
{
return Bool3.FALSE;
} else
{
return Bool3.MAYBE;
}
}
}
public Bool3 smaller(StridedInterval si)
{
if (this.upperBound < si.lowerBound)
{
return Bool3.TRUE;
} else if (this.lowerBound > si.upperBound)
{
return Bool3.FALSE;
} else
{
return Bool3.MAYBE;
}
}
public StridedInterval widen(StridedInterval stridedInterval)
{
StridedInterval answer = this;
answer = lowerBound <= stridedInterval.lowerBound ? answer : answer.removeLowerBound();
answer = upperBound >= stridedInterval.upperBound ? answer : answer.removeUpperBound();
return answer;
}
public StridedInterval extend(DataWidth dataWidth)
{
if (this.dataWidth.compareTo(dataWidth) >= 0)
{
return this;
} else
{
throw new UnsupportedOperationException("Not yet implemented.");
}
}
public StridedInterval signExtend(DataWidth dataWidth)
{
if (this.dataWidth.compareTo(dataWidth) >= 0)
{
return this;
} else
{
return getStridedInterval(stride, lowerBound, upperBound, dataWidth);
}
}
public Bool3 greater(StridedInterval si)
{
return smaller(si).not();
}
public Bool3 greaterOrEqual(StridedInterval si)
{
return greater(si).or(compare(si));
}
public Bool3 smallerOrEqual(StridedInterval si)
{
return smaller(si).or(compare(si));
}
private static long gcd(long a, long b)
{
if (b == 0)
{
return a;
}
return gcd(b, a % b);
}
private static long[] extended_gcd(long a, long b)
{
if (b == 0)
{
return new long[]{a, 1, 0};
}
long[] ans = extended_gcd(b, a % b);
return new long[]{ans[0], ans[2], ans[1] - ((a / b) * ans[2])};
}
private static long minOr(long a, long b, long c, long d)
{
// H.S. Warren, Jr. Hacker’s Delight. Addison-Wesley, 2003
long m, temp;
m = 0x8000000000000000L;
while (m != 0)
{
if ((~a & c & m) != 0)
{
temp = (a | m) & -m;
if (Long.compareUnsigned(temp, b) <= 0)
{
a = temp;
break;
}
} else if ((a & ~c & m) != 0)
{
temp = (c | m) & -m;
if (Long.compareUnsigned(temp, d) <= 0)
{
c = temp;
break;
}
}
m = m >>> 1;
}
return a | c;
}
private static long maxOr(long a, long b, long c, long d)
{
// H.S. Warren, Jr. Hacker’s Delight. Addison-Wesley, 2003
long m, temp;
m = 0x8000000000000000L;
while (m != 0)
{
if ((b & d & m) != 0)
{
temp = (b - m) | (m - 1);
if (Long.compareUnsigned(temp, a) >= 0)
{
b = temp;
break;
}
temp = (d - m) | (m - 1);
if (Long.compareUnsigned(temp, c) >= 0)
{
d = temp;
break;
}
}
m = m >>> 1;
}
return b | d;
}
private static long minOrSigned(long a, long b, long c, long d)
{
long m = 0x8000000000000000L;
if ((a & b & c & d & m) != 0)
{
return minOr(a, b, c, d);
} else if ((a & b & c & ~d & m) != 0)
{
return a;
} else if ((a & b & ~c & ~d & m) != 0)
{
return minOr(a, b, c, d);
} else if ((a & ~b & c & d & m) != 0)
{
return c;
} else if ((a & ~b & c & ~d & m) != 0)
{
return Long.min(a, c);
} else if ((a & ~b & ~c & ~d & m) != 0)
{
return minOr(a, -1, c, d);
} else if ((~a & ~b & c & d & m) != 0)
{
return minOr(a, b, c, d);
} else if ((~a & ~b & c & ~d & m) != 0)
{
return minOr(a, b, c, -1);
} else if ((~a & ~b & ~c & ~d & m) != 0)
{
return minOr(a, b, c, d);
} else
{
throw new IllegalArgumentException("Arguments are invalid bounds.");
}
}
private static long maxOrSigned(long a, long b, long c, long d)
{
long m = 0x8000000000000000L;
if ((a & b & c & d & m) != 0)
{
return maxOr(a, b, c, d);
} else if ((a & b & c & ~d & m) != 0)
{
return -1;
} else if ((a & b & ~c & ~d & m) != 0)
{
return maxOr(a, b, c, d);
} else if ((a & ~b & c & d & m) != 0)
{
return -1;
} else if ((a & ~b & c & ~d & m) != 0)
{
return maxOr(0, b, 0, d);
} else if ((a & ~b & ~c & ~d & m) != 0)
{
return maxOr(0, b, c, d);
} else if ((~a & ~b & c & d & m) != 0)
{
return maxOr(a, b, c, d);
} else if ((~a & ~b & c & ~d & m) != 0)
{
return maxOr(a, b, 0, d);
} else if ((~a & ~b & ~c & ~d & m) != 0)
{
return maxOr(a, b, c, d);
} else
{
throw new IllegalArgumentException("Arguments are invalid bounds.");
}
}
}
| gpl-3.0 |
jtux270/translate | ovirt/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ejb/EngineEJBUtilsStrategy.java | 1306 | /**
*
*/
package org.ovirt.engine.core.utils.ejb;
/**
*
*/
public class EngineEJBUtilsStrategy extends EJBUtilsStrategy {
public static final String ENGINE_CONTEXT_PREFIX = "java:global/engine/";
@Override
protected void addJNDIBeans() {
addBeanJNDIName(BeanType.BACKEND, ENGINE_CONTEXT_PREFIX.concat("bll/Backend"));
addBeanJNDIName(BeanType.SCHEDULER, ENGINE_CONTEXT_PREFIX.concat("scheduler/Scheduler"));
addBeanJNDIName(BeanType.VDS_EVENT_LISTENER, ENGINE_CONTEXT_PREFIX.concat("bll/VdsEventListener"));
addBeanJNDIName(BeanType.LOCK_MANAGER, ENGINE_CONTEXT_PREFIX.concat("bll/LockManager"));
addBeanJNDIName(BeanType.EVENTQUEUE_MANAGER, ENGINE_CONTEXT_PREFIX.concat("bll/EventQueue"));
addBeanJNDIName(BeanType.CACHE_CONTAINER, "java:jboss/infinispan/ovirt-engine");
}
@Override
protected String getBeanSuffix(BeanType beanType, BeanProxyType proxyType) {
String suffix = "";
if (beanType.equals(BeanType.BACKEND)) {
if (proxyType.equals(BeanProxyType.LOCAL)) {
suffix = "!org.ovirt.engine.core.bll.interfaces.BackendInternal";
} else {
suffix = "!org.ovirt.engine.core.bll.BackendRemote";
}
}
return suffix;
}
}
| gpl-3.0 |
YinYanfei/CadalWorkspace | WebSearchLucene3.5/src/cn/cadal/recommender/input/eachmovie/EachMovieItem.java | 2181 | /*
* Created on 2004-11-22
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package cn.cadal.recommender.input.eachmovie;
import java.util.ArrayList;
import java.util.List;
import cn.cadal.recommender.spi.Item;
/**
* @author zhangyin
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class EachMovieItem implements Item {
int itemId;
String itemName;
String prUrl;
ArrayList ratingsIdx;//this item's rating data
EachMovieItem(int iId, String iName, String pr_Url) {
itemId = iId;
itemName = iName;
prUrl = pr_Url;
ratingsIdx = new ArrayList();
}
public List getRatingIdxList(){
return ratingsIdx;
}
public String toString() {
return " itemId: " + itemId + " itemName:" + itemName + // prUrl: "+ prUrl+
" ratingsIdx: " + ratingsIdx;
}
public void addRatingIdx(int ratingIdx) {
ratingsIdx.add(new Integer(ratingIdx));
}
public int getId() {
return getItemId();
}
/**
* @return Returns the itemId.
*/
public int getItemId() {
return itemId;
}
/**
* @param itemId
* The itemId to set.
*/
public void setItemId(int itemId) {
this.itemId = itemId;
}
/**
* @return Returns the itemName.
*/
public String getItemName() {
return itemName;
}
/**
* @param itemName
* The itemName to set.
*/
public void setItemName(String itemName) {
this.itemName = itemName;
}
/**
* @return Returns the prUrl.
*/
public String getPrUrl() {
return prUrl;
}
/**
* @param prUrl
* The prUrl to set.
*/
public void setPrUrl(String prUrl) {
this.prUrl = prUrl;
}
/**
* @return Returns the ratingsIdx.
*/
public List getRatingsIdx() {
return ratingsIdx;
}
public static void main(String[] args) {
}
}
| gpl-3.0 |
SimonSuster/semafor | src/main/java/edu/cmu/cs/lti/ark/fn/identification/LinDekNeighbors.java | 14164 | /*******************************************************************************
* Copyright (c) 2011 Dipanjan Das
* Language Technologies Institute,
* Carnegie Mellon University,
* All Rights Reserved.
*
* LinDekNeighbors.java is part of SEMAFOR 2.0.
*
* SEMAFOR 2.0 is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SEMAFOR 2.0 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with SEMAFOR 2.0. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package edu.cmu.cs.lti.ark.fn.identification;
import edu.cmu.cs.lti.ark.fn.data.prep.ParsePreparation;
import edu.cmu.cs.lti.ark.fn.wordnet.WordNetRelations;
import edu.cmu.cs.lti.ark.util.ds.Pair;
import gnu.trove.THashSet;
import gnu.trove.TObjectIntHashMap;
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class LinDekNeighbors {
public static final int MAX_NEIGHBORS = 20;
public static void main(String[] args) {
Pair<TObjectIntHashMap<String>, TObjectIntHashMap<String>> p =
readAdjectivesAndAdverbs();
TObjectIntHashMap<String> adjectives = p.first;
TObjectIntHashMap<String> adverbs = p.second;
System.out.println("Number of adjectives:" + adjectives.size());
System.out.println("Number of adverbs:" + adverbs.size());
try {
//createNeighborsForAdverbsAndAdjectives(p);
//createNeighborsForNouns();
createNeighborsForVerbs();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void createNeighborsForVerbs()
throws IOException {
String stopfile = "lrdata/stopwords.txt";
String wnConfigFile = "file_properties.xml";
WordNetRelations wnr = new WordNetRelations(stopfile, wnConfigFile);
if (true)
System.exit(-1);
String lindekdirectory = "/home/dipanjan/work/fall2010/SSL/FNData";
String outFile = "/home/dipanjan/work/fall2010/SSL/FNData/lindekneighbors.dat";
BufferedWriter bWriter = new BufferedWriter(new FileWriter(outFile, true));
String line;
BufferedReader bReader = new BufferedReader(new FileReader(lindekdirectory + "/simV.lsp"));
line = bReader.readLine();
ArrayList<String> lines = new ArrayList<String>();
while (line != null) {
line = line.trim();
lines.clear();
while (!line.equals("))")) {
lines.add(line);
line = bReader.readLine();
}
String firstLine = lines.get(0);
firstLine = firstLine.substring(1);
int ind = firstLine.indexOf("(desc");
firstLine = firstLine.substring(0, ind).trim();
String pos = null;
// multiword case
boolean isAdjective = false;
boolean isAdverb = false;
int knn = 0;
String outline = "";
for (int i = 1; i < lines.size() ; i ++) {
StringTokenizer st = new StringTokenizer(lines.get(i).trim(), " \t", true);
ArrayList<String> toks = new ArrayList<String>();
while (st.hasMoreTokens()) {
toks.add(st.nextToken());
}
double value = new Double(toks.get(toks.size()-1));
String unit = "";
for (int j = 0; j < toks.size()-2; j++) {
unit += toks.get(j);
}
if (unit.startsWith("\"")) {
if (!unit.endsWith("\"")) {
System.out.println("Problem with unit:" + unit);
System.exit(-1);
}
unit = unit.substring(1, unit.length()-1).toLowerCase();
} else {
String lc = unit.toLowerCase();
lc = wnr.getLemma(lc, "V");
unit = lc;
}
outline += unit + ".v\t" + value +"\t";
knn++;
if (knn > MAX_NEIGHBORS) {
break;
}
}
outline = outline.trim();
if (firstLine.startsWith("\"")) {
if (!firstLine.endsWith("\"")) {
System.out.println("Problem with unit:" + firstLine);
System.exit(-1);
}
firstLine = firstLine.substring(1, firstLine.length()-1).toLowerCase();
} else {
String lc = firstLine.toLowerCase();
firstLine = wnr.getLemma(lc, "V");
}
bWriter.write(firstLine + ".v\t" + outline + "\n");
line = bReader.readLine();
}
bReader.close();
bWriter.close();
}
public static void createNeighborsForNouns()
throws IOException {
String stopfile = "lrdata/stopwords.txt";
String wnConfigFile = "file_properties.xml";
WordNetRelations wnr = new WordNetRelations(stopfile, wnConfigFile);
String lindekdirectory = "/home/dipanjan/work/fall2010/SSL/FNData";
String outFile = "/home/dipanjan/work/fall2010/SSL/FNData/lindekneighbors.dat";
BufferedWriter bWriter = new BufferedWriter(new FileWriter(outFile, true));
String line;
BufferedReader bReader = new BufferedReader(new FileReader(lindekdirectory + "/simN.lsp"));
line = bReader.readLine();
ArrayList<String> lines = new ArrayList<String>();
while (line != null) {
line = line.trim();
lines.clear();
while (!line.equals("))")) {
lines.add(line);
line = bReader.readLine();
}
String firstLine = lines.get(0);
firstLine = firstLine.substring(1);
int ind = firstLine.indexOf("(desc");
firstLine = firstLine.substring(0, ind).trim();
String pos = null;
// multiword case
boolean isAdjective = false;
boolean isAdverb = false;
int knn = 0;
String outline = "";
for (int i = 1; i < lines.size() ; i ++) {
StringTokenizer st = new StringTokenizer(lines.get(i).trim(), " \t", true);
ArrayList<String> toks = new ArrayList<String>();
while (st.hasMoreTokens()) {
toks.add(st.nextToken());
}
double value = new Double(toks.get(toks.size()-1));
String unit = "";
for (int j = 0; j < toks.size()-2; j++) {
unit += toks.get(j);
}
if (unit.startsWith("\"")) {
if (!unit.endsWith("\"")) {
System.out.println("Problem with unit:" + unit);
System.exit(-1);
}
unit = unit.substring(1, unit.length()-1).toLowerCase();
} else {
String lc = unit.toLowerCase();
lc = wnr.getLemma(lc, "N");
unit = lc;
}
outline += unit + ".n\t" + value +"\t";
knn++;
if (knn > MAX_NEIGHBORS) {
break;
}
}
outline = outline.trim();
if (firstLine.startsWith("\"")) {
if (!firstLine.endsWith("\"")) {
System.out.println("Problem with unit:" + firstLine);
System.exit(-1);
}
firstLine = firstLine.substring(1, firstLine.length()-1).toLowerCase();
} else {
String lc = firstLine.toLowerCase();
firstLine = wnr.getLemma(lc, "N");
}
bWriter.write(firstLine + ".n\t" + outline + "\n");
line = bReader.readLine();
}
bReader.close();
bWriter.close();
}
public static void createNeighborsForAdverbsAndAdjectives(Pair<TObjectIntHashMap<String>,
TObjectIntHashMap<String>> p)
throws IOException {
String lindekdirectory = "/home/dipanjan/work/fall2010/SSL/FNData";
String outFile = "/home/dipanjan/work/fall2010/SSL/FNData/lindekneighbors.dat";
BufferedWriter bWriter = new BufferedWriter(new FileWriter(outFile));
String line;
ArrayList<String> mAdjectives = ParsePreparation.readSentencesFromFile(lindekdirectory + "/mult.word.j");
THashSet<String> adjSet = new THashSet<String>();
for (int i = 0; i < mAdjectives.size(); i++) {
String w = mAdjectives.get(i).toLowerCase();
adjSet.add(w);
}
ArrayList<String> mAdverbs = ParsePreparation.readSentencesFromFile(lindekdirectory + "/mult.word.r");
THashSet<String> advSet = new THashSet<String>();
for (int i = 0; i < mAdverbs.size(); i++) {
String w = mAdverbs.get(i).toLowerCase();
advSet.add(w);
}
TObjectIntHashMap<String> dAdjectives = p.first;
TObjectIntHashMap<String> dAdverbs = p.second;
// adverbs and adjectives;
BufferedReader bReader = new BufferedReader(new FileReader(lindekdirectory + "/simA.lsp"));
line = bReader.readLine();
ArrayList<String> lines = new ArrayList<String>();
while (line != null) {
line = line.trim();
lines.clear();
while (!line.equals("))")) {
lines.add(line);
line = bReader.readLine();
}
String firstLine = lines.get(0);
firstLine = firstLine.substring(1);
int ind = firstLine.indexOf("(desc");
firstLine = firstLine.substring(0, ind).trim();
// multiword case
boolean isAdjective = false;
boolean isAdverb = false;
int knn = 0;
String outline = "";
for (int i = 1; i < lines.size() ; i ++) {
StringTokenizer st = new StringTokenizer(lines.get(i).trim(), " \t", true);
ArrayList<String> toks = new ArrayList<String>();
while (st.hasMoreTokens()) {
toks.add(st.nextToken());
}
double value = new Double(toks.get(toks.size()-1));
String unit = "";
for (int j = 0; j < toks.size()-2; j++) {
unit += toks.get(j);
}
if (unit.startsWith("\"")) {
if (!unit.endsWith("\"")) {
System.out.println("Problem with unit:" + unit);
System.exit(-1);
}
unit = unit.substring(1, unit.length()-1).toLowerCase();
isAdjective = isMultiWordAdjective(adjSet, unit);
isAdverb = isMultiWordAdverb(advSet, unit);
} else {
String lc = unit.toLowerCase();
int wpos = findWordPOS(dAdjectives,
dAdverbs,
lc);
if (wpos == 1) {
isAdjective = true;
} else if (wpos == 2) {
isAdverb = true;
} else {
isAdjective = true;
isAdverb = true;
}
unit = lc;
}
if (isAdjective)
outline += unit + ".a\t" + value +"\t";
if (isAdverb)
outline += unit + ".adv\t" + value +"\t";
knn++;
if (knn > MAX_NEIGHBORS) {
break;
}
}
outline = outline.trim();
if (firstLine.startsWith("\"")) {
if (!firstLine.endsWith("\"")) {
System.out.println("Problem with unit:" + firstLine);
System.exit(-1);
}
firstLine = firstLine.substring(1, firstLine.length()-1).toLowerCase();
isAdjective = isMultiWordAdjective(adjSet, firstLine);
isAdverb = isMultiWordAdverb(advSet, firstLine);
} else {
String lc = firstLine.toLowerCase();
int wpos = findWordPOS(dAdjectives,
dAdverbs,
lc);
if (wpos == 1) {
isAdjective = true;
} else if (wpos == 2) {
isAdverb = true;
} else {
isAdjective = true;
isAdverb = true;
}
firstLine = lc;
}
if (isAdjective) {
bWriter.write(firstLine + ".a\t" + outline + "\n");
}
if (isAdverb) {
bWriter.write(firstLine + ".adv\t" + outline + "\n");
}
line = bReader.readLine();
}
bReader.close();
bWriter.close();
}
public static boolean isMultiWordAdjective(THashSet<String> mAdjectives,
String word) {
return mAdjectives.contains(word);
}
public static boolean isMultiWordAdverb(THashSet<String> mAdverbs,
String word) {
return mAdverbs.contains(word);
}
// 1 : adjective
// 2: adverb
// 3: both
public static int findWordPOS(TObjectIntHashMap<String> dAdjectives,
TObjectIntHashMap<String> dAdverbs,
String word) {
int adjCount = dAdjectives.get(word);
int advCount = dAdverbs.get(word);
if (adjCount == 0 && advCount == 0) {
if (word.endsWith("ly"))
return 2;
else {
return 3;
}
}
int total = adjCount + advCount;
double adjProb = (double)adjCount / (double) total;
double advProb = (double)advCount / (double) total;
if (Math.abs(adjProb - advProb) < 0.2) {
return 3;
} else {
if (adjProb > advProb) {
return 1;
} else {
return 2;
}
}
}
public static Pair<TObjectIntHashMap<String>, TObjectIntHashMap<String>>
readAdjectivesAndAdverbs() {
String adjFile = "/home/dipanjan/work/fall2010/SSL/FNData/gw.a";
String advFile = "/home/dipanjan/work/fall2010/SSL/FNData/gw.adv";
ArrayList<String> adjectives =
ParsePreparation.readSentencesFromFile(adjFile);
ArrayList<String> adverbs =
ParsePreparation.readSentencesFromFile(advFile);
TObjectIntHashMap<String> adjMap =
new TObjectIntHashMap<String>();
TObjectIntHashMap<String> advMap =
new TObjectIntHashMap<String>();
for (String string: adjectives) {
String[] toks = string.trim().split("\t");
adjMap.put(toks[0], Integer.parseInt(toks[1]));
}
for (String string: adverbs) {
String[] toks = string.trim().split("\t");
try {
advMap.put(toks[0], Integer.parseInt(toks[1]));
} catch (Exception e) {
System.out.println(string + "\n\n");
e.printStackTrace();
System.exit(-1);
}
}
return new Pair<TObjectIntHashMap<String>, TObjectIntHashMap<String>>(adjMap, advMap);
}
public static Pair<TObjectIntHashMap<String>, TObjectIntHashMap<String>>
scanAdjectivesAndAdverbs() {
String largeFile =
"/home/dipanjan/work/fall2010/SSL/FNData/AP_1m.all.lemma.tags";
TObjectIntHashMap<String> adjectives = new TObjectIntHashMap<String>();
TObjectIntHashMap<String> adverbs = new TObjectIntHashMap<String>();
try {
BufferedReader bReader = new BufferedReader(new FileReader(largeFile));
String line = null;
int count = 0;
while ((line = bReader.readLine()) != null) {
line = line.trim();
String[] toks = line.split("\t");
int numTokens = Integer.parseInt(toks[0]);
for (int i = 0; i < numTokens; i++) {
String pos = toks[1 + numTokens + i];
if (pos.startsWith("J")) {
int c = adjectives.get(toks[1 + i].toLowerCase());
adjectives.put(toks[1 + i].toLowerCase(), c+1);
} else if (pos.startsWith("RB")) {
int c = adverbs.get(toks[1 + i].toLowerCase());
adverbs.put(toks[1 + i].toLowerCase(), c+1);
}
}
count++;
if (count % 1000 == 0) {
System.out.print(". ");
}
if (count % 10000 == 0) {
System.out.println(count);
}
// if (count > 1000)
// break;
}
bReader.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
return new Pair<TObjectIntHashMap<String>, TObjectIntHashMap<String>>(adjectives, adverbs);
}
}
| gpl-3.0 |
monzonj/core | src/com/dotmarketing/portlets/links/action/PublishLinksAction.java | 2562 | package com.dotmarketing.portlets.links.action;
import java.net.URLDecoder;
import com.dotcms.repackage.javax.portlet.ActionRequest;
import com.dotcms.repackage.javax.portlet.ActionResponse;
import com.dotcms.repackage.javax.portlet.PortletConfig;
import com.dotcms.repackage.org.apache.struts.action.ActionForm;
import com.dotcms.repackage.org.apache.struts.action.ActionMapping;
import com.dotmarketing.exception.WebAssetException;
import com.dotmarketing.factories.InodeFactory;
import com.dotmarketing.factories.PublishFactory;
import com.dotmarketing.portal.struts.DotPortletAction;
import com.dotmarketing.portlets.links.model.Link;
import com.dotmarketing.util.InodeUtils;
import com.dotmarketing.util.Logger;
import com.liferay.portal.model.User;
import com.liferay.portlet.ActionRequestImpl;
import com.liferay.util.servlet.SessionMessages;
/**
* <a href="ViewQuestionsAction.java.html"><b><i>View Source</i></b></a>
*
* @author Maria Ahues
* @version $Revision: 1.2 $
*
*/
public class PublishLinksAction extends DotPortletAction {
public void processAction(
ActionMapping mapping, ActionForm form, PortletConfig config,
ActionRequest req, ActionResponse res)
throws Exception {
Logger.debug(this, "Running PublishLinksAction!!!!");
String referer = req.getParameter("referer");
if ((referer!=null) && (referer.length()!=0)) {
referer = URLDecoder.decode(referer,"UTF-8");
}
try {
//get the user
User user = com.liferay.portal.util.PortalUtil.getUser(req);
_publishLinks(req, user);
if ((referer!=null) && (referer.length()!=0)) {
_sendToReferral(req, res, referer);
}
setForward(req, "portlet.ext.links.publish_links");
}
catch (Exception e) {
_handleException(e, req);
}
}
private void _publishLinks(ActionRequest req, User user) throws Exception {
String[] publishInode = req.getParameterValues("publishInode");
ActionRequestImpl reqImpl = (ActionRequestImpl)req;
if (publishInode!=null) {
for (int i=0;i<publishInode.length;i++) {
Link link = (Link) InodeFactory.getInode(publishInode[i],Link.class);
if (InodeUtils.isSet(link.getInode())) {
//calls the asset factory edit
try{
PublishFactory.publishAsset(link,reqImpl.getHttpServletRequest());
SessionMessages.add(req, "message", "message.link_list.published");
}catch(WebAssetException wax){
Logger.error(this, wax.getMessage(),wax);
SessionMessages.add(req, "error", "message.webasset.published.failed");
}
}
}
}
}
} | gpl-3.0 |
Severed-Infinity/technium | build/tmp/recompileMc/sources/net/minecraft/advancements/ICriterionTrigger.java | 2729 | package net.minecraft.advancements;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import net.minecraft.util.ResourceLocation;
public interface ICriterionTrigger<T extends ICriterionInstance>
{
ResourceLocation getId();
void addListener(PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener<T> listener);
void removeListener(PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener<T> listener);
void removeAllListeners(PlayerAdvancements playerAdvancementsIn);
/**
* Deserialize a ICriterionInstance of this trigger from the data in the JSON.
*/
T deserializeInstance(JsonObject json, JsonDeserializationContext context);
public static class Listener<T extends ICriterionInstance>
{
private final T criterionInstance;
private final Advancement advancement;
private final String criterionName;
public Listener(T criterionInstanceIn, Advancement advancementIn, String criterionNameIn)
{
this.criterionInstance = criterionInstanceIn;
this.advancement = advancementIn;
this.criterionName = criterionNameIn;
}
public T getCriterionInstance()
{
return this.criterionInstance;
}
public void grantCriterion(PlayerAdvancements playerAdvancementsIn)
{
playerAdvancementsIn.grantCriterion(this.advancement, this.criterionName);
}
public boolean equals(Object p_equals_1_)
{
if (this == p_equals_1_)
{
return true;
}
else if (p_equals_1_ != null && this.getClass() == p_equals_1_.getClass())
{
ICriterionTrigger.Listener<?> listener = (ICriterionTrigger.Listener)p_equals_1_;
if (!this.criterionInstance.equals(listener.criterionInstance))
{
return false;
}
else
{
return !this.advancement.equals(listener.advancement) ? false : this.criterionName.equals(listener.criterionName);
}
}
else
{
return false;
}
}
public int hashCode()
{
int i = this.criterionInstance.hashCode();
i = 31 * i + this.advancement.hashCode();
i = 31 * i + this.criterionName.hashCode();
return i;
}
}
} | gpl-3.0 |
pritam176/UAQ | UAQCashierPayment/Model/src/ae/payment/model/pojo/PaymentResponseECR.java | 9895 | package ae.payment.model.pojo;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "PaymentResponseECR")
public class PaymentResponseECR {
private String transactionType;
private String transactionId; // pos transaction id, not to be confused with ecrIdNo which is application assigned transaction id
private Integer servicesCount = 0;
private Double service1Amount = 0.0;
private Double service1Fee1Amount = 0.0;
private String service1Fee1Name;
private Integer dynamicFeeCount = 0;
private Double dynamicFee1Amount = 0.0;
private String dynamicFee1Text;
private Double dynamicFee2Amount = 0.0;
private String dynamicFee2Text;
private Double dynamicFee3Amount = 0.0;
private String dynamicFee3Text;
private String approvalCode;
private String ecrIdNo; // application generated transaction id
private String retrievalRefNo;
private String invoiceNo;
private String posDate;
private String posTime;
private String lrc;
private String customLRC;
private String responseCode;
private String responseMessage;
private String autoUpdateStatus;
private String autoUpdateStatusMessage;
private String other;
public Double getTotalAmount(){
double total = 0.0;
if(service1Amount != null && service1Amount > 0){
total += service1Amount;
}
if(service1Fee1Amount != null && service1Fee1Amount > 0){
total += service1Fee1Amount;
}
if(dynamicFee1Amount != null && dynamicFee1Amount > 0){
total += dynamicFee1Amount;
}
if(dynamicFee2Amount != null && dynamicFee2Amount > 0){
total += dynamicFee2Amount;
}
if(dynamicFee3Amount != null && dynamicFee3Amount > 0){
total += dynamicFee3Amount;
}
return total;
}
/**
* This method is used to return the date in ddmmyyhhMMss
* @return
*/
public String getTransactionResponseDate(){
String strDate = null;
if(posDate != null && posTime != null){
strDate = posDate + posTime + "00";
}
return strDate;
}
/**
* @return the transactionType
*/
public String getTransactionType() {
return transactionType;
}
/**
* @param transactionType the transactionType to set
*/
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
/**
* @return the transactionId
*/
public String getTransactionId() {
return transactionId;
}
/**
* @param transactionId the transactionId to set
*/
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
/**
* @return the servicesCount
*/
public Integer getServicesCount() {
return servicesCount;
}
/**
* @param servicesCount the servicesCount to set
*/
public void setServicesCount(Integer servicesCount) {
this.servicesCount = servicesCount;
}
/**
* @return the service1Amount
*/
public Double getService1Amount() {
return service1Amount;
}
/**
* @param service1Amount the service1Amount to set
*/
public void setService1Amount(Double service1Amount) {
this.service1Amount = service1Amount;
}
/**
* @return the service1Fee1Amount
*/
public Double getService1Fee1Amount() {
return service1Fee1Amount;
}
/**
* @param service1Fee1Amount the service1Fee1Amount to set
*/
public void setService1Fee1Amount(Double service1Fee1Amount) {
this.service1Fee1Amount = service1Fee1Amount;
}
/**
* @return the service1Fee1Name
*/
public String getService1Fee1Name() {
return service1Fee1Name;
}
/**
* @param service1Fee1Name the service1Fee1Name to set
*/
public void setService1Fee1Name(String service1Fee1Name) {
this.service1Fee1Name = service1Fee1Name;
}
/**
* @return the dynamicFeeCount
*/
public Integer getDynamicFeeCount() {
return dynamicFeeCount;
}
/**
* @param dynamicFeeCount the dynamicFeeCount to set
*/
public void setDynamicFeeCount(Integer dynamicFeeCount) {
this.dynamicFeeCount = dynamicFeeCount;
}
/**
* @return the dynamicFee1Amount
*/
public Double getDynamicFee1Amount() {
return dynamicFee1Amount;
}
/**
* @param dynamicFee1Amount the dynamicFee1Amount to set
*/
public void setDynamicFee1Amount(Double dynamicFee1Amount) {
this.dynamicFee1Amount = dynamicFee1Amount;
}
/**
* @return the dynamicFee1Text
*/
public String getDynamicFee1Text() {
return dynamicFee1Text;
}
/**
* @param dynamicFee1Text the dynamicFee1Text to set
*/
public void setDynamicFee1Text(String dynamicFee1Text) {
this.dynamicFee1Text = dynamicFee1Text;
}
/**
* @return the dynamicFee2Amount
*/
public Double getDynamicFee2Amount() {
return dynamicFee2Amount;
}
/**
* @param dynamicFee2Amount the dynamicFee2Amount to set
*/
public void setDynamicFee2Amount(Double dynamicFee2Amount) {
this.dynamicFee2Amount = dynamicFee2Amount;
}
/**
* @return the dynamicFee2Text
*/
public String getDynamicFee2Text() {
return dynamicFee2Text;
}
/**
* @param dynamicFee2Text the dynamicFee2Text to set
*/
public void setDynamicFee2Text(String dynamicFee2Text) {
this.dynamicFee2Text = dynamicFee2Text;
}
/**
* @return the dynamicFee3Amount
*/
public Double getDynamicFee3Amount() {
return dynamicFee3Amount;
}
/**
* @param dynamicFee3Amount the dynamicFee3Amount to set
*/
public void setDynamicFee3Amount(Double dynamicFee3Amount) {
this.dynamicFee3Amount = dynamicFee3Amount;
}
/**
* @return the dynamicFee3Text
*/
public String getDynamicFee3Text() {
return dynamicFee3Text;
}
/**
* @param dynamicFee3Text the dynamicFee3Text to set
*/
public void setDynamicFee3Text(String dynamicFee3Text) {
this.dynamicFee3Text = dynamicFee3Text;
}
/**
* @return the approvalCode
*/
public String getApprovalCode() {
return approvalCode;
}
/**
* @param approvalCode the approvalCode to set
*/
public void setApprovalCode(String approvalCode) {
this.approvalCode = approvalCode;
}
/**
* @return the ecrIdNo
*/
public String getEcrIdNo() {
return ecrIdNo;
}
/**
* @param ecrIdNo the ecrIdNo to set
*/
public void setEcrIdNo(String ecrIdNo) {
this.ecrIdNo = ecrIdNo;
}
/**
* @return the retrievalRefNo
*/
public String getRetrievalRefNo() {
return retrievalRefNo;
}
/**
* @param retrievalRefNo the retrievalRefNo to set
*/
public void setRetrievalRefNo(String retrievalRefNo) {
this.retrievalRefNo = retrievalRefNo;
}
/**
* @return the invoiceNo
*/
public String getInvoiceNo() {
return invoiceNo;
}
/**
* @param invoiceNo the invoiceNo to set
*/
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
/**
* @return the posDate
*/
public String getPosDate() {
return posDate;
}
/**
* @param posDate the posDate to set
*/
public void setPosDate(String posDate) {
this.posDate = posDate;
}
/**
* @return the posTime
*/
public String getPosTime() {
return posTime;
}
/**
* @param posTime the posTime to set
*/
public void setPosTime(String posTime) {
this.posTime = posTime;
}
/**
* @return the lrc
*/
public String getLrc() {
return lrc;
}
/**
* @param lrc the lrc to set
*/
public void setLrc(String lrc) {
this.lrc = lrc;
}
/**
* @return the customLRC
*/
public String getCustomLRC() {
return customLRC;
}
/**
* @param customLRC the customLRC to set
*/
public void setCustomLRC(String customLRC) {
this.customLRC = customLRC;
}
/**
* @return the responseCode
*/
public String getResponseCode() {
return responseCode;
}
/**
* @param responseCode the responseCode to set
*/
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
/**
* @return the responseMessage
*/
public String getResponseMessage() {
return responseMessage;
}
/**
* @param responseMessage the responseMessage to set
*/
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}
/**
* @return the autoUpdateStatus
*/
public String getAutoUpdateStatus() {
return autoUpdateStatus;
}
/**
* @param autoUpdateStatus the autoUpdateStatus to set
*/
public void setAutoUpdateStatus(String autoUpdateStatus) {
this.autoUpdateStatus = autoUpdateStatus;
}
/**
* @return the autoUpdateStatusMessage
*/
public String getAutoUpdateStatusMessage() {
return autoUpdateStatusMessage;
}
/**
* @param autoUpdateStatusMessage the autoUpdateStatusMessage to set
*/
public void setAutoUpdateStatusMessage(String autoUpdateStatusMessage) {
this.autoUpdateStatusMessage = autoUpdateStatusMessage;
}
/**
* @return the other
*/
public String getOther() {
return other;
}
/**
* @param other the other to set
*/
public void setOther(String other) {
this.other = other;
}
@Override
public String toString() {
return "PaymentResponseECR [transactionType=" + transactionType + ", transactionId=" + transactionId + ", servicesCount=" + servicesCount
+ ", service1Amount=" + service1Amount + ", service1Fee1Amount=" + service1Fee1Amount + ", service1Fee1Name=" + service1Fee1Name
+ ", dynamicFeeCount=" + dynamicFeeCount + ", dynamicFee1Amount=" + dynamicFee1Amount + ", dynamicFee1Text=" + dynamicFee1Text
+ ", dynamicFee2Amount=" + dynamicFee2Amount + ", dynamicFee2Text=" + dynamicFee2Text + ", dynamicFee3Amount=" + dynamicFee3Amount
+ ", dynamicFee3Text=" + dynamicFee3Text + ", approvalCode=" + approvalCode + ", ecrIdNo=" + ecrIdNo + ", retrievalRefNo="
+ retrievalRefNo + ", invoiceNo=" + invoiceNo + ", posDate=" + posDate + ", posTime=" + posTime + ", lrc=" + lrc + ", customLRC="
+ customLRC + ", responseCode=" + responseCode + ", responseMessage=" + responseMessage + ", autoUpdateStatus=" + autoUpdateStatus
+ ", autoUpdateStatusMessage=" + autoUpdateStatusMessage + ", other=" + other + ", getTotalAmount()=" + getTotalAmount() + "]";
}
}
| gpl-3.0 |
obiba/mica2 | mica-rest/src/main/java/org/obiba/mica/web/rest/FileUploadExceptionMapper.java | 779 | /*
* Copyright (c) 2018 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.mica.web.rest;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.apache.commons.fileupload.FileUploadException;
@Provider
public class FileUploadExceptionMapper implements ExceptionMapper<FileUploadException> {
@Override
public Response toResponse(FileUploadException exception) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
| gpl-3.0 |
ldo/neotextureedit | src/engine/graphics/synthesis/texture/FilterBlur.java | 3267 | package engine.graphics.synthesis.texture;
import engine.base.FMath;
import engine.base.Vector4;
import engine.graphics.synthesis.texture.CacheTileManager.TileCacheEntry;
import engine.parameters.EnumParam;
import engine.parameters.FloatParam;
import engine.parameters.IntParam;
public class FilterBlur extends Channel {
FloatParam radius = CreateLocalFloatParam("Radius", 1, 0, 50).setDefaultIncrement(0.25f);
IntParam numSamples = CreateLocalIntParam("# Samples", 64, 8, 1024);
EnumParam weightFunction = CreateLocalEnumParam("Weight", "Gaussian,Box");
FloatParam anisotropy = CreateLocalFloatParam("Anisotropy", 0.0f, 0.0f, 1.0f).setDefaultIncrement(0.125f);
FloatParam angle = CreateLocalFloatParam("Angle", 0.0f, 0.0f, 180.0f).setDefaultIncrement(30.0f);
public String getName() {
return "Blur";
}
public FilterBlur() {
super(1);
vizType = ChannelVizType.SLOW;
}
public String getHelpText() {
return "Basic Blur Filter \n" +
"Warning: This filter can be very SLOW. \n" +
"In the current implementation it uses a fixed # Samples\n" +
"independent of the filter radius or output resolution.\n\n" +
"radius: the blur radius in % of the image width.\n" +
"anisotropy: 0: no anisotropy 1:full anisotropy.\n" +
"angle: 0-180 degree angle of anisotropy.";
}
public OutputType getOutputType() {
return OutputType.RGBA;
}
public OutputType getChannelInputType(int idx) {
return OutputType.RGBA;
}
private Vector4 performFilter(Vector4 out, TileCacheEntry[] caches, float u, float v) {
Vector4 val = new Vector4();
float r = radius.get()/100.0f;
float weightSum = 0.0f;
float rotU = FMath.cos(FMath.PI*angle.get()/180.0f);
float rotV = FMath.sin(FMath.PI*angle.get()/180.0f);
if (weightFunction.getEnumPos() == 0 && r > 0.0f) { // Gaussian
for (int i = 0; i < numSamples.get(); i++) {
float du = (FMath.radicalInverse_vdC(2, i)*2.0f - 1.0f)*r;
float dv = (FMath.radicalInverse_vdC(3, i)*2.0f - 1.0f)*r;
// apply anisotropy
du *= (1.0f - anisotropy.get());
float nu = du*rotU - dv*rotV;
float nv = dv*rotU + du*rotV;
du = nu;
dv = nv;
float l = FMath.sqrt(du*du + dv*dv);
float w = FMath.exp(-(l/r));
if (caches != null) val.add_ip(caches[0].sample_Normalized(du+u, dv+v).mult_ip(w));
else val.add_ip(inputChannels[0].valueRGBA(du+u, dv+v).mult_ip(w));
weightSum += w;
}
} else { // Box
for (int i = 0; i < numSamples.get(); i++) {
float du = (FMath.radicalInverse_vdC(2, i)*2.0f - 1.0f)*r;
float dv = (FMath.radicalInverse_vdC(3, i)*2.0f - 1.0f)*r;
// apply anisotropy
du *= (1.0f - anisotropy.get());
float nu = du*rotU - dv*rotV;
float nv = dv*rotU + du*rotV;
du = nu;
dv = nv;
if (caches != null) val.add_ip(caches[0].sample_Normalized(du+u, dv+v));
else val.add_ip(inputChannels[0].valueRGBA(du+u, dv+v));
weightSum += 1.0f;
}
}
val.mult_ip(1.0f/weightSum);
if (out != null) out.set(val);
return val;
}
protected void cache_function(Vector4 out, TileCacheEntry[] caches, int localX, int localY, float u, float v) {
performFilter(out, caches, u, v);
}
protected Vector4 _valueRGBA(float u, float v) {
return performFilter(null, null, u, v);
}
}
| gpl-3.0 |
nvoron23/opensearchserver | src/main/java/com/jaeksoft/searchlib/webservice/index/IndexInfo.java | 3541 | /**
* License Agreement for OpenSearchServer
*
* Copyright (C) 2014 Emmanuel Keller / Jaeksoft
*
* http://www.open-search-server.com
*
* This file is part of OpenSearchServer.
*
* OpenSearchServer is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenSearchServer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenSearchServer.
* If not, see <http://www.gnu.org/licenses/>.
**/
package com.jaeksoft.searchlib.webservice.index;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.jaeksoft.searchlib.Client;
import com.jaeksoft.searchlib.ClientCatalogItem;
import com.jaeksoft.searchlib.SearchLibException;
import com.jaeksoft.searchlib.util.ThreadUtils;
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement(name = "info")
@JsonInclude(Include.NON_EMPTY)
public class IndexInfo {
final public String indexName;
final public Date lastModified;
final public Integer numDocs;
final public Long size;
final public String humanSize;
final public List<String> threads;
final public Boolean loaded;
public IndexInfo() {
indexName = null;
lastModified = null;
numDocs = null;
size = null;
humanSize = null;
threads = null;
loaded = null;
}
public IndexInfo(ClientCatalogItem clientCatalogItem) throws IOException,
SearchLibException {
indexName = clientCatalogItem.getIndexName();
lastModified = clientCatalogItem.getLastModifiedDate();
numDocs = clientCatalogItem.getNumDocs();
size = clientCatalogItem.getSize();
humanSize = clientCatalogItem.getSizeString();
Client client = clientCatalogItem.getClient();
List<String> threadList = null;
if (client != null) {
loaded = true;
ThreadGroup threadGroup = client.getThreadGroup();
if (threadGroup != null) {
Thread[] threadArray = ThreadUtils.getThreadArray(threadGroup);
if (threadArray != null) {
threadList = new ArrayList<String>(threadArray.length);
for (Thread thread : threadArray)
threadList.add(thread.getName());
}
}
} else {
loaded = false;
}
threads = threadList;
}
/**
* @return the indexName
*/
public String getIndexName() {
return indexName;
}
/**
* @return the lastModified
*/
public Date getLastModified() {
return lastModified;
}
/**
* @return the numDocs
*/
public Integer getNumDocs() {
return numDocs;
}
/**
* @return the size
*/
public Long getSize() {
return size;
}
/**
* @return the humanSize
*/
public String getHumanSize() {
return humanSize;
}
/**
* @return the threads
*/
public List<String> getThreads() {
return threads;
}
public Integer getThreadCount() {
return threads == null ? null : threads.size();
}
/**
* @return the loaded
*/
public Boolean getLoaded() {
return loaded;
}
} | gpl-3.0 |
kidaa/RealmSpeak | magic_realm/applications/RealmCharacterBuilder/source/com/robin/magic_realm/RealmCharacterBuilder/EditPanel/ExtraChitEditPanel.java | 4255 | /*
* RealmSpeak is the Java application for playing the board game Magic Realm.
* Copyright (c) 2005-2015 Robin Warren
* E-mail: robin@dewkid.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
*
* http://www.gnu.org/licenses/
*/
package com.robin.magic_realm.RealmCharacterBuilder.EditPanel;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import com.robin.game.objects.GameObject;
import com.robin.game.objects.GameObjectBlockManager;
import com.robin.general.swing.ComponentTools;
import com.robin.magic_realm.RealmCharacterBuilder.ChitEditDialog;
import com.robin.magic_realm.components.CharacterActionChitComponent;
import com.robin.magic_realm.components.utility.Constants;
import com.robin.magic_realm.components.wrapper.CharacterWrapper;
public class ExtraChitEditPanel extends AdvantageEditPanel {
private CharacterActionChitComponent extraChit;
private JLabel iconLabel;
private JDialog parentFrame;
public ExtraChitEditPanel(JDialog frame,CharacterWrapper pChar, String levelKey) {
super(pChar, levelKey);
parentFrame = frame;
GameObject go = GameObject.createEmptyGameObject();
go.setName("Extra Chit");
go.setThisAttribute("action","FIGHT");
go.setThisAttribute("strength","L");
go.setThisAttribute("speed",4);
go.setThisAttribute("character_chit","");
go.setThisAttribute("stage",0);
go.setThisAttribute("level",0);
go.setThisAttribute("effort",0);
go.setThisAttribute(Constants.BONUS_CHIT,levelKey);
extraChit = new CharacterActionChitComponent(go);
extraChit.setFaceUp();
setLayout(new BorderLayout());
Box main = Box.createVerticalBox();
main.add(Box.createVerticalGlue());
Box line;
line = Box.createHorizontalBox();
line.add(Box.createHorizontalGlue());
iconLabel = new JLabel(extraChit.getIcon());
line.add(iconLabel);
line.add(Box.createHorizontalGlue());
main.add(line);
main.add(Box.createVerticalStrut(25));
line = Box.createHorizontalBox();
line.add(Box.createHorizontalGlue());
JButton editButton = new JButton("Edit");
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
ChitEditDialog editor = new ChitEditDialog(parentFrame,extraChit);
editor.setLocationRelativeTo(ExtraChitEditPanel.this);
editor.setVisible(true);
updateIcon();
}
});
ComponentTools.lockComponentSize(editButton,100,40);
line.add(editButton);
line.add(Box.createHorizontalGlue());
main.add(line);
main.add(Box.createVerticalGlue());
add(main,"Center");
if (hasAttribute(Constants.BONUS_CHIT)) {
GameObjectBlockManager man = new GameObjectBlockManager(character);
go = man.extractGameObjectFromBlocks(getBaseBlockName(),true);
extraChit = new CharacterActionChitComponent(go);
man.clearBlocks(getBaseBlockName());
updateIcon();
}
}
private void updateIcon() {
iconLabel.setIcon(extraChit.getIcon());
}
private String getBaseBlockName() {
return Constants.BONUS_CHIT+getLevelKey();
}
protected void applyAdvantage() {
setAttribute(Constants.BONUS_CHIT);
GameObjectBlockManager man = new GameObjectBlockManager(character);
man.storeGameObjectInBlocks(extraChit.getGameObject(),getBaseBlockName());
}
public boolean isCurrent() {
return hasAttribute(Constants.BONUS_CHIT);
}
public String toString() {
return "Extra Chit";
}
public String getSuggestedDescription() {
StringBuffer sb = new StringBuffer();
sb.append("Starts with an extra ");
sb.append(extraChit.getGameObject().getThisAttribute("action").toUpperCase());
sb.append(" chit.");
return sb.toString();
}
} | gpl-3.0 |
jtux270/translate | ovirt/frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/uicommon/popup/template/TemplateNewPopupWidget.java | 1849 | package org.ovirt.engine.ui.common.widget.uicommon.popup.template;
import static org.ovirt.engine.ui.common.widget.uicommon.popup.vm.PopupWidgetConfig.hiddenField;
import com.google.gwt.event.shared.EventBus;
import org.ovirt.engine.ui.common.CommonApplicationConstants;
import org.ovirt.engine.ui.common.CommonApplicationMessages;
import org.ovirt.engine.ui.common.CommonApplicationResources;
import org.ovirt.engine.ui.common.CommonApplicationTemplates;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.widget.uicommon.popup.AbstractVmPopupWidget;
import org.ovirt.engine.ui.common.widget.uicommon.popup.vm.PopupWidgetConfigMap;
import com.google.gwt.core.client.GWT;
public class TemplateNewPopupWidget extends AbstractVmPopupWidget {
interface ViewIdHandler extends ElementIdHandler<TemplateNewPopupWidget> {
ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
}
public TemplateNewPopupWidget(CommonApplicationConstants constants,
CommonApplicationResources resources,
CommonApplicationMessages messages,
CommonApplicationTemplates applicationTemplates,
EventBus eventBus) {
super(constants, resources, messages, applicationTemplates, eventBus);
}
@Override
protected void generateIds() {
ViewIdHandler.idHandler.generateAndSetIds(this);
}
@Override
protected PopupWidgetConfigMap createWidgetConfiguration() {
return super.createWidgetConfiguration().
putOne(logicalNetworksEditorPanel, hiddenField()).
putAll(poolSpecificFields(), hiddenField()).
putOne(templateEditor, hiddenField()).
putOne(instanceTypesEditor, hiddenField()).
update(resourceAllocationTab, hiddenField());
}
}
| gpl-3.0 |
ShatalovYaroslav/catalog | src/main/java/org/ow2/proactive/catalog/rest/controller/GraphqlController.java | 3157 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.catalog.rest.controller;
import java.io.IOException;
import java.util.Map;
import org.ow2.proactive.catalog.service.GraphqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import lombok.extern.log4j.Log4j2;
/**
* @author ActiveEon Team
* @since 04/07/2017
*/
@Controller
@Log4j2
public class GraphqlController {
private static final String DEFAULT_OPERATION_NAME = "operationName";
private static final String DEFAULT_QUERY_KEY = "query";
private static final String DEFAULT_VARIABLES_KEY = "variables";
private static final String REQUEST_HEADER_NAME_SESSION_ID = "sessionid";
@Autowired
private GraphqlService graphqlService;
@RequestMapping(value = "/graphiql", method = RequestMethod.GET)
public String graphiql() {
return "/index.html";
}
/*
* http://graphql.org/learn/serving-over-http/#post-request
*/
@RequestMapping(value = "/graphql", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> executeOperation(@RequestHeader(value = REQUEST_HEADER_NAME_SESSION_ID) String sessionId,
@RequestBody Map<String, Object> body) throws IOException {
log.debug("sessionId={}", sessionId);
String query = (String) body.get(DEFAULT_QUERY_KEY);
String operationName = (String) body.get(DEFAULT_OPERATION_NAME);
Map<String, Object> variables = (Map<String, Object>) body.get(DEFAULT_VARIABLES_KEY);
log.debug("query={}, operationName={}, variables={}", query, operationName, variables);
return graphqlService.executeQuery(query, operationName, (Object) null, variables);
}
}
| agpl-3.0 |
kerr-huang/openss7 | src/java/javax/telephony/callcenter/capabilities/CallCenterProviderCapabilities.java | 2128 | /*
* Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for NON-COMMERCIAL purposes and without
* fee is hereby granted provided that this copyright notice
* appears in all copies. Please refer to the file "copyright.html"
* for further important copyright and licensing information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
package javax.telephony.callcenter.capabilities;
import javax.telephony.capabilities.ProviderCapabilities;
/**
* The CallCenterProviderCapabilities interface extends the
* ProviderCapabilities interface to add capabilities methods for the
* CallCenterProvider interface. Applications query these methods to find out
* what actions are possible on the CallCenterProvider interface.
*/
public interface CallCenterProviderCapabilities extends ProviderCapabilities {
/**
* This method returns true if the method getRouteableAddresses on the
* CallCenterProvider interface is supported.
* <p>
* @return True if the method addCallObserver on the CallCenterProvider
* interface is supported.
*/
public boolean canGetRouteableAddresses();
/**
* This method returns true if the method getACDAddresses on the
* CallCenterProvider interface is supported.
* <p>
* @return True if the method getACDAddresses on the CallCenterProvider
* interface is supported.
*/
public boolean canGetACDAddresses();
/**
* This method returns true if the method getACDManagerAddresses on the
* CallCenterProvider interface is supported.
* <p>
* @return True if the method CallCenterProvodier.getACDManagerAddresses()
* is supported.
*/
public boolean canGetACDManagerAddresses();
}
| agpl-3.0 |
paraita/programming | programming-core/src/main/java/org/objectweb/proactive/core/descriptor/data/VirtualMachine.java | 4340 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.objectweb.proactive.core.descriptor.data;
import java.io.IOException;
import org.objectweb.proactive.core.descriptor.services.ServiceUser;
import org.objectweb.proactive.core.descriptor.services.UniversalService;
import org.objectweb.proactive.core.process.ExternalProcess;
/**
* A <code>VirtualMachine</code> is a conceptual entity that represents
* a JVM running a ProActiveRuntime
*
* @author The ProActive Team
* @version 1.0, 2002/09/20
* @since ProActive 0.9.3
* @see ProActiveDescriptorInternal
* @see VirtualNodeInternal
*/
public interface VirtualMachine extends ServiceUser {
/**
* Sets the number of nodes that will be created on this VirtualMachine.
* @param nodeNumber
* @throws IOException
*/
public void setNbNodes(int nodeNumber) throws java.io.IOException;
/**
* Returns the number of nodes that will be created for each of the virtual machines
* associated to this VirtualMachine object
* @return String
*/
public int getNbNodesOnCreatedVMs();
/**
* Sets the name of this VirtualMachine
* @param s
*/
public void setName(String s);
/**
* Returns the name of this VirtualMachine
* @return String
*/
public String getName();
// /**
// * Sets the acquisitionMethod field to the given value
// * @param s
// */
// public void setAcquisitionMethod(String s);
//
// /**
// * Returns the AcquisitionMethod value
// * @return String
// */
// public String getAcquisitionMethod();
// /**
// * Sets the port number of the acquisition process
// * @param s
// */
// public void setPortNumber(String s);
//
// /**
// * Return the Acquisition port number
// * @param s
// */
// public String getPortNumber();
/**
* Sets the process mapped to this VirtualMachine to the given process
* @param p
*/
public void setProcess(ExternalProcess p);
/**
* Returns the process mapped to this VirtualMachine
* @return ExternalProcess
*/
public ExternalProcess getProcess();
/**
* Sets the service mapped to this VirtualMachine to the given service
* @param service
*/
public void setService(UniversalService service);
/**
* Returns the service mapped to this VirtualMachine
* @return the service mapped to this VirtualMachine
*/
public UniversalService getService();
/**
* Returns the name of the machine where the process mapped to this virtual machine
* was launched.
* @return String
*/
public String getHostName();
/**
* Sets the creatorId field to the given value
* @param creatorId The Id of the VirtualNode that created this VirtualMachine
*/
public void setCreatorId(String creatorId);
/**
* Returns the value of creatorId field.
* @return String The Id of the VirtualNode that created this VirtualMachine
*/
public String getCreatorId();
/**
* Returns true if this machine his mapped onto a process false if mapped
* onto a service
* @return boolean if the machine result of a lookup
*/
public boolean hasProcess();
}
| agpl-3.0 |
JordanReiter/railo | railo-java/railo-core/src/railo/commons/io/res/type/http/HTTPResourceProvider.java | 2880 | package railo.commons.io.res.type.http;
import java.io.IOException;
import java.util.Map;
import railo.commons.io.res.Resource;
import railo.commons.io.res.ResourceProvider;
import railo.commons.io.res.Resources;
import railo.commons.io.res.util.ResourceLockImpl;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.StringUtil;
import railo.runtime.op.Caster;
public class HTTPResourceProvider implements ResourceProvider {
private int lockTimeout=20000;
private final ResourceLockImpl lock=new ResourceLockImpl(lockTimeout,false);
private String scheme="http";
private int clientTimeout=30000;
private int socketTimeout=20000;
private Map arguments;
public String getScheme() {
return scheme;
}
public String getProtocol() {
return scheme;
}
public void setScheme(String scheme) {
if(!StringUtil.isEmpty(scheme))this.scheme=scheme;
}
public ResourceProvider init(String scheme, Map arguments) {
setScheme(scheme);
if(arguments!=null) {
this.arguments=arguments;
// client-timeout
String strTimeout=(String) arguments.get("client-timeout");
if(strTimeout!=null) {
clientTimeout = Caster.toIntValue(strTimeout,clientTimeout);
}
// socket-timeout
strTimeout=(String) arguments.get("socket-timeout");
if(strTimeout!=null) {
socketTimeout=Caster.toIntValue(strTimeout,socketTimeout);
}
// lock-timeout
strTimeout = (String) arguments.get("lock-timeout");
if(strTimeout!=null) {
lockTimeout=Caster.toIntValue(strTimeout,lockTimeout);
}
}
lock.setLockTimeout(lockTimeout);
return this;
}
@Override
public Resource getResource(String path) {
int indexQ=path.indexOf('?');
if(indexQ!=-1){
int indexS=path.lastIndexOf('/');
while((indexS=path.lastIndexOf('/'))>indexQ){
path=path.substring(0,indexS)+"%2F"+path.substring(indexS+1);
}
}
path=ResourceUtil.translatePath(ResourceUtil.removeScheme(scheme,path),false,false);
return new HTTPResource(this,new HTTPConnectionData(path,getSocketTimeout()));
}
public boolean isAttributesSupported() {
return false;
}
public boolean isCaseSensitive() {
return false;
}
public boolean isModeSupported() {
return false;
}
public void setResources(Resources resources) {
}
@Override
public void lock(Resource res) throws IOException {
lock.lock(res);
}
@Override
public void unlock(Resource res) {
lock.unlock(res);
}
@Override
public void read(Resource res) throws IOException {
lock.read(res);
}
/**
* @return the clientTimeout
*/
public int getClientTimeout() {
return clientTimeout;
}
/**
* @return the lockTimeout
*/
public int getLockTimeout() {
return lockTimeout;
}
/**
* @return the socketTimeout
*/
public int getSocketTimeout() {
return socketTimeout;
}
@Override
public Map getArguments() {
return arguments;
}
}
| lgpl-2.1 |
elaatifi/disko | src/java/disko/utils/SAN.java | 5783 | /*******************************************************************************
* Copyright (c) 2005, Kobrix Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Borislav Iordanov - initial API and implementation
* Murilo Saraiva de Queiroz - initial API and implementation
******************************************************************************/
package disko.utils;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
import org.hypergraphdb.util.Pair;
/**
*
* <p>
* Implements a Spread Activation Network. Construct the network by adding nodes
* and edges between them. Make sure the type of nodes behaves well as a key
* in hash tables (i.e. has properly defined and efficient hashCode and equals
* methods). Once the network is constructed, call the <code>run</code> and then
* read the resulting weights from <code>getNodeWeights</code> and <code>getTimeOfDeathMap</code>
* methods.
* </p>
*
* <p>
* Activation is spread following Berger et al. (google their paper called
* "An Adaptive Information Retrieval System based on Associative Networks", 2004). The network
* doesn't have to be fully connected and there are no designed initial nodes (this
* effect can be achieved by simply setting the weights of non-initial nodes to 0). Edges
* can have positive or negative weights. In the latter case, they are called "inhibitory".
* </p>
*
* @author Borislav Iordanov
*
* @param <NodeType>
*/
public class SAN<NodeType>
{
class Edge
{
NodeType src, dest; // dest is not really needed, added for completeness but may be removed
double weight;
}
double threshold;
Map<NodeType, Double> nodeWeights = new HashMap<NodeType, Double>();
Map<NodeType, List<Edge>> srcToDest = new HashMap<NodeType, List<Edge>>();
Map<NodeType, List<Edge>> destToSrc = new HashMap<NodeType, List<Edge>>();
HashMap<NodeType, Double> sources = new HashMap<NodeType, Double>();
Map<NodeType, Pair<Integer, Double>> timeOfDeath = new HashMap<NodeType, Pair<Integer, Double>>();
private double activationOutput(Map<NodeType, Double> weights, int iteration, NodeType n)
{
double weight = weights.get(n);
double fanoutFactor = 1.0 - (double)srcToDest.get(n).size()/(double)srcToDest.size();
double result = fanoutFactor * weight / (double)(iteration + 1);
return result;
}
public SAN(double threshold)
{
this.threshold = threshold;
}
public void clear()
{
nodeWeights.clear();
srcToDest.clear();
destToSrc.clear();
timeOfDeath.clear();
}
/**
* <p>
* Add a node with a specified initial weight.
* </p>
*
* @param node
* @param initialWeight
*/
public void addNode(NodeType node, double initialWeight)
{
nodeWeights.put(node, initialWeight);
}
/**
* <p>
* Add a directed edge with a given weight.
* </p>
*
* @param source
* @param destination
* @param weight
*/
public void addEdge(NodeType source, NodeType destination, double weight)
{
if (!nodeWeights.containsKey(source))
throw new RuntimeException("Source node has not been previously added: " + source);
else if (!nodeWeights.containsKey(destination))
throw new RuntimeException("Destination node has not been previously added: " + destination);
Edge e = new Edge();
e.src = source;
e.dest = destination;
e.weight = weight;
List<Edge> L = srcToDest.get(source);
if (L == null)
{
L = new ArrayList<Edge>();
srcToDest.put(source, L);
}
L.add(e);
L = destToSrc.get(destination);
if (L == null)
{
L = new ArrayList<Edge>();
destToSrc.put(destination, L);
}
L.add(e);
}
/**
* <p>
* Add a bi-directional edge with the same weight in both directions.
* </p>
*
* @param n1
* @param n2
* @param weight
*/
public void addBiEdge(NodeType n1, NodeType n2, double weight)
{
addEdge(n1, n2, weight);
addEdge(n2, n1, weight);
}
public void run()
{
boolean done = false;
sources.clear();
for (Map.Entry<NodeType, Double> e : nodeWeights.entrySet())
if (!destToSrc.containsKey(e.getKey()))
sources.put(e.getKey(), e.getValue());
Map<NodeType, Double> weights = nodeWeights;
for (int iteration = 1; !done; iteration++)
{
Map<NodeType, Double> nextWeights = new HashMap<NodeType, Double>();
done = true;
for (Map.Entry<NodeType, List<Edge>> n : destToSrc.entrySet())
{
if (timeOfDeath.containsKey(n.getKey()))
continue;
double nextWeight = 0.0;
for (Edge e : n.getValue())
if (!timeOfDeath.containsKey(e.src))
{
done = false;
nextWeight += activationOutput(weights, iteration, e.src) * e.weight;
}
if (nextWeight < threshold) // node becomes inactive
timeOfDeath.put(n.getKey(),new Pair<Integer, Double>(iteration, nextWeight));
nextWeights.put(n.getKey(), nextWeight);
}
weights = nextWeights;
weights.putAll(sources);
}
}
public Map<NodeType, Double> getNodeWeights()
{
return nodeWeights;
}
HashMap<NodeType, Double> getSources()
{
return sources;
}
public Map<NodeType, Pair<Integer, Double>> getTimeOfDeathMap()
{
return timeOfDeath;
}
public Collection<NodeType> getNodes()
{
return srcToDest.keySet();
}
public void print(PrintStream out) throws IOException
{
}
public String toString()
{
int edgeCount = 0;
for (List<Edge> L : srcToDest.values()) edgeCount += L.size();
for (List<Edge> L : destToSrc.values()) edgeCount += L.size();
return "SAN(" + nodeWeights.size() + " nodes, " + edgeCount + " edges)";
}
}
| lgpl-2.1 |
xien777/yajsw | yajsw/hessian4/src/main/java/com/caucho/hessian4/client/HessianURLConnection.java | 5695 | /*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian4.client;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
/**
* Internal connection to a server. The default connection is based on
* java.net
*/
public class HessianURLConnection extends AbstractHessianConnection {
private URL _url;
private URLConnection _conn;
private int _statusCode;
private String _statusMessage;
private InputStream _inputStream;
private InputStream _errorStream;
HessianURLConnection(URL url, URLConnection conn)
{
_url = url;
_conn = conn;
}
/**
* Adds a HTTP header.
*/
@Override
public void addHeader(String key, String value)
{
_conn.setRequestProperty(key, value);
}
/**
* Returns the output stream for the request.
*/
public OutputStream getOutputStream()
throws IOException
{
return _conn.getOutputStream();
}
/**
* Sends the request
*/
public void sendRequest()
throws IOException
{
if (_conn instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) _conn;
_statusCode = 500;
try {
_statusCode = httpConn.getResponseCode();
} catch (Exception e) {
}
parseResponseHeaders(httpConn);
InputStream is = null;
if (_statusCode != 200) {
StringBuffer sb = new StringBuffer();
int ch;
try {
is = httpConn.getInputStream();
if (is != null) {
while ((ch = is.read()) >= 0)
sb.append((char) ch);
is.close();
}
is = httpConn.getErrorStream();
if (is != null) {
while ((ch = is.read()) >= 0)
sb.append((char) ch);
}
_statusMessage = sb.toString();
} catch (FileNotFoundException e) {
throw new HessianConnectionException("HessianProxy cannot connect to '" + _url, e);
} catch (IOException e) {
if (is == null)
throw new HessianConnectionException(_statusCode + ": " + e, e);
else
throw new HessianConnectionException(_statusCode + ": " + sb, e);
}
if (is != null)
is.close();
throw new HessianConnectionException(_statusCode + ": " + sb.toString());
}
}
}
protected void parseResponseHeaders(HttpURLConnection conn)
throws IOException
{
}
/**
* Returns the status code.
*/
public int getStatusCode()
{
return _statusCode;
}
/**
* Returns the status string.
*/
public String getStatusMessage()
{
return _statusMessage;
}
/**
* Returns the InputStream to the result
*/
@Override
public InputStream getInputStream()
throws IOException
{
return _conn.getInputStream();
}
@Override
public String getContentEncoding()
{
return _conn.getContentEncoding();
}
/**
* Close/free the connection
*/
@Override
public void close()
{
_inputStream = null;
}
/**
* Disconnect the connection
*/
@Override
public void destroy()
{
close();
URLConnection conn = _conn;
_conn = null;
if (conn instanceof HttpURLConnection)
((HttpURLConnection) conn).disconnect();
}
}
| lgpl-2.1 |
alvin-reyes/abixen-platform | abixen-platform-modules/src/main/java/com/abixen/platform/module/magicnumber/util/impl/MagicNumberModuleBuilderImpl.java | 3137 | /**
* Copyright (c) 2010-present Abixen Systems. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.abixen.platform.module.magicnumber.util.impl;
import com.abixen.platform.core.util.EntityBuilder;
import com.abixen.platform.module.magicnumber.model.enumtype.ColorCode;
import com.abixen.platform.module.magicnumber.model.impl.MagicNumberModule;
import com.abixen.platform.module.magicnumber.util.MagicNumberModuleBuilder;
public class MagicNumberModuleBuilderImpl extends EntityBuilder<MagicNumberModule> implements MagicNumberModuleBuilder {
@Override
public MagicNumberModuleBuilder create() {
return this;
}
@Override
public MagicNumberModuleBuilder basic(Long moduleId, ColorCode colorCode, String iconClass) {
this.product.setModuleId(moduleId);
this.product.setColorCode(colorCode);
this.product.setIconClass(iconClass);
return this;
}
@Override
public MagicNumberModuleBuilder number(Double magicNumberValue, Integer magicNumberDisplayPrecision) {
this.product.setMagicNumberValue(magicNumberValue);
this.product.setMagicNumberDisplayPrecision(magicNumberDisplayPrecision);
return this;
}
@Override
public MagicNumberModuleBuilder numberDescription(String magicNumberDescription) {
this.product.setMagicNumberDescription(magicNumberDescription);
return this;
}
@Override
public MagicNumberModuleBuilder numberAfix(String prefixValue, String sufixValue) {
this.product.setPrefixValue(prefixValue);
this.product.setSufixValue(sufixValue);
return this;
}
@Override
public MagicNumberModuleBuilder additionalNumber(Double additionalNumberValue, Integer additionalNumberDisplayPrecision) {
this.product.setAdditionalNumberValue(additionalNumberValue);
this.product.setAdditionalNumberDisplayPrecision(additionalNumberDisplayPrecision);
return this;
}
@Override
public MagicNumberModuleBuilder additionalNumberDescription(String additionalNumberDescription) {
this.product.setAdditionalNumberDescription(additionalNumberDescription);
return this;
}
@Override
public MagicNumberModuleBuilder additionalNumberAfix(String additionalNumberprefixValue, String additionalNumberSufixValue) {
this.product.setAdditionalNumberPrefixValue(additionalNumberprefixValue);
this.product.setAdditionalNumberSufixValue(additionalNumberSufixValue);
return this;
}
@Override
protected void initProduct() {
this.product = new MagicNumberModule();
}
} | lgpl-2.1 |
automenta/jadehell | src/main/java/jade/domain/DFGUIManagement/DFAppletOntology.java | 4085 | /*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.domain.DFGUIManagement;
import jade.util.leap.List;
import jade.util.leap.LinkedList;
import jade.domain.FIPAAgentManagement.*;
import jade.content.lang.Codec;
import jade.content.onto.basic.*;
import jade.content.schema.*;
import jade.content.onto.*;
/**
@author Elisabetta Cortese - TiLab S.p.A.
@version $Date: 2003-08-26 11:15:34 +0200 (mar, 26 ago 2003) $ $Revision: 4243 $
*/
/**
This class represents the ontology
<code>DFApplet-management</code>, containing all JADE extensions
related to applet management. There is only a single instance of
this class.
<p>
The package contains one class for each Frame in the ontology.
<p>
*/
public class DFAppletOntology extends Ontology implements DFAppletVocabulary {
private static Ontology theInstance = new DFAppletOntology();
/**
This method grants access to the unique instance of the
ontology.
@return An <code>Ontology</code> object, containing the concepts
of the ontology.
*/
public static Ontology getInstance() {
return theInstance;
}
private DFAppletOntology() {
super(NAME, FIPAManagementOntology.getInstance(), new ReflectiveIntrospector());
try {
add(new AgentActionSchema(GETDESCRIPTION), GetDescription.class);
add(new AgentActionSchema(FEDERATE), Federate.class);
add(new AgentActionSchema(REGISTERWITH), RegisterWith.class);
add(new AgentActionSchema(DEREGISTERFROM), DeregisterFrom.class);
add(new AgentActionSchema(MODIFYON), ModifyOn.class);
add(new AgentActionSchema(SEARCHON), SearchOn.class);
add(new AgentActionSchema(GETPARENTS), GetParents.class);
add(new AgentActionSchema(GETDESCRIPTIONUSED), GetDescriptionUsed.class);
AgentActionSchema as = (AgentActionSchema)getSchema(FEDERATE);
as.add(FEDERATE_DF, (TermSchema) getSchema(BasicOntology.AID));
as.add(FEDERATE_DESCRIPTION, (TermSchema)getSchema(DFAGENTDESCRIPTION), ObjectSchema.OPTIONAL);
as = (AgentActionSchema)getSchema(REGISTERWITH);
as.add(REGISTERWITH_DF, (TermSchema) getSchema(BasicOntology.AID));
as.add(REGISTERWITH_DESCRIPTION, (TermSchema)getSchema(DFAGENTDESCRIPTION));
as = (AgentActionSchema)getSchema(DEREGISTERFROM);
as.add(DEREGISTERFROM_DF, (TermSchema) getSchema(BasicOntology.AID));
as.add(DEREGISTERFROM_DESCRIPTION, (TermSchema) getSchema(DFAGENTDESCRIPTION));
as = (AgentActionSchema)getSchema(MODIFYON);
as.add(MODIFYON_DF, (TermSchema) getSchema(BasicOntology.AID));
as.add(MODIFYON_DESCRIPTION, (TermSchema) getSchema(DFAGENTDESCRIPTION));
as = (AgentActionSchema)getSchema(SEARCHON);
as.add(SEARCHON_DF, (TermSchema) getSchema(BasicOntology.AID));
as.add(SEARCHON_DESCRIPTION, (TermSchema)getSchema(DFAGENTDESCRIPTION));
as.add(SEARCHON_CONSTRAINTS, (TermSchema)getSchema(SEARCHCONSTRAINTS));
as = (AgentActionSchema)getSchema(GETDESCRIPTIONUSED);
as.add(GETDESCRIPTIONUSED_PARENTDF, (TermSchema) getSchema(BasicOntology.AID));
}
catch(OntologyException oe) {
oe.printStackTrace();
}
}
}
| lgpl-2.1 |
bluenote10/TuxguitarParser | tuxguitar-src/TuxGuitar/src/org/herac/tuxguitar/app/view/dialog/grace/TGGraceDialog.java | 14735 | package org.herac.tuxguitar.app.view.dialog.grace;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.herac.tuxguitar.app.TuxGuitar;
import org.herac.tuxguitar.app.util.DialogUtils;
import org.herac.tuxguitar.app.view.controller.TGViewContext;
import org.herac.tuxguitar.document.TGDocumentContextAttributes;
import org.herac.tuxguitar.editor.action.TGActionProcessor;
import org.herac.tuxguitar.editor.action.effect.TGChangeGraceNoteAction;
import org.herac.tuxguitar.song.models.TGBeat;
import org.herac.tuxguitar.song.models.TGDuration;
import org.herac.tuxguitar.song.models.TGMeasure;
import org.herac.tuxguitar.song.models.TGNote;
import org.herac.tuxguitar.song.models.TGString;
import org.herac.tuxguitar.song.models.TGVelocities;
import org.herac.tuxguitar.song.models.effects.TGEffectGrace;
import org.herac.tuxguitar.util.TGContext;
public class TGGraceDialog extends SelectionAdapter{
private static final int LAYOUT_COLUMNS = 2;
private Spinner fretSpinner;
private Button deadButton;
private Button beforeBeatButton;
private Button onBeatButton;
private Button durationButton1;
private Button durationButton2;
private Button durationButton3;
private Button pppButton;
private Button ppButton;
private Button pButton;
private Button mpButton;
private Button mfButton;
private Button fButton;
private Button ffButton;
private Button fffButton;
private Button noneButton;
private Button slideButton;
private Button bendButton;
private Button hammerButton;
public TGGraceDialog(){
super();
}
public void show(final TGViewContext context){
final TGMeasure measure = context.getAttribute(TGDocumentContextAttributes.ATTRIBUTE_MEASURE);
final TGBeat beat = context.getAttribute(TGDocumentContextAttributes.ATTRIBUTE_BEAT);
final TGString string = context.getAttribute(TGDocumentContextAttributes.ATTRIBUTE_STRING);
final TGNote note = context.getAttribute(TGDocumentContextAttributes.ATTRIBUTE_NOTE);
if( measure != null && beat != null && note != null && string != null ) {
final Shell parent = context.getAttribute(TGViewContext.ATTRIBUTE_PARENT);
final Shell dialog = DialogUtils.newDialog(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
dialog.setLayout(new GridLayout());
dialog.setText(TuxGuitar.getProperty("effects.grace-editor"));
dialog.setMinimumSize(360,360);
Composite composite = new Composite(dialog,SWT.NONE);
composite.setLayout(new GridLayout(LAYOUT_COLUMNS,false));
composite.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
int horizontalSpan = 2;
//-----defaults-------------------------------------------------
boolean dead = false;
boolean onBeat = false;
int fret = note.getValue();
int duration = 1;
int dynamic = TGVelocities.DEFAULT;
int transition = TGEffectGrace.TRANSITION_NONE;
if(note.getEffect().isGrace()){
dead = note.getEffect().getGrace().isDead();
fret = note.getEffect().getGrace().getFret();
onBeat = note.getEffect().getGrace().isOnBeat();
duration = note.getEffect().getGrace().getDuration();
dynamic = note.getEffect().getGrace().getDynamic();
transition = note.getEffect().getGrace().getTransition();
}
//---------------------------------------------------
//------------------NOTE-----------------------------
//---------------------------------------------------
Group noteGroup = makeGroup(composite,horizontalSpan, TuxGuitar.getProperty("note"));
noteGroup.setLayout(new GridLayout(2,false));
Label fretLabel = new Label(noteGroup,SWT.NONE);
fretLabel.setText(TuxGuitar.getProperty("fret") + ": ");
this.fretSpinner = new Spinner(noteGroup,SWT.BORDER);
this.fretSpinner.setLayoutData(makeGridData(1));
this.fretSpinner.setSelection(fret);
this.deadButton = new Button(noteGroup,SWT.CHECK);
this.deadButton.setText(TuxGuitar.getProperty("note.deadnote"));
this.deadButton.setLayoutData(makeGridData(2));
this.deadButton.setSelection(dead);
//---------------------------------------------------
//------------------POSITION-------------------------
//---------------------------------------------------
Group positionGroup = makeGroup(composite,horizontalSpan, TuxGuitar.getProperty("position"));
positionGroup.setLayout(new GridLayout());
this.beforeBeatButton = new Button(positionGroup,SWT.RADIO);
this.beforeBeatButton.setText(TuxGuitar.getProperty("effects.grace.before-beat"));
this.beforeBeatButton.setLayoutData(makeGridData(1));
this.beforeBeatButton.setSelection(!onBeat);
this.onBeatButton = new Button(positionGroup,SWT.RADIO);
this.onBeatButton.setText(TuxGuitar.getProperty("effects.grace.on-beat"));
this.onBeatButton.setLayoutData(makeGridData(1));
this.onBeatButton.setSelection(onBeat);
//---------------------------------------------------
//------------------DURATION-------------------------
//---------------------------------------------------
Group durationGroup = makeGroup(composite,horizontalSpan, TuxGuitar.getProperty("duration"));
durationGroup.setLayout(new GridLayout(3,false));
this.durationButton1 = new Button(durationGroup,SWT.RADIO);
this.durationButton1.setImage(TuxGuitar.getInstance().getIconManager().getDuration(TGDuration.SIXTY_FOURTH));
this.durationButton1.setLayoutData(makeGridData(1));
this.durationButton1.setSelection(duration == 1);
this.durationButton2 = new Button(durationGroup,SWT.RADIO);
this.durationButton2.setImage(TuxGuitar.getInstance().getIconManager().getDuration(TGDuration.THIRTY_SECOND));
this.durationButton2.setLayoutData(makeGridData(1));
this.durationButton2.setSelection(duration == 2);
this.durationButton3 = new Button(durationGroup,SWT.RADIO);
this.durationButton3.setImage(TuxGuitar.getInstance().getIconManager().getDuration(TGDuration.SIXTEENTH));
this.durationButton3.setLayoutData(makeGridData(1));
this.durationButton3.setSelection(duration == 3);
horizontalSpan = 1;
//---------------------------------------------------
//------------------DYNAMIC--------------------------
//---------------------------------------------------
Group dynamicGroup = makeGroup(composite,horizontalSpan, TuxGuitar.getProperty("dynamic"));
dynamicGroup.setLayout(new GridLayout(2,false));
this.pppButton = new Button(dynamicGroup,SWT.RADIO);
this.pppButton.setImage(TuxGuitar.getInstance().getIconManager().getDynamicPPP());
this.pppButton.setLayoutData(makeGridData(1));
this.pppButton.setSelection(dynamic == TGVelocities.PIANO_PIANISSIMO);
this.mfButton = new Button(dynamicGroup,SWT.RADIO);
this.mfButton.setImage(TuxGuitar.getInstance().getIconManager().getDynamicMF());
this.mfButton.setLayoutData(makeGridData(1));
this.mfButton.setSelection(dynamic == TGVelocities.MEZZO_FORTE);
this.ppButton = new Button(dynamicGroup,SWT.RADIO);
this.ppButton.setImage(TuxGuitar.getInstance().getIconManager().getDynamicPP());
this.ppButton.setLayoutData(makeGridData(1));
this.ppButton.setSelection(dynamic == TGVelocities.PIANISSIMO);
this.fButton = new Button(dynamicGroup,SWT.RADIO);
this.fButton.setImage(TuxGuitar.getInstance().getIconManager().getDynamicF());
this.fButton.setLayoutData(makeGridData(1));
this.fButton.setSelection(dynamic == TGVelocities.FORTE);
this.pButton = new Button(dynamicGroup,SWT.RADIO);
this.pButton.setImage(TuxGuitar.getInstance().getIconManager().getDynamicP());
this.pButton.setLayoutData(makeGridData(1));
this.pButton.setSelection(dynamic == TGVelocities.PIANO);
this.ffButton = new Button(dynamicGroup,SWT.RADIO);
this.ffButton.setImage(TuxGuitar.getInstance().getIconManager().getDynamicFF());
this.ffButton.setLayoutData(makeGridData(1));
this.ffButton.setSelection(dynamic == TGVelocities.FORTISSIMO);
this.mpButton = new Button(dynamicGroup,SWT.RADIO);
this.mpButton.setImage(TuxGuitar.getInstance().getIconManager().getDynamicMP());
this.mpButton.setLayoutData(makeGridData(1));
this.mpButton.setSelection(dynamic == TGVelocities.MEZZO_PIANO);
this.fffButton = new Button(dynamicGroup,SWT.RADIO);
this.fffButton.setImage(TuxGuitar.getInstance().getIconManager().getDynamicFFF());
this.fffButton.setLayoutData(makeGridData(1));
this.fffButton.setSelection(dynamic == TGVelocities.FORTE_FORTISSIMO);
//---------------------------------------------------
//------------------TRANSITION-----------------------
//---------------------------------------------------
Group transitionGroup = makeGroup(composite,horizontalSpan, TuxGuitar.getProperty("effects.grace.transition"));
transitionGroup.setLayout(new GridLayout());
this.noneButton = new Button(transitionGroup,SWT.RADIO);
this.noneButton.setText(TuxGuitar.getProperty("effects.grace.transition-none"));
this.noneButton.setLayoutData(makeGridData(1));
this.noneButton.setSelection(transition == TGEffectGrace.TRANSITION_NONE);
this.bendButton = new Button(transitionGroup,SWT.RADIO);
this.bendButton.setText(TuxGuitar.getProperty("effects.grace.transition-bend"));
this.bendButton.setLayoutData(makeGridData(1));
this.bendButton.setSelection(transition == TGEffectGrace.TRANSITION_BEND);
this.slideButton = new Button(transitionGroup,SWT.RADIO);
this.slideButton.setText(TuxGuitar.getProperty("effects.grace.transition-slide"));
this.slideButton.setLayoutData(makeGridData(1));
this.slideButton.setSelection(transition == TGEffectGrace.TRANSITION_SLIDE);
this.hammerButton = new Button(transitionGroup,SWT.RADIO);
this.hammerButton.setText(TuxGuitar.getProperty("effects.grace.transition-hammer"));
this.hammerButton.setLayoutData(makeGridData(1));
this.hammerButton.setSelection(transition == TGEffectGrace.TRANSITION_HAMMER);
//---------------------------------------------------
//------------------BUTTONS--------------------------
//---------------------------------------------------
Composite buttons = new Composite(dialog, SWT.NONE);
buttons.setLayout(new GridLayout(3,false));
buttons.setLayoutData(new GridData(SWT.END,SWT.BOTTOM,true,true));
final Button buttonOK = new Button(buttons, SWT.PUSH);
buttonOK.setText(TuxGuitar.getProperty("ok"));
buttonOK.setLayoutData(getButtonData());
buttonOK.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
changeGrace(context.getContext(), measure, beat, string, getGrace());
dialog.dispose();
}
});
Button buttonClean = new Button(buttons, SWT.PUSH);
buttonClean.setText(TuxGuitar.getProperty("clean"));
buttonClean.setLayoutData(getButtonData());
buttonClean.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
changeGrace(context.getContext(), measure, beat, string, null);
dialog.dispose();
}
});
Button buttonCancel = new Button(buttons, SWT.PUSH);
buttonCancel.setText(TuxGuitar.getProperty("cancel"));
buttonCancel.setLayoutData(getButtonData());
buttonCancel.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
dialog.dispose();
}
});
dialog.setDefaultButton( buttonOK );
DialogUtils.openDialog(dialog, DialogUtils.OPEN_STYLE_CENTER | DialogUtils.OPEN_STYLE_PACK);
}
}
private Group makeGroup(Composite parent,int horizontalSpan,String text){
Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
group.setLayoutData(makeGridData(horizontalSpan));
group.setText(text);
return group;
}
private GridData getButtonData(){
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.minimumWidth = 80;
data.minimumHeight = 25;
return data;
}
private GridData makeGridData(int horizontalSpan){
GridData data = new GridData(SWT.FILL,SWT.FILL,true,true);
data.horizontalSpan = horizontalSpan;
return data;
}
public TGEffectGrace getGrace(){
TGEffectGrace effect = TuxGuitar.getInstance().getSongManager().getFactory().newEffectGrace();
effect.setFret(this.fretSpinner.getSelection());
effect.setDead(this.deadButton.getSelection());
effect.setOnBeat(this.onBeatButton.getSelection());
//duration
if(this.durationButton1.getSelection()){
effect.setDuration(1);
}else if(this.durationButton2.getSelection()){
effect.setDuration(2);
}else if(this.durationButton3.getSelection()){
effect.setDuration(3);
}
//velocity
if(this.pppButton.getSelection()){
effect.setDynamic(TGVelocities.PIANO_PIANISSIMO);
}else if(this.ppButton.getSelection()){
effect.setDynamic(TGVelocities.PIANISSIMO);
}else if(this.pButton.getSelection()){
effect.setDynamic(TGVelocities.PIANO);
}else if(this.mpButton.getSelection()){
effect.setDynamic(TGVelocities.MEZZO_PIANO);
}else if(this.mfButton.getSelection()){
effect.setDynamic(TGVelocities.MEZZO_FORTE);
}else if(this.fButton.getSelection()){
effect.setDynamic(TGVelocities.FORTE);
}else if(this.ffButton.getSelection()){
effect.setDynamic(TGVelocities.FORTISSIMO);
}else if(this.fffButton.getSelection()){
effect.setDynamic(TGVelocities.FORTE_FORTISSIMO);
}
//transition
if(this.noneButton.getSelection()){
effect.setTransition(TGEffectGrace.TRANSITION_NONE);
}else if(this.slideButton.getSelection()){
effect.setTransition(TGEffectGrace.TRANSITION_SLIDE);
}else if(this.bendButton.getSelection()){
effect.setTransition(TGEffectGrace.TRANSITION_BEND);
}else if(this.hammerButton.getSelection()){
effect.setTransition(TGEffectGrace.TRANSITION_HAMMER);
}
return effect;
}
public void changeGrace(TGContext context, TGMeasure measure, TGBeat beat, TGString string, TGEffectGrace effect) {
TGActionProcessor tgActionProcessor = new TGActionProcessor(context, TGChangeGraceNoteAction.NAME);
tgActionProcessor.setAttribute(TGDocumentContextAttributes.ATTRIBUTE_MEASURE, measure);
tgActionProcessor.setAttribute(TGDocumentContextAttributes.ATTRIBUTE_BEAT, beat);
tgActionProcessor.setAttribute(TGDocumentContextAttributes.ATTRIBUTE_STRING, string);
tgActionProcessor.setAttribute(TGChangeGraceNoteAction.ATTRIBUTE_EFFECT, effect);
tgActionProcessor.process();
}
}
| lgpl-2.1 |
alisdev/dss | dss-tsl-jaxb/src/main/java/eu/europa/esig/jaxb/xmldsig/DigestMethodType.java | 3230 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.10.27 at 09:23:34 AM CEST
//
package eu.europa.esig.jaxb.xmldsig;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;
/**
* <p>Java class for DigestMethodType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="DigestMethodType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DigestMethodType", propOrder = {
"content"
})
public class DigestMethodType
implements Serializable
{
private final static long serialVersionUID = 1L;
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
@XmlAttribute(name = "Algorithm", required = true)
@XmlSchemaType(name = "anyURI")
protected String algorithm;
/**
* Gets the value of the content property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Element }
* {@link Object }
* {@link String }
*
*
*/
public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
/**
* Gets the value of the algorithm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlgorithm() {
return algorithm;
}
/**
* Sets the value of the algorithm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlgorithm(String value) {
this.algorithm = value;
}
}
| lgpl-2.1 |
Alfresco/community-edition | projects/remote-api/source/test-java/org/alfresco/rest/api/tests/TestSiteMembershipRequests.java | 55226 | /*
* #%L
* Alfresco Remote API
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.api.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import org.alfresco.repo.tenant.TenantUtil;
import org.alfresco.repo.tenant.TenantUtil.TenantRunAsWork;
import org.alfresco.rest.api.tests.RepoService.SiteInformation;
import org.alfresco.rest.api.tests.RepoService.TestNetwork;
import org.alfresco.rest.api.tests.RepoService.TestPerson;
import org.alfresco.rest.api.tests.RepoService.TestSite;
import org.alfresco.rest.api.tests.client.PublicApiClient.ListResponse;
import org.alfresco.rest.api.tests.client.PublicApiClient.Paging;
import org.alfresco.rest.api.tests.client.PublicApiClient.SiteMembershipRequests;
import org.alfresco.rest.api.tests.client.PublicApiException;
import org.alfresco.rest.api.tests.client.RequestContext;
import org.alfresco.rest.api.tests.client.data.SiteMembershipRequest;
import org.alfresco.rest.api.tests.client.data.SiteRole;
import org.alfresco.service.cmr.invitation.Invitation;
import org.alfresco.service.cmr.invitation.ModeratedInvitation;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.site.SiteVisibility;
import org.alfresco.util.GUID;
import org.apache.commons.httpclient.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@SuppressWarnings("unused")
public class TestSiteMembershipRequests extends EnterpriseTestApi
{
private TestNetwork network1;
private TestNetwork network2;
private String person11Id; // network1
private String person12Id; // network1
private String person13Id; // network1
private String person14Id; // network1
private String person15Id; // network1
private String person24Id; // network2
private List<TestSite> personModeratedSites = new ArrayList<TestSite>();
private List<TestSite> personPublicSites = new ArrayList<TestSite>();
private List<TestSite> person1PrivateSites = new ArrayList<TestSite>();
private List<TestSite> person1ModeratedSites = new ArrayList<TestSite>();
private List<TestSite> person1MixedCaseModeratedSites = new ArrayList<TestSite>();
private List<TestSite> person1PublicSites = new ArrayList<TestSite>();
private List<TestSite> person4ModeratedSites = new ArrayList<TestSite>();
private List<NodeRef> personDocs = new ArrayList<NodeRef>();
private List<NodeRef> personFolders = new ArrayList<NodeRef>();
private List<NodeRef> person1Docs = new ArrayList<NodeRef>();
private List<NodeRef> person1Folders = new ArrayList<NodeRef>();
private SiteMembershipRequests siteMembershipRequestsProxy;
private Random random = new Random(System.currentTimeMillis());
@Override
@Before
public void setup() throws Exception
{
// init networks
super.setup();
Iterator<TestNetwork> networksIt = getTestFixture().networksIterator();
this.network1 = networksIt.next();
Iterator<String> personIt = network1.getPersonIds().iterator();
this.person11Id = personIt.next();
assertNotNull(person11Id);
this.person12Id = personIt.next();
assertNotNull(person12Id);
this.person13Id = personIt.next();
assertNotNull(person13Id);
this.person14Id = personIt.next();
assertNotNull(person14Id);
this.person15Id = personIt.next();
assertNotNull(person15Id);
this.network2 = networksIt.next();
Iterator<String> person1It = network2.getPersonIds().iterator();
this.person24Id = person1It.next();
assertNotNull(person24Id);
// Create some sites, files and folders
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
String guid = GUID.generate();
String[] siteNames = new String[] {"sitex" + guid, "sitea" + guid, "sitef" + guid, "site234" + guid,
"sitey" + guid, "siteb" + guid, "site643" + guid, "site24" + guid, "site8d6sc" + guid};
String siteName = siteNames[0];
SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.MODERATED);
TestSite site = network1.createSite(siteInfo);
person1ModeratedSites.add(site);
for(int i = 1; i < siteNames.length; i++)
{
siteName = siteNames[i];
siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.MODERATED);
site = network1.createSite(siteInfo);
person1ModeratedSites.add(site);
}
String[] mixedCaseSiteNames = new String[] {"MixedCase" + guid, "mixedCaseA" + guid};
for(int i = 0; i < mixedCaseSiteNames.length; i++)
{
siteName = mixedCaseSiteNames[i];
siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.MODERATED);
site = network1.createSite(siteInfo);
person1MixedCaseModeratedSites.add(site);
}
for(int i = 0; i < 1; i++)
{
siteName = "privatesite" + GUID.generate();
siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PRIVATE);
site = network1.createSite(siteInfo);
person1PrivateSites.add(site);
}
NodeRef nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc1", "Test Content");
person1Docs.add(nodeRef);
nodeRef = repoService.createFolder(site.getContainerNodeRef("documentLibrary"), "Test Folder1");
person1Folders.add(nodeRef);
nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc2", "Test Content");
person1Docs.add(nodeRef);
nodeRef = repoService.createFolder(site.getContainerNodeRef("documentLibrary"), "Test Folder2");
person1Folders.add(nodeRef);
nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc3", "Test Content");
person1Docs.add(nodeRef);
nodeRef = repoService.createFolder(site.getContainerNodeRef("documentLibrary"), "Test Folder3");
person1Folders.add(nodeRef);
siteName = "site" + GUID.generate();
siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
site = network1.createSite(siteInfo);
person1PublicSites.add(site);
return null;
}
}, person12Id, network1.getId());
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
String siteName = "site" + System.currentTimeMillis();
SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
TestSite site = network1.createSite(siteInfo);
NodeRef nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc1", "Test Content");
personDocs.add(nodeRef);
nodeRef = repoService.createFolder(site.getContainerNodeRef("documentLibrary"), "Test Folder1");
personFolders.add(nodeRef);
nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc2", "Test Content");
personDocs.add(nodeRef);
nodeRef = repoService.createFolder(site.getContainerNodeRef("documentLibrary"), "Test Folder2");
personFolders.add(nodeRef);
nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc3", "Test Content");
personDocs.add(nodeRef);
nodeRef = repoService.createFolder(site.getContainerNodeRef("documentLibrary"), "Test Folder3");
personFolders.add(nodeRef);
return null;
}
}, person11Id, network1.getId());
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
String siteName = "site" + GUID.generate();
SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
TestSite site = network1.createSite(siteInfo);
personPublicSites.add(site);
site.inviteToSite(person12Id, SiteRole.SiteCollaborator);
siteName = "site" + GUID.generate();
siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
site = network1.createSite(siteInfo);
personPublicSites.add(site);
return null;
}
}, person11Id, network1.getId());
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
String siteName = "site" + GUID.generate();
SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.MODERATED);
TestSite site = network1.createSite(siteInfo);
person4ModeratedSites.add(site);
return null;
}
}, person24Id, network2.getId());
this.siteMembershipRequestsProxy = publicApiClient.siteMembershipRequests();
}
private SiteMembershipRequest getSiteMembershipRequest(String networkId, String runAsUserId, String personId) throws PublicApiException, ParseException
{
publicApiClient.setRequestContext(new RequestContext(networkId, runAsUserId));
int skipCount = 0;
int maxItems = Integer.MAX_VALUE;
Paging paging = getPaging(skipCount, maxItems);
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(personId, createParams(paging, null));
List<SiteMembershipRequest> list = resp.getList();
int size = list.size();
assertTrue(size > 0);
int idx = random.nextInt(size);
SiteMembershipRequest request = list.get(idx);
return request;
}
@Test
public void testInvalidRequests() throws Exception
{
{
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12Id));
// unknown invitee
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(GUID.generate(), siteMembershipRequest);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12Id));
// unknown siteId
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(GUID.generate());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12Id));
// create site membership for another user
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
// cloud-2506
// get requests for another user
try
{
log("cloud-2506");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// get site membership requests for another user
int skipCount = 0;
int maxItems = 4;
Paging paging = getPaging(skipCount, maxItems);
siteMembershipRequestsProxy.getSiteMembershipRequests(person12Id, createParams(paging, null));
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
// get site membership requests for unknown user
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
int skipCount = 0;
int maxItems = 4;
Paging paging = getPaging(skipCount, maxItems);
siteMembershipRequestsProxy.getSiteMembershipRequests(GUID.generate(), createParams(paging, null));
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
// DELETEs
{
{
// cloud-2524
// runAs user != target user
log("cloud-2524");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
// create moderated site invitation to delete
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id, siteMembershipRequest);
SiteMembershipRequest request = getSiteMembershipRequest(network1.getId(), person14Id, person14Id);
// user from another network
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person24Id));
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person14Id, request.getId());
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
}
// cloud-2525
// unknown personId
try
{
log("cloud-2525");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
siteMembershipRequestsProxy.cancelSiteMembershipRequest(GUID.generate(), request.getId());
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
// cloud-2526
// cloud-2527
// unknown siteId
try
{
log("cloud-2526");
log("cloud-2527");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
SiteMembershipRequest request = new SiteMembershipRequest();
request.setId(GUID.generate());
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person14Id, request.getId());
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
// unknown request id
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person14Id, GUID.generate());
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
// PUTs
// cloud-2519 - PUT to site membership requests
try
{
log("cloud-2519");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
SiteMembershipRequest request = new SiteMembershipRequest();
request.setId(GUID.generate());
request.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.update("people", person11Id, "favorites", null, request.toJSON().toString(), "Unable to PUT site membership requests");
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
}
// cloud-2520 - unknown request/site id
try
{
log("cloud-2516");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
SiteMembershipRequest request = new SiteMembershipRequest();
request.setId(GUID.generate());
request.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.updateSiteMembershipRequest(person11Id, request);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
}
@Test
public void testValidRequests() throws Exception
{
final List<SiteMembershipRequest> expectedSiteMembershipRequests = new ArrayList<SiteMembershipRequest>();
{
// GET
// cloud-2531
// user has no site membership requests
{
log("cloud-2531");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
int skipCount = 0;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
}
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
int skipCount = 0;
Paging paging = getPaging(skipCount, null, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
}
// POSTs
// cloud-2502
// cloud-2510
{
log("cloud-2502");
log("cloud-2510");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// moderated site
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
final SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy.createSiteMembershipRequest("-me-", siteMembershipRequest);
expectedSiteMembershipRequests.add(moderatedSiteResponse);
siteMembershipRequest.expected(moderatedSiteResponse);
// public site
siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1PublicSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
SiteMembershipRequest ret = siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
siteMembershipRequest.expected(ret);
// test we have a moderated site request only
// cloud-2532
{
log("cloud-2532");
int skipCount = 0;
int maxItems = 4;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests, paging.getExpectedPaging(), resp);
}
// test against the underlying invitation service
List<Invitation> invitations = repoService.getModeratedSiteInvitations(network1.getId(), person11Id, person11Id, null);
assertEquals(1, invitations.size());
Invitation invitation = invitations.get(0);
assertTrue(invitation instanceof ModeratedInvitation);
ModeratedInvitation moderatedInvitation = (ModeratedInvitation)invitation;
String siteId = moderatedInvitation.getResourceName();
Invitation.InvitationType invitationType = moderatedInvitation.getInvitationType();
Invitation.ResourceType resourceType = moderatedInvitation.getResourceType();
String inviteeId = moderatedInvitation.getInviteeUserName();
assertEquals(person11Id, inviteeId);
assertEquals(Invitation.ResourceType.WEB_SITE, resourceType);
assertEquals(Invitation.InvitationType.MODERATED, invitationType);
assertEquals(person1ModeratedSites.get(0).getSiteId(), siteId);
// test that personId is a member of the public site
assertTrue(person1PublicSites.get(0).isMember(person11Id));
// cloud-2534
// approve the moderated site invitation and check that it is gone from the list
{
log("cloud-2534");
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
repoService.approveSiteInvitation(person11Id, moderatedSiteResponse.getId());
expectedSiteMembershipRequests.remove(0);
return null;
}
}, person12Id, network1.getId());
// make sure the outstanding request has gone
int skipCount = 0;
int maxItems = 4;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests, paging.getExpectedPaging(), resp);
}
}
// user from another network - un-authorised
try
{
log("cloud-2511");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person24Id));
// moderated site
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person24Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
}
// cloud-2512
// cloud-2535
// invitee from another network
{
log("cloud-2512");
log("cloud-2535");
log("cloud-2536");
final List<SiteMembershipRequest> person4ExpectedSiteMembershipRequests = new ArrayList<SiteMembershipRequest>();
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person24Id));
{
// public site
try
{
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1PublicSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person24Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
}
}
{
// moderated site
try
{
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person24Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
}
try
{
int skipCount = 0;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
siteMembershipRequestsProxy.getSiteMembershipRequests(person24Id, createParams(paging, null));
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
}
}
{
// private site
try
{
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1PrivateSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person24Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
}
try
{
int skipCount = 0;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
siteMembershipRequestsProxy.getSiteMembershipRequests(person24Id, createParams(paging, null));
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
}
}
}
// cloud-2513
try
{
log("cloud-2513");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// unknown site
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(GUID.generate());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// private site
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1PrivateSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// moderated site in another network
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person4ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
// cloud-2514
try
{
log("cloud-2514");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// already joined the site
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
}
try
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// already requested to join the site but not yet joined
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
}
// cloud-2538
// blank message
{
log("cloud-2538");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(1).getSiteId());
siteMembershipRequest.setMessage("");
SiteMembershipRequest ret = siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
expectedSiteMembershipRequests.add(ret);
}
// GETs
// cloud-2501
// cloud-2509
// test paging
{
log("cloud-2501");
log("cloud-2509");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// add some more site membership requests to moderated sites
for(int i = 1; i < person1ModeratedSites.size(); i++)
{
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(person1ModeratedSites.get(i).getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
try
{
SiteMembershipRequest ret = siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);
expectedSiteMembershipRequests.add(ret);
siteMembershipRequest.expected(ret);
}
catch(PublicApiException e)
{
// this is ok, already created
}
}
Collections.sort(expectedSiteMembershipRequests);
{
int skipCount = 0;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
skipCount = 2;
maxItems = 5;
paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
skipCount = 5;
maxItems = 10;
paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
skipCount = 0;
maxItems = expectedSiteMembershipRequests.size();
paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
}
// skipCount is greater than the number of site membership requests in the list
{
int skipCount = 1000;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(sublist(expectedSiteMembershipRequests, skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
}
// cloud-2537
// -me- user
{
log("cloud-2537");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
int skipCount = 0;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests("-me-", createParams(paging, null));
checkList(expectedSiteMembershipRequests.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
}
}
// DELETEs
// cloud-2504
{
log("cloud-2504");
SiteMembershipRequest request = getSiteMembershipRequest(network1.getId(), person11Id, person11Id);
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person11Id, request.getId());
expectedSiteMembershipRequests.remove(request);
Collections.sort(expectedSiteMembershipRequests);
// cloud-2533
// check that the site membership request has gone
log("cloud-2533");
int skipCount = 0;
int maxItems = Integer.MAX_VALUE;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests, paging.getExpectedPaging(), resp);
// cloud-2528
// try to cancel the same request
try
{
log("cloud-2528");
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person11Id, request.getId());
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
// cloud-2529
// cancel a site membership request that has been rejected
{
log("cloud-2529");
final String siteId = person1ModeratedSites.get(1).getSiteId();
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(siteId);
siteMembershipRequest.setMessage("Please can I join your site?");
SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id, siteMembershipRequest);
expectedSiteMembershipRequests.add(moderatedSiteResponse);
Collections.sort(expectedSiteMembershipRequests);
siteMembershipRequest.expected(moderatedSiteResponse);
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
Invitation invitation = repoService.rejectSiteInvitation(person14Id, siteId);
assertNotNull(invitation);
return null;
}
}, person12Id, network1.getId());
// try to cancel the request
try
{
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person14Id, siteId);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
// cloud-2530
// cancel a site membership request that has been approved
{
log("cloud-2530");
final String siteId = person1ModeratedSites.get(2).getSiteId();
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(siteId);
siteMembershipRequest.setMessage("Please can I join your site?");
SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id, siteMembershipRequest);
expectedSiteMembershipRequests.add(moderatedSiteResponse);
Collections.sort(expectedSiteMembershipRequests);
siteMembershipRequest.expected(moderatedSiteResponse);
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
Invitation invitation = repoService.approveSiteInvitation(person14Id, siteId);
assertNotNull(invitation);
return null;
}
}, person12Id, network1.getId());
// try to cancel the request
try
{
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person14Id, siteId);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
// PUTs
// cloud-2503
// cloud-2517
// cloud-2518
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
// merged these tests
// cloud-2503: use -me- pseudo user
// cloud-2517: initially no message
log("cloud-2503");
log("cloud-2517");
// create a request without a message
String siteId = person1ModeratedSites.get(7).getSiteId();
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(siteId);
SiteMembershipRequest request = siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id, siteMembershipRequest);
assertNotNull(request);
// update it, with a message
request.setMessage("Please can I join your site?");
SiteMembershipRequest updated = siteMembershipRequestsProxy.updateSiteMembershipRequest(person14Id, request);
request.expected(updated);
// check it's updated
int skipCount = 0;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person14Id, createParams(paging, null));
List<SiteMembershipRequest> requests = resp.getList();
assertTrue(requests.size() > 0);
int idx = requests.indexOf(request);
SiteMembershipRequest toCheck = requests.get(idx);
updated.expected(toCheck);
// cloud-2518
// update it again, with ammended message
log("cloud-2518");
request.setMessage("Please can I join your site, pretty please?");
updated = siteMembershipRequestsProxy.updateSiteMembershipRequest(person14Id, request);
request.expected(updated);
// check it's updated
skipCount = 0;
maxItems = 2;
paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person14Id, createParams(paging, null));
requests = resp.getList();
assertTrue(requests.size() > 0);
idx = requests.indexOf(request);
toCheck = requests.get(idx);
updated.expected(toCheck);
}
// cloud-2515 - no changes
{
log("cloud-2515");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
// create a request
String siteId = person1ModeratedSites.get(8).getSiteId();
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(siteId);
siteMembershipRequest.setMessage("Please can I join your site?");
SiteMembershipRequest request = siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id, siteMembershipRequest);
assertNotNull(request);
// update it, with no changes
SiteMembershipRequest updated = siteMembershipRequestsProxy.updateSiteMembershipRequest(person14Id, request);
request.expected(updated); // should not have changed
}
// cloud-2516 - unknown person id
try
{
log("cloud-2516");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
// get an outstanding request
int skipCount = 0;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id, createParams(paging, null));
List<SiteMembershipRequest> requests = resp.getList();
assertTrue(requests.size() > 0);
SiteMembershipRequest request = requests.get(0);
siteMembershipRequestsProxy.updateSiteMembershipRequest(GUID.generate(), request);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
// cloud-2521 - unknown site membership request
try
{
log("cloud-2521");
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
SiteMembershipRequest request = new SiteMembershipRequest();
request.setId(GUID.generate());
siteMembershipRequestsProxy.updateSiteMembershipRequest(person11Id, request);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
// cloud-2522
// update a site membership request that has been rejected
{
log("cloud-2522");
String siteId = person1ModeratedSites.get(5).getSiteId();
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(siteId);
siteMembershipRequest.setMessage("Please can I join your site?");
SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id, siteMembershipRequest);
expectedSiteMembershipRequests.add(moderatedSiteResponse);
Collections.sort(expectedSiteMembershipRequests);
siteMembershipRequest.expected(moderatedSiteResponse);
repoService.rejectSiteInvitation(person14Id, siteId);
// try to update the request
try
{
siteMembershipRequestsProxy.updateSiteMembershipRequest(siteId, moderatedSiteResponse);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
// cloud-2523
// update a site membership request that has been approved
{
log("cloud-2523");
String siteId = person1ModeratedSites.get(6).getSiteId();
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(siteId);
siteMembershipRequest.setMessage("Please can I join your site?");
SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id, siteMembershipRequest);
expectedSiteMembershipRequests.add(moderatedSiteResponse);
Collections.sort(expectedSiteMembershipRequests);
siteMembershipRequest.expected(moderatedSiteResponse);
repoService.approveSiteInvitation(person14Id, siteId);
// try to update the request
try
{
siteMembershipRequestsProxy.updateSiteMembershipRequest(siteId, moderatedSiteResponse);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
{
// cloud-2539 - probing attack tests
log("cloud-2539");
// i) create site membership request to a moderated site
// ii) site owner changes the site to a private site
// iii) re-issue create site membership request should be a 404
{
final List<SiteMembershipRequest> person2ExpectedSiteMembershipRequests = new ArrayList<SiteMembershipRequest>();
final TestSite site = person1ModeratedSites.get(0);
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(site.getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
site.setSiteVisibility(SiteVisibility.PRIVATE);
return null;
}
}, person12Id, network1.getId());
// Can we still GET it? Should be a 404 (private site)
try
{
siteMembershipRequestsProxy.getSiteMembershipRequest(person13Id, siteMembershipRequest.getId());
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
// GET should not contain the site
{
int skipCount = 0;
int maxItems = 10;
assertEquals(0, person2ExpectedSiteMembershipRequests.size());
Paging paging = getPaging(skipCount, maxItems, person2ExpectedSiteMembershipRequests.size(), person2ExpectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person13Id, createParams(paging, null));
checkList(sublist(person2ExpectedSiteMembershipRequests, skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
}
try
{
siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
// i) create site membership request to a public site
// ii) site owner changes the site to a private site
// iii) re-issue create site membership request should be a 404
{
final TestSite site = person1PublicSites.get(0);
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(site.getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
site.setSiteVisibility(SiteVisibility.PRIVATE);
return null;
}
}, person12Id, network1.getId());
try
{
siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
try
{
siteMembershipRequestsProxy.updateSiteMembershipRequest(person13Id, siteMembershipRequest);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
try
{
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person13Id, siteMembershipRequest.getId());
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
}
// i) create site membership request to a moderated site
// ii) site owner accepts the request -> user is now a member of the site
// iii) site owner changes the site to a private site
// iv) re-issue create site membership request should be a 404
{
final TestSite site = person1ModeratedSites.get(1);
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(site.getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);
// approve the site invitation request and convert the site to a private site
TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
repoService.approveSiteInvitation(person13Id, site.getSiteId());
site.setSiteVisibility(SiteVisibility.PRIVATE);
return null;
}
}, person12Id, network1.getId());
try
{
siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);
fail("");
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
// blank message in POST and PUT
{
final TestSite site = person1ModeratedSites.get(2);
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13Id));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(site.getSiteId());
siteMembershipRequest.setMessage("");
SiteMembershipRequest created = siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);
SiteMembershipRequest updated = siteMembershipRequestsProxy.updateSiteMembershipRequest(person13Id, siteMembershipRequest);
assertTrue(updated.getModifiedAt().after(created.getCreatedAt()));
}
}
}
// PUBLICAPI-126, PUBLICAPI-132
@Test
public void testMixedCase() throws Exception
{
final List<SiteMembershipRequest> expectedSiteMembershipRequests = new ArrayList<SiteMembershipRequest>();
{
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person15Id));
// moderated site
String siteId = person1MixedCaseModeratedSites.get(0).getSiteId().toLowerCase();
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(siteId); // lower case to test mixed case
siteMembershipRequest.setMessage("Please can I join your site?");
final SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy.createSiteMembershipRequest("-me-", siteMembershipRequest);
expectedSiteMembershipRequests.add(moderatedSiteResponse);
Collections.sort(expectedSiteMembershipRequests);
siteMembershipRequest.expected(moderatedSiteResponse);
int skipCount = 0;
int maxItems = 2;
Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(), expectedSiteMembershipRequests.size());
ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person15Id, createParams(paging, null));
checkList(expectedSiteMembershipRequests.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
SiteMembershipRequest ret = siteMembershipRequestsProxy.getSiteMembershipRequest(person15Id, siteId);
siteMembershipRequest.expected(ret);
siteMembershipRequestsProxy.cancelSiteMembershipRequest(person15Id, ret.getId());
try
{
siteMembershipRequestsProxy.getSiteMembershipRequest(person15Id, siteId);
fail();
}
catch(PublicApiException e)
{
assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
}
}
}
@Test
public void testALF19332() throws Exception
{
String networkId = network1.getId();
final TestNetwork systemNetwork = getRepoService().getSystemNetwork();
long time = System.currentTimeMillis();
// note: username for site creator is of the form user@network
PersonInfo personInfo = new PersonInfo("test", "test", "test" + time, "password", null, "test", "test", "test", "test", "test", "test");
TestPerson person = network1.createUser(personInfo);
personInfo = new PersonInfo("test", "test", "test1" + time, "password", null, "test", "test", "test", "test", "test", "test");
TestPerson person1 = network1.createUser(personInfo);
TestSite site = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>()
{
@Override
public TestSite doWork() throws Exception
{
TestSite site = systemNetwork.createSite(SiteVisibility.PUBLIC);
return site;
}
}, person.getId(), networkId);
publicApiClient.setRequestContext(new RequestContext("-default-", person1.getId()));
SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
siteMembershipRequest.setId(site.getSiteId());
siteMembershipRequest.setMessage("Please can I join your site?");
SiteMembershipRequest ret = siteMembershipRequestsProxy.createSiteMembershipRequest(person1.getId(), siteMembershipRequest);
}
}
| lgpl-3.0 |
sidohaakma/molgenis | molgenis-data-index/src/main/java/org/molgenis/data/index/IndexedRepositoryDecorator.java | 6957 | package org.molgenis.data.index;
import static java.lang.String.format;
import static java.util.Collections.unmodifiableSet;
import static java.util.Objects.requireNonNull;
import static org.molgenis.data.QueryUtils.containsAnyOperator;
import static org.molgenis.data.QueryUtils.containsComputedAttribute;
import static org.molgenis.data.QueryUtils.containsNestedQueryRuleField;
import static org.molgenis.data.RepositoryCapability.AGGREGATEABLE;
import static org.molgenis.data.RepositoryCapability.QUERYABLE;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.molgenis.data.AbstractRepositoryDecorator;
import org.molgenis.data.Entity;
import org.molgenis.data.MolgenisDataException;
import org.molgenis.data.Query;
import org.molgenis.data.QueryRule.Operator;
import org.molgenis.data.Repository;
import org.molgenis.data.RepositoryCapability;
import org.molgenis.data.aggregation.AggregateQuery;
import org.molgenis.data.aggregation.AggregateResult;
import org.molgenis.data.index.exception.UnknownIndexException;
import org.molgenis.data.index.job.IndexJobScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Decorator for indexed repositories. Sends all queries with operators that are not supported by
* the decorated repository to the index.
*/
class IndexedRepositoryDecorator extends AbstractRepositoryDecorator<Entity> {
private static final Logger LOG = LoggerFactory.getLogger(IndexedRepositoryDecorator.class);
private static final String INDEX_REPOSITORY = "Index Repository";
private static final String DECORATED_REPOSITORY = "Decorated Repository";
private final SearchService searchService;
private final IndexJobScheduler indexJobScheduler;
/** Operators NOT supported by the decorated repository. */
private final Set<Operator> unsupportedOperators;
IndexedRepositoryDecorator(
Repository<Entity> delegateRepository,
SearchService searchService,
IndexJobScheduler indexJobScheduler) {
super(delegateRepository);
this.searchService = requireNonNull(searchService);
this.indexJobScheduler = requireNonNull(indexJobScheduler);
Set<Operator> operators = getQueryOperators();
operators.removeAll(delegate().getQueryOperators());
unsupportedOperators = Collections.unmodifiableSet(operators);
}
@Override
public Entity findOne(Query<Entity> q) {
if (querySupported(q)) {
LOG.debug(
"public Entity findOne({}) entityTypeId: [{}] repository: [{}]",
q,
getEntityType().getId(),
DECORATED_REPOSITORY);
return delegate().findOne(q);
} else {
LOG.debug(
"public Entity findOne({}) entityTypeId: [{}] repository: [{}]",
q,
getEntityType().getId(),
INDEX_REPOSITORY);
Object entityId = tryTwice(() -> searchService.searchOne(getEntityType(), q));
return entityId != null ? delegate().findOneById(entityId, q.getFetch()) : null;
}
}
@Override
public Stream<Entity> findAll(Query<Entity> q) {
if (querySupported(q)) {
LOG.debug(
"public Entity findAll({}) entityTypeId: [{}] repository: [{}]",
q,
getEntityType().getId(),
DECORATED_REPOSITORY);
return delegate().findAll(q);
} else {
LOG.debug(
"public Entity findAll({}) entityTypeId: [{}] repository: [{}]",
q,
getEntityType().getId(),
INDEX_REPOSITORY);
Stream<Object> entityIds = tryTwice(() -> searchService.search(getEntityType(), q));
return delegate().findAll(entityIds, q.getFetch());
}
}
/**
* Gets the capabilities of the underlying repository and adds three read capabilities provided by
* the index: {@link RepositoryCapability#INDEXABLE}, {@link RepositoryCapability#QUERYABLE} and
* {@link RepositoryCapability#AGGREGATEABLE}. Does not add other index capabilities like{@link
* RepositoryCapability#WRITABLE} because those might conflict with the underlying repository.
*/
@Override
public Set<RepositoryCapability> getCapabilities() {
Set<RepositoryCapability> capabilities = new HashSet<>();
capabilities.addAll(delegate().getCapabilities());
capabilities.addAll(EnumSet.of(QUERYABLE, AGGREGATEABLE));
return unmodifiableSet(capabilities);
}
@Override
public Set<Operator> getQueryOperators() {
return EnumSet.allOf(Operator.class);
}
@Override
public long count(Query<Entity> q) {
// TODO check if the index is stable. If index is stable you can better check index for count
// results
if (querySupported(q)) {
LOG.debug(
"public long count({}) entityTypeId: [{}] repository: [{}]",
q,
getEntityType().getId(),
DECORATED_REPOSITORY);
return delegate().count(q);
} else {
LOG.debug(
"public long count({}) entityTypeId: [{}] repository: [{}]",
q,
getEntityType().getId(),
INDEX_REPOSITORY);
return tryTwice(() -> searchService.count(getEntityType(), q));
}
}
@Override
public AggregateResult aggregate(AggregateQuery aggregateQuery) {
return tryTwice(() -> searchService.aggregate(getEntityType(), aggregateQuery));
}
/**
* Executes an action on an index that may be unstable.
*
* <p>If the Index was unknown, waits for the index to be stable and then tries again.
*
* @param action the action that gets executed
* @param <R> the result type of the action
* @return the result
* @throws MolgenisDataException if the action still failed when the index was stable, with a
* translated error message.
*/
private <R> R tryTwice(Supplier<R> action) {
try {
return action.get();
} catch (UnknownIndexException e) {
waitForIndexToBeStable();
try {
return action.get();
} catch (UnknownIndexException e1) {
throw new MolgenisDataException(
format(
"Error executing query, index for entity type '%s' with id '%s' does not exist",
getEntityType().getLabel(), getEntityType().getId()));
}
}
}
/**
* Checks if the underlying repository can handle this query. Queries with unsupported operators,
* queries that use attributes with computed values or queries with nested query rule field are
* delegated to the index.
*/
private boolean querySupported(Query<Entity> q) {
return !containsAnyOperator(q, unsupportedOperators)
&& !containsComputedAttribute(q, getEntityType())
&& !containsNestedQueryRuleField(q);
}
private void waitForIndexToBeStable() {
try {
indexJobScheduler.waitForIndexToBeStableIncludingReferences(getEntityType());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| lgpl-3.0 |
joerivandervelde/molgenis | molgenis-integration-tests/src/test/java/org/molgenis/integrationtest/data/mysql/MySqlDatetimeDatatypeIT.java | 767 | package org.molgenis.integrationtest.data.mysql;
import org.molgenis.integrationtest.data.AbstractDatetimeDatatypeIT;
import org.molgenis.integrationtest.data.myqsl.AbstractMySqlTestConfig;
import org.molgenis.integrationtest.data.mysql.MySqlDatetimeDatatypeIT.DatetimeMySqlTestConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.Test;
@ContextConfiguration(classes = DatetimeMySqlTestConfig.class)
public class MySqlDatetimeDatatypeIT extends AbstractDatetimeDatatypeIT
{
@Configuration
public static class DatetimeMySqlTestConfig extends AbstractMySqlTestConfig
{
}
@Override
@Test
public void testIt() throws Exception
{
super.testIt();
}
}
| lgpl-3.0 |
MesquiteProject/MesquiteCore | LibrarySource/com/lowagie/text/pdf/codec/postscript/PAToken.java | 1979 | /*
* Copyright 1998 by Sun Microsystems, Inc.,
* 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
* All rights reserved.
*
* This software is the confidential and proprietary information
* of Sun Microsystems, Inc. ("Confidential Information"). You
* shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement
* you entered into with Sun.
*/
package com.lowagie.text.pdf.codec.postscript;
import java.lang.*;
import java.lang.reflect.*;
import java.util.*;
import headless.awt.*;
import headless.awt.geom.*;
import headless.awt.color.*;
import headless.awt.font.*;
public class PAToken extends Object {
static public final int IDENTIFIER = 0;
static public final int KEY = 1;
static public final int PROCEDURE = 2;
static public final int MARK = 3;
static public final int START_PROCEDURE = 4;
static public final int END_PROCEDURE = 5;
static public final int IMMEDIATE = 6;
static public final int START_ARRAY = 7;
static public final int END_ARRAY = 8;
public Object value;
public int type;
public PAToken(Object value, int type){
super();
this.value = value;
this.type = type;
}
public String toString(){
switch(this.type){
case IDENTIFIER:
return "IDENTIFIER " + this.value.toString();
case KEY:
return "KEY " + this.value.toString();
case PROCEDURE:
return "PROCEDURE " + this.value.toString();
case MARK:
return "MARK";
case START_PROCEDURE:
return "START_PROCEDURE";
case END_PROCEDURE:
return "END_PROCEDURE";
case IMMEDIATE:
return "IMMEDIATE " + this.value.toString();
case START_ARRAY:
return "START_ARRAY";
case END_ARRAY:
return "END_ARRAY";
}
return this.value.toString();
}
}
| lgpl-3.0 |
akdasari/SparkAdmin | spark-admin-module/src/main/java/org/sparkcommerce/admin/server/service/handler/ChildCategoriesCustomPersistenceHandler.java | 4164 | /*
* #%L
* SparkCommerce Admin Module
* %%
* Copyright (C) 2009 - 2013 Spark Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.sparkcommerce.admin.server.service.handler;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.sparkcommerce.common.exception.ServiceException;
import org.sparkcommerce.common.presentation.client.OperationType;
import org.sparkcommerce.common.presentation.client.PersistencePerspectiveItemType;
import org.sparkcommerce.core.catalog.domain.Category;
import org.sparkcommerce.core.catalog.domain.CategoryImpl;
import org.sparkcommerce.core.catalog.domain.CategoryXref;
import org.sparkcommerce.core.catalog.domain.CategoryXrefImpl;
import org.sparkcommerce.openadmin.dto.AdornedTargetList;
import org.sparkcommerce.openadmin.dto.Entity;
import org.sparkcommerce.openadmin.dto.PersistencePackage;
import org.sparkcommerce.openadmin.server.dao.DynamicEntityDao;
import org.sparkcommerce.openadmin.server.service.handler.CustomPersistenceHandlerAdapter;
import org.sparkcommerce.openadmin.server.service.persistence.module.RecordHelper;
import org.springframework.stereotype.Component;
/**
* @author Jeff Fischer
*/
@Component("blChildCategoriesCustomPersistenceHandler")
public class ChildCategoriesCustomPersistenceHandler extends CustomPersistenceHandlerAdapter {
@Override
public Boolean canHandleAdd(PersistencePackage persistencePackage) {
return (!ArrayUtils.isEmpty(persistencePackage.getCustomCriteria()) && persistencePackage.getCustomCriteria()[0].equals("blcAllParentCategories"));
}
@Override
public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
AdornedTargetList adornedTargetList = (AdornedTargetList) persistencePackage.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST);
String targetPath = adornedTargetList.getTargetObjectPath() + "." + adornedTargetList.getTargetIdProperty();
String linkedPath = adornedTargetList.getLinkedObjectPath() + "." + adornedTargetList.getLinkedIdProperty();
Long parentId = Long.parseLong(persistencePackage.getEntity().findProperty(linkedPath).getValue());
Long childId = Long.parseLong(persistencePackage.getEntity().findProperty(targetPath).getValue());
Category parent = (Category) dynamicEntityDao.retrieve(CategoryImpl.class, parentId);
Category child = (Category) dynamicEntityDao.retrieve(CategoryImpl.class, childId);
CategoryXref categoryXref = new CategoryXrefImpl();
categoryXref.setSubCategory(child);
categoryXref.setCategory(parent);
if (parent.getAllChildCategoryXrefs().contains(categoryXref)) {
throw new ServiceException("Add unsuccessful. Cannot add a duplicate child category.");
}
checkParents(child, parent);
return helper.getCompatibleModule(OperationType.ADORNEDTARGETLIST).add(persistencePackage);
}
protected void checkParents(Category child, Category parent) throws ServiceException {
if (child.getId().equals(parent.getId())) {
throw new ServiceException("Add unsuccessful. Cannot add a category to itself.");
}
for (CategoryXref category : parent.getAllParentCategoryXrefs()) {
if (!CollectionUtils.isEmpty(category.getCategory().getAllParentCategoryXrefs())) {
checkParents(child, category.getCategory());
}
}
}
}
| apache-2.0 |
aozisik/Android-SDK | library/src/androidTest/java/com/baasbox/android/test/TestSignup.java | 2401 | /*
* Copyright (C) 2014. BaasBox
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.baasbox.android.test;
import com.baasbox.android.*;
import com.baasbox.android.test.common.BaasTestBase;
/**
* Created by Andrea Tortorella on 05/02/14.
*/
public class TestSignup extends BaasTestBase {
private static final String USER_NAME="username";
private static final String USER_PASSWORD ="userpass";
@Override
protected void beforeTest() throws Exception {
super.beforeTest();
resetDb();
}
public void testPreconditions(){
assertNotNull("baasbox not initialized",box);
}
public void testSignupNewUser(){
RequestToken token= BaasUser.withUserName(USER_NAME)
.setPassword(USER_PASSWORD)
.signup(new BaasHandler<BaasUser>() {
@Override
public void handle(BaasResult<BaasUser> result) {
}
});
BaasResult<BaasUser> await = token.await();
try {
BaasUser user = await.get();
assertNotNull(BaasUser.current());
assertEquals(user, BaasUser.current());
} catch (BaasException e) {
fail(e.toString());
}
}
public void testSignupExistingShouldFail(){
BaasResult<BaasUser> precedingUser = BaasUser.withUserName(USER_NAME)
.setPassword(USER_PASSWORD)
.signupSync();
if (precedingUser.isSuccess()){
BaasResult<BaasUser> await = BaasUser.withUserName(USER_NAME)
.setPassword(USER_PASSWORD)
.signup(BaasHandler.NOOP)
.await();
assertFalse(await.isSuccess());
} else {
fail("unable to create first user");
}
}
}
| apache-2.0 |
bzz/kythe | kythe/java/com/google/devtools/kythe/util/SourceBuilder.java | 4290 | /*
* Copyright 2017 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.kythe.util;
import com.google.common.collect.Sets;
import com.google.devtools.kythe.proto.Internal.Source;
import com.google.devtools.kythe.proto.Storage.Entry;
import com.google.devtools.kythe.proto.Storage.VName;
import com.google.protobuf.ByteString;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Accumulates facts and edges from {@link Entry} messages sharing the same source {@link VName}
* into a {@link Source} message.
*/
public class SourceBuilder {
private static final Pattern ORDINAL_EDGE_KIND_PATTERN = Pattern.compile("^(.+)\\.(\\d+)$");
private static final Comparator<Source.Edge> EDGE_ORDER =
Comparator.comparing(Source.Edge::getOrdinal).thenComparing(Source.Edge::getTicket);
private final Map<String, ByteString> facts = new HashMap<>();
private final Map<String, Set<Source.Edge>> edgeGroups = new HashMap<>();
/** Constructs an empty {@link SourceBuilder}. */
public SourceBuilder() {}
/**
* Constructs a {@link SourceBuilder} initialized with the edges and facts from the given {@link
* Source}.
*/
public SourceBuilder(Source src) {
src.getFactsMap().forEach(facts::put);
src.getEdgeGroupsMap()
.forEach((kind, edges) -> edgeGroups.put(kind, Sets.newHashSet(edges.getEdgesList())));
}
/**
* Add a single fact to {@link Source} being built. If two facts are given with the same {@code
* name}, only the latter fact value is kept.
*/
public SourceBuilder addFact(String name, ByteString value) {
facts.put(name, value);
return this;
}
/**
* Add a single edge to {@link Source} being built. If the edge has already been added, this is a
* no-op.
*/
public SourceBuilder addEdge(String edgeKind, VName target) {
Source.Edge.Builder edge = Source.Edge.newBuilder().setTicket(KytheURI.asString(target));
Matcher m = ORDINAL_EDGE_KIND_PATTERN.matcher(edgeKind);
if (m.matches()) {
edgeKind = m.group(1);
try {
edge.setOrdinal(Integer.parseInt(m.group(2)));
} catch (NumberFormatException nfe) {
throw new IllegalStateException(nfe);
}
}
edgeGroups.computeIfAbsent(edgeKind, k -> new HashSet<>()).add(edge.build());
return this;
}
/**
* Adds the given {@link Entry} fact or edge to the {@link Source} being built. The source {@link
* VName} of the {@link Entry} is ignored and assumed to be the same amongst all {@link Entry}
* messages being added.
*
* @see addFact(String, ByteString)
* @see addEdge(String, VName)
*/
public SourceBuilder addEntry(Entry e) {
if (e.getEdgeKind().isEmpty()) {
return addFact(e.getFactName(), e.getFactValue());
} else {
return addEdge(e.getEdgeKind(), e.getTarget());
}
}
/** Returns the accumulated {@link Source}. */
public Source build() {
Source.Builder builder = Source.newBuilder();
facts.forEach(builder::putFacts);
edgeGroups.forEach(
(kind, edges) -> {
Source.EdgeGroup.Builder group = Source.EdgeGroup.newBuilder();
edges.stream().sorted(EDGE_ORDER).forEach(group::addEdges);
builder.putEdgeGroups(kind, group.build());
});
return builder.build();
}
/** Adds all facts and edges from the given {@link SourceBuilder} into {@code this}. */
public void mergeWith(SourceBuilder o) {
this.facts.putAll(o.facts);
o.edgeGroups.forEach(
(kind, edges) -> this.edgeGroups.computeIfAbsent(kind, k -> new HashSet<>()).addAll(edges));
}
}
| apache-2.0 |
msebire/intellij-community | platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarModelBuilderImpl.java | 2024 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.navigationToolbar;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiCompiledElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilCore;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Set;
public class NavBarModelBuilderImpl extends NavBarModelBuilder {
@Override
public void traverseToRoot(@NotNull PsiElement psiElement, @NotNull Set<VirtualFile> roots, @NotNull List<Object> model) {
List<NavBarModelExtension> extensions = NavBarModelExtension.EP_NAME.getExtensionList();
for (PsiElement e = normalize(psiElement), next = null; e != null; e = normalize(next), next = null) {
// check if we're running circles due to getParent()->normalize/adjust()
if (model.contains(e)) break;
model.add(e);
// check if a root is reached
VirtualFile vFile = PsiUtilCore.getVirtualFile(e);
if (roots.contains(vFile)) break;
for (NavBarModelExtension ext : extensions) {
PsiElement parent = ext.getParent(e);
if (parent != null && parent != e) {
//noinspection AssignmentToForLoopParameter
next = parent;
break;
}
}
}
}
@Nullable
protected static PsiElement normalize(@Nullable PsiElement e) {
return NavBarModel.normalize(getOriginalElement(e));
}
@Nullable
private static PsiElement getOriginalElement(@Nullable PsiElement e) {
if (e == null || !e.isValid()) return null;
PsiFile containingFile = e.getContainingFile();
if (containingFile != null && containingFile.getVirtualFile() == null) return null;
PsiElement orig = e.getOriginalElement();
return !(e instanceof PsiCompiledElement) && orig instanceof PsiCompiledElement ? e : orig;
}
}
| apache-2.0 |
llvasconcellos/client | app/src/main/java/org/projectbuendia/client/net/OpenMrsXformsConnection.java | 8116 | // Copyright 2015 The Project Buendia Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distrib-
// uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied. See the License for
// specific language governing permissions and limitations under the License.
package org.projectbuendia.client.net;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.projectbuendia.client.utils.Logger;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
/**
* A connection to the module deployed in OpenMRS to provide xforms (which is part of the Buendia
* API module). This is not part of OpenMrsServer as it has entirely its own interface, but should
* be merged in the future.
*/
public class OpenMrsXformsConnection {
private static final Logger LOG = Logger.create();
private final OpenMrsConnectionDetails mConnectionDetails;
public OpenMrsXformsConnection(OpenMrsConnectionDetails connection) {
this.mConnectionDetails = connection;
}
/**
* Get a single (full) Xform from the OpenMRS server.
* @param uuid the uuid of the form to fetch
* @param resultListener the listener to be informed of the form asynchronously
* @param errorListener a listener to be informed of any errors
*/
public void getXform(String uuid, final Response.Listener<String> resultListener,
Response.ErrorListener errorListener) {
Request request = new OpenMrsJsonRequest(mConnectionDetails,
"/xforms/" + uuid + "?v=full",
null, // null implies GET
new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject response) {
try {
String xml = response.getString("xml");
resultListener.onResponse(xml);
} catch (JSONException e) {
// The result was not in the expected format. Just log, and return
// results so far.
LOG.e(e, "response was in bad format: " + response);
}
}
}, errorListener
);
// Typical response times should be close to 10s, but as the number of users grows, this
// number scales up quickly, so use a 30s timeout to be safe.
request.setRetryPolicy(new DefaultRetryPolicy(Common.REQUEST_TIMEOUT_MS_MEDIUM, 1, 1f));
mConnectionDetails.getVolley().addToRequestQueue(request);
}
/**
* List all xforms on the server, but not their contents.
* @param listener a listener to be told about the index entries for all forms asynchronously.
* @param errorListener a listener to be told about any errors.
*/
public void listXforms(final Response.Listener<List<OpenMrsXformIndexEntry>> listener,
final Response.ErrorListener errorListener) {
Request request = new OpenMrsJsonRequest(mConnectionDetails, "/xforms", // list all forms
null, // null implies GET
new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject response) {
LOG.i("got forms: " + response);
ArrayList<OpenMrsXformIndexEntry> result = new ArrayList<>();
try {
// This seems quite code heavy (parsing manually), but is reasonably
// efficient as we only look at the fields we need, so we are robust to
// changes in the rest of the object.
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject entry = results.getJSONObject(i);
// Sometimes date_changed is not set; in this case, date_changed is
// simply date_created.
long dateChanged;
if (entry.get("date_changed") == JSONObject.NULL) {
dateChanged = entry.getLong("date_created");
} else {
dateChanged = entry.getLong("date_changed");
}
OpenMrsXformIndexEntry indexEntry = new OpenMrsXformIndexEntry(
entry.getString("uuid"),
entry.getString("name"),
dateChanged);
result.add(indexEntry);
}
} catch (JSONException e) {
// The result was not in the expected format. Just log, and return
// results so far.
LOG.e(e, "response was in bad format: " + response);
}
LOG.i("returning response: " + response);
listener.onResponse(result);
}
},
errorListener
);
request.setRetryPolicy(new DefaultRetryPolicy(Common.REQUEST_TIMEOUT_MS_MEDIUM, 1, 1f));
mConnectionDetails.getVolley().addToRequestQueue(request);
}
/**
* Send a single Xform to the OpenMRS server.
* @param patientUuid null if this is to add a new patient, non-null for observation on existing
* patient
* @param resultListener the listener to be informed of the form asynchronously
* @param errorListener a listener to be informed of any errors
*/
public void postXformInstance(
@Nullable String patientUuid,
String xform,
final Response.Listener<JSONObject> resultListener,
Response.ErrorListener errorListener) {
// The JsonObject members in the API as written at the moment.
// int "patient_id"
// int "enterer_id"
// String "date_entered" in ISO8601 format (1977-01-10T
// String "xml" the form.
JsonObject post = new JsonObject();
post.addProperty("xml", xform);
// Don't add patient property for create new patient
if (patientUuid != null) {
post.addProperty("patient_uuid", patientUuid);
}
// TODO: get the enterer from the user login
post.addProperty("enterer_id", 1);
post.addProperty("date_entered", ISODateTimeFormat.dateTime().print(new DateTime()));
JSONObject postBody = null;
try {
postBody = new JSONObject(post.toString());
} catch (JSONException e) {
LOG.e(e, "This should never happen converting one JSON object to another. " + post);
errorListener.onErrorResponse(new VolleyError("failed to convert to JSON", e));
}
OpenMrsJsonRequest request = new OpenMrsJsonRequest(
mConnectionDetails, "/xforminstances",
postBody, // non-null implies POST
new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject response) {
resultListener.onResponse(response);
}
}, errorListener
);
// Set a permissive timeout.
request.setRetryPolicy(new DefaultRetryPolicy(Common.REQUEST_TIMEOUT_MS_MEDIUM, 1, 1f));
mConnectionDetails.getVolley().addToRequestQueue(request);
}
}
| apache-2.0 |
microprofile/microprofile-conference | web-application/src/main/local/java/io/microprofile/showcase/web/Endpoints.java | 2816 | /*
* Copyright(c) 2016-2017 IBM, Red Hat, and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.microprofile.showcase.web;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Simple wrapper for named application endpoints
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Endpoints implements Serializable {
private static final long serialVersionUID = -7130557896231134141L;
private Set<Endpoint> endpoints;
private String application;
//TODO @XmlElement(name = "_links") Who cam up with this name? It just causes a whole world of serialization and config issues
private Map<String, URI> links = new HashMap<>();
public Set<Endpoint> getEndpoints() {
return this.endpoints;
}
public void setEndpoints(final Set<Endpoint> endpoints) {
this.endpoints = endpoints;
}
public void setApplication(final String application) {
this.application = application;
}
public String getApplication() {
return this.application;
}
public Map<String, URI> getLinks() {
return this.links;
}
public void setLinks(final Map<String, URI> links) {
this.links = links;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
final Endpoints endpoints = (Endpoints) o;
return new EqualsBuilder()
.append(this.application, endpoints.application)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(this.application)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("application", this.application)
.toString();
}
}
| apache-2.0 |
tectronics/splinelibrary | 2.3/src/org/drip/spline/stretch/MultiSegmentSequenceBuilder.java | 19430 |
package org.drip.spline.stretch;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2014 Lakshmi Krishnamurthy
* Copyright (C) 2013 Lakshmi Krishnamurthy
*
* This file is part of DRIP, a free-software/open-source library for fixed income analysts and developers -
* http://www.credit-trader.org/Begin.html
*
* DRIP is a free, full featured, fixed income rates, credit, and FX analytics library with a focus towards
* pricing/valuation, risk, and market making.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* MultiSegmentSequenceBuilder exports Stretch creation/calibration methods to generate customized basis
* splines, with customized segment behavior using the segment control. It exports the following
* method of Stretch Creation:
* - Create an uncalibrated Stretch instance over the specified Predictor Ordinate Array using the specified
* Basis Spline Parameters for the Segment.
* - Create a calibrated Stretch Instance over the specified array of Predictor Ordinates and Response
* Values using the specified Basis Splines.
* - Create a calibrated Stretch Instance over the specified Predictor Ordinates, Response Values, and their
* Constraints, using the specified Segment Builder Parameters.
* - Create a Calibrated Stretch Instance from the Array of Predictor Ordinates and a flat Response Value.
* - Create a Regression Spline Instance over the specified array of Predictor Ordinate Knot Points and the
* Set of the Points to be Best Fit.
*
* @author Lakshmi Krishnamurthy
*/
public class MultiSegmentSequenceBuilder {
/**
* Polynomial Spline
*/
public static final java.lang.String BASIS_SPLINE_POLYNOMIAL = "Polynomial";
/**
* Bernstein Polynomial Spline
*/
public static final java.lang.String BASIS_SPLINE_BERNSTEIN_POLYNOMIAL = "BernsteinPolynomial";
/**
* Hyperbolic Tension Spline
*/
public static final java.lang.String BASIS_SPLINE_HYPERBOLIC_TENSION = "HyperbolicTension";
/**
* Exponential Tension Spline
*/
public static final java.lang.String BASIS_SPLINE_EXPONENTIAL_TENSION = "ExponentialTension";
/**
* Kaklis Pandelis Spline
*/
public static final java.lang.String BASIS_SPLINE_KAKLIS_PANDELIS = "KaklisPandelis";
/**
* Exponential Rational Basis Spline
*/
public static final java.lang.String BASIS_SPLINE_EXPONENTIAL_RATIONAL = "ExponentialRational";
/**
* Exponential Mixture Basis Spline
*/
public static final java.lang.String BASIS_SPLINE_EXPONENTIAL_MIXTURE = "ExponentialMixture";
/**
* Koch-Lyche-Kvasov Exponential Tension Spline
*/
public static final java.lang.String BASIS_SPLINE_KLK_EXPONENTIAL_TENSION = "KLKExponentialTension";
/**
* Koch-Lyche-Kvasov Hyperbolic Tension Spline
*/
public static final java.lang.String BASIS_SPLINE_KLK_HYPERBOLIC_TENSION = "KLKHyperbolicTension";
/**
* Koch-Lyche-Kvasov Rational Linear Tension Spline
*/
public static final java.lang.String BASIS_SPLINE_KLK_RATIONAL_LINEAR_TENSION = "KLKRationalLinearTension";
/**
* Koch-Lyche-Kvasov Rational Quadratic Tension Spline
*/
public static final java.lang.String BASIS_SPLINE_KLK_RATIONAL_QUADRATIC_TENSION = "KLKRationalQuadraticTension";
/**
* Create an uncalibrated Stretch instance over the specified Predictor Ordinate Array using the
* specified Basis Spline Parameters for the Segment.
*
* @param adblPredictorOrdinate Predictor Ordinate Array
* @param aSCBC Array of Segment Builder Parameters
*
* @return Stretch instance
*/
public static final org.drip.spline.segment.ConstitutiveState[] CreateSegmentSet (
final double[] adblPredictorOrdinate,
final org.drip.spline.params.SegmentCustomBuilderControl[] aSCBC)
{
if (null == adblPredictorOrdinate || null == aSCBC) return null;
int iNumSegment = adblPredictorOrdinate.length - 1;
if (1 > iNumSegment || iNumSegment != aSCBC.length) return null;
org.drip.spline.segment.ConstitutiveState[] aCS = new
org.drip.spline.segment.ConstitutiveState[iNumSegment];
for (int i = 0; i < iNumSegment; ++i) {
if (null == aSCBC[i]) return null;
java.lang.String strBasisSpline = aSCBC[i].basisSpline();
if (null == strBasisSpline || (!BASIS_SPLINE_POLYNOMIAL.equalsIgnoreCase (strBasisSpline) &&
!BASIS_SPLINE_BERNSTEIN_POLYNOMIAL.equalsIgnoreCase (strBasisSpline) &&
!BASIS_SPLINE_HYPERBOLIC_TENSION.equalsIgnoreCase (strBasisSpline) &&
!BASIS_SPLINE_EXPONENTIAL_TENSION.equalsIgnoreCase (strBasisSpline) &&
!BASIS_SPLINE_KAKLIS_PANDELIS.equalsIgnoreCase (strBasisSpline) &&
!BASIS_SPLINE_EXPONENTIAL_RATIONAL.equalsIgnoreCase (strBasisSpline) &&
!BASIS_SPLINE_EXPONENTIAL_MIXTURE.equalsIgnoreCase (strBasisSpline) &&
!BASIS_SPLINE_KLK_EXPONENTIAL_TENSION.equalsIgnoreCase
(strBasisSpline) &&
!BASIS_SPLINE_KLK_HYPERBOLIC_TENSION.equalsIgnoreCase
(strBasisSpline) &&
!BASIS_SPLINE_KLK_RATIONAL_LINEAR_TENSION.equalsIgnoreCase
(strBasisSpline) && !BASIS_SPLINE_KLK_RATIONAL_QUADRATIC_TENSION.equalsIgnoreCase
(strBasisSpline)))
return null;
if (BASIS_SPLINE_POLYNOMIAL.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.basis.FunctionSetBuilder.PolynomialBasisSet
((org.drip.spline.basis.PolynomialFunctionSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_BERNSTEIN_POLYNOMIAL.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.basis.FunctionSetBuilder.BernsteinPolynomialBasisSet
((org.drip.spline.basis.PolynomialFunctionSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_HYPERBOLIC_TENSION.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.basis.FunctionSetBuilder.HyperbolicTensionBasisSet
((org.drip.spline.basis.ExponentialTensionSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_EXPONENTIAL_TENSION.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.basis.FunctionSetBuilder.ExponentialTensionBasisSet
((org.drip.spline.basis.ExponentialTensionSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_KAKLIS_PANDELIS.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.basis.FunctionSetBuilder.KaklisPandelisBasisSet
((org.drip.spline.basis.KaklisPandelisSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_EXPONENTIAL_RATIONAL.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.basis.FunctionSetBuilder.ExponentialRationalBasisSet
((org.drip.spline.basis.ExponentialRationalSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_EXPONENTIAL_MIXTURE.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.basis.FunctionSetBuilder.ExponentialMixtureBasisSet
((org.drip.spline.basis.ExponentialMixtureSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_KLK_EXPONENTIAL_TENSION.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.tension.KochLycheKvasovFamily.FromExponentialPrimitive
((org.drip.spline.basis.ExponentialTensionSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_KLK_HYPERBOLIC_TENSION.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.tension.KochLycheKvasovFamily.FromHyperbolicPrimitive
((org.drip.spline.basis.ExponentialTensionSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_KLK_RATIONAL_LINEAR_TENSION.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.tension.KochLycheKvasovFamily.FromRationalLinearPrimitive
((org.drip.spline.basis.ExponentialTensionSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
} else if (BASIS_SPLINE_KLK_RATIONAL_QUADRATIC_TENSION.equalsIgnoreCase (strBasisSpline)) {
if (null == (aCS[i] = org.drip.spline.segment.ConstitutiveState.Create
(adblPredictorOrdinate[i], adblPredictorOrdinate[i + 1],
org.drip.spline.tension.KochLycheKvasovFamily.FromRationalQuadraticPrimitive
((org.drip.spline.basis.ExponentialTensionSetParams) aSCBC[i].basisSetParams()),
aSCBC[i].shapeController(), aSCBC[i].inelasticParams())))
return null;
}
}
return aCS;
}
/**
* Create an uncalibrated Stretch instance over the specified Predictor Ordinate Array using the specified
* Basis Spline Parameters for the Segment.
*
* @param strName Name of the Stretch
* @param adblPredictorOrdinate Predictor Ordinate Array
* @param aSCBC Array of Segment Builder Parameters
*
* @return Stretch instance
*/
public static final org.drip.spline.stretch.MultiSegmentSequence CreateUncalibratedStretchEstimator (
final java.lang.String strName,
final double[] adblPredictorOrdinate,
final org.drip.spline.params.SegmentCustomBuilderControl[] aSCBC)
{
try {
return new org.drip.spline.stretch.CalibratableMultiSegmentSequence (strName, CreateSegmentSet
(adblPredictorOrdinate, aSCBC), aSCBC);
} catch (java.lang.Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Create a calibrated Stretch Instance over the specified array of Predictor Ordinates and Response
* Values using the specified Basis Splines.
*
* @param strName Name of the Stretch
* @param adblPredictorOrdinate Predictor Ordinate Array
* @param adblResponseValue Response Value Array
* @param aSCBC Array of Segment Builder Parameters
* @param rbfr Stretch Fitness Weighted Response
* @param bs The Calibration Boundary Condition
* @param iCalibrationDetail The Calibration Detail
*
* @return Stretch instance
*/
public static final org.drip.spline.stretch.MultiSegmentSequence CreateCalibratedStretchEstimator (
final java.lang.String strName,
final double[] adblPredictorOrdinate,
final double[] adblResponseValue,
final org.drip.spline.params.SegmentCustomBuilderControl[] aSCBC,
final org.drip.spline.params.StretchBestFitResponse rbfr,
final org.drip.spline.stretch.BoundarySettings bs,
final int iCalibrationDetail)
{
org.drip.spline.stretch.MultiSegmentSequence mss = CreateUncalibratedStretchEstimator (strName,
adblPredictorOrdinate, aSCBC);
if (null == mss || null == adblResponseValue) return null;
int iNumRightNode = adblResponseValue.length - 1;
double[] adblResponseValueRight = new double[iNumRightNode];
if (0 == iNumRightNode) return null;
for (int i = 0; i < iNumRightNode; ++i)
adblResponseValueRight[i] = adblResponseValue[i + 1];
return mss.setup (adblResponseValue[0], adblResponseValueRight, rbfr, bs, iCalibrationDetail) ? mss :
null;
}
/**
* Create a calibrated Stretch Instance over the specified Predictor Ordinates, Response Values, and their
* Constraints, using the specified Segment Builder Parameters.
*
* @param strName Name of the Stretch
* @param adblPredictorOrdinate Predictor Ordinate Array
* @param dblStretchLeftResponseValue Left-most Y Point
* @param aSRVC Array of Response Value Constraints - One per Segment
* @param aSCBC Array of Segment Builder Parameters - One per Segment
* @param rbfr Stretch Fitness Weighted Response
* @param bs The Calibration Boundary Condition
* @param iCalibrationDetail The Calibration Detail
*
* @return Stretch Instance
*/
public static final org.drip.spline.stretch.MultiSegmentSequence CreateCalibratedStretchEstimator (
final java.lang.String strName,
final double[] adblPredictorOrdinate,
final double dblStretchLeftResponseValue,
final org.drip.spline.params.SegmentResponseValueConstraint[] aSRVC,
final org.drip.spline.params.SegmentCustomBuilderControl[] aSCBC,
final org.drip.spline.params.StretchBestFitResponse rbfr,
final org.drip.spline.stretch.BoundarySettings bs,
final int iCalibrationDetail)
{
org.drip.spline.stretch.MultiSegmentSequence mss = CreateUncalibratedStretchEstimator (strName,
adblPredictorOrdinate, aSCBC);
return null == mss ? null : mss.setup (dblStretchLeftResponseValue, aSRVC, rbfr, bs,
iCalibrationDetail) ? mss : null;
}
/**
* Create a calibrated Stretch Instance over the specified Predictor Ordinates and the Response Value
* Constraints, with the Segment Builder Parameters.
*
* @param strName Name of the Stretch
* @param adblPredictorOrdinate Predictor Ordinate Array
* @param srvcStretchLeft Stretch Left Constraint
* @param aSRVC Array of Segment Constraints - One per Segment
* @param aSCBC Array of Segment Builder Parameters - One per Segment
* @param sbfr Stretch Fitness Weighted Response
* @param bs The Calibration Boundary Condition
* @param iCalibrationDetail The Calibration Detail
*
* @return Stretch Instance
*/
public static final org.drip.spline.stretch.MultiSegmentSequence CreateCalibratedStretchEstimator (
final java.lang.String strName,
final double[] adblPredictorOrdinate,
final org.drip.spline.params.SegmentResponseValueConstraint srvcStretchLeft,
final org.drip.spline.params.SegmentResponseValueConstraint[] aSRVC,
final org.drip.spline.params.SegmentCustomBuilderControl[] aSCBC,
final org.drip.spline.params.StretchBestFitResponse sbfr,
final org.drip.spline.stretch.BoundarySettings bs,
final int iCalibrationDetail)
{
org.drip.spline.stretch.MultiSegmentSequence mss = CreateUncalibratedStretchEstimator (strName,
adblPredictorOrdinate, aSCBC);
return null == mss ? null : mss.setup (srvcStretchLeft, aSRVC, sbfr, bs, iCalibrationDetail) ? mss :
null;
}
/**
* Create a Calibrated Stretch Instance from the Array of Predictor Ordinates and a flat Response Value
*
* @param strName Name of the Stretch
* @param adblPredictorOrdinate Predictor Ordinate Array
* @param dblResponseValue Response Value
* @param scbc Segment Builder Parameters - One per Segment
* @param sbfr Stretch Fitness Weighted Response
* @param bs The Calibration Boundary Condition
* @param iCalibrationDetail The Calibration Detail
*
* @return Stretch Instance
*/
public static final org.drip.spline.stretch.MultiSegmentSequence CreateCalibratedStretchEstimator (
final java.lang.String strName,
final double[] adblPredictorOrdinate,
final double dblResponseValue,
final org.drip.spline.params.SegmentCustomBuilderControl scbc,
final org.drip.spline.params.StretchBestFitResponse sbfr,
final org.drip.spline.stretch.BoundarySettings bs,
final int iCalibrationDetail)
{
if (!org.drip.quant.common.NumberUtil.IsValid (dblResponseValue) || null == adblPredictorOrdinate ||
null == scbc)
return null;
int iNumPredictorOrdinate = adblPredictorOrdinate.length;
if (1 >= iNumPredictorOrdinate) return null;
double[] adblResponseValue = new double[iNumPredictorOrdinate];
org.drip.spline.params.SegmentCustomBuilderControl[] aSCBC = new
org.drip.spline.params.SegmentCustomBuilderControl[iNumPredictorOrdinate - 1];
for (int i = 0; i < iNumPredictorOrdinate; ++i) {
adblResponseValue[i] = dblResponseValue;
if (0 != i) aSCBC[i - 1] = scbc;
}
return CreateCalibratedStretchEstimator (strName, adblPredictorOrdinate, adblResponseValue, aSCBC,
sbfr, bs, iCalibrationDetail);
}
/**
* Create a Regression Spline Instance over the specified array of Predictor Ordinate Knot Points and the
* Set of the Points to be Best Fit.
*
* @param strName Name of the Stretch
* @param adblKnotPredictorOrdinate Array of the Predictor Ordinate Knots
* @param aSCBC Array of Segment Builder Parameters
* @param sbfr Stretch Fitness Weighted Response
* @param bs The Calibration Boundary Condition
* @param iCalibrationDetail The Calibration Detail
*
* @return Stretch instance
*/
public static final org.drip.spline.stretch.MultiSegmentSequence CreateRegressionSplineEstimator (
final java.lang.String strName,
final double[] adblKnotPredictorOrdinate,
final org.drip.spline.params.SegmentCustomBuilderControl[] aSCBC,
final org.drip.spline.params.StretchBestFitResponse sbfr,
final org.drip.spline.stretch.BoundarySettings bs,
final int iCalibrationDetail)
{
org.drip.spline.stretch.MultiSegmentSequence mss = CreateUncalibratedStretchEstimator (strName,
adblKnotPredictorOrdinate, aSCBC);
if (null == mss) return null;
return mss.setup (null, null, sbfr, bs, iCalibrationDetail) ? mss : null;
}
}
| apache-2.0 |
lstav/accumulo | shell/src/main/java/org/apache/accumulo/shell/commands/DeleteCommand.java | 4474 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.shell.commands;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.conf.ConfigurationTypeHelper;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.accumulo.core.tabletserver.thrift.ConstraintViolationException;
import org.apache.accumulo.shell.Shell;
import org.apache.accumulo.shell.Shell.Command;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.hadoop.io.Text;
public class DeleteCommand extends Command {
private Option deleteOptAuths, timestampOpt;
private Option timeoutOption;
protected long getTimeout(final CommandLine cl) {
if (cl.hasOption(timeoutOption.getLongOpt())) {
return ConfigurationTypeHelper.getTimeInMillis(cl.getOptionValue(timeoutOption.getLongOpt()));
}
return Long.MAX_VALUE;
}
@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException, IOException,
ConstraintViolationException {
shellState.checkTableState();
final Mutation m = new Mutation(new Text(cl.getArgs()[0].getBytes(Shell.CHARSET)));
final Text colf = new Text(cl.getArgs()[1].getBytes(Shell.CHARSET));
final Text colq = new Text(cl.getArgs()[2].getBytes(Shell.CHARSET));
if (cl.hasOption(deleteOptAuths.getOpt())) {
final ColumnVisibility le = new ColumnVisibility(cl.getOptionValue(deleteOptAuths.getOpt()));
if (cl.hasOption(timestampOpt.getOpt())) {
m.putDelete(colf, colq, le, Long.parseLong(cl.getOptionValue(timestampOpt.getOpt())));
} else {
m.putDelete(colf, colq, le);
}
} else if (cl.hasOption(timestampOpt.getOpt())) {
m.putDelete(colf, colq, Long.parseLong(cl.getOptionValue(timestampOpt.getOpt())));
} else {
m.putDelete(colf, colq);
}
final BatchWriter bw =
shellState.getAccumuloClient().createBatchWriter(shellState.getTableName(),
new BatchWriterConfig().setMaxMemory(Math.max(m.estimatedMemoryUsed(), 1024))
.setMaxWriteThreads(1).setTimeout(getTimeout(cl), TimeUnit.MILLISECONDS));
bw.addMutation(m);
bw.close();
return 0;
}
@Override
public String description() {
return "deletes a record from a table";
}
@Override
public String usage() {
return getName() + " <row> <colfamily> <colqualifier>";
}
@Override
public Options getOptions() {
final Options o = new Options();
deleteOptAuths = new Option("l", "visibility-label", true, "formatted visibility");
deleteOptAuths.setArgName("expression");
o.addOption(deleteOptAuths);
timestampOpt = new Option("ts", "timestamp", true, "timestamp to use for deletion");
timestampOpt.setArgName("timestamp");
o.addOption(timestampOpt);
timeoutOption = new Option(null, "timeout", true,
"time before insert should fail if no data is written. If no unit is"
+ " given assumes seconds. Units d,h,m,s,and ms are supported. e.g. 30s" + " or 100ms");
timeoutOption.setArgName("timeout");
o.addOption(timeoutOption);
return o;
}
@Override
public int numArgs() {
return 3;
}
}
| apache-2.0 |
Esjob-Cloud-DevOps/elastic-job | elastic-job-common/elastic-job-common-core/src/main/java/com/dangdang/ddframe/job/exception/JobSystemException.java | 1090 | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package com.dangdang.ddframe.job.exception;
/**
* 作业系统异常.
*
* @author zhangliang
*/
public final class JobSystemException extends RuntimeException {
private static final long serialVersionUID = 5018901344199973515L;
public JobSystemException(final String errorMessage, final Object... args) {
super(String.format(errorMessage, args));
}
public JobSystemException(final Throwable cause) {
super(cause);
}
}
| apache-2.0 |
xasx/camunda-bpm-platform | distro/wildfly8/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/deployment/processor/ProcessesXmlProcessor.java | 6632 | /*
* Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.container.impl.jboss.deployment.processor;
import static org.jboss.as.server.deployment.Attachments.MODULE;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.camunda.bpm.application.ProcessApplication;
import org.camunda.bpm.application.impl.metadata.ProcessesXmlParser;
import org.camunda.bpm.application.impl.metadata.spi.ProcessesXml;
import org.camunda.bpm.container.impl.jboss.deployment.marker.ProcessApplicationAttachments;
import org.camunda.bpm.container.impl.jboss.util.ProcessesXmlWrapper;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.util.IoUtil;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.modules.Module;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VirtualFile;
/**
* <p>Detects and processes all <em>META-INF/processes.xml</em> files that are visible from the module
* classloader of the {@link DeploymentUnit}.</p>
*
* <p>This is POST_MODULE so we can take into account module visibility in case of composite deployments
* (EARs)</p>
*
* @author Daniel Meyer
*
*/
public class ProcessesXmlProcessor implements DeploymentUnitProcessor {
public static final String PROCESSES_XML = "META-INF/processes.xml";
public static final int PRIORITY = 0x0000; // this can happen ASAP in the POST_MODULE Phase
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if(!ProcessApplicationAttachments.isProcessApplication(deploymentUnit)) {
return;
}
final Module module = deploymentUnit.getAttachment(MODULE);
// read @ProcessApplication annotation of PA-component
String[] deploymentDescriptors = getDeploymentDescriptors(deploymentUnit);
// load all processes.xml files
List<URL> deploymentDescriptorURLs = getDeploymentDescriptorUrls(module, deploymentDescriptors);
for (URL processesXmlResource : deploymentDescriptorURLs) {
VirtualFile processesXmlFile = getFile(processesXmlResource);
// parse processes.xml metadata.
ProcessesXml processesXml = null;
if(isEmptyFile(processesXmlResource)) {
processesXml = ProcessesXml.EMPTY_PROCESSES_XML;
} else {
processesXml = parseProcessesXml(processesXmlResource);
}
// add the parsed metadata to the attachment list
ProcessApplicationAttachments.addProcessesXml(deploymentUnit, new ProcessesXmlWrapper(processesXml, processesXmlFile));
}
}
protected List<URL> getDeploymentDescriptorUrls(final Module module, String[] deploymentDescriptors) throws DeploymentUnitProcessingException {
List<URL> deploymentDescriptorURLs = new ArrayList<URL>();
for (String deploymentDescriptor : deploymentDescriptors) {
Enumeration<URL> resources = null;
try {
resources = module.getClassLoader().getResources(deploymentDescriptor);
} catch (IOException e) {
throw new DeploymentUnitProcessingException("Could not load processes.xml resource: ", e);
}
while (resources.hasMoreElements()) {
deploymentDescriptorURLs.add((URL) resources.nextElement());
}
}
return deploymentDescriptorURLs;
}
protected String[] getDeploymentDescriptors(DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {
final ComponentDescription processApplicationComponent = ProcessApplicationAttachments.getProcessApplicationComponent(deploymentUnit);
final String paClassName = processApplicationComponent.getComponentClassName();
String[] deploymentDescriptorResourceNames = null;
Module module = deploymentUnit.getAttachment(MODULE);
Class<?> paClass = null;
try {
paClass = (Class<?>) module.getClassLoader().loadClass(paClassName);
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException("Unable to load process application class '"+paClassName+"'.");
}
ProcessApplication annotation = paClass.getAnnotation(ProcessApplication.class);
if(annotation == null) {
deploymentDescriptorResourceNames = new String[]{ PROCESSES_XML };
} else {
deploymentDescriptorResourceNames = annotation.deploymentDescriptors();
}
return deploymentDescriptorResourceNames;
}
protected Enumeration<URL> getProcessesXmlResources(Module module, String[] deploymentDescriptors) throws DeploymentUnitProcessingException {
try {
return module.getClassLoader().getResources(PROCESSES_XML);
} catch (IOException e) {
throw new DeploymentUnitProcessingException(e);
}
}
protected VirtualFile getFile(URL processesXmlResource) throws DeploymentUnitProcessingException {
try {
return VFS.getChild(processesXmlResource.toURI());
} catch(Exception e) {
throw new DeploymentUnitProcessingException(e);
}
}
protected boolean isEmptyFile(URL url) {
InputStream inputStream = null;
try {
inputStream = url.openStream();
return inputStream.available() == 0;
} catch (IOException e) {
throw new ProcessEngineException("Could not open stream for " + url, e);
} finally {
IoUtil.closeSilently(inputStream);
}
}
protected ProcessesXml parseProcessesXml(URL url) {
final ProcessesXmlParser processesXmlParser = new ProcessesXmlParser();
ProcessesXml processesXml = processesXmlParser.createParse()
.sourceUrl(url)
.execute()
.getProcessesXml();
return processesXml;
}
public void undeploy(DeploymentUnit context) {
}
}
| apache-2.0 |
karreiro/uberfire | uberfire-workingset/uberfire-workingset-api/src/main/java/org/guvnor/common/services/workingset/client/factconstraints/customform/predefined/DefaultCustomFormImplementation.java | 1835 | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.guvnor.common.services.workingset.client.factconstraints.customform.predefined;
import org.guvnor.common.services.workingset.client.factconstraints.customform.CustomFormConfiguration;
public class DefaultCustomFormImplementation
implements CustomFormConfiguration {
private int width = 200;
private int height = 200;
private String factType;
private String fieldName;
private String url;
public String getFactType() {
return this.factType;
}
public void setFactType(String factType) {
this.factType = factType;
}
public String getFieldName() {
return this.fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getCustomFormURL() {
return this.url;
}
public void setCustomFormURL(String url) {
this.url = url;
}
public int getCustomFormHeight() {
return height;
}
public void setCustomFormHeight(int height) {
this.height = height;
}
public int getCustomFormWidth() {
return width;
}
public void setCustomFormWidth(int width) {
this.width = width;
}
}
| apache-2.0 |
tripodsan/jackrabbit-filevault | vault-core/src/main/java/org/apache/jackrabbit/vault/util/CredentialsProvider.java | 1085 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.vault.util;
import javax.jcr.Credentials;
import org.apache.jackrabbit.vault.fs.api.RepositoryAddress;
/**
* {@code CredentialsProvider}...
*/
public interface CredentialsProvider {
Credentials getCredentials(RepositoryAddress mountpoint);
} | apache-2.0 |
lepdou/apollo | apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/AccessKeyService.java | 2056 | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.dto.AccessKeyDTO;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI.AccessKeyAPI;
import com.ctrip.framework.apollo.portal.constant.TracerEventType;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.tracer.Tracer;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccessKeyService {
private final AdminServiceAPI.AccessKeyAPI accessKeyAPI;
public AccessKeyService(AccessKeyAPI accessKeyAPI) {
this.accessKeyAPI = accessKeyAPI;
}
public List<AccessKeyDTO> findByAppId(Env env, String appId) {
return accessKeyAPI.findByAppId(env, appId);
}
public AccessKeyDTO createAccessKey(Env env, AccessKeyDTO accessKey) {
AccessKeyDTO accessKeyDTO = accessKeyAPI.create(env, accessKey);
Tracer.logEvent(TracerEventType.CREATE_ACCESS_KEY, accessKey.getAppId());
return accessKeyDTO;
}
public void deleteAccessKey(Env env, String appId, long id, String operator) {
accessKeyAPI.delete(env, appId, id, operator);
}
public void enable(Env env, String appId, long id, String operator) {
accessKeyAPI.enable(env, appId, id, operator);
}
public void disable(Env env, String appId, long id, String operator) {
accessKeyAPI.disable(env, appId, id, operator);
}
}
| apache-2.0 |
YangliAtGitHub/HanLP | src/main/java/com/hankcs/hanlp/corpus/io/IOUtil.java | 11757 | /*
* <summary></summary>
* <author>He Han</author>
* <email>hankcs.cn@gmail.com</email>
* <create-date>2014/9/8 23:04</create-date>
*
* <copyright file="Util.java" company="上海林原信息科技有限公司">
* Copyright (c) 2003-2014, 上海林原信息科技有限公司. All Right Reserved, http://www.linrunsoft.com/
* This source is subject to the LinrunSpace License. Please contact 上海林原信息科技有限公司 to get more information.
* </copyright>
*/
package com.hankcs.hanlp.corpus.io;
import com.hankcs.hanlp.utility.TextUtility;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.*;
import static com.hankcs.hanlp.utility.Predefine.logger;
/**
* 一些常用的IO操作
*
* @author hankcs
*/
public class IOUtil
{
/**
* 序列化对象
*
* @param o
* @param path
* @return
*/
public static boolean saveObjectTo(Object o, String path)
{
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
oos.writeObject(o);
oos.close();
}
catch (IOException e)
{
logger.warning("在保存对象" + o + "到" + path + "时发生异常" + e);
return false;
}
return true;
}
/**
* 反序列化对象
*
* @param path
* @return
*/
public static Object readObjectFrom(String path)
{
ObjectInputStream ois = null;
try
{
ois = new ObjectInputStream(new FileInputStream(path));
Object o = ois.readObject();
ois.close();
return o;
}
catch (Exception e)
{
logger.warning("在从" + path + "读取对象时发生异常" + e);
}
return null;
}
/**
* 一次性读入纯文本
*
* @param path
* @return
*/
public static String readTxt(String path)
{
if (path == null) return null;
File file = new File(path);
Long fileLength = file.length();
byte[] fileContent = new byte[fileLength.intValue()];
try
{
FileInputStream in = new FileInputStream(file);
in.read(fileContent);
in.close();
}
catch (FileNotFoundException e)
{
logger.warning("找不到" + path + e);
return null;
}
catch (IOException e)
{
logger.warning("读取" + path + "发生IO异常" + e);
return null;
}
return new String(fileContent, Charset.forName("UTF-8"));
}
public static LinkedList<String[]> readCsv(String path)
{
LinkedList<String[]> resultList = new LinkedList<String[]>();
LinkedList<String> lineList = readLineList(path);
for (String line : lineList)
{
resultList.add(line.split(","));
}
return resultList;
}
/**
* 快速保存
*
* @param path
* @param content
* @return
*/
public static boolean saveTxt(String path, String content)
{
try
{
FileChannel fc = new FileOutputStream(path).getChannel();
fc.write(ByteBuffer.wrap(content.getBytes()));
fc.close();
}
catch (Exception e)
{
logger.throwing("IOUtil", "saveTxt", e);
logger.warning("IOUtil saveTxt 到" + path + "失败" + e.toString());
return false;
}
return true;
}
public static boolean saveTxt(String path, StringBuilder content)
{
return saveTxt(path, content.toString());
}
public static <T> boolean saveCollectionToTxt(Collection<T> collection, String path)
{
StringBuilder sb = new StringBuilder();
for (Object o : collection)
{
sb.append(o);
sb.append('\n');
}
return saveTxt(path, sb.toString());
}
/**
* 将整个文件读取为字节数组
*
* @param path
* @return
*/
public static byte[] readBytes(String path)
{
try
{
FileInputStream fis = new FileInputStream(path);
FileChannel channel = fis.getChannel();
int fileSize = (int) channel.size();
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
channel.read(byteBuffer);
byteBuffer.flip();
byte[] bytes = byteBuffer.array();
byteBuffer.clear();
channel.close();
fis.close();
return bytes;
}
catch (Exception e)
{
logger.warning("读取" + path + "时发生异常" + e);
}
return null;
}
public static LinkedList<String> readLineList(String path)
{
LinkedList<String> result = new LinkedList<String>();
String txt = readTxt(path);
if (txt == null) return result;
StringTokenizer tokenizer = new StringTokenizer(txt, "\n");
while (tokenizer.hasMoreTokens())
{
result.add(tokenizer.nextToken());
}
return result;
}
/**
* 用省内存的方式读取大文件
*
* @param path
* @return
*/
public static LinkedList<String> readLineListWithLessMemory(String path)
{
LinkedList<String> result = new LinkedList<String>();
String line = null;
try
{
BufferedReader bw = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
while ((line = bw.readLine()) != null)
{
result.add(line);
}
bw.close();
}
catch (Exception e)
{
logger.warning("加载" + path + "失败," + e);
}
return result;
}
public static boolean saveMapToTxt(Map<Object, Object> map, String path)
{
return saveMapToTxt(map, path, "=");
}
public static boolean saveMapToTxt(Map<Object, Object> map, String path, String separator)
{
map = new TreeMap<Object, Object>(map);
return saveEntrySetToTxt(map.entrySet(), path, separator);
}
public static boolean saveEntrySetToTxt(Set<Map.Entry<Object, Object>> entrySet, String path, String separator)
{
StringBuilder sbOut = new StringBuilder();
for (Map.Entry<Object, Object> entry : entrySet)
{
sbOut.append(entry.getKey());
sbOut.append(separator);
sbOut.append(entry.getValue());
sbOut.append('\n');
}
return saveTxt(path, sbOut.toString());
}
/**
* 获取文件所在目录的路径
* @param path
* @return
*/
public static String dirname(String path)
{
int index = path.lastIndexOf('/');
if (index == -1) return path;
return path.substring(0, index + 1);
}
public static LineIterator readLine(String path)
{
return new LineIterator(path);
}
/**
* 方便读取按行读取大文件
*/
public static class LineIterator implements Iterator<String>
{
BufferedReader bw;
String line;
public LineIterator(String path)
{
try
{
bw = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
line = bw.readLine();
}
catch (FileNotFoundException e)
{
logger.warning("文件" + path + "不存在,接下来的调用会返回null" + TextUtility.exceptionToString(e));
bw = null;
}
catch (IOException e)
{
logger.warning("在读取过程中发生错误" + TextUtility.exceptionToString(e));
bw = null;
}
}
public void close()
{
if (bw == null) return;
try
{
bw.close();
bw = null;
}
catch (IOException e)
{
logger.warning("关闭文件失败" + TextUtility.exceptionToString(e));
}
return;
}
@Override
public boolean hasNext()
{
if (bw == null) return false;
if (line == null)
{
try
{
bw.close();
bw = null;
}
catch (IOException e)
{
logger.warning("关闭文件失败" + TextUtility.exceptionToString(e));
}
return false;
}
return true;
}
@Override
public String next()
{
String preLine = line;
try
{
if (bw != null)
{
line = bw.readLine();
if (line == null && bw != null)
{
try
{
bw.close();
bw = null;
}
catch (IOException e)
{
logger.warning("关闭文件失败" + TextUtility.exceptionToString(e));
}
}
}
else
{
line = null;
}
}
catch (IOException e)
{
logger.warning("在读取过程中发生错误" + TextUtility.exceptionToString(e));
}
return preLine;
}
@Override
public void remove()
{
throw new UnsupportedOperationException("只读,不可写!");
}
}
/**
* 创建一个BufferedWriter
*
* @param path
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static BufferedWriter newBufferedWriter(String path) throws FileNotFoundException, UnsupportedEncodingException
{
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
}
/**
* 创建一个BufferedReader
* @param path
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static BufferedReader newBufferedReader(String path) throws FileNotFoundException, UnsupportedEncodingException
{
return new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
}
public static BufferedWriter newBufferedWriter(String path, boolean append) throws FileNotFoundException, UnsupportedEncodingException
{
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, append), "UTF-8"));
}
/**
* 获取最后一个分隔符的后缀
* @param name
* @param delimiter
* @return
*/
public static String getSuffix(String name, String delimiter)
{
return name.substring(name.lastIndexOf(delimiter) + 1);
}
/**
* 写数组,用制表符分割
* @param bw
* @param params
* @throws IOException
*/
public static void writeLine(BufferedWriter bw, String... params) throws IOException
{
for (int i = 0; i < params.length - 1; i++)
{
bw.write(params[i]);
bw.write('\t');
}
bw.write(params[params.length - 1]);
}
}
| apache-2.0 |
nikhilvibhav/camel | components/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java | 22359 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.mina;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelExchangeException;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePropertyKey;
import org.apache.camel.ExchangeTimedOutException;
import org.apache.camel.spi.CamelLogger;
import org.apache.camel.support.DefaultProducer;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.util.IOHelper;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.executor.OrderedThreadPoolExecutor;
import org.apache.mina.filter.executor.UnorderedThreadPoolExecutor;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.apache.mina.transport.vmpipe.VmPipeAddress;
import org.apache.mina.transport.vmpipe.VmPipeConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link org.apache.camel.Producer} implementation for MINA
*/
public class MinaProducer extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(MinaProducer.class);
private final ResponseHandler handler;
private IoSession session;
private CountDownLatch responseLatch;
private CountDownLatch closeLatch;
private boolean lazySessionCreation;
private long writeTimeout;
private long timeout;
private SocketAddress address;
private IoConnector connector;
private boolean sync;
private CamelLogger noReplyLogger;
private MinaConfiguration configuration;
private IoSessionConfig connectorConfig;
private ExecutorService workerPool;
public MinaProducer(MinaEndpoint endpoint) throws Exception {
super(endpoint);
this.configuration = endpoint.getConfiguration();
this.lazySessionCreation = configuration.isLazySessionCreation();
this.writeTimeout = configuration.getWriteTimeout();
this.timeout = configuration.getTimeout();
this.sync = configuration.isSync();
this.noReplyLogger = new CamelLogger(LOG, configuration.getNoReplyLogLevel());
String protocol = configuration.getProtocol();
if (protocol.equals("tcp")) {
setupSocketProtocol(protocol);
} else if (configuration.isDatagramProtocol()) {
setupDatagramProtocol(protocol);
} else if (protocol.equals("vm")) {
setupVmProtocol(protocol);
}
handler = new ResponseHandler();
connector.setHandler(handler);
}
@Override
public MinaEndpoint getEndpoint() {
return (MinaEndpoint) super.getEndpoint();
}
@Override
public boolean isSingleton() {
// the producer should not be singleton otherwise cannot use concurrent producers and safely
// use request/reply with correct correlation
return !sync;
}
@Override
public void process(Exchange exchange) throws Exception {
try {
doProcess(exchange);
} finally {
// ensure we always disconnect if configured
maybeDisconnectOnDone(exchange);
}
}
protected void doProcess(Exchange exchange) throws Exception {
if (session == null && !lazySessionCreation) {
throw new IllegalStateException("Not started yet!");
}
if (session == null || !session.isConnected()) {
openConnection();
}
// set the exchange encoding property
if (getEndpoint().getConfiguration().getCharsetName() != null) {
exchange.setProperty(ExchangePropertyKey.CHARSET_NAME,
IOHelper.normalizeCharset(getEndpoint().getConfiguration().getCharsetName()));
}
Object body = MinaPayloadHelper.getIn(getEndpoint(), exchange);
if (body == null) {
noReplyLogger.log("No payload to send for exchange: " + exchange);
return; // exit early since nothing to write
}
// if textline enabled then covert to a String which must be used for textline
if (getEndpoint().getConfiguration().isTextline()) {
body = getEndpoint().getCamelContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, body);
}
// if sync is true then we should also wait for a response (synchronous mode)
if (sync) {
// only initialize responseLatch if we should get a response
responseLatch = new CountDownLatch(1);
// reset handler if we expect a response
handler.reset();
}
// log what we are writing
if (LOG.isDebugEnabled()) {
Object out = body;
if (body instanceof byte[]) {
// byte arrays is not readable so convert to string
out = exchange.getContext().getTypeConverter().convertTo(String.class, body);
}
LOG.debug("Writing body: {}", out);
}
// write the body
MinaHelper.writeBody(session, body, exchange, writeTimeout);
if (sync) {
// wait for response, consider timeout
LOG.debug("Waiting for response using timeout {} millis.", timeout);
boolean done = responseLatch.await(timeout, TimeUnit.MILLISECONDS);
if (!done) {
throw new ExchangeTimedOutException(exchange, timeout);
}
// did we get a response
if (handler.getCause() != null) {
throw new CamelExchangeException("Error occurred in ResponseHandler", exchange, handler.getCause());
} else if (!handler.isMessageReceived()) {
// no message received
throw new ExchangeTimedOutException(exchange, timeout);
} else {
// set the result on either IN or OUT on the original exchange depending on its pattern
if (ExchangeHelper.isOutCapable(exchange)) {
MinaPayloadHelper.setOut(exchange, handler.getMessage());
} else {
MinaPayloadHelper.setIn(exchange, handler.getMessage());
}
}
}
}
protected void maybeDisconnectOnDone(Exchange exchange) throws InterruptedException {
if (session == null) {
return;
}
// should session be closed after complete?
Boolean close;
if (ExchangeHelper.isOutCapable(exchange)) {
close = exchange.getOut().getHeader(MinaConstants.MINA_CLOSE_SESSION_WHEN_COMPLETE, Boolean.class);
} else {
close = exchange.getIn().getHeader(MinaConstants.MINA_CLOSE_SESSION_WHEN_COMPLETE, Boolean.class);
}
// should we disconnect, the header can override the configuration
boolean disconnect = getEndpoint().getConfiguration().isDisconnect();
if (close != null) {
disconnect = close;
}
if (disconnect) {
LOG.debug("Closing session when complete at address: {}", address);
closeSessionIfNeededAndAwaitCloseInHandler(session);
}
}
private void closeSessionIfNeededAndAwaitCloseInHandler(IoSession sessionToBeClosed) throws InterruptedException {
closeLatch = new CountDownLatch(1);
if (!sessionToBeClosed.isClosing()) {
CloseFuture closeFuture = sessionToBeClosed.closeNow();
closeFuture.await(timeout, TimeUnit.MILLISECONDS);
closeLatch.await(timeout, TimeUnit.MILLISECONDS);
}
}
public DefaultIoFilterChainBuilder getFilterChain() {
return connector.getFilterChain();
}
@Override
protected void doStart() throws Exception {
super.doStart();
if (!lazySessionCreation) {
openConnection();
}
}
@Override
protected void doStop() throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("Stopping connector: {} at address: {}", connector, address);
}
closeConnection();
super.doStop();
}
@Override
protected void doShutdown() throws Exception {
if (workerPool != null) {
workerPool.shutdown();
}
super.doShutdown();
}
private void closeConnection() throws InterruptedException {
if (session != null) {
closeSessionIfNeededAndAwaitCloseInHandler(session);
}
connector.dispose(true);
}
private void openConnection() {
if (this.address == null || !this.configuration.isCachedAddress()) {
setSocketAddress(this.configuration.getProtocol());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Creating connector to address: {} using connector: {} timeout: {} millis.", address, connector, timeout);
}
// connect and wait until the connection is established
if (connectorConfig != null) {
connector.getSessionConfig().setAll(connectorConfig);
}
ConnectFuture future = connector.connect(address);
future.awaitUninterruptibly();
session = future.getSession();
}
// Implementation methods
//-------------------------------------------------------------------------
protected void setupVmProtocol(String uri) {
boolean minaLogger = configuration.isMinaLogger();
List<IoFilter> filters = configuration.getFilters();
address = new VmPipeAddress(configuration.getPort());
connector = new VmPipeConnector();
// connector config
if (minaLogger) {
connector.getFilterChain().addLast("logger", new LoggingFilter());
}
appendIoFiltersToChain(filters, connector.getFilterChain());
if (configuration.getSslContextParameters() != null) {
LOG.warn("Using vm protocol"
+ ", but an SSLContextParameters instance was provided. SSLContextParameters is only supported on the TCP protocol.");
}
configureCodecFactory("MinaProducer", connector);
}
protected void setupSocketProtocol(String uri) throws Exception {
boolean minaLogger = configuration.isMinaLogger();
long timeout = configuration.getTimeout();
List<IoFilter> filters = configuration.getFilters();
address = new InetSocketAddress(configuration.getHost(), configuration.getPort());
final int processorCount = Runtime.getRuntime().availableProcessors() + 1;
connector = new NioSocketConnector(processorCount);
// connector config
connectorConfig = connector.getSessionConfig();
if (configuration.isOrderedThreadPoolExecutor()) {
workerPool = new OrderedThreadPoolExecutor(configuration.getMaximumPoolSize());
} else {
workerPool = new UnorderedThreadPoolExecutor(configuration.getMaximumPoolSize());
}
connector.getFilterChain().addLast("threadPool", new ExecutorFilter(workerPool));
if (minaLogger) {
connector.getFilterChain().addLast("logger", new LoggingFilter());
}
appendIoFiltersToChain(filters, connector.getFilterChain());
if (configuration.getSslContextParameters() != null) {
SslFilter filter = new SslFilter(
configuration.getSslContextParameters().createSSLContext(getEndpoint().getCamelContext()),
configuration.isAutoStartTls());
filter.setUseClientMode(true);
connector.getFilterChain().addFirst("sslFilter", filter);
}
configureCodecFactory("MinaProducer", connector);
connector.setConnectTimeoutMillis(timeout);
}
protected void configureCodecFactory(String type, IoService service) {
if (configuration.getCodec() != null) {
addCodecFactory(service, configuration.getCodec());
} else if (configuration.isAllowDefaultCodec()) {
configureDefaultCodecFactory(type, service);
}
}
protected void configureDefaultCodecFactory(String type, IoService service) {
if (configuration.isTextline()) {
Charset charset = getEncodingParameter(type, configuration);
LineDelimiter delimiter = getLineDelimiterParameter(configuration.getTextlineDelimiter());
MinaTextLineCodecFactory codecFactory = new MinaTextLineCodecFactory(charset, delimiter);
if (configuration.getEncoderMaxLineLength() > 0) {
codecFactory.setEncoderMaxLineLength(configuration.getEncoderMaxLineLength());
}
if (configuration.getDecoderMaxLineLength() > 0) {
codecFactory.setDecoderMaxLineLength(configuration.getDecoderMaxLineLength());
}
addCodecFactory(service, codecFactory);
LOG.debug("{}: Using TextLineCodecFactory: {} using encoding: {} line delimiter: {}({})",
type, codecFactory, charset, configuration.getTextlineDelimiter(), delimiter);
LOG.debug("Encoder maximum line length: {}. Decoder maximum line length: {}",
codecFactory.getEncoderMaxLineLength(), codecFactory.getDecoderMaxLineLength());
} else {
ObjectSerializationCodecFactory codecFactory = new ObjectSerializationCodecFactory();
addCodecFactory(service, codecFactory);
LOG.debug("{}: Using ObjectSerializationCodecFactory: {}", type, codecFactory);
}
}
protected void setupDatagramProtocol(String uri) {
boolean minaLogger = configuration.isMinaLogger();
boolean transferExchange = configuration.isTransferExchange();
List<IoFilter> filters = configuration.getFilters();
if (transferExchange) {
throw new IllegalArgumentException("transferExchange=true is not supported for datagram protocol");
}
address = new InetSocketAddress(configuration.getHost(), configuration.getPort());
final int processorCount = Runtime.getRuntime().availableProcessors() + 1;
connector = new NioDatagramConnector(processorCount);
if (configuration.isOrderedThreadPoolExecutor()) {
workerPool = new OrderedThreadPoolExecutor(configuration.getMaximumPoolSize());
} else {
workerPool = new UnorderedThreadPoolExecutor(configuration.getMaximumPoolSize());
}
connectorConfig = connector.getSessionConfig();
connector.getFilterChain().addLast("threadPool", new ExecutorFilter(workerPool));
if (minaLogger) {
connector.getFilterChain().addLast("logger", new LoggingFilter());
}
appendIoFiltersToChain(filters, connector.getFilterChain());
if (configuration.getSslContextParameters() != null) {
LOG.warn("Using datagram protocol, {}, but an SSLContextParameters instance was provided. "
+ "SSLContextParameters is only supported on the TCP protocol.",
configuration.getProtocol());
}
configureDataGramCodecFactory("MinaProducer", connector, configuration);
// set connect timeout to mina in seconds
connector.setConnectTimeoutMillis(timeout);
}
/**
* For datagrams the entire message is available as a single IoBuffer so lets just pass those around by default and
* try converting whatever they payload is into IoBuffer unless some custom converter is specified
*/
protected void configureDataGramCodecFactory(
final String type, final IoService service, final MinaConfiguration configuration) {
ProtocolCodecFactory codecFactory = configuration.getCodec();
if (codecFactory == null) {
codecFactory = new MinaUdpProtocolCodecFactory(this.getEndpoint().getCamelContext());
if (LOG.isDebugEnabled()) {
LOG.debug("{}: Using CodecFactory: {}", type, codecFactory);
}
}
addCodecFactory(service, codecFactory);
}
private void addCodecFactory(IoService service, ProtocolCodecFactory codecFactory) {
LOG.debug("addCodecFactory name: {}", codecFactory.getClass().getName());
service.getFilterChain().addLast("codec", new ProtocolCodecFilter(codecFactory));
}
private static LineDelimiter getLineDelimiterParameter(MinaTextLineDelimiter delimiter) {
if (delimiter == null) {
return LineDelimiter.DEFAULT;
}
return delimiter.getLineDelimiter();
}
private Charset getEncodingParameter(String type, MinaConfiguration configuration) {
String encoding = configuration.getEncoding();
if (encoding == null) {
encoding = Charset.defaultCharset().name();
// set in on configuration so its updated
configuration.setEncoding(encoding);
LOG.debug("{}: No encoding parameter using default charset: {}", type, encoding);
}
if (!Charset.isSupported(encoding)) {
throw new IllegalArgumentException("The encoding: " + encoding + " is not supported");
}
return Charset.forName(encoding);
}
private void appendIoFiltersToChain(List<IoFilter> filters, DefaultIoFilterChainBuilder filterChain) {
if (filters != null && !filters.isEmpty()) {
for (IoFilter ioFilter : filters) {
filterChain.addLast(ioFilter.getClass().getCanonicalName(), ioFilter);
}
}
}
private void setSocketAddress(String protocol) {
if (protocol.equals("tcp")) {
this.address = new InetSocketAddress(configuration.getHost(), configuration.getPort());
} else if (configuration.isDatagramProtocol()) {
this.address = new InetSocketAddress(configuration.getHost(), configuration.getPort());
} else if (protocol.equals("vm")) {
this.address = new VmPipeAddress(configuration.getPort());
}
}
/**
* Handles response from session writes
*/
private final class ResponseHandler extends IoHandlerAdapter {
private Object message;
private Throwable cause;
private boolean messageReceived;
public void reset() {
this.message = null;
this.cause = null;
this.messageReceived = false;
}
@Override
public void messageReceived(IoSession ioSession, Object message) throws Exception {
LOG.debug("Message received: {}", message);
this.message = message;
messageReceived = true;
cause = null;
notifyResultAvailable();
}
protected void notifyResultAvailable() {
CountDownLatch downLatch = responseLatch;
if (downLatch != null) {
downLatch.countDown();
}
}
@Override
public void sessionClosed(IoSession session) throws Exception {
if (sync && !messageReceived) {
// sync=true (InOut mode) so we expected a message as reply but did not get one before the session is closed
LOG.debug("Session closed but no message received from address: {}", address);
// session was closed but no message received. This could be because the remote server had an internal error
// and could not return a response. We should count down to stop waiting for a response
notifyResultAvailable();
}
notifySessionClosed();
}
private void notifySessionClosed() {
if (closeLatch != null) {
closeLatch.countDown();
}
}
@Override
public void exceptionCaught(IoSession ioSession, Throwable cause) {
this.message = null;
this.messageReceived = false;
this.cause = cause;
if (ioSession != null && !closedByMina(cause)) {
CloseFuture closeFuture = ioSession.closeNow();
closeFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
}
}
private boolean closedByMina(Throwable cause) {
return cause instanceof IOException;
}
public Throwable getCause() {
return this.cause;
}
public Object getMessage() {
return this.message;
}
public boolean isMessageReceived() {
return messageReceived;
}
}
}
| apache-2.0 |
zliu41/gobblin | gobblin-utility/src/main/java/gobblin/util/JobConfigurationUtils.java | 4591 | /*
* Copyright (C) 2014-2016 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
package gobblin.util;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import java.util.Properties;
import java.util.Map.Entry;
import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import gobblin.configuration.State;
/**
* A utility class for working with job configurations.
*
* @author Yinan Li
*/
public class JobConfigurationUtils {
/**
* Get a new {@link Properties} instance by combining a given system configuration {@link Properties}
* object (first) and a job configuration {@link Properties} object (second).
*
* @param sysProps the given system configuration {@link Properties} object
* @param jobProps the given job configuration {@link Properties} object
* @return a new {@link Properties} instance
*/
public static Properties combineSysAndJobProperties(Properties sysProps, Properties jobProps) {
Properties combinedJobProps = new Properties();
combinedJobProps.putAll(sysProps);
combinedJobProps.putAll(jobProps);
return combinedJobProps;
}
/**
* Put all configuration properties in a given {@link Properties} object into a given
* {@link Configuration} object.
*
* @param properties the given {@link Properties} object
* @param configuration the given {@link Configuration} object
*/
public static void putPropertiesIntoConfiguration(Properties properties, Configuration configuration) {
for (String name : properties.stringPropertyNames()) {
configuration.set(name, properties.getProperty(name));
}
}
/**
* Put all configuration properties in a given {@link Configuration} object into a given
* {@link Properties} object.
*
* @param configuration the given {@link Configuration} object
* @param properties the given {@link Properties} object
*/
public static void putConfigurationIntoProperties(Configuration configuration, Properties properties) {
for (Iterator<Entry<String, String>> it = configuration.iterator(); it.hasNext();) {
Entry<String, String> entry = it.next();
properties.put(entry.getKey(), entry.getValue());
}
}
/**
* Put all configuration properties in a given {@link State} object into a given
* {@link Configuration} object.
*
* @param state the given {@link State} object
* @param configuration the given {@link Configuration} object
*/
public static void putStateIntoConfiguration(State state, Configuration configuration) {
for (String key : state.getPropertyNames()) {
configuration.set(key, state.getProp(key));
}
}
/**
* Load the properties from the specified file into a {@link Properties} object.
*
* @param fileName the name of the file to load properties from
* @param conf configuration object to determine the file system to be used
* @return a new {@link Properties} instance
*/
public static Properties fileToProperties(String fileName, Configuration conf)
throws IOException, ConfigurationException {
PropertiesConfiguration propsConfig = new PropertiesConfiguration();
Path filePath = new Path(fileName);
URI fileURI = filePath.toUri();
if (fileURI.getScheme() == null && fileURI.getAuthority() == null) {
propsConfig.load(FileSystem.getLocal(conf).open(filePath));
} else {
propsConfig.load(filePath.getFileSystem(conf).open(filePath));
}
return ConfigurationConverter.getProperties(propsConfig);
}
/**
* Load the properties from the specified file into a {@link Properties} object.
*
* @param fileName the name of the file to load properties from
* @return a new {@link Properties} instance
*/
public static Properties fileToProperties(String fileName) throws IOException, ConfigurationException {
return fileToProperties(fileName, new Configuration());
}
}
| apache-2.0 |
NuwanSameera/carbon-device-mgt-plugins | components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows/src/main/java/org/wso2/carbon/device/mgt/mobile/windows/impl/WindowsFeatureManager.java | 7937 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.mobile.windows.impl;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileFeatureDAO;
import org.wso2.carbon.device.mgt.mobile.dto.MobileFeature;
import org.wso2.carbon.device.mgt.mobile.windows.impl.dao.WindowsDAOFactory;
import org.wso2.carbon.device.mgt.mobile.util.MobileDeviceManagementUtil;
import java.util.ArrayList;
import java.util.List;
public class WindowsFeatureManager implements FeatureManager {
private MobileFeatureDAO featureDAO;
public WindowsFeatureManager() {
MobileDeviceManagementDAOFactory daoFactory = new WindowsDAOFactory();
this.featureDAO = daoFactory.getMobileFeatureDAO();
}
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
try {
WindowsDAOFactory.beginTransaction();
MobileFeature mobileFeature = MobileDeviceManagementUtil.convertToMobileFeature(feature);
featureDAO.addFeature(mobileFeature);
WindowsDAOFactory.commitTransaction();
return true;
} catch (MobileDeviceManagementDAOException e) {
WindowsDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while adding the feature", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
List<MobileFeature> mobileFeatures = new ArrayList<MobileFeature>(features.size());
for (Feature feature : features) {
mobileFeatures.add(MobileDeviceManagementUtil.convertToMobileFeature(feature));
}
try {
WindowsDAOFactory.beginTransaction();
featureDAO.addFeatures(mobileFeatures);
WindowsDAOFactory.commitTransaction();
return true;
} catch (MobileDeviceManagementDAOException e) {
WindowsDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while adding the features", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
try {
WindowsDAOFactory.openConnection();
MobileFeature mobileFeature = featureDAO.getFeatureByCode(name);
Feature feature = MobileDeviceManagementUtil.convertToFeature(mobileFeature);
return feature;
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the feature", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
try {
WindowsDAOFactory.openConnection();
List<MobileFeature> mobileFeatures = featureDAO.getAllFeatures();
List<Feature> featureList = new ArrayList<Feature>(mobileFeatures.size());
for (MobileFeature mobileFeature : mobileFeatures) {
featureList.add(MobileDeviceManagementUtil.convertToFeature(mobileFeature));
}
return featureList;
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the list of features registered for " +
"Windows platform", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public boolean removeFeature(String code) throws DeviceManagementException {
boolean status;
try {
WindowsDAOFactory.beginTransaction();
featureDAO.deleteFeatureByCode(code);
WindowsDAOFactory.commitTransaction();
status = true;
} catch (MobileDeviceManagementDAOException e) {
WindowsDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while removing the feature", e);
} finally {
WindowsDAOFactory.closeConnection();
}
return status;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
synchronized (this) {
List<Feature> supportedFeatures = getSupportedFeatures();
List<Feature> existingFeatures = this.getFeatures();
List<Feature> missingFeatures = MobileDeviceManagementUtil.
getMissingFeatures(supportedFeatures, existingFeatures);
if (missingFeatures.size() > 0) {
return this.addFeatures(missingFeatures);
}
return true;
}
}
/**
* Get supported Windows features.
*
* @return Supported features.
*/
public static List<Feature> getSupportedFeatures() {
List<Feature> supportedFeatures = new ArrayList<Feature>();
Feature feature = new Feature();
feature.setCode("DEVICE_LOCK");
feature.setName("Device Lock");
feature.setDescription("Lock the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("CAMERA");
feature.setName("camera");
feature.setDescription("Enable or disable camera");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_INFO");
feature.setName("Device info");
feature.setDescription("Request device information");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("WIPE_DATA");
feature.setName("Wipe Data");
feature.setDescription("Factory reset the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("ENCRYPT_STORAGE");
feature.setName("Encrypt storage");
feature.setDescription("Encrypt storage");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_RING");
feature.setName("Ring");
feature.setDescription("Ring the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("PASSCODE_POLICY");
feature.setName("Password Policy");
feature.setDescription("Set passcode policy");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DISENROLL");
feature.setName("DisEnroll");
feature.setDescription("DisEnroll the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("LOCK_RESET");
feature.setName("LockReset");
feature.setDescription("Lock Reset device");
supportedFeatures.add(feature);
return supportedFeatures;
}
}
| apache-2.0 |
the7thgoldrunner/FacebookNewsfeedSample-Android | FacebookNewsfeedSample/src/com/dhsoftware/android/FacebookNewsfeedSample/tasks/FacebookGraphAPIRequestTask.java | 4719 | package com.dhsoftware.android.FacebookNewsfeedSample.tasks;
import android.os.AsyncTask;
import com.dhsoftware.android.FacebookNewsfeedSample.model.GraphAPIRequest;
import com.dhsoftware.android.FacebookNewsfeedSample.model.IRequestCallback;
import com.dhsoftware.android.FacebookNewsfeedSample.model.newsfeed.INewsfeedItem;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* This distinct {@link android.os.AsyncTask AsyncTask} can be used to perform any sort of Graph API Request on Facebook.
* All you've got to do is set a {@link com.dhsoftware.android.FacebookNewsfeedSample.model.IRequestCallback IRequestCallback} Interface so you're
* notified of when your tasks are completed, and you'll receive an {@link java.util.ArrayList ArrayList} full of {@link com.dhsoftware.android.FacebookNewsfeedSample.model.newsfeed.INewsfeedItem INewsfeedItem}s
* for you tu use. Of course, you may also change and update this code in any way that suits your use of the Graph API. I just wanted to make it
* as simple as possible to show a user's Newsfeed onscreen.
* <br></br>
* <br></br>
* User: Dinesh Harjani (email: goldrunner18725@gmail.com) (github: the7thgoldrunner) (Twitter: @dinesharjani)
* <br></br>
* Date: 4/23/13
*/
public class FacebookGraphAPIRequestTask extends AsyncTask<GraphAPIRequest, Integer, Void> {
private ArrayList<INewsfeedItem> mItems;
private IRequestCallback mCallback;
public IRequestCallback getCallback() {
return mCallback;
}
public void setCallback(IRequestCallback callback) {
mCallback = callback;
}
/**
* We "open" the given JSONObject and add its items to our internal list.
*/
private void processResponse(JSONObject data) {
try {
JSONArray dataArray = (JSONArray)data.get("data");
GraphObjectList<INewsfeedItem> newsFeedItems = GraphObject.Factory.createList(dataArray, INewsfeedItem.class);
for (INewsfeedItem newsfeedItem : newsFeedItems) {
mItems.add(newsfeedItem);
}
}
catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
/**
* This is the method performing all of this Tasks' work. It loops through all of the {@link com.dhsoftware.android.FacebookNewsfeedSample.model.GraphAPIRequest GraphAPIRequest}s and
* adds all the downloaded items into a list.
*/
@Override
protected Void doInBackground(GraphAPIRequest... params) {
mItems = new ArrayList<INewsfeedItem>();
final Session session = Session.getActiveSession();
for (GraphAPIRequest request : params) {
Request graphApiRequest = Request.newGraphPathRequest(session, request.getGraphPath(), null);
graphApiRequest.setParameters(request.getParameters());
// this call blocks the calling thread, but in this case it's OK, since we're already in a background thread
// in this way, you can see both uses of making requests to the Facebook API
Response response = graphApiRequest.executeAndWait();
// we could also check here that our Session's valid; which is recommended in Facebook's own samples
// in this sample's case, I check it in MyNewsfeedFragment just before adding the downloaded items to the Adapter
if (response != null) {
// if we did get a response, we
processResponse(response.getGraphObject().getInnerJSONObject());
}
}
// We sort all items we've downloaded from newest to oldest,
// in this way, the items will fill in naturally to how we display
// Newsfeed items.
Collections.sort(mItems, new Comparator<INewsfeedItem>() {
@Override
public int compare(INewsfeedItem lhs, INewsfeedItem rhs) {
DateTime lhsDateTime = new DateTime(lhs.getCreated_Time());
DateTime rhsDateTime = new DateTime(rhs.getCreated_Time());
return (lhsDateTime.compareTo(rhsDateTime));
}
});
// this is not the method returning the objects,
// since we're still running in a background thread
return null;
}
/**
* This is where we give back the caller the items we've downloaded off the Facebook Graph API.
*/
@Override
protected void onPostExecute(Void object) {
if (mCallback != null) {
mCallback.requestCompleted(mItems);
}
}
}
| apache-2.0 |
strapdata/elassandra-test | core/src/test/java/org/elasticsearch/script/NativeScriptTests.java | 5381 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.script;
import com.google.common.collect.ImmutableSet;
import org.elasticsearch.common.ContextAndHeaderHolder;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.inject.Injector;
import org.elasticsearch.common.inject.ModulesBuilder;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.EnvironmentModule;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.ThreadPoolModule;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
public class NativeScriptTests extends ESTestCase {
@Test
public void testNativeScript() throws InterruptedException {
ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder();
Settings settings = Settings.settingsBuilder()
.put("name", "testNativeScript")
.put("path.home", createTempDir())
.build();
ScriptModule scriptModule = new ScriptModule(settings);
scriptModule.registerScript("my", MyNativeScriptFactory.class);
Injector injector = new ModulesBuilder().add(
new EnvironmentModule(new Environment(settings)),
new ThreadPoolModule(new ThreadPool(settings)),
new SettingsModule(settings),
scriptModule).createInjector();
ScriptService scriptService = injector.getInstance(ScriptService.class);
ExecutableScript executable = scriptService.executable(new Script("my", ScriptType.INLINE, NativeScriptEngineService.NAME, null),
ScriptContext.Standard.SEARCH, contextAndHeaders, Collections.<String, String>emptyMap());
assertThat(executable.run().toString(), equalTo("test"));
terminate(injector.getInstance(ThreadPool.class));
}
@Test
public void testFineGrainedSettingsDontAffectNativeScripts() throws IOException {
ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder();
Settings.Builder builder = Settings.settingsBuilder();
if (randomBoolean()) {
ScriptType scriptType = randomFrom(ScriptType.values());
builder.put(ScriptModes.SCRIPT_SETTINGS_PREFIX + scriptType, randomFrom(ScriptMode.values()));
} else {
String scriptContext = randomFrom(ScriptContext.Standard.values()).getKey();
builder.put(ScriptModes.SCRIPT_SETTINGS_PREFIX + scriptContext, randomFrom(ScriptMode.values()));
}
Settings settings = builder.put("path.home", createTempDir()).build();
Environment environment = new Environment(settings);
ResourceWatcherService resourceWatcherService = new ResourceWatcherService(settings, null);
Map<String, NativeScriptFactory> nativeScriptFactoryMap = new HashMap<>();
nativeScriptFactoryMap.put("my", new MyNativeScriptFactory());
Set<ScriptEngineService> scriptEngineServices = ImmutableSet.<ScriptEngineService>of(new NativeScriptEngineService(settings, nativeScriptFactoryMap));
ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(new ArrayList<ScriptContext.Plugin>());
ScriptService scriptService = new ScriptService(settings, environment, scriptEngineServices, resourceWatcherService, scriptContextRegistry);
for (ScriptContext scriptContext : scriptContextRegistry.scriptContexts()) {
assertThat(scriptService.compile(new Script("my", ScriptType.INLINE, NativeScriptEngineService.NAME, null), scriptContext,
contextAndHeaders, Collections.<String, String>emptyMap()), notNullValue());
}
}
public static class MyNativeScriptFactory implements NativeScriptFactory {
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
return new MyScript();
}
@Override
public boolean needsScores() {
return false;
}
}
static class MyScript extends AbstractExecutableScript {
@Override
public Object run() {
return "test";
}
}
}
| apache-2.0 |
Apelon-VA/ISAAC | refex-view/src/main/java/gov/va/isaac/gui/refexViews/refexEdit/HeaderNode.java | 6410 | /**
* Copyright Notice
*
* This is a work of the U.S. Government and is not subject to copyright
* protection in the United States. Foreign copyrights may apply.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gov.va.isaac.gui.refexViews.refexEdit;
import gov.va.isaac.gui.dialog.UserPrompt.UserPromptResponse;
import gov.va.isaac.gui.util.Images;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import com.sun.javafx.collections.ObservableListWrapper;
/**
* HeaderNode
*
* @author <a href="mailto:joel.kniaz@gmail.com">Joel Kniaz</a>
*
*
*/
public class HeaderNode<T> {
public static interface DataProvider<T> {
public T getData(RefexDynamicGUI source);
}
public static class Filter<T> {
private final Set<T> allPotentialFilterValues = new HashSet<>();
private final ObservableList<Object> filterValues = new ObservableListWrapper<>(new ArrayList<>());
private final ColumnId columnId;
private DataProvider<T> dataProvider;
/**
* @param columnKey
*/
public Filter(ColumnId columnId, DataProvider<T> dataProvider) {
super();
this.columnId = columnId;
this.dataProvider = dataProvider;
}
public boolean accept(RefexDynamicGUI data) {
if (filterValues.size() > 0) {
return filterValues.contains(dataProvider.getData(data));
} else {
return true;
}
}
public ObservableList<Object> getFilterValues() {
return filterValues;
}
/**
* @return the allPotentialFilterValues
*/
public Set<T> getAllPotentialFilterValues() {
return allPotentialFilterValues;
}
/**
* @return the columnId
*/
public ColumnId getColumnId() {
return columnId;
}
}
private final TreeTableColumn<RefexDynamicGUI, ?> column;
private final Scene scene;
private final DataProvider<T> dataProvider;
private final Button filterConfigurationButton = new Button();
private final Filter<T> filter;
private final ImageView image = Images.FILTER_16.createImageView();
@SuppressWarnings("unchecked")
private Filter<T> castFilterFromCache(Filter<?> filter) {
return (Filter<T>)filter;
}
public HeaderNode(
ObservableMap<ColumnId, Filter<?>> filterCache,
TreeTableColumn<RefexDynamicGUI, ?> col,
ColumnId columnId,
Scene scene,
DataProvider<T> dataProvider) {
this.column = col;
this.scene = scene;
this.image.setFitHeight(8);
this.image.setFitWidth(8);
this.dataProvider = dataProvider;
if (filterCache.get(columnId) != null) {
this.filter = castFilterFromCache(filterCache.get(columnId));
this.filter.dataProvider = dataProvider;
} else {
this.filter = new Filter<>(columnId, dataProvider);
filterCache.put(columnId, filter);
}
filterConfigurationButton.setGraphic(image);
Platform.runLater(() ->
{
filterConfigurationButton.setTooltip(new Tooltip("Press to configure filters for " + col.getText()));
});
filter.getFilterValues().addListener(new ListChangeListener<Object>() {
@Override
public void onChanged(
javafx.collections.ListChangeListener.Change<? extends Object> c) {
updateButton();
}
});
updateButton();
filterConfigurationButton.setOnAction(event -> { setUserFilters(column.getText()); });
}
private void updateButton() {
if (filter.getFilterValues().size() > 0) {
filterConfigurationButton.setStyle(
"-fx-background-color: red;"
+ "-fx-padding: 0 0 0 0;");
} else {
filterConfigurationButton.setStyle(
"-fx-background-color: white;"
+ "-fx-padding: 0 0 0 0;");
}
}
private static <T> Set<T> getUniqueDisplayObjects(TreeItem<RefexDynamicGUI> item, DataProvider<T> dataProvider) {
Set<T> stringSet = new HashSet<>();
if (item == null) {
return stringSet;
}
if (item.getValue() != null) {
stringSet.add(dataProvider.getData(item.getValue()));
}
for (TreeItem<RefexDynamicGUI> childItem : item.getChildren()) {
stringSet.addAll(getUniqueDisplayObjects(childItem, dataProvider));
}
return stringSet;
}
private void setUserFilters(String text) {
List<String> testList = new ArrayList<String>();
for (T obj : getUniqueDisplayObjects(column.getTreeTableView().getRoot(), dataProvider)) {
if (obj != null) {
filter.allPotentialFilterValues.add(obj);
}
}
// TODO (artf231431) allPotentialFilterValues should be populated on initial, unfiltered, load, not deferred until HeaderNode activation
for (T obj : filter.allPotentialFilterValues) {
testList.add(obj.toString());
}
Collections.sort(testList);
RefexContentFilterPrompt prompt = new RefexContentFilterPrompt(text, testList, filter.getFilterValues());
prompt.showUserPrompt((Stage)scene.getWindow(), "Select Filters");
if (prompt.getButtonSelected() == UserPromptResponse.APPROVE) {
filter.getFilterValues().setAll(prompt.getSelectedValues());
} else {
//filter.getFilterValues().clear();
}
}
public Button getButton() { return filterConfigurationButton; }
public TreeTableColumn<RefexDynamicGUI, ?> getColumn() { return column; }
public ObservableList<Object> getUserFilters() { return filter.getFilterValues(); }
public Node getNode() { return filterConfigurationButton; }
}
| apache-2.0 |
krosenvold/AxonFramework | messaging/src/test/java/org/axonframework/messaging/unitofwork/AbstractUnitOfWorkTest.java | 8439 | /*
* Copyright (c) 2010-2018. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.messaging.unitofwork;
import org.axonframework.utils.MockException;
import org.axonframework.common.transaction.Transaction;
import org.axonframework.common.transaction.TransactionManager;
import org.axonframework.eventhandling.GenericEventMessage;
import org.axonframework.messaging.ResultMessage;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.axonframework.messaging.GenericResultMessage.asResultMessage;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* @author Allard Buijze
*/
class AbstractUnitOfWorkTest {
private List<PhaseTransition> phaseTransitions;
private UnitOfWork<?> subject;
@SuppressWarnings({"unchecked"})
@BeforeEach
void setUp() {
while (CurrentUnitOfWork.isStarted()) {
CurrentUnitOfWork.get().rollback();
}
subject = spy(new DefaultUnitOfWork(new GenericEventMessage<>("Input 1")) {
@Override
public String toString() {
return "unitOfWork";
}
});
phaseTransitions = new ArrayList<>();
registerListeners(subject);
}
private void registerListeners(UnitOfWork<?> unitOfWork) {
unitOfWork.onPrepareCommit(u -> phaseTransitions.add(new PhaseTransition(u, UnitOfWork.Phase.PREPARE_COMMIT)));
unitOfWork.onCommit(u -> phaseTransitions.add(new PhaseTransition(u, UnitOfWork.Phase.COMMIT)));
unitOfWork.afterCommit(u -> phaseTransitions.add(new PhaseTransition(u, UnitOfWork.Phase.AFTER_COMMIT)));
unitOfWork.onRollback(u -> phaseTransitions.add(new PhaseTransition(u, UnitOfWork.Phase.ROLLBACK)));
unitOfWork.onCleanup(u -> phaseTransitions.add(new PhaseTransition(u, UnitOfWork.Phase.CLEANUP)));
}
@AfterEach
void tearDown() {
assertFalse(CurrentUnitOfWork.isStarted(), "A UnitOfWork was not properly cleared");
}
@Test
void testHandlersForCurrentPhaseAreExecuted() {
AtomicBoolean prepareCommit = new AtomicBoolean();
AtomicBoolean commit = new AtomicBoolean();
AtomicBoolean afterCommit = new AtomicBoolean();
AtomicBoolean cleanup = new AtomicBoolean();
subject.onPrepareCommit(u -> subject.onPrepareCommit(i -> prepareCommit.set(true)));
subject.onCommit(u -> subject.onCommit(i -> commit.set(true)));
subject.afterCommit(u -> subject.afterCommit(i -> afterCommit.set(true)));
subject.onCleanup(u -> subject.onCleanup(i -> cleanup.set(true)));
subject.start();
subject.commit();
assertTrue(prepareCommit.get());
assertTrue(commit.get());
assertTrue(afterCommit.get());
assertTrue(cleanup.get());
}
@Test
void testExecuteTask() {
Runnable task = mock(Runnable.class);
doNothing().when(task).run();
subject.execute(task);
InOrder inOrder = inOrder(task, subject);
inOrder.verify(subject).start();
inOrder.verify(task).run();
inOrder.verify(subject).commit();
assertFalse(subject.isActive());
}
@Test
void testExecuteFailingTask() {
Runnable task = mock(Runnable.class);
MockException mockException = new MockException();
doThrow(mockException).when(task).run();
try {
subject.execute(task);
} catch (MockException e) {
InOrder inOrder = inOrder(task, subject);
inOrder.verify(subject).start();
inOrder.verify(task).run();
inOrder.verify(subject).rollback(e);
assertNotNull(subject.getExecutionResult());
assertSame(mockException, subject.getExecutionResult().getExceptionResult());
return;
}
throw new AssertionError();
}
@Test
void testExecuteTaskWithResult() throws Exception {
Object taskResult = new Object();
Callable<Object> task = mock(Callable.class);
when(task.call()).thenReturn(taskResult);
ResultMessage result = subject.executeWithResult(task);
InOrder inOrder = inOrder(task, subject);
inOrder.verify(subject).start();
inOrder.verify(task).call();
inOrder.verify(subject).commit();
assertFalse(subject.isActive());
assertSame(taskResult, result.getPayload());
assertNotNull(subject.getExecutionResult());
assertSame(taskResult, subject.getExecutionResult().getResult().getPayload());
}
@Test
void testExecuteTaskReturnsResultMessage() throws Exception {
ResultMessage<Object> resultMessage = asResultMessage(new Object());
Callable<ResultMessage<Object>> task = mock(Callable.class);
when(task.call()).thenReturn(resultMessage);
ResultMessage actualResultMessage = subject.executeWithResult(task);
assertSame(resultMessage, actualResultMessage);
}
@Test
void testAttachedTransactionCommittedOnUnitOfWorkCommit() {
TransactionManager transactionManager = mock(TransactionManager.class);
Transaction transaction = mock(Transaction.class);
when(transactionManager.startTransaction()).thenReturn(transaction);
subject.attachTransaction(transactionManager);
subject.start();
verify(transactionManager).startTransaction();
verify(transaction, never()).commit();
subject.commit();
verify(transaction).commit();
}
@Test
void testAttachedTransactionRolledBackOnUnitOfWorkRollBack() {
TransactionManager transactionManager = mock(TransactionManager.class);
Transaction transaction = mock(Transaction.class);
when(transactionManager.startTransaction()).thenReturn(transaction);
subject.attachTransaction(transactionManager);
subject.start();
verify(transactionManager).startTransaction();
verify(transaction, never()).commit();
verify(transaction, never()).rollback();
subject.rollback();
verify(transaction).rollback();
verify(transaction, never()).commit();
}
@Test
void unitOfWorkIsRolledBackWhenTransactionFailsToStart() {
TransactionManager transactionManager = mock(TransactionManager.class);
when(transactionManager.startTransaction()).thenThrow(new MockException());
try {
subject.attachTransaction(transactionManager);
fail("Expected MockException to be propagated");
} catch (Exception e) {
// expected
}
verify(subject).rollback(isA(MockException.class));
}
private static class PhaseTransition {
private final UnitOfWork.Phase phase;
private final UnitOfWork<?> unitOfWork;
public PhaseTransition(UnitOfWork<?> unitOfWork, UnitOfWork.Phase phase) {
this.unitOfWork = unitOfWork;
this.phase = phase;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PhaseTransition that = (PhaseTransition) o;
return Objects.equals(phase, that.phase) &&
Objects.equals(unitOfWork, that.unitOfWork);
}
@Override
public int hashCode() {
return Objects.hash(phase, unitOfWork);
}
@Override
public String toString() {
return unitOfWork + " " + phase;
}
}
}
| apache-2.0 |
rafaelgarrote/metamodel | sugarcrm/src/main/java/org/apache/metamodel/sugarcrm/SugarCrmTable.java | 5728 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.metamodel.sugarcrm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.metamodel.schema.AbstractTable;
import org.apache.metamodel.schema.Column;
import org.apache.metamodel.schema.ColumnType;
import org.apache.metamodel.schema.MutableColumn;
import org.apache.metamodel.schema.Relationship;
import org.apache.metamodel.schema.Schema;
import org.apache.metamodel.schema.TableType;
import org.apache.metamodel.util.LazyRef;
import org.apache.metamodel.util.Ref;
import org.w3c.dom.Node;
import com.sugarcrm.ws.soap.FieldList;
import com.sugarcrm.ws.soap.NewModuleFields;
import com.sugarcrm.ws.soap.SelectFields;
import com.sugarcrm.ws.soap.SugarsoapPortType;
final class SugarCrmTable extends AbstractTable {
private static final long serialVersionUID = 1L;
private static final Map<String, ColumnType> TYPE_MAPPING;
static {
TYPE_MAPPING = new HashMap<String, ColumnType>();
// known string types
TYPE_MAPPING.put("name", ColumnType.VARCHAR);
TYPE_MAPPING.put("assigned_user_name", ColumnType.VARCHAR);
TYPE_MAPPING.put("text", ColumnType.VARCHAR);
TYPE_MAPPING.put("enum", ColumnType.VARCHAR);
TYPE_MAPPING.put("varchar", ColumnType.VARCHAR);
TYPE_MAPPING.put("phone", ColumnType.VARCHAR);
TYPE_MAPPING.put("fullname", ColumnType.VARCHAR);
TYPE_MAPPING.put("url", ColumnType.VARCHAR);
TYPE_MAPPING.put("relate", ColumnType.VARCHAR);
TYPE_MAPPING.put("email", ColumnType.VARCHAR);
TYPE_MAPPING.put("parent", ColumnType.VARCHAR);
TYPE_MAPPING.put("parent_type", ColumnType.VARCHAR);
TYPE_MAPPING.put("currency", ColumnType.VARCHAR);
TYPE_MAPPING.put("none", ColumnType.VARCHAR);
TYPE_MAPPING.put("user_name", ColumnType.VARCHAR);
TYPE_MAPPING.put("file", ColumnType.VARCHAR);
TYPE_MAPPING.put("id", ColumnType.VARCHAR);
// known numbers
TYPE_MAPPING.put("int", ColumnType.INTEGER);
// known booleans
TYPE_MAPPING.put("bool", ColumnType.BOOLEAN);
// known timebased
TYPE_MAPPING.put("date", ColumnType.DATE);
TYPE_MAPPING.put("datetime", ColumnType.DATE);
TYPE_MAPPING.put("datetimecombo", ColumnType.DATE);
}
private final String _name;
private final Schema _schema;
private final Ref<List<Column>> _columnsRef;
public SugarCrmTable(String name, Schema schema, final SugarsoapPortType service, final Ref<String> sessionId) {
_name = name;
_schema = schema;
_columnsRef = new LazyRef<List<Column>>() {
@Override
protected List<Column> fetch() {
final List<Column> result = new ArrayList<Column>();
final String session = sessionId.get();
final NewModuleFields fields = service.getModuleFields(session, _name, new SelectFields());
final FieldList moduleFields = fields.getModuleFields();
final List<Object> list = moduleFields.getAny();
for (Object object : list) {
if (object instanceof Node) {
final Node node = (Node) object;
final String name = SugarCrmXmlHelper.getChildElementText(node, "name");
final String nativeType = SugarCrmXmlHelper.getChildElementText(node, "type");
final String remarks = SugarCrmXmlHelper.getChildElementText(node, "label");
final ColumnType columnType = convertToColumnType(nativeType);
final Column column = new MutableColumn(name, columnType).setNativeType(nativeType)
.setRemarks(remarks).setTable(SugarCrmTable.this);
result.add(column);
}
}
return result;
}
};
}
@Override
public String getName() {
return _name;
}
@Override
public Column[] getColumns() {
final List<Column> columns = _columnsRef.get();
return columns.toArray(new Column[columns.size()]);
}
@Override
public Schema getSchema() {
return _schema;
}
@Override
public TableType getType() {
return TableType.TABLE;
}
@Override
public Relationship[] getRelationships() {
return new Relationship[0];
}
@Override
public String getRemarks() {
return null;
}
@Override
public String getQuote() {
return null;
}
private ColumnType convertToColumnType(String sugarType) {
ColumnType columnType = TYPE_MAPPING.get(sugarType);
if (columnType == null) {
columnType = ColumnType.OTHER;
}
return columnType;
}
}
| apache-2.0 |
nknize/elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/pipeline/MovFnPipelineAggregationBuilder.java | 9304 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.pipeline;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.BUCKETS_PATH;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.FORMAT;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregator.Parser.GAP_POLICY;
public class MovFnPipelineAggregationBuilder extends AbstractPipelineAggregationBuilder<MovFnPipelineAggregationBuilder> {
public static final String NAME = "moving_fn";
private static final ParseField WINDOW = new ParseField("window");
private static final ParseField SHIFT = new ParseField("shift");
private final Script script;
private final String bucketsPathString;
private String format = null;
private GapPolicy gapPolicy = GapPolicy.SKIP;
private int window;
private int shift;
public static final ConstructingObjectParser<MovFnPipelineAggregationBuilder, String> PARSER = new ConstructingObjectParser<>(
NAME, false,
(args, name) -> new MovFnPipelineAggregationBuilder(name, (String) args[0], (Script) args[1], (int)args[2]));
static {
PARSER.declareString(constructorArg(), BUCKETS_PATH_FIELD);
PARSER.declareField(constructorArg(),
(p, c) -> Script.parse(p), Script.SCRIPT_PARSE_FIELD, ObjectParser.ValueType.OBJECT_OR_STRING);
PARSER.declareInt(constructorArg(), WINDOW);
PARSER.declareInt(MovFnPipelineAggregationBuilder::setShift, SHIFT);
PARSER.declareString(MovFnPipelineAggregationBuilder::format, FORMAT);
PARSER.declareField(MovFnPipelineAggregationBuilder::gapPolicy, p -> {
if (p.currentToken() == XContentParser.Token.VALUE_STRING) {
return GapPolicy.parse(p.text().toLowerCase(Locale.ROOT), p.getTokenLocation());
}
throw new IllegalArgumentException("Unsupported token [" + p.currentToken() + "]");
}, GAP_POLICY, ObjectParser.ValueType.STRING);
};
public MovFnPipelineAggregationBuilder(String name, String bucketsPath, Script script, int window) {
super(name, NAME, new String[]{bucketsPath});
this.bucketsPathString = bucketsPath;
this.script = script;
if (window <= 0) {
throw new IllegalArgumentException("[" + WINDOW.getPreferredName() + "] must be a positive, non-zero integer.");
}
this.window = window;
}
public MovFnPipelineAggregationBuilder(StreamInput in) throws IOException {
super(in, NAME);
bucketsPathString = in.readString();
script = new Script(in);
format = in.readOptionalString();
gapPolicy = GapPolicy.readFrom(in);
window = in.readInt();
shift = in.readInt();
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeString(bucketsPathString);
script.writeTo(out);
out.writeOptionalString(format);
gapPolicy.writeTo(out);
out.writeInt(window);
out.writeInt(shift);
}
/**
* Sets the format to use on the output of this aggregation.
*/
public MovFnPipelineAggregationBuilder format(String format) {
if (Strings.isNullOrEmpty(format)) {
throw new IllegalArgumentException("[" + FORMAT.getPreferredName() + "] must not be null or an empty string.");
}
this.format = format;
return this;
}
/**
* Gets the format to use on the output of this aggregation.
*/
public String format() {
return format;
}
protected DocValueFormat formatter() {
if (format != null) {
return new DocValueFormat.Decimal(format);
}
return DocValueFormat.RAW;
}
/**
* Sets the gap policy to use for this aggregation.
*/
public MovFnPipelineAggregationBuilder gapPolicy(GapPolicy gapPolicy) {
if (gapPolicy == null) {
throw new IllegalArgumentException("[" + GAP_POLICY.getPreferredName() + "] must not be null.");
}
this.gapPolicy = gapPolicy;
return this;
}
/**
* Gets the gap policy to use for this aggregation.
*/
public GapPolicy gapPolicy() {
return gapPolicy;
}
/**
* Returns the window size for this aggregation
*/
public int getWindow() {
return window;
}
/**
* Sets the window size for this aggregation
*/
public void setWindow(int window) {
if (window <= 0) {
throw new IllegalArgumentException("[" + WINDOW.getPreferredName() + "] must be a positive, non-zero integer.");
}
this.window = window;
}
public void setShift(int shift) {
this.shift = shift;
}
@Override
protected void validate(ValidationContext context) {
if (window <= 0) {
context.addValidationError("[" + WINDOW.getPreferredName() + "] must be a positive, non-zero integer.");
}
context.validateParentAggSequentiallyOrdered(NAME, name);
}
@Override
protected PipelineAggregator createInternal(Map<String, Object> metadata) {
return new MovFnPipelineAggregator(name, bucketsPathString, script, window, shift, formatter(), gapPolicy, metadata);
}
@Override
protected XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(BUCKETS_PATH.getPreferredName(), bucketsPathString);
builder.field(Script.SCRIPT_PARSE_FIELD.getPreferredName(), script);
if (format != null) {
builder.field(FORMAT.getPreferredName(), format);
}
builder.field(GAP_POLICY.getPreferredName(), gapPolicy.getName());
builder.field(WINDOW.getPreferredName(), window);
builder.field(SHIFT.getPreferredName(), shift);
return builder;
}
/**
* Used for serialization testing, since pipeline aggs serialize themselves as a named object but are parsed
* as a regular object with the name passed in.
*/
static MovFnPipelineAggregationBuilder parse(XContentParser parser) throws IOException {
parser.nextToken();
if (parser.currentToken().equals(XContentParser.Token.START_OBJECT)) {
parser.nextToken();
if (parser.currentToken().equals(XContentParser.Token.FIELD_NAME)) {
String aggName = parser.currentName();
parser.nextToken(); // "moving_fn"
parser.nextToken(); // start_object
return PARSER.apply(parser, aggName);
}
}
throw new IllegalStateException("Expected aggregation name but none found");
}
@Override
protected boolean overrideBucketsPath() {
return true;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), bucketsPathString, script, format, gapPolicy, window, shift);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
if (super.equals(obj) == false) return false;
MovFnPipelineAggregationBuilder other = (MovFnPipelineAggregationBuilder) obj;
return Objects.equals(bucketsPathString, other.bucketsPathString)
&& Objects.equals(script, other.script)
&& Objects.equals(format, other.format)
&& Objects.equals(gapPolicy, other.gapPolicy)
&& Objects.equals(window, other.window)
&& Objects.equals(shift, other.shift);
}
@Override
public String getWriteableName() {
return NAME;
}
}
| apache-2.0 |
yauritux/venice-legacy | Venice/Venice-Web/target/classes/com/gdn/venice/client/app/administration/data/AdministrationData.java | 19581 | package com.gdn.venice.client.app.administration.data;
import java.util.HashMap;
import com.gdn.venice.client.app.DataNameTokens;
import com.gdn.venice.client.app.administration.presenter.ModuleConfigurationPresenter;
import com.gdn.venice.client.app.administration.presenter.RoleProfileUserGroupManagementPresenter;
import com.gdn.venice.client.data.RafDataSource;
import com.google.gwt.core.client.GWT;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.widgets.tree.TreeNode;
/**
* Defines the data sources for the user, group, role and profile data for testing purposes.
* @author David Forden
*
*/
public class AdministrationData {
private static DataSource profileScreenDataDs= null;
private static DataSource moduleDataDs = null;
public static RafDataSource getRoleData() {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFROLE_ROLEID, "Role ID"),
new DataSourceTextField(DataNameTokens.RAFROLE_ROLENAME, "Role Name"),
new DataSourceTextField(DataNameTokens.RAFROLE_ROLEDESC, "Description"),
new DataSourceTextField(DataNameTokens.RAFROLE_PARENTROLE, "Reports to")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchRoleData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addRoleData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateRoleData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteRoleData&type=DataSource",
dataSourceFields);
return retVal;
}
public static DataSource getRoleDetailProfileData(String roleId) {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFROLEPROFILE_RAFROLEPROFILEID, "Role Profile ID"),
new DataSourceTextField(DataNameTokens.RAFROLE_RAFROLEPROFILES_ROLEID, "Role Name"),
new DataSourceTextField(DataNameTokens.RAFROLE_RAFROLEPROFILES_PROFILEID, "Assigned Profile")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchRoleDetailProfileData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addRoleDetailProfileData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateRoleDetailProfileData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteRoleDetailProfileData&type=DataSource",
dataSourceFields);
HashMap<String, String> params = new HashMap<String, String>();
params.put(DataNameTokens.RAFROLE_ROLEID, roleId);
retVal.getOperationBinding(DSOperationType.FETCH).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.ADD).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.UPDATE).setDefaultParams(params);
return retVal;
}
public static DataSource getRoleDetailUserData(String roleId) {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFUSERROLE_RAFUSERROLEID, "User Role ID"),
new DataSourceTextField(DataNameTokens.RAFROLE_RAFUSERROLES_ROLEID, "Role Name"),
new DataSourceTextField(DataNameTokens.RAFROLE_RAFUSERROLES_USERID, "Assigned User")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchRoleDetailUserData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addRoleDetailUserData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateRoleDetailUserData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteRoleDetailUserData&type=DataSource",
dataSourceFields);
HashMap<String, String> params = new HashMap<String, String>();
params.put(DataNameTokens.RAFROLE_ROLEID, roleId);
retVal.getOperationBinding(DSOperationType.FETCH).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.ADD).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.UPDATE).setDefaultParams(params);
return retVal;
}
public static RafDataSource getProfileData() {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFPROFILE_PROFILEID, "Profile ID"),
new DataSourceTextField(DataNameTokens.RAFPROFILE_PROFILENAME, "Profile Name"),
new DataSourceTextField(DataNameTokens.RAFPROFILE_PROFILEDESC, "Description")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchProfileData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addProfileData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateProfileData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteProfileData&type=DataSource",
dataSourceFields);
return retVal;
}
public static DataSource getProfileDetailData(String profileId) {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFPROFILEPERMISSION_RAFPROFILEPERMISSIONID, "Profile Permission ID"),
new DataSourceTextField(DataNameTokens.RAFPROFILEPERMISSION_PROFILEID, "Profile Name"),
new DataSourceTextField(DataNameTokens.RAFPROFILEPERMISSION_APPLICATIONOBJECTID, "Screen Name"),
new DataSourceTextField(DataNameTokens.RAFPROFILEPERMISSION_PERMISSIONTYPEID, "Permission Type")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchProfileDetailData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addProfileDetailData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateProfileDetailData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteProfileDetailData&type=DataSource",
dataSourceFields);
HashMap<String, String> params = new HashMap<String, String>();
params.put(DataNameTokens.RAFPROFILE_PROFILEID, profileId);
retVal.getOperationBinding(DSOperationType.FETCH).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.ADD).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.UPDATE).setDefaultParams(params);
return retVal;
}
// public static DataSource getProfileScreenData() {
// if (profileScreenDataDs != null) {
// return profileScreenDataDs;
// } else {
// profileScreenDataDs = new DataSource();
// profileScreenDataDs.setRecordXPath("/admin/screens/screen");
//
// DataSourceTextField screenNameField = new DataSourceTextField("name", "Screen");
// DataSourceTextField fieldNameField = new DataSourceTextField("field", "Field");
// DataSourceBooleanField editField = new DataSourceBooleanField("edit", "Edit");
// DataSourceBooleanField viewField = new DataSourceBooleanField("view", "View");
// DataSourceBooleanField deleteField = new DataSourceBooleanField("delete", "Delete");
//
// profileScreenDataDs.setFields(screenNameField, fieldNameField, editField, viewField, deleteField);
// profileScreenDataDs.setDataURL("ds/test_data/admin.data.xml");
// profileScreenDataDs.setClientOnly(true);
//
// return profileScreenDataDs;
// }
//
// }
public static RafDataSource getUserData() {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFUSER_USERID, "User ID"),
new DataSourceTextField(DataNameTokens.RAFUSER_LOGINNAME, "User Name")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchUserData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addUserData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateUserData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteUserData&type=DataSource",
dataSourceFields);
return retVal;
}
public static DataSource getUserDetailGroupData(String userId) {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFUSERGROUP_RAFUSERGROUPID, "User Group ID"),
new DataSourceTextField(DataNameTokens.RAFUSER_RAFUSERGROUP_USERID, "User Name"),
new DataSourceTextField(DataNameTokens.RAFUSER_RAFUSERGROUP_GROUPID, "Assigned Group")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchUserDetailGroupData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addUserDetailGroupData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateUserDetailGroupData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteUserDetailGroupData&type=DataSource",
dataSourceFields);
HashMap<String, String> params = new HashMap<String, String>();
params.put(DataNameTokens.RAFUSER_USERID, userId);
retVal.getOperationBinding(DSOperationType.FETCH).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.ADD).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.UPDATE).setDefaultParams(params);
return retVal;
}
public static DataSource getUserDetailRoleData(String userId) {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFUSERROLE_RAFUSERROLEID, "User Role ID"),
new DataSourceTextField(DataNameTokens.RAFUSER_RAFUSERROLES_USERID, "User Name"),
new DataSourceTextField(DataNameTokens.RAFUSER_RAFUSERROLES_ROLEID, "Assigned Role")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchUserDetailRoleData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addUserDetailRoleData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateUserDetailRoleData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteUserDetailRoleData&type=DataSource",
dataSourceFields);
HashMap<String, String> params = new HashMap<String, String>();
params.put(DataNameTokens.RAFUSER_USERID, userId);
retVal.getOperationBinding(DSOperationType.FETCH).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.ADD).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.UPDATE).setDefaultParams(params);
return retVal;
}
public static RafDataSource getGroupData() {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFGROUP_GROUPID, "Group ID"),
new DataSourceTextField(DataNameTokens.RAFGROUP_GROUPNAME, "Group Name"),
new DataSourceTextField(DataNameTokens.RAFGROUP_GROUPDESC, "Description")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchGroupData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addGroupData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateGroupData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteGroupData&type=DataSource",
dataSourceFields);
return retVal;
}
public static RafDataSource getGroupDetailData(String groupId) {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFGROUPROLE_RAFGROUPROLEID, "Group Role ID"),
new DataSourceTextField(DataNameTokens.RAFGROUP_RAFGROUPROLES_GROUPID, "Group"),
new DataSourceTextField(DataNameTokens.RAFGROUP_RAFGROUPROLES_ROLEID, "Assigned Role")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=fetchGroupDetailData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=addGroupDetailData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=updateGroupDetailData&type=DataSource",
GWT.getHostPageBaseURL() + RoleProfileUserGroupManagementPresenter.roleProfileUserGroupManagementPresenterServlet + "?method=deleteGroupDetailData&type=DataSource",
dataSourceFields);
HashMap<String, String> params = new HashMap<String, String>();
params.put(DataNameTokens.RAFGROUP_GROUPID, groupId);
retVal.getOperationBinding(DSOperationType.FETCH).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.ADD).setDefaultParams(params);
retVal.getOperationBinding(DSOperationType.UPDATE).setDefaultParams(params);
return retVal;
}
public static RafDataSource getModuleConfigurationData() {
DataSourceField[] dataSourceFields = {
new DataSourceTextField(DataNameTokens.RAFAPPLICATIONOBJECT_APPLICATIONOBJECTID, "Module ID"),
new DataSourceTextField(DataNameTokens.RAFAPPLICATIONOBJECT_APPLICATIONOBJECTUUID, "Module UUID"),
new DataSourceTextField(DataNameTokens.RAFAPPLICATIONOBJECT_APPLICATIONOBJECTTYPEID, "Module Type"),
new DataSourceTextField(DataNameTokens.RAFAPPLICATIONOBJECT_APPLICATIONOBJECTCANONICALNAME, "Module Name"),
new DataSourceTextField(DataNameTokens.RAFAPPLICATIONOBJECT_PARENTAPPLICATIONOBJECTID, "Parent Module")
};
dataSourceFields[0].setPrimaryKey(true);
RafDataSource retVal = new RafDataSource(
"/response/data/*",
GWT.getHostPageBaseURL() + ModuleConfigurationPresenter.moduleConfigurationPresenterServlet + "?method=fetchModuleConfigurationData&type=DataSource",
GWT.getHostPageBaseURL() + ModuleConfigurationPresenter.moduleConfigurationPresenterServlet + "?method=addModuleConfigurationData&type=DataSource",
GWT.getHostPageBaseURL() + ModuleConfigurationPresenter.moduleConfigurationPresenterServlet + "?method=updateModuleConfigurationData&type=DataSource",
GWT.getHostPageBaseURL() + ModuleConfigurationPresenter.moduleConfigurationPresenterServlet + "?method=deleteModuleConfigurationData&type=DataSource",
dataSourceFields);
return retVal;
}
public static TreeNode[] getRoleTreeData() {
return new RoleTreeNode[]{
new RoleTreeNode("2", "1", "CEO"),
new RoleTreeNode("3", "2", "Operations Head"),
new RoleTreeNode("4", "3", "Operations Officer"),
new RoleTreeNode("5", "4", "Operations Staff"),
new RoleTreeNode("6", "2", "Finance Head"),
new RoleTreeNode("7", "6", "Finance Officer"),
new RoleTreeNode("8", "7", "Finance Staff")
};
}
private static class RoleTreeNode extends TreeNode{
public RoleTreeNode(String roleId, String roleParent, String roleName) {
setNavigationId(roleId);
setNavigationParent(roleParent);
setNavigationName(roleName);
}
public void setNavigationId(String id) {
setAttribute("RoleId", id);
}
public void setNavigationParent(String navigationParent) {
setAttribute("RoleParent", navigationParent);
}
public void setNavigationName(String navigationName) {
setAttribute("RoleName", navigationName);
}
}
// public static DataSource getModuleData() {
// if (moduleDataDs != null) {
// return moduleDataDs;
// } else {
// moduleDataDs = new DataSource();
// moduleDataDs.setRecordXPath("/admin/modules/module");
//
// DataSourceTextField moduleIdField = new DataSourceTextField("moduleid", "Module Id");
// DataSourceTextField moduleUuidField = new DataSourceTextField("uuid", "UUID");
// DataSourceTextField moduleTypeField = new DataSourceTextField("type", "Module Type");
// DataSourceTextField moduleNameField = new DataSourceTextField("name", "Module Name");
//
// moduleDataDs.setFields(moduleIdField, moduleUuidField,moduleTypeField, moduleNameField);
// moduleDataDs.setDataURL("ds/test_data/admin.data.xml");
// moduleDataDs.setClientOnly(true);
//
// return moduleDataDs;
// }
//
// }
}
| apache-2.0 |
daversilva/nfe | src/main/java/com/fincatto/nfe200/transformers/NFNotaInfoSituacaoTributariaIPITransformer.java | 632 | package com.fincatto.nfe200.transformers;
import org.simpleframework.xml.transform.Transform;
import com.fincatto.nfe200.classes.NFNotaInfoSituacaoTributariaIPI;
public class NFNotaInfoSituacaoTributariaIPITransformer implements Transform<NFNotaInfoSituacaoTributariaIPI> {
@Override
public NFNotaInfoSituacaoTributariaIPI read(final String codigo) throws Exception {
return NFNotaInfoSituacaoTributariaIPI.valueOfCodigo(codigo);
}
@Override
public String write(final NFNotaInfoSituacaoTributariaIPI situacaoTributariaIPI) throws Exception {
return situacaoTributariaIPI.getCodigo();
}
} | apache-2.0 |
predix/acs | model/src/main/java/com/ge/predix/acs/model/Effect.java | 984 | /*******************************************************************************
* Copyright 2017 General Electric Company
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*******************************************************************************/
package com.ge.predix.acs.model;
/**
*
* @author acs-engineers@ge.com
*/
@SuppressWarnings("javadoc")
public enum Effect {
PERMIT, DENY, NOT_APPLICABLE, INDETERMINATE
}
| apache-2.0 |
dbmalkovsky/flowable-engine | modules/flowable-crystalball/src/test/java/org/flowable/crystalball/simulator/impl/playback/CheckStatus.java | 881 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.crystalball.simulator.impl.playback;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckStatus {
/** Specify resources that make up the process definition. */
String methodName() default "";
}
| apache-2.0 |
ekcs/congress | thirdparty/antlr3-antlr-3.5/runtime/Java/src/main/java/org/antlr/runtime/tree/TreeRewriter.java | 4949 | /*
[The "BSD license"]
Copyright (c) 2005-2009 Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.runtime.tree;
import org.antlr.runtime.RecognizerSharedState;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
public class TreeRewriter extends TreeParser {
public interface fptr {
public Object rule() throws RecognitionException;
}
protected boolean showTransformations = false;
protected TokenStream originalTokenStream;
protected TreeAdaptor originalAdaptor;
public TreeRewriter(TreeNodeStream input) {
this(input, new RecognizerSharedState());
}
public TreeRewriter(TreeNodeStream input, RecognizerSharedState state) {
super(input, state);
originalAdaptor = input.getTreeAdaptor();
originalTokenStream = input.getTokenStream();
}
public Object applyOnce(Object t, fptr whichRule) {
if ( t==null ) return null;
try {
// share TreeParser object but not parsing-related state
state = new RecognizerSharedState();
input = new CommonTreeNodeStream(originalAdaptor, t);
((CommonTreeNodeStream)input).setTokenStream(originalTokenStream);
setBacktrackingLevel(1);
TreeRuleReturnScope r = (TreeRuleReturnScope)whichRule.rule();
setBacktrackingLevel(0);
if ( failed() ) return t;
if ( showTransformations &&
r!=null && !t.equals(r.getTree()) && r.getTree()!=null )
{
reportTransformation(t, r.getTree());
}
if ( r!=null && r.getTree()!=null ) return r.getTree();
else return t;
}
catch (RecognitionException e) { ; }
return t;
}
public Object applyRepeatedly(Object t, fptr whichRule) {
boolean treeChanged = true;
while ( treeChanged ) {
Object u = applyOnce(t, whichRule);
treeChanged = !t.equals(u);
t = u;
}
return t;
}
public Object downup(Object t) { return downup(t, false); }
public Object downup(Object t, boolean showTransformations) {
this.showTransformations = showTransformations;
TreeVisitor v = new TreeVisitor(new CommonTreeAdaptor());
TreeVisitorAction actions = new TreeVisitorAction() {
@Override
public Object pre(Object t) { return applyOnce(t, topdown_fptr); }
@Override
public Object post(Object t) { return applyRepeatedly(t, bottomup_ftpr); }
};
t = v.visit(t, actions);
return t;
}
/** Override this if you need transformation tracing to go somewhere
* other than stdout or if you're not using Tree-derived trees.
*/
public void reportTransformation(Object oldTree, Object newTree) {
System.out.println(((Tree)oldTree).toStringTree()+" -> "+
((Tree)newTree).toStringTree());
}
fptr topdown_fptr = new fptr() {
@Override
public Object rule() throws RecognitionException { return topdown(); }
};
fptr bottomup_ftpr = new fptr() {
@Override
public Object rule() throws RecognitionException { return bottomup(); }
};
// methods the downup strategy uses to do the up and down rules.
// to override, just define tree grammar rule topdown and turn on
// filter=true.
public Object topdown() throws RecognitionException { return null; }
public Object bottomup() throws RecognitionException { return null; }
}
| apache-2.0 |
roberthafner/flowable-engine | modules/flowable5-engine/src/main/java/org/activiti5/engine/impl/delegate/ActivityBehaviorInvocation.java | 1306 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti5.engine.impl.delegate;
import org.activiti.engine.impl.delegate.ActivityBehavior;
import org.activiti5.engine.impl.pvm.delegate.ActivityExecution;
/**
*
* @author Daniel Meyer
*/
public class ActivityBehaviorInvocation extends DelegateInvocation {
protected final ActivityBehavior behaviorInstance;
protected final ActivityExecution execution;
public ActivityBehaviorInvocation(ActivityBehavior behaviorInstance, ActivityExecution execution) {
this.behaviorInstance = behaviorInstance;
this.execution = execution;
}
protected void invoke() {
behaviorInstance.execute(execution);
}
public Object getTarget() {
return behaviorInstance;
}
}
| apache-2.0 |
congwiny/MyAndroidTest | emoji_library/src/main/java/com/vanniktech/emoji/listeners/OnEmojiPopupDismissListener.java | 122 | package com.vanniktech.emoji.listeners;
public interface OnEmojiPopupDismissListener {
void onEmojiPopupDismiss();
}
| apache-2.0 |
vorburger/mifos-head | application/src/main/java/org/mifos/customers/ppi/helpers/Country.java | 1260 | /*
* Copyright (c) 2005-2010 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.customers.ppi.helpers;
public enum Country {
INDIA(1);
private int value;
private Country(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static Country fromInt(int id) {
for (Country country : Country.values()) {
if (country.getValue() == id) {
return country;
}
}
throw new RuntimeException("No countries have id " + id);
}
}
| apache-2.0 |
lejingw/hermes | hermes-portal/src/main/java/com/ctrip/hermes/portal/resource/view/TopicDelayDetailView.java | 1993 | package com.ctrip.hermes.portal.resource.view;
import java.util.ArrayList;
import java.util.List;
public class TopicDelayDetailView extends TopicDelayBriefView {
private List<DelayDetail> details = new ArrayList<DelayDetail>();
public TopicDelayDetailView() {
}
public TopicDelayDetailView(String topic) {
setTopic(topic);
}
public void addDelay(String consumer, int partitionId, int delay) {
details.add(new DelayDetail(consumer, partitionId, delay));
}
public List<DelayDetail> getDetails() {
return details;
}
public void setDetails(List<DelayDetail> details) {
this.details = details;
}
public static class DelayDetail {
private String consumer;
private int partitionId;
private int delay;
public DelayDetail() {
}
public DelayDetail(String consumer, int partitionId, int delay) {
this.consumer = consumer;
this.partitionId = partitionId;
this.delay = delay;
}
public String getConsumer() {
return consumer;
}
public void setConsumer(String consumer) {
this.consumer = consumer;
}
public int getPartitionId() {
return partitionId;
}
public void setPartitionId(int partitionId) {
this.partitionId = partitionId;
}
public int getDelay() {
return delay;
}
public void setDelay(int delay) {
this.delay = delay;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((consumer == null) ? 0 : consumer.hashCode());
result = prime * result + partitionId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DelayDetail other = (DelayDetail) obj;
if (consumer == null) {
if (other.consumer != null)
return false;
} else if (!consumer.equals(other.consumer))
return false;
if (partitionId != other.partitionId)
return false;
return true;
}
}
}
| apache-2.0 |
aozarov/appengine-gcs-client | java/src/test/java/com/google/appengine/tools/cloudstorage/GcsOutputChannelTest.java | 13141 | /*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.appengine.tools.cloudstorage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.appengine.tools.development.testing.LocalBlobstoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalTaskQueueTestConfig;
import com.google.common.collect.ImmutableMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;
/**
* Test the OutputChannels (writing to GCS)
*/
@RunWith(Parameterized.class)
public class GcsOutputChannelTest {
private static final int BUFFER_SIZE = 2 * 1024 * 1024;
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
new LocalTaskQueueTestConfig(), new LocalBlobstoreServiceTestConfig(),
new LocalDatastoreServiceTestConfig());
private final boolean reconstruct;
public GcsOutputChannelTest(boolean reconstruct) {
this.reconstruct = reconstruct;
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{true}, {false}});
}
@Before
public void setUp() throws Exception {
helper.setUp();
}
@After
public void tearDown() throws Exception {
helper.tearDown();
}
/**
* Writes a file with the content supplied by pattern repeated over and over until the desired
* size is reached. After each write call reconstruct is called the output channel.
*
* We don't want to call close on the output channel while writing because this will prevent
* additional writes. Similarly we don't put the close in a finally block, because we don't want
* the partly written data to be used in the event of an exception.
*/
@SuppressWarnings("resource")
public void writeFile(String name, int size, byte[]... patterns)
throws IOException, ClassNotFoundException {
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename filename = new GcsFilename("GcsOutputChannelTestBucket", name);
GcsOutputChannelImpl outputChannel = (GcsOutputChannelImpl) gcsService.createOrReplace(
filename, GcsFileOptions.getDefaultInstance());
outputChannel = reconstruct(outputChannel);
assertEquals(0, outputChannel.buf.capacity());
int written = 0;
while (written < size) {
for (byte[] pattern : patterns) {
int toWrite = Math.min(pattern.length, size - written);
if (toWrite > 0) {
outputChannel.write(ByteBuffer.wrap(pattern, 0, toWrite));
assertTrue("Unexpected buffer size: " + outputChannel.buf,
outputChannel.buf.capacity() <= outputChannel.getBufferSizeBytes());
written += toWrite;
}
}
if (reconstruct) {
outputChannel.waitForOutstandingWrites();
int remaining = outputChannel.buf.remaining();
outputChannel = reconstruct(outputChannel);
if (remaining == 0) {
assertEquals(0, outputChannel.buf.capacity());
} else {
assertEquals(outputChannel.getBufferSizeBytes(), outputChannel.buf.capacity());
assertEquals(remaining, outputChannel.buf.remaining());
}
}
}
outputChannel.close();
assertNull(outputChannel.buf);
outputChannel = reconstruct(outputChannel);
assertNull(outputChannel.buf);
assertFalse(outputChannel.isOpen());
outputChannel = reconstruct(outputChannel);
}
/**
* Read the file and verify it contains the expected pattern the expected number of times.
*/
private void verifyContent(String name, int expectedSize, byte[]... contents) throws IOException {
@SuppressWarnings("resource")
ByteArrayOutputStream bout = new ByteArrayOutputStream();
for (byte[] content : contents) {
bout.write(content);
}
bout.close();
byte[] content = bout.toByteArray();
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename filename = new GcsFilename("GcsOutputChannelTestBucket", name);
try (GcsInputChannel readChannel =
gcsService.openPrefetchingReadChannel(filename, 0, BUFFER_SIZE)) {
ByteBuffer result = ByteBuffer.allocate(content.length);
ByteBuffer wrapped = ByteBuffer.wrap(content);
int size = 0;
int read = readFully(readChannel, result);
while (read != -1) {
assertTrue(read > 0);
size += read;
result.rewind();
result.limit(read);
wrapped.limit(read);
if (!wrapped.equals(result)) {
assertEquals(wrapped, result);
}
read = readFully(readChannel, result);
}
assertEquals(expectedSize, size);
}
}
private int readFully(GcsInputChannel readChannel, ByteBuffer result) throws IOException {
int totalRead = 0;
while (result.hasRemaining()) {
int read = readChannel.read(result);
if (read == -1) {
if (totalRead == 0) {
totalRead = -1;
}
break;
} else {
totalRead += read;
}
}
return totalRead;
}
/**
* Serializes and deserializes the the GcsOutputChannel. This simulates the writing of the file
* continuing from a different request.
*/
@SuppressWarnings("unchecked")
private static <T> T reconstruct(T writeChannel)
throws IOException, ClassNotFoundException {
ByteArrayOutputStream bout = writeChannelToStream(writeChannel);
try (ObjectInputStream in =
new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()))) {
return (T) in.readObject();
}
}
private static ByteArrayOutputStream writeChannelToStream(Object value) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try (ObjectOutputStream oout = new ObjectOutputStream(bout)) {
oout.writeObject(value);
}
return bout;
}
@Test
public void testSettingBufferSize() throws IOException {
RawGcsService raw = GcsServiceFactory.createRawGcsService(ImmutableMap.<String, String>of());
GcsFilename filename = new GcsFilename("GcsOutputChannelTestBucket", "testSettingBufferSize");
GcsFileOptions fileOptions = GcsFileOptions.getDefaultInstance();
int chunkSizeBytes = raw.getChunkSizeBytes();
GcsService out = GcsServiceFactory.createGcsService(
new GcsServiceOptions.Builder().setDefaultWriteBufferSize(null).build());
assertEquals(BUFFER_SIZE, out.createOrReplace(filename, fileOptions).getBufferSizeBytes());
out = GcsServiceFactory.createGcsService(
new GcsServiceOptions.Builder().setDefaultWriteBufferSize(0).build());
assertEquals(chunkSizeBytes, out.createOrReplace(filename, fileOptions).getBufferSizeBytes());
out = GcsServiceFactory.createGcsService(
new GcsServiceOptions.Builder().setDefaultWriteBufferSize(chunkSizeBytes).build());
assertEquals(chunkSizeBytes, out.createOrReplace(filename, fileOptions).getBufferSizeBytes());
out = GcsServiceFactory.createGcsService(
new GcsServiceOptions.Builder().setDefaultWriteBufferSize(chunkSizeBytes + 1).build());
assertEquals(chunkSizeBytes, out.createOrReplace(filename, fileOptions).getBufferSizeBytes());
out = GcsServiceFactory.createGcsService(
new GcsServiceOptions.Builder().setDefaultWriteBufferSize(chunkSizeBytes * 2).build());
assertEquals(chunkSizeBytes * 2,
out.createOrReplace(filename, fileOptions).getBufferSizeBytes());
out = GcsServiceFactory.createGcsService(
new GcsServiceOptions.Builder().setDefaultWriteBufferSize(Integer.MAX_VALUE).build());
assertEquals((raw.getMaxWriteSizeByte() / chunkSizeBytes) * chunkSizeBytes,
out.createOrReplace(filename, fileOptions).getBufferSizeBytes());
}
@Test
public void testSingleLargeWrite() throws IOException, ClassNotFoundException {
int size = 5 * BUFFER_SIZE;
byte[] content = new byte[size];
Random r = new Random();
r.nextBytes(content);
writeFile("SingleLargeWrite", size, content);
verifyContent("SingleLargeWrite", size, content);
}
@Test
public void testSmallWrites() throws IOException, ClassNotFoundException {
byte[] content = new byte[100];
Random r = new Random();
r.nextBytes(content);
int size = 27 * 1024;
assertTrue(size < BUFFER_SIZE);
writeFile("testSmallWrites", size, content);
verifyContent("testSmallWrites", size, content);
}
/**
* Tests writing in multiple segments that is > RawGcsService.getChunkSizeBytes() but less than
* the buffer size in {@link GcsOutputChannelImpl}.
*/
@Test
public void testLargeWrites() throws IOException, ClassNotFoundException {
byte[] content = new byte[(int) (BUFFER_SIZE * 0.477)];
Random r = new Random();
r.nextBytes(content);
int size = (int) (2.5 * BUFFER_SIZE);
writeFile("testLargeWrites", size, content);
verifyContent("testLargeWrites", size, content);
}
@Test
public void testWithRandomWriteSize() throws IOException, ClassNotFoundException {
Random r = new Random();
int writesNum = 30 + r.nextInt(30);
byte[][] bytes = new byte[writesNum][];
int size = 0;
for (int i = 0; i < writesNum; i++) {
byte[] temp;
int type = r.nextInt(10);
if (type < 6) {
temp = new byte[1 + r.nextInt(2_000_000)];
} else if (type < 8) {
temp = new byte[2_000_000 + r.nextInt(3_000_000)];
} else {
temp = new byte[5_000_000 + r.nextInt(15_000_000)];
}
r.nextBytes(temp);
bytes[i] = temp;
size += temp.length;
}
writeFile("testRandomSize", size, bytes);
verifyContent("testRandomSize", size, bytes);
}
@Test
public void testUnalignedWrites() throws IOException, ClassNotFoundException {
byte[] content = new byte[997];
Random r = new Random();
r.nextBytes(content);
int size = 2377 * 1033;
assertTrue(size > BUFFER_SIZE);
writeFile("testUnalignedWrites", size, content);
verifyContent("testUnalignedWrites", size, content);
}
@Test
public void testAlignedWrites() throws IOException, ClassNotFoundException {
byte[] content = new byte[BUFFER_SIZE];
Random r = new Random();
r.nextBytes(content);
writeFile("testUnalignedWrites", 5 * BUFFER_SIZE, content);
verifyContent("testUnalignedWrites", 5 * BUFFER_SIZE, content);
}
@Test
public void testPartialFlush() throws IOException {
byte[] content = new byte[BUFFER_SIZE - 1];
Random r = new Random();
r.nextBytes(content);
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename filename = new GcsFilename("GcsOutputChannelTestBucket", "testPartialFlush");
try (GcsOutputChannel outputChannel =
gcsService.createOrReplace(filename, GcsFileOptions.getDefaultInstance())) {
outputChannel.write(ByteBuffer.wrap(content, 0, content.length));
try (ByteArrayOutputStream bout = writeChannelToStream(outputChannel)) {
assertTrue(bout.size() >= BUFFER_SIZE);
outputChannel.waitForOutstandingWrites();
}
try (ByteArrayOutputStream bout = writeChannelToStream(outputChannel)) {
assertTrue(bout.size() < BUFFER_SIZE);
assertTrue(bout.size() > 0);
}
}
verifyContent("testPartialFlush", BUFFER_SIZE - 1, content);
}
/**
* The other tests in this file assume a buffer size of 2mb. If this is changed this test will
* fail. Before fixing it update the other tests.
* @throws IOException
*/
@Test
public void testBufferSize() throws IOException {
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename filename = new GcsFilename("GcsOutputChannelTestBucket", "testBufferSize");
@SuppressWarnings("resource")
GcsOutputChannel outputChannel =
gcsService.createOrReplace(filename, GcsFileOptions.getDefaultInstance());
assertEquals(BUFFER_SIZE, outputChannel.getBufferSizeBytes());
}
}
| apache-2.0 |
akozlova/testng | src/test/java/test/InvokedMethodNameListener.java | 6467 | package test;
import com.google.common.base.Joiner;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// TODO replace other test IInvokedMethodListener by this one
public class InvokedMethodNameListener implements IInvokedMethodListener, ITestListener {
private final List<String> foundMethodNames = new ArrayList<>();
private final List<String> invokedMethodNames = new ArrayList<>();
private final List<String> failedMethodNames = new ArrayList<>();
private final List<String> failedBeforeInvocationMethodNames = new ArrayList<>();
private final List<String> skippedMethodNames = new ArrayList<>();
private final List<String> skippedAfterInvocationMethodNames = new ArrayList<>();
private final List<String> succeedMethodNames = new ArrayList<>();
private final Map<String, ITestResult> results = new HashMap<>();
private final Map<Class<?>, List<String>> mapping = Maps.newHashMap();
private final boolean skipConfiguration;
private final boolean wantSkippedMethodAfterInvocation;
public InvokedMethodNameListener() {
this(false);
}
public InvokedMethodNameListener(boolean skipConfiguration) {
this(skipConfiguration, false);
}
public InvokedMethodNameListener(boolean skipConfiguration, boolean wantSkippedMethodAfterInvocation) {
this.skipConfiguration = skipConfiguration;
this.wantSkippedMethodAfterInvocation = wantSkippedMethodAfterInvocation;
}
@Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (!(skipConfiguration && method.isConfigurationMethod())) {
invokedMethodNames.add(getName(testResult));
}
}
@Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
List<String> methodNames = mapping.get(testResult.getMethod().getRealClass());
if (methodNames == null) {
methodNames = Lists.newArrayList();
mapping.put(testResult.getMethod().getRealClass(), methodNames);
}
methodNames.add(method.getTestMethod().getMethodName());
String name = getName(testResult);
switch (testResult.getStatus()) {
case ITestResult.FAILURE:
if (!(skipConfiguration && method.isConfigurationMethod())) {
failedMethodNames.add(name);
}
break;
case ITestResult.SKIP:
if (!(skipConfiguration && method.isConfigurationMethod())) {
if (wantSkippedMethodAfterInvocation) {
skippedAfterInvocationMethodNames.add(name);
} else {
throw new IllegalStateException("A skipped test is not supposed to be invoked");
}
}
break;
case ITestResult.SUCCESS:
if (!(skipConfiguration && method.isConfigurationMethod())) {
succeedMethodNames.add(name);
}
break;
default:
throw new AssertionError("Unexpected value: " + testResult.getStatus());
}
}
@Override
public void onTestStart(ITestResult result) {
foundMethodNames.add(getName(result));
}
@Override
public void onTestSuccess(ITestResult result) {
String name = getName(result);
results.put(name, result);
if (!succeedMethodNames.contains(name)) {
throw new IllegalStateException("A succeed test is supposed to be invoked");
}
}
@Override
public void onTestFailure(ITestResult result) {
String name = getName(result);
results.put(name, result);
if (!failedMethodNames.contains(name)) {
failedBeforeInvocationMethodNames.add(name);
}
}
@Override
public void onTestSkipped(ITestResult result) {
String name = getName(result);
results.put(name, result);
if (!skippedAfterInvocationMethodNames.contains(name)) {
skippedMethodNames.add(name);
}
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
String name = getName(result);
results.put(name, result);
if (!succeedMethodNames.contains(name) || !failedMethodNames.contains(name)) {
throw new IllegalStateException("A FailedButWithinSuccessPercentage test is supposed to be invoked");
}
}
@Override
public void onStart(ITestContext context) {
}
@Override
public void onFinish(ITestContext context) {
}
private static String getName(ITestResult result) {
String testName = result.getName();
String methodName = result.getMethod().getConstructorOrMethod().getName();
String name;
if (testName.contains(methodName)) {
name = methodName;
} else {
name = testName + "#" + methodName;
}
if (result.getParameters().length != 0) {
name = name + "(" + Joiner.on(",").useForNull("null").join(getParameterNames(result.getParameters())) + ")";
}
return name;
}
private static List<String> getParameterNames(Object[] parameters) {
List<String> result = new ArrayList<>(parameters.length);
for (Object parameter : parameters) {
if (parameter == null) {
result.add("null");
} else {
if (parameter instanceof Object[]) {
result.add("[" + Joiner.on(",").useForNull("null").join((Object[]) parameter) + "]");
} else {
result.add(parameter.toString());
}
}
}
return result;
}
public List<String> getInvokedMethodNames() {
return Collections.unmodifiableList(invokedMethodNames);
}
public List<String> getFailedMethodNames() {
return Collections.unmodifiableList(failedMethodNames);
}
public List<String> getSkippedMethodNames() {
return Collections.unmodifiableList(skippedMethodNames);
}
public List<String> getSucceedMethodNames() {
return new ArrayList<>(succeedMethodNames);
}
public List<String> getFailedBeforeInvocationMethodNames() {
return Collections.unmodifiableList(failedBeforeInvocationMethodNames);
}
public List<String> getSkippedAfterInvocationMethodNames() {
return Collections.unmodifiableList(skippedAfterInvocationMethodNames);
}
public ITestResult getResult(String name) {
return results.get(name);
}
public List<String> getMethodsForTestClass(Class<?> testClass) {
return mapping.get(testClass);
}
}
| apache-2.0 |
zstackorg/zstack | sdk/src/main/java/org/zstack/sdk/CreateL2VxlanNetworkPoolAction.java | 3759 | package org.zstack.sdk;
import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;
public class CreateL2VxlanNetworkPoolAction extends AbstractAction {
private static final HashMap<String, Parameter> parameterMap = new HashMap<>();
private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();
public static class Result {
public ErrorCode error;
public org.zstack.sdk.CreateL2VxlanNetworkPoolResult value;
public Result throwExceptionIfError() {
if (error != null) {
throw new ApiException(
String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
);
}
return this;
}
}
@Param(required = true, maxLength = 255, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String name;
@Param(required = false, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String description;
@Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String zoneUuid;
@Param(required = false, maxLength = 1024, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String physicalInterface;
@Param(required = false)
public java.lang.String type;
@Param(required = false, validValues = {"LinuxBridge","OvsDpdk"}, maxLength = 1024, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String vSwitchType = "LinuxBridge";
@Param(required = false)
public java.lang.String resourceUuid;
@Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.util.List tagUuids;
@Param(required = false)
public java.util.List systemTags;
@Param(required = false)
public java.util.List userTags;
@Param(required = false)
public String sessionId;
@Param(required = false)
public String accessKeyId;
@Param(required = false)
public String accessKeySecret;
@Param(required = false)
public String requestIp;
@NonAPIParam
public long timeout = -1;
@NonAPIParam
public long pollingInterval = -1;
private Result makeResult(ApiResult res) {
Result ret = new Result();
if (res.error != null) {
ret.error = res.error;
return ret;
}
org.zstack.sdk.CreateL2VxlanNetworkPoolResult value = res.getResult(org.zstack.sdk.CreateL2VxlanNetworkPoolResult.class);
ret.value = value == null ? new org.zstack.sdk.CreateL2VxlanNetworkPoolResult() : value;
return ret;
}
public Result call() {
ApiResult res = ZSClient.call(this);
return makeResult(res);
}
public void call(final Completion<Result> completion) {
ZSClient.call(this, new InternalCompletion() {
@Override
public void complete(ApiResult res) {
completion.complete(makeResult(res));
}
});
}
protected Map<String, Parameter> getParameterMap() {
return parameterMap;
}
protected Map<String, Parameter> getNonAPIParameterMap() {
return nonAPIParameterMap;
}
protected RestInfo getRestInfo() {
RestInfo info = new RestInfo();
info.httpMethod = "POST";
info.path = "/l2-networks/vxlan-pool";
info.needSession = true;
info.needPoll = true;
info.parameterName = "params";
return info;
}
}
| apache-2.0 |
damienmg/bazel | src/main/java/com/google/devtools/build/lib/rules/objc/IosTest.java | 13771 | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.objc;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.STORYBOARD;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.XCDATAMODEL;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ExecutionRequirements;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.RunfilesSupport;
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.test.ExecutionInfo;
import com.google.devtools.build.lib.analysis.test.InstrumentedFilesProvider;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.rules.apple.AppleConfiguration;
import com.google.devtools.build.lib.rules.apple.ApplePlatform.PlatformType;
import com.google.devtools.build.lib.rules.apple.XcodeConfig;
import com.google.devtools.build.lib.rules.objc.CompilationSupport.ExtraLinkArgs;
import com.google.devtools.build.lib.rules.objc.ObjcCommon.ResourceAttributes;
import com.google.devtools.build.lib.rules.objc.ReleaseBundlingSupport.LinkedBinary;
import com.google.devtools.build.lib.rules.proto.ProtoSourcesProvider;
import com.google.devtools.build.lib.syntax.Type;
/** Implementation for {@code ios_test} rule in Bazel. */
public final class IosTest implements RuleConfiguredTargetFactory {
private static final ImmutableList<SdkFramework> AUTOMATIC_SDK_FRAMEWORKS_FOR_XCTEST =
ImmutableList.of(new SdkFramework("XCTest"));
// Attributes for IosTest rules.
// Documentation on usage is in {@link IosTestRule@}.
static final String OBJC_GCOV_ATTR = "$objc_gcov";
static final String DEVICE_ARG_ATTR = "ios_device_arg";
static final String IS_XCTEST_ATTR = "xctest";
static final String MEMLEAKS_DEP_ATTR = "$memleaks_dep";
static final String MEMLEAKS_PLUGIN_ATTR = "$memleaks_plugin";
static final String PLUGINS_ATTR = "plugins";
static final String TARGET_DEVICE = "target_device";
static final String TEST_RUNNER_ATTR = "$test_runner";
static final String TEST_TARGET_DEVICE_ATTR = "ios_test_target_device";
static final String TEST_TEMPLATE_ATTR = "$test_template";
static final String XCTEST_APP_ATTR = "xctest_app";
static final String MCOV_TOOL_ATTR = ":mcov";
@VisibleForTesting
public static final String REQUIRES_SOURCE_ERROR =
"ios_test requires at least one source file in srcs or non_arc_srcs";
@VisibleForTesting
public static final String NO_MULTI_CPUS_ERROR =
"ios_test cannot be built for multiple CPUs at the same time";
/**
* {@inheritDoc}
*
* <p>Creates a target, including registering actions, just as {@link #create(RuleContext)} does.
* The difference between {@link #create(RuleContext)} and this method is that this method does
* only what is needed to support tests on the environment besides build the app and test {@code
* .ipa}s. The {@link #create(RuleContext)} method delegates to this method.
*/
@Override
public final ConfiguredTarget create(RuleContext ruleContext)
throws InterruptedException, RuleErrorException {
ruleContext.ruleWarning(
"This rule is deprecated. Please use the new Apple build rules "
+ "(https://github.com/bazelbuild/rules_apple) to build Apple targets.");
Iterable<ObjcProtoProvider> objcProtoProviders =
ruleContext.getPrerequisites("deps", Mode.TARGET, ObjcProtoProvider.class);
ProtobufSupport protoSupport =
new ProtobufSupport(
ruleContext,
ruleContext.getConfiguration(),
ImmutableList.<ProtoSourcesProvider>of(),
objcProtoProviders,
ProtobufSupport.getTransitivePortableProtoFilters(objcProtoProviders))
.registerGenerationActions()
.registerCompilationActions();
Optional<ObjcProvider> protosObjcProvider = protoSupport.getObjcProvider();
ObjcCommon common = common(ruleContext, protosObjcProvider);
if (!common.getCompilationArtifacts().get().getArchive().isPresent()) {
ruleContext.ruleError(REQUIRES_SOURCE_ERROR);
}
if (!ruleContext.getFragment(AppleConfiguration.class).getIosMultiCpus().isEmpty()) {
ruleContext.ruleError(NO_MULTI_CPUS_ERROR);
}
NestedSetBuilder<Artifact> filesToBuild = NestedSetBuilder.stableOrder();
addResourceFilesToBuild(ruleContext, common.getObjcProvider(), filesToBuild);
ExtraLinkArgs extraLinkArgs;
Iterable<Artifact> extraLinkInputs;
String bundleFormat;
if (!isXcTest(ruleContext)) {
extraLinkArgs = new ExtraLinkArgs();
extraLinkInputs = ImmutableList.of();
bundleFormat = ReleaseBundlingSupport.APP_BUNDLE_DIR_FORMAT;
} else {
XcTestAppProvider testApp = xcTestAppProvider(ruleContext);
Artifact bundleLoader = testApp.getBundleLoader();
// -bundle causes this binary to be linked as a bundle and not require an entry point
// (i.e. main())
// -bundle_loader causes the code in this test to have access to the symbols in the test rig,
// or more specifically, the flag causes ld to consider the given binary when checking for
// missing symbols.
// -rpath @loader_path/Frameworks allows test bundles to load dylibs from the app's
// Frameworks directory.
extraLinkArgs =
new ExtraLinkArgs(
"-bundle",
"-bundle_loader",
bundleLoader.getExecPathString(),
"-Xlinker",
"-rpath",
"-Xlinker",
"@loader_path/Frameworks");
extraLinkInputs = ImmutableList.of(bundleLoader);
bundleFormat = ReleaseBundlingSupport.XCTEST_BUNDLE_DIR_FORMAT;
filesToBuild.add(testApp.getIpa());
}
J2ObjcMappingFileProvider j2ObjcMappingFileProvider =
J2ObjcMappingFileProvider.union(
ruleContext.getPrerequisites("deps", Mode.TARGET, J2ObjcMappingFileProvider.class));
J2ObjcEntryClassProvider j2ObjcEntryClassProvider =
new J2ObjcEntryClassProvider.Builder()
.addTransitive(
ruleContext.getPrerequisites("deps", Mode.TARGET, J2ObjcEntryClassProvider.class))
.build();
CompilationSupport compilationSupport =
new CompilationSupport.Builder().setRuleContext(ruleContext).setIsTestRule().build();
compilationSupport
.registerLinkActions(
common.getObjcProvider(),
j2ObjcMappingFileProvider,
j2ObjcEntryClassProvider,
extraLinkArgs,
extraLinkInputs,
DsymOutputType.TEST)
.registerCompileAndArchiveActions(common)
.registerFullyLinkAction(
common.getObjcProvider(),
ruleContext.getImplicitOutputArtifact(CompilationSupport.FULLY_LINKED_LIB))
.validateAttributes();
AppleConfiguration appleConfiguration = ruleContext.getFragment(AppleConfiguration.class);
new ReleaseBundlingSupport(
ruleContext,
common.getObjcProvider(),
LinkedBinary.LOCAL_AND_DEPENDENCIES,
bundleFormat,
XcodeConfig.getMinimumOsForPlatformType(ruleContext, PlatformType.IOS),
appleConfiguration.getMultiArchPlatform(PlatformType.IOS))
.registerActions(DsymOutputType.TEST)
.addFilesToBuild(filesToBuild, Optional.of(DsymOutputType.TEST))
.validateResources()
.validateAttributes();
new ResourceSupport(ruleContext).validateAttributes();
NestedSet<Artifact> filesToBuildSet = filesToBuild.build();
Runfiles.Builder runfilesBuilder =
new Runfiles.Builder(
ruleContext.getWorkspaceName(),
ruleContext.getConfiguration().legacyExternalRunfiles())
.addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES);
NestedSetBuilder<Artifact> filesToBuildBuilder =
NestedSetBuilder.<Artifact>stableOrder().addTransitive(filesToBuildSet);
InstrumentedFilesProvider instrumentedFilesProvider =
new CompilationSupport.Builder()
.setRuleContext(ruleContext)
.build()
.getInstrumentedFilesProvider(common);
TestSupport testSupport =
new TestSupport(ruleContext)
.registerTestRunnerActions()
.addRunfiles(runfilesBuilder, instrumentedFilesProvider)
.addFilesToBuild(filesToBuildBuilder);
Artifact executable = testSupport.generatedTestScript();
Runfiles runfiles = runfilesBuilder.build();
RunfilesSupport runfilesSupport =
RunfilesSupport.withExecutable(ruleContext, runfiles, executable);
ImmutableMap.Builder<String, String> execInfoMapBuilder = new ImmutableMap.Builder<>();
execInfoMapBuilder.put(ExecutionRequirements.REQUIRES_DARWIN, "");
if (ruleContext.getFragment(ObjcConfiguration.class).runMemleaks()) {
execInfoMapBuilder.put("nosandbox", "");
}
return new RuleConfiguredTargetBuilder(ruleContext)
.setFilesToBuild(filesToBuildBuilder.build())
.addProvider(RunfilesProvider.simple(runfiles))
.addNativeDeclaredProvider(new ExecutionInfo(execInfoMapBuilder.build()))
.addNativeDeclaredProviders(testSupport.getExtraProviders())
.addProvider(InstrumentedFilesProvider.class, instrumentedFilesProvider)
.setRunfilesSupport(runfilesSupport, executable)
.build();
}
private void addResourceFilesToBuild(
RuleContext ruleContext, ObjcProvider objcProvider, NestedSetBuilder<Artifact> filesToBuild) {
IntermediateArtifacts intermediateArtifacts =
ObjcRuleClasses.intermediateArtifacts(ruleContext);
Iterable<Xcdatamodel> xcdatamodels =
Xcdatamodels.xcdatamodels(intermediateArtifacts, objcProvider.get(XCDATAMODEL));
filesToBuild.addAll(Xcdatamodel.outputZips(xcdatamodels));
for (Artifact storyboard : objcProvider.get(STORYBOARD)) {
filesToBuild.add(intermediateArtifacts.compiledStoryboardZip(storyboard));
}
}
/** Constructs an {@link ObjcCommon} instance based on the attributes. */
private ObjcCommon common(RuleContext ruleContext, Optional<ObjcProvider> protosObjcProvider) {
CompilationArtifacts compilationArtifacts =
CompilationSupport.compilationArtifacts(ruleContext);
ObjcCommon.Builder builder =
new ObjcCommon.Builder(ruleContext)
.setCompilationAttributes(
CompilationAttributes.Builder.fromRuleContext(ruleContext).build())
.setCompilationArtifacts(compilationArtifacts)
.setResourceAttributes(new ResourceAttributes(ruleContext))
.addDefines(ruleContext.getExpander().withDataLocations().tokenized("defines"))
.addDeps(ruleContext.getPrerequisites("deps", Mode.TARGET))
.addRuntimeDeps(ruleContext.getPrerequisites("runtime_deps", Mode.TARGET))
.addDeps(ruleContext.getPrerequisites("bundles", Mode.TARGET))
.addDepObjcProviders(protosObjcProvider.asSet())
.addNonPropagatedDepObjcProviders(
ruleContext.getPrerequisites(
"non_propagated_deps", Mode.TARGET, ObjcProvider.SKYLARK_CONSTRUCTOR))
.setIntermediateArtifacts(ObjcRuleClasses.intermediateArtifacts(ruleContext))
.setHasModuleMap();
if (isXcTest(ruleContext)) {
builder
.addExtraSdkFrameworks(AUTOMATIC_SDK_FRAMEWORKS_FOR_XCTEST)
.addDepObjcProviders(ImmutableList.of(xcTestAppProvider(ruleContext).getObjcProvider()));
}
// Add the memleaks library if the --ios_memleaks flag is true. The library pauses the test
// after all tests have been executed so that leaks can be run.
ObjcConfiguration config = ruleContext.getFragment(ObjcConfiguration.class);
if (config.runMemleaks()) {
builder.addDepObjcProviders(
ruleContext.getPrerequisites(
MEMLEAKS_DEP_ATTR, Mode.TARGET, ObjcProvider.SKYLARK_CONSTRUCTOR));
}
return builder.build();
}
protected static boolean isXcTest(RuleContext ruleContext) {
return ruleContext.attributes().get(IS_XCTEST_ATTR, Type.BOOLEAN);
}
/** Returns the {@link XcTestAppProvider} of the {@code xctest_app} attribute. */
protected static XcTestAppProvider xcTestAppProvider(RuleContext ruleContext) {
return ruleContext.getPrerequisite(
XCTEST_APP_ATTR, Mode.TARGET, XcTestAppProvider.SKYLARK_CONSTRUCTOR);
}
}
| apache-2.0 |
Qi4j/qi4j-sdk | extensions/indexing-rdf/src/main/java/org/apache/polygene/index/rdf/query/QualifiedIdentityResultCallback.java | 1265 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package org.apache.polygene.index.rdf.query;
import org.apache.polygene.api.entity.EntityReference;
public interface QualifiedIdentityResultCallback
{
/**
* @param row the current row of the resultset
* @param entityReference The entity reference found via the query.
*
* @return true if resultset processing should stop.
*/
boolean processRow( long row, EntityReference entityReference );
}
| apache-2.0 |
Jasig/cas | support/cas-server-support-saml-idp-metadata/src/test/java/org/apereo/cas/support/saml/services/idp/metadata/cache/resolver/UrlResourceMetadataResolverTests.java | 5335 | package org.apereo.cas.support.saml.services.idp.metadata.cache.resolver;
import org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties;
import org.apereo.cas.services.DefaultRegisteredServiceAccessStrategy;
import org.apereo.cas.support.saml.SamlException;
import org.apereo.cas.support.saml.services.BaseSamlIdPServicesTests;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.util.MockWebServer;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.TestPropertySource;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is {@link UrlResourceMetadataResolverTests}.
*
* @author Misagh Moayyed
* @since 5.3.0
*/
@Tag("SAMLMetadata")
@TestPropertySource(properties = "cas.authn.saml-idp.metadata.file-system.location=${#systemProperties['java.io.tmpdir']}/saml")
public class UrlResourceMetadataResolverTests extends BaseSamlIdPServicesTests {
public static final String MDQ_URL = "https://mdq.incommon.org/entities/{0}";
@Test
public void verifyResolverSupports() throws Exception {
try (val webServer = new MockWebServer(9155, new ClassPathResource("sample-metadata.xml"), HttpStatus.OK)) {
webServer.start();
val props = new SamlIdPProperties();
props.getMetadata().getFileSystem().setLocation(new FileSystemResource(FileUtils.getTempDirectory()).getFile().getCanonicalPath());
val resolver = new UrlResourceMetadataResolver(props, openSamlConfigBean);
val service = new SamlRegisteredService();
service.setMetadataLocation("http://localhost:9155");
assertTrue(resolver.supports(service));
service.setMetadataLocation("classpath:sample-sp.xml");
assertFalse(resolver.supports(service));
service.setMetadataLocation(MDQ_URL);
assertFalse(resolver.supports(service));
}
}
@Test
public void verifyResolverResolves() throws Exception {
try (val webServer = new MockWebServer(9155, new ClassPathResource("sample-metadata.xml"), HttpStatus.OK)) {
webServer.start();
val props = new SamlIdPProperties();
props.getMetadata().getFileSystem().setLocation(new FileSystemResource(FileUtils.getTempDirectory()).getFile().getCanonicalPath());
val service = new SamlRegisteredService();
val resolver = new UrlResourceMetadataResolver(props, openSamlConfigBean);
service.setName("TestShib");
service.setId(1000);
service.setMetadataLocation("http://localhost:9155");
val results = resolver.resolve(service);
assertFalse(results.isEmpty());
assertTrue(resolver.isAvailable(service));
assertFalse(resolver.supports(null));
}
}
@Test
public void verifyResolverResolvesFailsAccess() throws Exception {
try (val webServer = new MockWebServer(9155, new ClassPathResource("sample-metadata.xml"), HttpStatus.OK)) {
webServer.start();
val props = new SamlIdPProperties();
props.getMetadata().getFileSystem().setLocation(new FileSystemResource(FileUtils.getTempDirectory()).getFile().getCanonicalPath());
val service = new SamlRegisteredService();
service.setAccessStrategy(new DefaultRegisteredServiceAccessStrategy(false, false));
val resolver = new UrlResourceMetadataResolver(props, openSamlConfigBean);
service.setName("TestShib");
service.setId(1000);
service.setMetadataLocation("http://localhost:9155");
assertThrows(SamlException.class, () -> resolver.resolve(service));
}
}
@Test
public void verifyResolverUnknownUrl() throws Exception {
val props = new SamlIdPProperties();
props.getMetadata().getFileSystem().setLocation(new FileSystemResource(FileUtils.getTempDirectory()).getFile().getCanonicalPath());
val service = new SamlRegisteredService();
val resolver = new UrlResourceMetadataResolver(props, openSamlConfigBean);
service.setName("TestShib");
service.setId(1000);
service.setMetadataLocation("https://localhost:9999");
assertTrue(resolver.resolve(service).isEmpty());
}
@Test
public void verifyResolverWithProtocol() {
try (val webServer = new MockWebServer(9155, new ClassPathResource("sample-metadata.xml"), HttpStatus.OK)) {
webServer.start();
val props = new SamlIdPProperties();
props.getMetadata().getFileSystem().setLocation("file:/" + FileUtils.getTempDirectory());
val service = new SamlRegisteredService();
val resolver = new UrlResourceMetadataResolver(props, openSamlConfigBean);
service.setName("TestShib");
service.setId(1000);
service.setMetadataLocation("http://localhost:9155");
val results = resolver.resolve(service);
assertFalse(results.isEmpty());
}
}
}
| apache-2.0 |
chubbymaggie/binnavi | src/main/java/com/google/security/zynamics/reil/translators/x86/ScasbTranslator.java | 2393 | /*
Copyright 2011-2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.reil.translators.x86;
import com.google.security.zynamics.reil.OperandSize;
import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.translators.IInstructionTranslator;
import com.google.security.zynamics.reil.translators.ITranslationEnvironment;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.TranslationHelpers;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import java.util.List;
/**
* Translates SCAS instructions to REIL code.
*/
public class ScasbTranslator implements IInstructionTranslator {
/**
* Translates a SCASB instruction to REIL code.
*
* @param environment A valid translation environment.
* @param instruction The SCASB instruction to translate.
* @param instructions The generated REIL code will be added to this list
*
* @throws InternalTranslationException if any of the arguments are null the passed instruction is
* not an SCASB instruction
*/
@Override
public void translate(final ITranslationEnvironment environment, final IInstruction instruction,
final List<ReilInstruction> instructions) throws InternalTranslationException {
TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "scasb");
if (instruction.getOperands().size() != 0) {
throw new InternalTranslationException(
"Error: Argument instruction is not a scasb instruction (invalid number of operands)");
}
new ScasGenerator().generate(environment, ReilHelpers.toReilAddress(instruction.getAddress())
.toLong(), OperandSize.BYTE, instructions);
}
}
| apache-2.0 |
deepakddixit/incubator-geode | geode-lucene/geode-lucene-test/src/main/java/org/apache/geode/cache/lucene/test/LuceneTestUtilities.java | 12246 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.lucene.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.apache.lucene.document.FloatPoint;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.search.Query;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.EntryOperation;
import org.apache.geode.cache.FixedPartitionAttributes;
import org.apache.geode.cache.FixedPartitionResolver;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.asyncqueue.AsyncEventQueue;
import org.apache.geode.cache.asyncqueue.internal.AsyncEventQueueImpl;
import org.apache.geode.cache.lucene.LuceneIndex;
import org.apache.geode.cache.lucene.LuceneIndexFactory;
import org.apache.geode.cache.lucene.LuceneQuery;
import org.apache.geode.cache.lucene.LuceneQueryException;
import org.apache.geode.cache.lucene.LuceneQueryProvider;
import org.apache.geode.cache.lucene.LuceneService;
import org.apache.geode.cache.lucene.LuceneServiceProvider;
import org.apache.geode.cache.lucene.PageableLuceneQueryResults;
import org.apache.geode.cache.lucene.internal.LuceneIndexForPartitionedRegion;
import org.apache.geode.cache.lucene.internal.LuceneServiceImpl;
import org.apache.geode.cache.lucene.internal.distributed.EntryScore;
import org.apache.geode.internal.cache.LocalRegion;
import org.apache.geode.internal.cache.wan.AbstractGatewaySender;
public class LuceneTestUtilities {
public static final String INDEX_NAME = "index";
public static final String REGION_NAME = "region";
public static final String DEFAULT_FIELD = "text";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_FIELDS =
"Cannot create Lucene index index on region /region with fields [field1, field2] because another member defines the same index with fields [field1].";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_FIELDS_2 =
"Cannot create Lucene index index on region /region with fields [field1] because another member defines the same index with fields [field1, field2].";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_ANALYZERS =
"Cannot create Lucene index index on region /region with analyzer StandardAnalyzer on field field2 because another member defines the same index with analyzer KeywordAnalyzer on that field.";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_ANALYZERS_1 =
"Cannot create Lucene index index on region /region with analyzer StandardAnalyzer on field field1 because another member defines the same index with analyzer KeywordAnalyzer on that field.";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_ANALYZERS_2 =
"Cannot create Lucene index index on region /region with analyzer KeywordAnalyzer on field field1 because another member defines the same index with analyzer StandardAnalyzer on that field.";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_ANALYZERS_3 =
"Cannot create Lucene index index on region /region with analyzer KeywordAnalyzer on field field2 because another member defines the same index with analyzer StandardAnalyzer on that field.";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_NAMES =
"Cannot create Lucene index index2 on region /region because it is not defined in another member.";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_INDEXES_1 =
"Must create Lucene index index on region /region because it is defined in another member.";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_INDEXES_2 =
"Cannot create Lucene index index2 on region /region because it is not defined in another member.";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_INDEXES_3 =
"Cannot create Lucene index index on region /region because it is not defined in another member.";
public static final String CANNOT_CREATE_LUCENE_INDEX_DIFFERENT_SERIALIZER =
"Cannot create Lucene index index on region /region with serializer DummyLuceneSerializer because another member defines the same index with different serializer HeterogeneousLuceneSerializer.";
public static String Quarter1 = "Q1";
public static String Quarter2 = "Q2";
public static String Quarter3 = "Q3";
public static String Quarter4 = "Q4";
public static void verifyResultOrder(Collection<EntryScore<String>> list,
EntryScore<String>... expectedEntries) {
Iterator<EntryScore<String>> iter = list.iterator();
for (EntryScore expectedEntry : expectedEntries) {
if (!iter.hasNext()) {
fail();
}
EntryScore toVerify = iter.next();
assertEquals(expectedEntry.getKey(), toVerify.getKey());
assertEquals(expectedEntry.getScore(), toVerify.getScore(), .0f);
}
}
public static class IntRangeQueryProvider implements LuceneQueryProvider {
String fieldName;
int lowerValue;
int upperValue;
private transient Query luceneQuery;
public IntRangeQueryProvider(String fieldName, int lowerValue, int upperValue) {
this.fieldName = fieldName;
this.lowerValue = lowerValue;
this.upperValue = upperValue;
}
@Override
public Query getQuery(LuceneIndex index) throws LuceneQueryException {
if (luceneQuery == null) {
luceneQuery = IntPoint.newRangeQuery(fieldName, lowerValue, upperValue);
}
System.out.println("IntRangeQueryProvider, using java serializable");
return luceneQuery;
}
}
public static class FloatRangeQueryProvider implements LuceneQueryProvider {
String fieldName;
float lowerValue;
float upperValue;
private transient Query luceneQuery;
public FloatRangeQueryProvider(String fieldName, float lowerValue, float upperValue) {
this.fieldName = fieldName;
this.lowerValue = lowerValue;
this.upperValue = upperValue;
}
@Override
public Query getQuery(LuceneIndex index) throws LuceneQueryException {
if (luceneQuery == null) {
luceneQuery = FloatPoint.newRangeQuery(fieldName, lowerValue, upperValue);
// luceneQuery = DoublePoint.newRangeQuery(fieldName, lowerValue, upperValue);
}
System.out.println("IntRangeQueryProvider, using java serializable");
return luceneQuery;
}
}
public static Region createFixedPartitionedRegion(final Cache cache, String regionName,
List<FixedPartitionAttributes> fpaList, int localMaxMemory) {
List<String> allPartitions = new ArrayList();
if (fpaList != null) {
for (FixedPartitionAttributes fpa : fpaList) {
allPartitions.add(fpa.getPartitionName());
}
} else {
allPartitions.add("Q1");
allPartitions.add("Q2");
}
AttributesFactory fact = new AttributesFactory();
PartitionAttributesFactory pfact = new PartitionAttributesFactory();
pfact.setTotalNumBuckets(16);
pfact.setRedundantCopies(1);
pfact.setLocalMaxMemory(localMaxMemory);
if (fpaList != null) {
for (FixedPartitionAttributes fpa : fpaList) {
pfact.addFixedPartitionAttributes(fpa);
}
}
pfact.setPartitionResolver(new MyFixedPartitionResolver(allPartitions));
fact.setPartitionAttributes(pfact.create());
Region r = cache.createRegionFactory(fact.create()).create(regionName);
assertNotNull(r);
return r;
}
static class MyFixedPartitionResolver implements FixedPartitionResolver {
private final List<String> allPartitions;
public MyFixedPartitionResolver(final List<String> allPartitions) {
this.allPartitions = allPartitions;
}
@Override
public String getPartitionName(final EntryOperation opDetails,
@Deprecated final Set targetPartitions) {
int hash = Math.abs(opDetails.getKey().hashCode() % allPartitions.size());
return allPartitions.get(hash);
}
@Override
public Object getRoutingObject(final EntryOperation opDetails) {
return opDetails.getKey();
}
@Override
public String getName() {
return getClass().getName();
}
@Override
public void close() {
}
}
public static void verifyInternalRegions(LuceneService luceneService, Cache cache,
Consumer<LocalRegion> verify) {
// Get index
LuceneIndexForPartitionedRegion index =
(LuceneIndexForPartitionedRegion) luceneService.getIndex(INDEX_NAME, REGION_NAME);
LocalRegion fileRegion = (LocalRegion) cache.getRegion(index.createFileRegionName());
verify.accept(fileRegion);
}
public static AsyncEventQueue getIndexQueue(Cache cache) {
String aeqId = LuceneServiceImpl.getUniqueIndexName(INDEX_NAME, REGION_NAME);
return cache.getAsyncEventQueue(aeqId);
}
public static void createIndex(Cache cache, String... fieldNames) {
final LuceneIndexFactory indexFactory = LuceneServiceProvider.get(cache).createIndexFactory();
indexFactory.setFields(fieldNames).create(INDEX_NAME, REGION_NAME);
}
public static void verifyIndexFinishFlushing(Cache cache, String indexName, String regionName)
throws InterruptedException {
LuceneService luceneService = LuceneServiceProvider.get(cache);
LuceneIndex index = luceneService.getIndex(indexName, regionName);
boolean flushed =
luceneService.waitUntilFlushed(indexName, regionName, 60000, TimeUnit.MILLISECONDS);
assertTrue(flushed);
}
/**
* Verify that a query returns the expected list of keys. Ordering is ignored.
*/
public static <K> void verifyQueryKeys(LuceneQuery<K, Object> query, K... expectedKeys)
throws LuceneQueryException {
Set<K> expectedKeySet = new HashSet<>(Arrays.asList(expectedKeys));
Set<K> actualKeySet = new HashSet<>(query.findKeys());
assertEquals(expectedKeySet, actualKeySet);
}
/**
* Verify that a query returns the expected map of key-value. Ordering is ignored.
*/
public static <K> void verifyQueryKeyAndValues(LuceneQuery<K, Object> query,
HashMap expectedResults) throws LuceneQueryException {
HashMap actualResults = new HashMap<>();
final PageableLuceneQueryResults<K, Object> results = query.findPages();
while (results.hasNext()) {
results.next().stream().forEach(struct -> {
Object value = struct.getValue();
actualResults.put(struct.getKey(), value);
});
}
assertEquals(expectedResults, actualResults);
}
public static void pauseSender(final Cache cache) {
final AsyncEventQueueImpl queue = (AsyncEventQueueImpl) getIndexQueue(cache);
if (queue == null) {
return;
}
queue.getSender().pause();
AbstractGatewaySender sender = (AbstractGatewaySender) queue.getSender();
sender.getEventProcessor().waitForDispatcherToPause();
}
public static void resumeSender(final Cache cache) {
final AsyncEventQueueImpl queue = (AsyncEventQueueImpl) getIndexQueue(cache);
if (queue == null) {
return;
}
queue.getSender().resume();
}
}
| apache-2.0 |
hgschmie/shindig | java/gadgets/src/main/java/org/apache/shindig/gadgets/RequestSigningException.java | 1320 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.apache.shindig.gadgets;
/**
* Exception thrown during request signing.
*/
public class RequestSigningException extends GadgetException {
public RequestSigningException(Throwable cause) {
super(GadgetException.Code.REQUEST_SIGNING_FAILURE, cause);
}
public RequestSigningException(String msg, Throwable cause) {
super(GadgetException.Code.REQUEST_SIGNING_FAILURE, msg, cause);
}
public RequestSigningException(String msg) {
super(GadgetException.Code.REQUEST_SIGNING_FAILURE, msg);
}
}
| apache-2.0 |
diennea/majordodo | majordodo-core/src/main/java/majordodo/task/StatusChangesLog.java | 3301 | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package majordodo.task;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
/**
* Log of mofications, this is the base of the replication system
*
* @author enrico.olivelli
*/
public abstract class StatusChangesLog implements AutoCloseable {
protected BrokerFailureListener failureListener;
public String getSharedSecret() {
return null;
}
public boolean isSslUnsecure() {
return true;
}
public void setSslUnsecure(boolean sslUnsecure) {
}
public void setSharedSecret(String secret) {
}
public BrokerFailureListener getFailureListener() {
return failureListener;
}
public void setFailureListener(BrokerFailureListener failureListener) {
this.failureListener = failureListener;
}
public final void signalBrokerFailed(Throwable error) {
if (failureListener != null) {
failureListener.brokerFailed(error);
}
}
public abstract LogSequenceNumber logStatusEdit(StatusEdit edit) throws LogNotAvailableException;
public abstract void recovery(LogSequenceNumber snapshotSequenceNumber, BiConsumer<LogSequenceNumber, StatusEdit> consumer, boolean fencing) throws LogNotAvailableException;
public void clear() throws LogNotAvailableException {
}
public void startWriting() throws LogNotAvailableException {
}
public abstract void checkpoint(BrokerStatusSnapshot snapshotData) throws LogNotAvailableException;
public abstract BrokerStatusSnapshot loadBrokerStatusSnapshot() throws LogNotAvailableException;
@Override
public void close() throws LogNotAvailableException {
}
public abstract LogSequenceNumber getLastSequenceNumber();
public boolean isLeader() {
return true;
}
public void followTheLeader(LogSequenceNumber snapshotSequenceNumber, BiConsumer<LogSequenceNumber, StatusEdit> consumer) throws LogNotAvailableException {
}
public abstract boolean isClosed();
public abstract boolean isWritable();
public void requestLeadership() throws LogNotAvailableException {
}
public List<LogSequenceNumber> logStatusEditBatch(List<StatusEdit> edits) throws LogNotAvailableException {
List<LogSequenceNumber> batch = new ArrayList<>();
for (StatusEdit edit : edits) {
batch.add(logStatusEdit(edit));
}
return batch;
}
}
| apache-2.0 |
arenadata/ambari | ambari-metrics/ambari-metrics-timelineservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestApplicationHistoryClientService.java | 9353 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.applicationhistoryservice;
import java.io.IOException;
import java.util.List;
import junit.framework.Assert;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainersRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainersResponse;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptReport;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerReport;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.webapp.util.WebAppUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
// Timeline service client support is not enabled for AMBARI_METRICS
@Ignore
public class TestApplicationHistoryClientService extends
ApplicationHistoryStoreTestUtils {
ApplicationHistoryServer historyServer = null;
String expectedLogUrl = null;
@Before
public void setup() {
historyServer = new ApplicationHistoryServer();
Configuration config = new YarnConfiguration();
expectedLogUrl = WebAppUtils.getHttpSchemePrefix(config) +
WebAppUtils.getAHSWebAppURLWithoutScheme(config) +
"/applicationhistory/logs/localhost:0/container_0_0001_01_000001/" +
"container_0_0001_01_000001/test user";
config.setClass(YarnConfiguration.APPLICATION_HISTORY_STORE,
MemoryApplicationHistoryStore.class, ApplicationHistoryStore.class);
historyServer.init(config);
historyServer.start();
store =
((ApplicationHistoryManagerImpl) historyServer.getApplicationHistory())
.getHistoryStore();
}
@After
public void tearDown() throws Exception {
historyServer.stop();
}
@Test
public void testApplicationReport() throws IOException, YarnException {
ApplicationId appId = null;
appId = ApplicationId.newInstance(0, 1);
writeApplicationStartData(appId);
writeApplicationFinishData(appId);
GetApplicationReportRequest request =
GetApplicationReportRequest.newInstance(appId);
GetApplicationReportResponse response =
historyServer.getClientService().getClientHandler()
.getApplicationReport(request);
ApplicationReport appReport = response.getApplicationReport();
Assert.assertNotNull(appReport);
Assert.assertEquals("application_0_0001", appReport.getApplicationId()
.toString());
Assert.assertEquals("test type", appReport.getApplicationType().toString());
Assert.assertEquals("test queue", appReport.getQueue().toString());
}
@Test
public void testApplications() throws IOException, YarnException {
ApplicationId appId = null;
appId = ApplicationId.newInstance(0, 1);
writeApplicationStartData(appId);
writeApplicationFinishData(appId);
ApplicationId appId1 = ApplicationId.newInstance(0, 2);
writeApplicationStartData(appId1);
writeApplicationFinishData(appId1);
GetApplicationsRequest request = GetApplicationsRequest.newInstance();
GetApplicationsResponse response =
historyServer.getClientService().getClientHandler()
.getApplications(request);
List<ApplicationReport> appReport = response.getApplicationList();
Assert.assertNotNull(appReport);
Assert.assertEquals(appId, appReport.get(0).getApplicationId());
Assert.assertEquals(appId1, appReport.get(1).getApplicationId());
}
@Test
public void testApplicationAttemptReport() throws IOException, YarnException {
ApplicationId appId = ApplicationId.newInstance(0, 1);
ApplicationAttemptId appAttemptId =
ApplicationAttemptId.newInstance(appId, 1);
writeApplicationAttemptStartData(appAttemptId);
writeApplicationAttemptFinishData(appAttemptId);
GetApplicationAttemptReportRequest request =
GetApplicationAttemptReportRequest.newInstance(appAttemptId);
GetApplicationAttemptReportResponse response =
historyServer.getClientService().getClientHandler()
.getApplicationAttemptReport(request);
ApplicationAttemptReport attemptReport =
response.getApplicationAttemptReport();
Assert.assertNotNull(attemptReport);
Assert.assertEquals("appattempt_0_0001_000001", attemptReport
.getApplicationAttemptId().toString());
}
@Test
public void testApplicationAttempts() throws IOException, YarnException {
ApplicationId appId = ApplicationId.newInstance(0, 1);
ApplicationAttemptId appAttemptId =
ApplicationAttemptId.newInstance(appId, 1);
ApplicationAttemptId appAttemptId1 =
ApplicationAttemptId.newInstance(appId, 2);
writeApplicationAttemptStartData(appAttemptId);
writeApplicationAttemptFinishData(appAttemptId);
writeApplicationAttemptStartData(appAttemptId1);
writeApplicationAttemptFinishData(appAttemptId1);
GetApplicationAttemptsRequest request =
GetApplicationAttemptsRequest.newInstance(appId);
GetApplicationAttemptsResponse response =
historyServer.getClientService().getClientHandler()
.getApplicationAttempts(request);
List<ApplicationAttemptReport> attemptReports =
response.getApplicationAttemptList();
Assert.assertNotNull(attemptReports);
Assert.assertEquals(appAttemptId, attemptReports.get(0)
.getApplicationAttemptId());
Assert.assertEquals(appAttemptId1, attemptReports.get(1)
.getApplicationAttemptId());
}
@Test
public void testContainerReport() throws IOException, YarnException {
ApplicationId appId = ApplicationId.newInstance(0, 1);
writeApplicationStartData(appId);
ApplicationAttemptId appAttemptId =
ApplicationAttemptId.newInstance(appId, 1);
ContainerId containerId = ContainerId.newContainerId(appAttemptId, 1);
writeContainerStartData(containerId);
writeContainerFinishData(containerId);
writeApplicationFinishData(appId);
GetContainerReportRequest request =
GetContainerReportRequest.newInstance(containerId);
GetContainerReportResponse response =
historyServer.getClientService().getClientHandler()
.getContainerReport(request);
ContainerReport container = response.getContainerReport();
Assert.assertNotNull(container);
Assert.assertEquals(containerId, container.getContainerId());
Assert.assertEquals(expectedLogUrl, container.getLogUrl());
}
@Test
public void testContainers() throws IOException, YarnException {
ApplicationId appId = ApplicationId.newInstance(0, 1);
writeApplicationStartData(appId);
ApplicationAttemptId appAttemptId =
ApplicationAttemptId.newInstance(appId, 1);
ContainerId containerId = ContainerId.newContainerId(appAttemptId, 1);
ContainerId containerId1 = ContainerId.newContainerId(appAttemptId, 2);
writeContainerStartData(containerId);
writeContainerFinishData(containerId);
writeContainerStartData(containerId1);
writeContainerFinishData(containerId1);
writeApplicationFinishData(appId);
GetContainersRequest request =
GetContainersRequest.newInstance(appAttemptId);
GetContainersResponse response =
historyServer.getClientService().getClientHandler()
.getContainers(request);
List<ContainerReport> containers = response.getContainerList();
Assert.assertNotNull(containers);
Assert.assertEquals(containerId, containers.get(1).getContainerId());
Assert.assertEquals(containerId1, containers.get(0).getContainerId());
}
}
| apache-2.0 |