repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
cheesebro/CRONOMETER
src/ca/spaz/gui/SpazPosition.java
2708
package ca.spaz.gui; import java.awt.Rectangle; /** */ public class SpazPosition { public int leftA, rightA, topA, bottomA; public double leftR, rightR, topR, bottomR; public SpazPosition(){} public SpazPosition(SpazPosition copy) { this.leftA = copy.leftA; this.leftR = copy.leftR; this.rightA = copy.rightA; this.rightR = copy.rightR; this.topA = copy.topA; this.topR = copy.topR; this.bottomA = copy.bottomA; this.bottomR = copy.bottomR; } public void setHPos(double lR, int lA, double rR, int rA) { this.leftR = lR; this.leftA = lA; this.rightR = rR; this.rightA = rA; } public void setVPos(double tR, int tA, double bR, int bA) { this.topR = tR; this.topA = tA; this.bottomR = bR; this.bottomA = bA; } public Rectangle getRectangle(int width, int height) { int top = (int)(topR*height) + topA; int bottom = (int)(bottomR*height) + bottomA; int left = (int)(leftR*width) + leftA; int right = (int)(rightR*width) + rightA; return ( new Rectangle(left, top, (right - left), (bottom - top)) ); } public Rectangle getMinRectangle() { return ( new Rectangle(leftA, topA, (rightA - leftA), (bottomA - topA)) ); } public String toString() { return (leftA + ", " + rightA + ", " + topA + ", " + bottomA); } public void adjustLeft(int val, int width) { int cur = (int)(width * leftR); this.leftA = (val - cur); } public void adjustRight(int val, int width) { int cur = (int)(width * rightR); this.rightA = (val - cur); } public void adjustTop(int val, int height) { int cur = (int)(height * topR); this.topA = (val - cur); } public void adjustBottom(int val, int height) { int cur = (int)(height * bottomR); this.bottomA = (val - cur); } public boolean valid() { if ((topA + (topR*500)) > (bottomA + (bottomR*500))) return false; if ((leftA + (leftR*500)) > (rightA + (rightR*500))) return false; if (leftR < 0 || leftR > 1) return false; if (rightR < 0 || rightR > 1) return false; if (topR < 0 || topR > 1) return false; if (bottomR < 0 || bottomR > 1) return false; return true; } public String toXMLString() { StringBuffer sb = new StringBuffer(); sb.append("<position "); sb.append(" left_rel=\""+ leftR + '"'); sb.append(" left_abs=\""+ leftA + '"'); sb.append(" right_rel=\""+ rightR + '"'); sb.append(" right_abs=\""+ rightA + '"'); sb.append(" top_rel=\""+ topR + '"'); sb.append(" top_abs=\""+ topA + '"'); sb.append(" bottom_rel=\""+ bottomR + '"'); sb.append(" bottom_abs=\""+ bottomA + '"'); sb.append("/>\n"); return sb.toString(); } }
epl-1.0
Treehopper/EclipseAugments
pom-editor/eu.hohenegger.xsd.pom/src-gen/eu/hohenegger/xsd/pom/FiltersType1.java
1201
/** */ package eu.hohenegger.xsd.pom; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Filters Type1</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link eu.hohenegger.xsd.pom.FiltersType1#getFilter <em>Filter</em>}</li> * </ul> * * @see eu.hohenegger.xsd.pom.PomPackage#getFiltersType1() * @model extendedMetaData="name='filters_._1_._type' kind='elementOnly'" * @generated */ public interface FiltersType1 extends EObject { /** * Returns the value of the '<em><b>Filter</b></em>' attribute list. * The list contents are of type {@link java.lang.String}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Filter</em>' attribute list. * @see eu.hohenegger.xsd.pom.PomPackage#getFiltersType1_Filter() * @model unique="false" dataType="org.eclipse.emf.ecore.xml.type.String" * extendedMetaData="kind='element' name='filter' namespace='##targetNamespace'" * @generated */ EList<String> getFilter(); } // FiltersType1
epl-1.0
sleshchenko/che
ide/commons-gwt/src/main/java/org/eclipse/che/ide/rest/StringMapListUnmarshaller.java
1013
/* * Copyright (c) 2012-2018 Red Hat, Inc. * 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: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.rest; import com.google.gwt.http.client.Response; import java.util.List; import java.util.Map; import org.eclipse.che.ide.commons.exception.UnmarshallerException; import org.eclipse.che.ide.json.JsonHelper; /** @author Eugene Voevodin */ public class StringMapListUnmarshaller implements Unmarshallable<Map<String, List<String>>> { private Map<String, List<String>> payload; @Override public void unmarshal(Response response) throws UnmarshallerException { payload = JsonHelper.toMapOfLists(response.getText()); } @Override public Map<String, List<String>> getPayload() { return payload; } }
epl-1.0
opendaylight/yangtools
model/yang-model-ri/src/main/java/org/opendaylight/yangtools/yang/model/ri/stmt/impl/ref/RefTypedefStatement.java
920
/* * Copyright (c) 2021 PANTHEON.tech, s.r.o. 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 */ package org.opendaylight.yangtools.yang.model.ri.stmt.impl.ref; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.meta.DeclarationReference; import org.opendaylight.yangtools.yang.model.api.stmt.TypedefStatement; import org.opendaylight.yangtools.yang.model.spi.meta.AbstractRefStatement; public final class RefTypedefStatement extends AbstractRefStatement<QName, TypedefStatement> implements TypedefStatement { public RefTypedefStatement(final TypedefStatement delegate, final DeclarationReference ref) { super(delegate, ref); } }
epl-1.0
DavidGutknecht/elexis-3-base
bundles/ch.elexis.base.ch.arzttarife.model/src-gen/ch/elexis/base/ch/arzttarife/rfe/IReasonForEncounter.java
3118
/** * Copyright Text Copyright (c) 2018 MEDEVIT <office@medevit.at>.... */ package ch.elexis.base.ch.arzttarife.rfe; import ch.elexis.core.model.Deleteable; import ch.elexis.core.model.IEncounter; import ch.elexis.core.model.Identifiable; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>IReason For Encounter</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link ch.elexis.base.ch.arzttarife.rfe.IReasonForEncounter#getEncounter <em>Encounter</em>}</li> * <li>{@link ch.elexis.base.ch.arzttarife.rfe.IReasonForEncounter#getCode <em>Code</em>}</li> * <li>{@link ch.elexis.base.ch.arzttarife.rfe.IReasonForEncounter#getText <em>Text</em>}</li> * </ul> * * @see ch.elexis.base.ch.arzttarife.rfe.RfePackage#getIReasonForEncounter() * @model interface="true" abstract="true" * @generated */ public interface IReasonForEncounter extends Deleteable, Identifiable { /** * Returns the value of the '<em><b>Encounter</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Encounter</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Encounter</em>' reference. * @see #setEncounter(IEncounter) * @see ch.elexis.base.ch.arzttarife.rfe.RfePackage#getIReasonForEncounter_Encounter() * @model * @generated */ IEncounter getEncounter(); /** * Sets the value of the '{@link ch.elexis.base.ch.arzttarife.rfe.IReasonForEncounter#getEncounter <em>Encounter</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Encounter</em>' reference. * @see #getEncounter() * @generated */ void setEncounter(IEncounter value); /** * Returns the value of the '<em><b>Code</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Code</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Code</em>' attribute. * @see #setCode(String) * @see ch.elexis.base.ch.arzttarife.rfe.RfePackage#getIReasonForEncounter_Code() * @model * @generated */ String getCode(); /** * Sets the value of the '{@link ch.elexis.base.ch.arzttarife.rfe.IReasonForEncounter#getCode <em>Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Code</em>' attribute. * @see #getCode() * @generated */ void setCode(String value); /** * Returns the value of the '<em><b>Text</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Text</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Text</em>' attribute. * @see ch.elexis.base.ch.arzttarife.rfe.RfePackage#getIReasonForEncounter_Text() * @model changeable="false" * @generated */ String getText(); } // IReasonForEncounter
epl-1.0
rherrmann/eclipse-extras
com.codeaffine.extras.test.util/src/com/codeaffine/extras/test/util/ImageAssert.java
1189
package com.codeaffine.extras.test.util; import java.net.URL; import org.assertj.core.api.AbstractAssert; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.osgi.framework.Bundle; public class ImageAssert extends AbstractAssert<ImageAssert,ImageInfo> { private ImageAssert( ImageInfo actual ) { super( actual, ImageAssert.class ); } public static ImageAssert assertThat( String pluginId, String imagePath ) { return new ImageAssert( new ImageInfo( pluginId, imagePath ) ); } public ImageAssert exists() { Bundle bundle = Platform.getBundle( actual.pluginId ); URL location = FileLocator.find( bundle, new Path( actual.imagePath ), null ); ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL( location ); Image image = imageDescriptor.createImage( false ); boolean result = image != null; image.dispose(); if( !result ) { failWithMessage( "Image <%s> not found in plugin <%s>", actual.imagePath, actual.pluginId ); } return this; } }
epl-1.0
ELTE-Soft/xUML-RT-Executor
plugins/hu.eltesoft.modelexecution.runtime/src/hu/eltesoft/modelexecution/runtime/external/ExternalEntity.java
577
package hu.eltesoft.modelexecution.runtime.external; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Attaches meta-information to external entity skeleton classes. This * information will be used to lookup an implementation instance from a * behavior's generated code. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ExternalEntity { String implementationClass(); ExternalEntityType type(); }
epl-1.0
comutt/yukinoshita2
src/org/unitarou/sgf/util/provider/crdlp/NoCoordinatesProvider.java
1937
/* * Copyright 2004-2009 unitarou <boss@unitarou.org>. * All rights reserved. * * This program and the accompanying materials are made available under the terms of * the Common Public License v1.0 which accompanies this distribution, * and is available at http://opensource.org/licenses/cpl.php * * Contributors: * unitarou - initial API and implementation */ package org.unitarou.sgf.util.provider.crdlp; import org.unitarou.lang.Strings; import org.unitarou.ml.Message; import org.unitarou.sgf.type.SgfPoint; /** * {@link #getXLabel(SgfPoint)}‚Æ{@link #getYLabel(SgfPoint)}A * {@link #getMoveLabel(SgfPoint)}‚Å * À•W‚ð•\ަ‚µ‚È‚¢(‹ó•¶Žš‚ð•Ô‚·)ƒvƒƒoƒCƒ_[‚Å‚·B * * @author unitarou &lt;boss@unitarou.org&gt; */ public class NoCoordinatesProvider implements CoordinatesLabelProvider { /**u•\ަ‚È‚µv*/ static private final Message LB_DISPLAY_NAME = new Message(NoCoordinatesProvider.class, "lbDisplayName"); //$NON-NLS-1$ /** * */ public NoCoordinatesProvider() { super(); } /* (non-Javadoc) * @see org.unitarou.yukinoshita.view.clp.CoordinatesLabelProvider#stringX(org.unitarou.sgf.type.SgfPoint) */ public String getXLabel(SgfPoint sgfPoint) { return Strings.EMPTY; } /* (non-Javadoc) * @see org.unitarou.yukinoshita.view.clp.CoordinatesLabelProvider#stringY(org.unitarou.sgf.type.SgfPoint) */ public String getYLabel(SgfPoint sgfPoint) { return Strings.EMPTY; } /* (non-Javadoc) * @see org.unitarou.yukinoshita.view.clp.CoordinatesLabelProvider#stringMove(org.unitarou.sgf.type.SgfPoint) */ public String getMoveLabel(SgfPoint sgfPoint) { return Strings.EMPTY; } /* (non-Javadoc) * @see org.unitarou.yukinoshita.view.clp.CoordinatesLabelProvider#getDisplayName() */ public String displayName() { return LB_DISPLAY_NAME.get(); } }
epl-1.0
LM25TTD/HopperIDE
Eclipse_Plugin/org.hopper.language.parent/org.hopper.language/src-gen/org/hopper/language/portugol/impl/FunctionCallImpl.java
3784
/** * generated by Xtext 2.9.0 */ package org.hopper.language.portugol.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.hopper.language.portugol.FunctionCall; import org.hopper.language.portugol.FunctionName; import org.hopper.language.portugol.PortugolPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Function Call</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.hopper.language.portugol.impl.FunctionCallImpl#getFbName <em>Fb Name</em>}</li> * </ul> * * @generated */ public class FunctionCallImpl extends ExpressionImpl implements FunctionCall { /** * The cached value of the '{@link #getFbName() <em>Fb Name</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFbName() * @generated * @ordered */ protected FunctionName fbName; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected FunctionCallImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return PortugolPackage.Literals.FUNCTION_CALL; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FunctionName getFbName() { if (fbName != null && fbName.eIsProxy()) { InternalEObject oldFbName = (InternalEObject)fbName; fbName = (FunctionName)eResolveProxy(oldFbName); if (fbName != oldFbName) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, PortugolPackage.FUNCTION_CALL__FB_NAME, oldFbName, fbName)); } } return fbName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FunctionName basicGetFbName() { return fbName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFbName(FunctionName newFbName) { FunctionName oldFbName = fbName; fbName = newFbName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, PortugolPackage.FUNCTION_CALL__FB_NAME, oldFbName, fbName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case PortugolPackage.FUNCTION_CALL__FB_NAME: if (resolve) return getFbName(); return basicGetFbName(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case PortugolPackage.FUNCTION_CALL__FB_NAME: setFbName((FunctionName)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case PortugolPackage.FUNCTION_CALL__FB_NAME: setFbName((FunctionName)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case PortugolPackage.FUNCTION_CALL__FB_NAME: return fbName != null; } return super.eIsSet(featureID); } } //FunctionCallImpl
epl-1.0
magiclud/SpringMVCBootstrap
src/main/java/net/codejava/spring/SpringWebAppInitializer.java
864
package net.codejava.spring; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class SpringWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); appContext.register(ApplicationContextConfig.class); ServletRegistration.Dynamic dispatcher = container.addServlet( "SpringDispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
epl-1.0
debrief/debrief
org.mwc.cmap.core/src/org/mwc/cmap/core/property_support/RightClickSupport.java
40395
/******************************************************************************* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2020, Deep Blue C Technology Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * 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. *******************************************************************************/ package org.mwc.cmap.core.property_support; import java.awt.Color; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.MethodDescriptor; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.swt.dnd.Clipboard; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.operations.RightClickCutCopyAdaptor; import org.mwc.cmap.core.operations.RightClickPasteAdaptor; import Debrief.Wrappers.FixWrapper; import Debrief.Wrappers.LabelWrapper; import Debrief.Wrappers.SensorWrapper; import Debrief.Wrappers.ShapeWrapper; import MWC.GUI.Editable; import MWC.GUI.Editable.CategorisedPropertyDescriptor; import MWC.GUI.Editable.EditorType; import MWC.GUI.FireExtended; import MWC.GUI.FireReformatted; import MWC.GUI.HasEditables; import MWC.GUI.Layer; import MWC.GUI.Layers; import MWC.GUI.Shapes.RectangleShape; import MWC.GUI.Tools.SubjectAction; import MWC.GenericData.HiResDate; import MWC.GenericData.WorldLocation; import MWC.TacticalData.Fix; import MWC.Utilities.ReaderWriter.PlainImporterBase; public class RightClickSupport { /** * embedded class to store a property change in an action * * @author ian.mayo */ private static class ListPropertyAction extends AbstractOperation { private Object _oldValue; private final Method _setter; private final Layers _layers; private final Layer _parentLayer; private final Editable[] _subjects; private final Object _newValue; private final String _propertyName; public ListPropertyAction(final String propertyName, final Editable[] editable, final Method getter, final Method setter, final Object newValue, final Layers layers, final Layer parentLayer) { super(propertyName + " for " + (editable.length > 1 ? "multiple items" : editable[0].getName())); _propertyName = propertyName; _setter = setter; _layers = layers; _parentLayer = parentLayer; _subjects = editable; _newValue = newValue; try { _oldValue = getter.invoke(editable[0], (Object[]) null); } catch (final Exception e) { CorePlugin.logError(IStatus.ERROR, "Failed to retrieve old value for:" + "Multiple items starting with:" + _subjects[0].getName(), e); } if (CorePlugin.getUndoContext() != null) { super.addContext(CorePlugin.getUndoContext()); } } private IStatus doIt(final Object theValue) { IStatus res = Status.OK_STATUS; for (int cnt = 0; cnt < _subjects.length; cnt++) { final Editable thisSubject = _subjects[cnt]; try { _setter.invoke(thisSubject, new Object[] { theValue }); // and try to fire property change final EditorType info = thisSubject.getInfo(); if (info != null) { info.fireChanged(this, _propertyName, null, theValue); } } catch (final InvocationTargetException e) { CorePlugin.logError(IStatus.ERROR, "Setter call failed:" + thisSubject.getName() + " Error was:" + e.getTargetException().getMessage(), e.getTargetException()); res = Status.CANCEL_STATUS; } catch (final IllegalArgumentException e) { CorePlugin.logError(IStatus.ERROR, "Wrong parameters pass to:" + thisSubject.getName(), e); res = Status.CANCEL_STATUS; } catch (final IllegalAccessException e) { CorePlugin.logError(IStatus.ERROR, "Illegal access problem for:" + thisSubject.getName(), e); res = Status.CANCEL_STATUS; } } // and tell everybody (we only need to do this if the previous call // works, // if an exception is thrown we needn't worry about the update fireUpdate(); return res; } @Override public IStatus execute(final IProgressMonitor monitor, final IAdaptable info) throws ExecutionException { return doIt(_newValue); } private void fireUpdate() { // hmm, the method may have actually changed the data, we need to // find out if it // needs an extend if (_setter.isAnnotationPresent(FireExtended.class)) { _layers.fireExtended(null, _parentLayer); } else if (_setter.isAnnotationPresent(FireReformatted.class)) { _layers.fireReformatted(_parentLayer); } else { // hey, let's do a redraw aswell... _layers.fireModified(_parentLayer); } } @Override public IStatus redo(final IProgressMonitor monitor, final IAdaptable info) throws ExecutionException { return doIt(_newValue); } @Override public IStatus undo(final IProgressMonitor monitor, final IAdaptable info) throws ExecutionException { return doIt(_oldValue); } } /** * utility class that sorts property descriptors * * @author Ian * */ private static class PropertyComparator implements Comparator<PropertyDescriptor> { @Override public int compare(final PropertyDescriptor o1, final PropertyDescriptor o2) { return o1.getName().compareTo(o2.getName()); } } /** * template provide by support units that want to add items to the right-click * menu when something is selected * * @author ian.mayo */ public static interface RightClickContextItemGenerator { public void generate(IMenuManager parent, Layers theLayers, Layer[] parentLayers, Editable[] subjects); } /** * embedded class that encapsulates the information we need to fire an action. * It was really only refactored to aid debugging. * * @author ian.mayo */ private static class SubjectMethod extends Action { private final Editable[] _subjects; private final Method _method; private final Layer _topLayer; private final Layers _theLayers; /** * @param title what to call the action * @param subject the thing we're operating upon * @param method what we're going to run * @param topLayer the layer to update after the action is complete * @param theLayers the host for the target layer */ public SubjectMethod(final String title, final Editable[] subject, final Method method, final Layer topLayer, final Layers theLayers) { super(title); _subjects = subject; _method = method; _topLayer = topLayer; _theLayers = theLayers; } @Override public void run() { // SPECIAL HANDLING. If this is the exportThis() method // call, we should clear the output buffer first if ("exportThis".equals(_method.getName()) || "exportShape".equals(_method.getName())) { PlainImporterBase.clearBuffer(); } final int len = _subjects.length; for (int cnt = 0; cnt < len; cnt++) { final Editable thisSubject = _subjects[cnt]; try { _method.invoke(thisSubject, new Object[0]); } catch (final IllegalArgumentException e) { CorePlugin.logError(IStatus.ERROR, "whilst firing method from right-click", e); } catch (final IllegalAccessException e) { CorePlugin.logError(IStatus.ERROR, "whilst firing method from right-click", e); } catch (final InvocationTargetException e) { CorePlugin.logError(IStatus.ERROR, "whilst firing method from right-click", e); } } // hmm, the method may have actually changed the data, we need to // find out if it // needs an extend if (_method.isAnnotationPresent(FireExtended.class)) { _theLayers.fireExtended(null, _topLayer); } else if (_method.isAnnotationPresent(FireReformatted.class)) { _theLayers.fireReformatted(_topLayer); } else { // hey, let's do a redraw aswell... _theLayers.fireModified(_topLayer); } } }; // //////////////////////////////////////////////////////////////////////////////////////////////// // testing for this class // //////////////////////////////////////////////////////////////////////////////////////////////// static public final class testMe extends junit.framework.TestCase { static public final String TEST_ALL_TEST_TYPE = "UNIT"; public testMe(final String val) { super(val); } public final void testAdditionalNonePresent() { final ShapeWrapper sw = new ShapeWrapper("rect", new RectangleShape(new WorldLocation(12.1, 12.3, 12), new WorldLocation(1.1, 1.1, 12)), Color.red, new HiResDate(2222)); final Editable[] editables = new Editable[] { sw }; final MenuManager menu = new MenuManager("Holder"); RightClickSupport.getDropdownListFor(menu, editables, null, null, null, true); boolean foundTransparent = false; // note: this next test may return 4 if run from within IDE, // some contributions provided by plugins assertEquals("Has items", 2, menu.getSize(), 2); final IContributionItem[] items = menu.getItems(); for (int i = 0; i < items.length; i++) { final IContributionItem thisI = items[i]; if (thisI instanceof MenuManager) { final MenuManager subMenu = (MenuManager) thisI; final IContributionItem[] subItems = subMenu.getItems(); for (int j = 0; j < subItems.length; j++) { final IContributionItem subI = subItems[j]; if (subI instanceof ActionContributionItem) { final ActionContributionItem ac = (ActionContributionItem) subI; final String theName = ac.getAction().getText(); if (theName.equals("Semi transparent")) { foundTransparent = true; } } } } } assertTrue("The additional bean info got processed!", foundTransparent); } public final void testAdditionalSomePresent() { final LabelWrapper lw = new LabelWrapper("Some label", new WorldLocation(1.1, 1.1, 12), Color.red); final Editable[] editables = new Editable[] { lw }; final MenuManager menu = new MenuManager("Holder"); RightClickSupport.getDropdownListFor(menu, editables, null, null, null, true); // note: this next test may return 4 if run from within IDE, // some contributions provided by plugins assertEquals("Has items", 2, menu.getSize(), 2); } public final void testIntersection() { try { final PropertyDescriptor[] demo = new PropertyDescriptor[] {}; final PropertyDescriptor[] pa = new PropertyDescriptor[] { new PropertyDescriptor("Color", FixWrapper.class), new PropertyDescriptor("Font", FixWrapper.class), new PropertyDescriptor("Label", FixWrapper.class), new PropertyDescriptor("LabelShowing", FixWrapper.class), new PropertyDescriptor("Visible", FixWrapper.class) }; final PropertyDescriptor[] pb = new PropertyDescriptor[] { new PropertyDescriptor("Color", FixWrapper.class), new PropertyDescriptor("Font", FixWrapper.class), new PropertyDescriptor("Label", FixWrapper.class), new PropertyDescriptor("LabelShowing", FixWrapper.class), new PropertyDescriptor("SymbolShowing", FixWrapper.class), }; final PropertyDescriptor[] pc = new PropertyDescriptor[] { new PropertyDescriptor("LabelShowing", FixWrapper.class), new PropertyDescriptor("SymbolShowing", FixWrapper.class), }; final PropertyDescriptor[] pd = new PropertyDescriptor[] {}; PropertyDescriptor[] res = getIntersectionFor(pa, pb, demo); assertNotNull("failed to find intersection", res); assertEquals("Failed to find correct num", 4, res.length); res = getIntersectionFor(res, pc, demo); assertNotNull("failed to find intersection", res); assertEquals("Failed to find correct num", 1, res.length); res = getIntersectionFor(pa, pd, demo); assertNotNull("failed to find intersection", res); assertEquals("Failed to find correct num", 0, res.length); res = getIntersectionFor(pd, pa, demo); assertNotNull("failed to find intersection", res); assertEquals("Failed to find correct num", 0, res.length); } catch (final IntrospectionException e) { CorePlugin.logError(IStatus.ERROR, "Whilst doing tests", e); assertTrue("threw some error", false); } } public final void testPropMgt() { final Editable itemOne = new FixWrapper(new Fix(new HiResDate(122333), new WorldLocation(1, 2, 3), 12, 14)); final Editable itemTwo = new FixWrapper(new Fix(new HiResDate(122334), new WorldLocation(1, 2, 5), 13, 12)); final Editable itemThree = new SensorWrapper("alpha"); final Editable[] lst = new Editable[] { itemOne, itemTwo }; final Editable[] lst2 = new Editable[] { itemOne, itemThree }; final Editable[] lst3 = new Editable[] { itemThree, itemOne, itemThree }; final Editable[] lst4 = new Editable[] { itemThree, itemThree }; final Editable[] lst5 = new Editable[] { itemOne }; assertEquals("no data", 2, lst.length); PropertyDescriptor[] props = RightClickSupport.getCommonPropertiesFor(lst); assertNotNull("found some data", props); assertEquals("found right matches", 14, props.length); props = RightClickSupport.getCommonPropertiesFor(lst2); assertNotNull("found some data", props); assertEquals("found right matches", 1, props.length); props = RightClickSupport.getCommonPropertiesFor(lst3); assertNotNull("found some data", props); assertEquals("found right matches", 1, props.length); props = RightClickSupport.getCommonPropertiesFor(lst4); assertNotNull("found some data", props); assertEquals("found right matches", 10, props.length); props = RightClickSupport.getCommonPropertiesFor(lst5); assertNotNull("found some data", props); assertEquals("found right matches", 14, props.length); } } /** * embedded class to store a property change in an action * * @author ian.mayo */ public static class UndoableAction extends AbstractOperation { private final SubjectAction _action; private final Layers _layers; private final Layer _parentLayer; private final Editable[] _subjects; public UndoableAction(final String propertyName, final Editable[] editable, final SubjectAction action, final Layers layers, final Layer parentLayer) { super(propertyName + " for " + (editable.length > 1 ? "multiple items" : editable[0].getName())); _layers = layers; _action = action; _parentLayer = parentLayer; _subjects = editable; if (CorePlugin.getUndoContext() != null) { super.addContext(CorePlugin.getUndoContext()); } } @Override public IStatus execute(final IProgressMonitor monitor, final IAdaptable info) throws ExecutionException { IStatus res = Status.OK_STATUS; for (int cnt = 0; cnt < _subjects.length; cnt++) { final Editable thisSubject = _subjects[cnt]; try { _action.execute(thisSubject); } catch (final IllegalArgumentException e) { CorePlugin.logError(IStatus.ERROR, "Wrong parameters pass to:" + thisSubject.getName(), e); res = Status.CANCEL_STATUS; } } // and tell everybody fireUpdate(_action.doFireExtended()); return res; } /** * tell everyone we've updated * * @param fireExtended whether to fire extended (or just reformatted) */ private void fireUpdate(final boolean fireExtended) { if (fireExtended) { _layers.fireExtended(null, _parentLayer); } else { _layers.fireReformatted(_parentLayer); } } @Override public IStatus redo(final IProgressMonitor monitor, final IAdaptable info) throws ExecutionException { IStatus res = Status.OK_STATUS; for (int cnt = 0; cnt < _subjects.length; cnt++) { final Editable thisSubject = _subjects[cnt]; try { _action.execute(thisSubject); } catch (final Exception e) { CorePlugin.logError(IStatus.ERROR, "Failed to set new value for:" + thisSubject.getName(), e); res = Status.CANCEL_STATUS; } } // and tell everybody // fireUpdate(); return res; } @Override public IStatus undo(final IProgressMonitor monitor, final IAdaptable info) throws ExecutionException { IStatus res = Status.OK_STATUS; for (int cnt = 0; cnt < _subjects.length; cnt++) { final Editable thisSubject = _subjects[cnt]; try { _action.undo(thisSubject); } catch (final Exception e) { CorePlugin.logError(IStatus.ERROR, "Failed to set new value for:" + thisSubject.getName(), e); res = null; } } // and tell everybody fireUpdate(_action.doFireExtended()); return res; } } /** * fixed strings for the right click support extension * */ private static final String EXTENSION_POINT_ID = "RightClickSupport"; // Plug-in ID from <plugin> tag in plugin.xml private static final String PLUGIN_ID = "org.mwc.cmap.core"; private static final String MULTIPLE_ITEMS_STR = "Multiple items"; private static final int MAX_ITEMS_FOR_UNDO = 1000; /** * list of actions to be added to context-menu on right-click */ private static Vector<RightClickContextItemGenerator> _additionalRightClickItems = null;; /** * whether we've checked for any one that extends teh right click support via * plugin xml * */ private static boolean _rightClickExtensionsChecked = false; /** * add a right-click generator item to the list we manage * * @param generator the generator to add... */ public static void addRightClickGenerator(final RightClickContextItemGenerator generator) { if (_additionalRightClickItems == null) { _additionalRightClickItems = new Vector<RightClickContextItemGenerator>(1, 1); } _additionalRightClickItems.add(generator); } public static MenuManager createMenuFor(final IMenuManager manager, final Editable[] editables, final Layers theLayers, final Layer theTopLayer, MenuManager subMenu, final Map<String, SortedSet<PropertyDescriptor>> map) { for (final String thisCat : map.keySet()) { final SortedSet<PropertyDescriptor> list = map.get(thisCat); for (final PropertyDescriptor thisP : list) { // start off with the booleans if (supportsBooleanEditor(thisP)) { // generate boolean editors in the sub-menu subMenu = generateBooleanEditorFor(manager, subMenu, thisP, editables, theLayers, theTopLayer); } else { // now the drop-down lists if (supportsListEditor(thisP)) { // generate boolean editors in the sub-menu subMenu = generateListEditorFor(manager, subMenu, thisP, editables, theLayers, theTopLayer); } } } if (subMenu != null) { // and a separator subMenu.add(new Separator(thisCat)); } } return subMenu; } static private MenuManager generateBooleanEditorFor(final IMenuManager manager, final MenuManager subMenu, final PropertyDescriptor thisP, final Editable[] editables, final Layers theLayers, final Layer topLevelLayer) { boolean currentVal = false; final Method getter = thisP.getReadMethod(); final Method setter = thisP.getWriteMethod(); MenuManager result = subMenu; try { final Boolean valNow = (Boolean) getter.invoke(editables[0], (Object[]) null); currentVal = valNow.booleanValue(); } catch (final Exception e) { CorePlugin.logError(IStatus.ERROR, "Failed to retrieve old value for:" + editables[0].getName(), e); } final IAction changeThis = new Action(thisP.getDisplayName(), IAction.AS_CHECK_BOX) { @Override public void run() { try { final ListPropertyAction la = new ListPropertyAction(thisP.getDisplayName(), editables, getter, setter, Boolean.valueOf(isChecked()), theLayers, topLevelLayer); CorePlugin.run(la); } catch (final Exception e) { CorePlugin.logError(IStatus.INFO, "While executing boolean editor for:" + thisP, e); } } }; changeThis.setChecked(currentVal); changeThis.setToolTipText(thisP.getShortDescription()); // is our sub-menu already created? if (result == null) { String nameStr; if (editables.length > 1) { nameStr = MULTIPLE_ITEMS_STR; } else { nameStr = editables[0].getName(); } result = new MenuManager(nameStr); manager.add(result); } result.add(changeThis); return result; } @SuppressWarnings("rawtypes") static private MenuManager generateListEditorFor(final IMenuManager manager, final MenuManager subMenu, final PropertyDescriptor thisP, final Editable[] editables, final Layers theLayers, final Layer topLevelLayer) { // find out the type of the editor final Method m = thisP.getReadMethod(); final Class cl = m.getReturnType(); MenuManager result = subMenu; // is there a custom editor for this type? final Class c = thisP.getPropertyEditorClass(); PropertyEditor pe = null; // try to create an editor for this class try { if (c != null) { pe = (PropertyEditor) c.newInstance(); } } catch (final Exception e) { MWC.Utilities.Errors.Trace.trace(e); } // did it work? if (pe == null) { // try to find an editor for this through our manager pe = PropertyEditorManager.findEditor(cl); } // retrieve the tags final String[] tags = pe.getTags(); // are there any tags for this class? if (tags != null) { // create a drop-down list final MenuManager thisChoice = new MenuManager(thisP.getDisplayName()); // sort out the setter details final Method getter = thisP.getReadMethod(); // get the current value Object val = null; try { val = getter.invoke(editables[0], (Object[]) null); } catch (final Exception e) { MWC.Utilities.Errors.Trace.trace(e); } pe.setValue(val); // convert the current value to text final String currentValue = pe.getAsText(); // and now a drop-down item for each options for (int j = 0; j < tags.length; j++) { final String thisTag = tags[j]; pe.setAsText(thisTag); final Object thisValue = pe.getValue(); // create the item final IAction thisA = new Action(thisTag, IAction.AS_RADIO_BUTTON) { @Override public void run() { try { // hey, since this is a radio button, we get two events when the // selection changes - one for the value being unset, and the // other // for the value being set. So just fire for the new value (the // one that's checked) if (isChecked()) { final Method setter = thisP.getWriteMethod(); // ok, place the change in the action final ListPropertyAction la = new ListPropertyAction(thisP.getDisplayName(), editables, getter, setter, thisValue, theLayers, topLevelLayer); // and add it to the history CorePlugin.run(la); } } catch (final Exception e) { CorePlugin.logError(IStatus.INFO, "While executing select editor for:" + thisP, e); } } }; // is this the current one? if (thisTag.equals(currentValue)) { thisA.setChecked(true); } // add it to the menu thisChoice.add(thisA); } // is our sub-menu already created? if (result == null) { String nameStr; if (editables.length > 1) { nameStr = MULTIPLE_ITEMS_STR; } else { nameStr = editables[0].getName(); } result = new MenuManager(nameStr); manager.add(result); } result.add(thisChoice); } return result; } static private IAction generateUndoableActionFor(final MWC.GUI.Tools.SubjectAction theAction, final Editable[] editables, final Layers theLayers, final Layer topLevelLayer) { final IAction changeThis = new Action(theAction.toString(), IAction.AS_PUSH_BUTTON) { @Override public void run() { try { final AbstractOperation la = new UndoableAction(theAction.toString(), editables, theAction, theLayers, topLevelLayer); CorePlugin.run(la); } catch (final Exception e) { CorePlugin.logError(IStatus.INFO, "While executing undoable operations for for:" + theAction.toString(), e); } } }; changeThis.setEnabled(theAction.isEnabled()); return changeThis; } /** have a look at the supplied editors, find which properties are common */ protected static MethodDescriptor[] getCommonMethodsFor(final Editable[] editables) { MethodDescriptor[] res = null; final MethodDescriptor[] demo = new MethodDescriptor[] {}; final int len = editables.length; // right, get the first set of properties if (len > 0) { final Editable first = editables[0]; final EditorType firstInfo = first.getInfo(); if (firstInfo != null) { res = firstInfo.getMethodDescriptors(); // only continue if there are any methods to compare against if (res != null) { // right, are there any more? if (len > 1) { // pass through the others, finding the common ground for (int cnt = 1; cnt < len; cnt++) { final Editable thisE = editables[cnt]; // get its props final EditorType thisEditor = thisE.getInfo(); // do we have an editor? if (thisEditor != null) { final MethodDescriptor[] newSet = thisEditor.getMethodDescriptors(); // check we're not already looking at an instance of this type if (newSet != res) { // find the common ones res = getIntersectionFor(res, newSet, demo); } } else { // handle instance where editable doesn't have anything editable res = null; break; } } } } else { // handle instance where editable doesn't have anything editable res = null; } } } return res; } /** have a look at the supplied editors, find which properties are common */ protected static PropertyDescriptor[] getCommonPropertiesFor(final Editable[] editables) { PropertyDescriptor[] res = null; final PropertyDescriptor[] demo = new PropertyDescriptor[] {}; final int len = editables.length; // right, get the first set of properties if (len > 0) { final Editable first = editables[0]; final EditorType firstInfo = first.getInfo(); if (firstInfo != null) { res = firstInfo.getPropertyDescriptors(); // only continue if there are any property descriptors if (res != null) { // right, are there any more? if (len > 1) { // pass through the others, finding the common ground for (int cnt = 1; cnt < len; cnt++) { final Editable thisE = editables[cnt]; // get its props final EditorType thisEditor = thisE.getInfo(); // do we have an editor? if (thisEditor != null) { final PropertyDescriptor[] newSet = thisEditor.getPropertyDescriptors(); // just double-check that we aren't already looking at these props // (we do if it's lots of the same item selected if (res != newSet) { // find the common ones res = getIntersectionFor(res, newSet, demo); } } else { // handle instance where editable doesn't have anything editable res = null; break; } } } } else { // handle instance where editable doesn't have anything editable res = null; } } } return res; } /** * @param manager where we add our items to * @param editables the selected items * @param topLevelLayers the top-level layers that contain our elements * (it's these that get updated) * @param parentLayers the immediate parents of our items * @param theLayers the overall layers object * @param hideClipboardOperations */ static public void getDropdownListFor(final IMenuManager manager, final Editable[] editables, final Layer[] topLevelLayers, final HasEditables[] parentLayers, final Layers theLayers, final boolean hideClipboardOperations) { // sort out the top level layer, if we have a single one // Note: if we have more than one top level layer we don't populate the top // level layer - so the whole plot gets updated Layer theTopLayer = null; if (topLevelLayers != null) { if (topLevelLayers.length == 1) { theTopLayer = topLevelLayers[0]; } } // and now the edit-able bits if (editables.length > 0) { // first the parameters MenuManager subMenu = null; final PropertyDescriptor[] commonProps = getCommonPropertiesFor(editables); if (commonProps != null) { // hey, can we group these descriptors? final Map<String, SortedSet<PropertyDescriptor>> map = mapThese(commonProps); subMenu = createMenuFor(manager, editables, theLayers, theTopLayer, subMenu, map); } // special case: if only one item is selected, try adding any additional // methods if (editables.length == 1) { // any additional ones? final Editable theE = editables[0]; // ok, get the editor final EditorType info = theE.getInfo(); if (info != null) { final BeanInfo[] additional = info.getAdditionalBeanInfo(); // any there? if (additional != null) { // ok, loop through the beans for (int i = 0; i < additional.length; i++) { final BeanInfo thisB = additional[i]; if (thisB instanceof EditorType) { final EditorType editor = (EditorType) thisB; final Editable subject = (Editable) editor.getData(); // and the properties final PropertyDescriptor[] theseProps = thisB.getPropertyDescriptors(); // hey, can we group these descriptors? final Map<String, SortedSet<PropertyDescriptor>> map = mapThese(theseProps); // and wrap the object final Editable[] editables2 = new Editable[] { subject }; subMenu = createMenuFor(manager, editables2, theLayers, theTopLayer, subMenu, map); } } } } } // hmm, have a go at methods for this item // ok, try the methods final MethodDescriptor[] meths = getCommonMethodsFor(editables); if (meths != null) { for (int i = 0; i < meths.length; i++) { final Layer myTopLayer = theTopLayer; final MethodDescriptor thisMethD = meths[i]; if (thisMethD == null) { CorePlugin.logError(IStatus.ERROR, "Failed to create method, props may be wrongly named", null); } else { // create button for this method final Action doThisAction = new SubjectMethod(thisMethD.getDisplayName(), editables, thisMethD.getMethod(), myTopLayer, theLayers); // ok - add to the list. manager.add(doThisAction); } } } // hmm, now do the same for the undoable methods final SubjectAction[] actions = getUndoableActionsFor(editables); if (actions != null) { for (int i = 0; i < actions.length; i++) { final SubjectAction thisMethD = actions[i]; // create button for this method final IAction doThisAction = generateUndoableActionFor(thisMethD, editables, theLayers, theTopLayer); // ok - add to the list. manager.add(doThisAction); } } } // see if we're still looking at the parent element (we only show // clipboard // operations for item clicked on) if (!hideClipboardOperations) { final Clipboard theClipboard = CorePlugin.getDefault().getClipboard(); // hey, also see if we're going to do a cut/paste RightClickCutCopyAdaptor.getDropdownListFor(manager, editables, topLevelLayers, parentLayers, theLayers, theClipboard); // what about paste? Editable selectedItem = null; if (editables.length == 1) { selectedItem = editables[0]; } RightClickPasteAdaptor.getDropdownListFor(manager, selectedItem, topLevelLayers, parentLayers, theLayers, theClipboard); manager.add(new Separator()); } if (!_rightClickExtensionsChecked) { loadLoaderExtensions(); // ok, done _rightClickExtensionsChecked = true; } /* no params */ // hmm, do we have any right-click generators? if (_additionalRightClickItems != null) { for (final Iterator<RightClickContextItemGenerator> thisItem = _additionalRightClickItems .iterator(); thisItem.hasNext();) { final RightClickContextItemGenerator thisGen = thisItem.next(); try { thisGen.generate(manager, theLayers, topLevelLayers, editables); } catch (final Exception e) { // and log the error CorePlugin.logError(IStatus.ERROR, "failed whilst creating context menu", e); } } } } /** * have a look at the two arrays, and find the common elements (brute force) * * @param a first array * @param b second array * @return the common elements */ protected static MethodDescriptor[] getIntersectionFor(final MethodDescriptor[] a, final MethodDescriptor[] b, final MethodDescriptor[] demo) { final Vector<MethodDescriptor> res = new Vector<MethodDescriptor>(); if (a != null && b != null) { final int aLen = a.length; final int bLen = b.length; for (int cnta = 0; cnta < aLen; cnta++) { final MethodDescriptor thisP = a[cnta]; if (b != null) { for (int cntb = 0; cntb < bLen; cntb++) { final MethodDescriptor thatP = b[cntb]; if (thisP.getDisplayName().equals(thatP.getDisplayName())) { res.add(thisP); } } } } } return res.toArray(demo); } /** * have a look at the two arrays, and find the common elements (brute force) * * @param a first array * @param b second array * @return the common elements */ protected static PropertyDescriptor[] getIntersectionFor(final PropertyDescriptor[] a, final PropertyDescriptor[] b, final PropertyDescriptor[] demo) { final Vector<PropertyDescriptor> res = new Vector<PropertyDescriptor>(); final int aLen = a.length; final int bLen = b.length; for (int cnta = 0; cnta < aLen; cnta++) { final PropertyDescriptor thisP = a[cnta]; for (int cntb = 0; cntb < bLen; cntb++) { final PropertyDescriptor thatP = b[cntb]; if (thisP.equals(thatP)) { res.add(thisP); } } } return res.toArray(demo); } private static SubjectAction[] getIntersectionFor(final SubjectAction[] a, final SubjectAction[] b, final SubjectAction[] demo) { final Vector<SubjectAction> res = new Vector<SubjectAction>(); final int aLen = a.length; final int bLen = b.length; for (int cnta = 0; cnta < aLen; cnta++) { final SubjectAction thisP = a[cnta]; for (int cntb = 0; cntb < bLen; cntb++) { final SubjectAction thatP = b[cntb]; if (thisP.toString().equals(thatP.toString())) { res.add(thisP); } } } return res.toArray(demo); } /** have a look at the supplied editors, find which properties are common */ protected static SubjectAction[] getUndoableActionsFor(final Editable[] editables) { SubjectAction[] res = null; final SubjectAction[] demo = new SubjectAction[] {}; // right, get the first set of properties final int len = editables.length; // are there a reasonable number of them? if (len > 0 && len < MAX_ITEMS_FOR_UNDO) { final Editable first = editables[0]; final EditorType firstInfo = first.getInfo(); if (firstInfo != null) { res = firstInfo.getUndoableActions(); // only continue if there are any methods to compare against if (res != null) { // right, are there any more? if (len > 1) { // pass through the others, finding the common ground for (int cnt = 1; cnt < len; cnt++) { final Editable thisE = editables[cnt]; // get its props final EditorType thisEditor = thisE.getInfo(); // do we have an editor? if (thisEditor != null) { final SubjectAction[] newSet = thisEditor.getUndoableActions(); // find the common ones res = getIntersectionFor(res, newSet, demo); } } } } } } return res; } /** * see if any extra right click handlers are defined * */ private static void loadLoaderExtensions() { final IExtensionRegistry registry = Platform.getExtensionRegistry(); if (registry != null) { final IExtensionPoint point = registry.getExtensionPoint(PLUGIN_ID, EXTENSION_POINT_ID); final IExtension[] extensions = point.getExtensions(); for (int i = 0; i < extensions.length; i++) { final IExtension iExtension = extensions[i]; final IConfigurationElement[] confE = iExtension.getConfigurationElements(); for (int j = 0; j < confE.length; j++) { final IConfigurationElement iConfigurationElement = confE[j]; RightClickContextItemGenerator newInstance; try { newInstance = (RightClickContextItemGenerator) iConfigurationElement .createExecutableExtension("class"); addRightClickGenerator(newInstance); } catch (final CoreException e) { CorePlugin.logError(IStatus.ERROR, "Trouble whilst loading right-click handler extensions", e); } } } } } private static Map<String, SortedSet<PropertyDescriptor>> mapThese(final PropertyDescriptor[] theseProps) { final Map<String, SortedSet<PropertyDescriptor>> res = new TreeMap<String, SortedSet<PropertyDescriptor>>(); if (theseProps != null) { for (final PropertyDescriptor thisP : theseProps) { final String cat; if (thisP instanceof CategorisedPropertyDescriptor) { final CategorisedPropertyDescriptor catProp = (CategorisedPropertyDescriptor) thisP; cat = catProp.getCategory(); } else { cat = "Unknown"; } // do we have this list? SortedSet<PropertyDescriptor> thisL = res.get(cat); if (thisL == null) { final Comparator<PropertyDescriptor> comparator = new PropertyComparator(); thisL = new TreeSet<PropertyDescriptor>(comparator); res.put(cat, thisL); } thisL.add(thisP); } } return res; } /** * can we edit this property with a tick-box? * * @param thisP * @return yes/no */ @SuppressWarnings("rawtypes") static private boolean supportsBooleanEditor(final PropertyDescriptor thisP) { final boolean res; // get the prop type final Class thisType = thisP.getPropertyType(); final Class boolClass = Boolean.class; // is it boolean? if ((thisType == boolClass) || (thisType.equals(boolean.class))) { res = true; } else { res = false; } return res; } /** * can we edit this property with a drop-down list? * * @param thisP * @return yes/no */ @SuppressWarnings("rawtypes") static private boolean supportsListEditor(final PropertyDescriptor thisP) { boolean res = false; // find out the type of the editor final Method m = thisP.getReadMethod(); final Class cl = m.getReturnType(); // is there a custom editor for this type? final Class c = thisP.getPropertyEditorClass(); PropertyEditor pe = null; // try to create an editor for this class try { if (c != null) { pe = (PropertyEditor) c.newInstance(); } } catch (final Exception e) { MWC.Utilities.Errors.Trace.trace(e); } // did it work? if (pe == null) { // try to find an editor for this through our manager pe = PropertyEditorManager.findEditor(cl); } // have we managed to create an editor? if (pe != null) { // retrieve the tags final String[] tags = pe.getTags(); // are there any tags for this class? if (tags != null) { res = true; } } return res; } }
epl-1.0
kgibm/open-liberty
dev/com.ibm.websphere.security.wim.base/src/com/ibm/websphere/security/wim/ras/WIMMessageKey.java
57182
/******************************************************************************* * Copyright (c) 2012, 2021 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 com.ibm.websphere.security.wim.ras; /** * This file contains the virtual member manager message keys. */ public interface WIMMessageKey { /** * property 'prop_name' is not defined. */ String PROPERTY_NOT_DEFINED = "PROPERTY_NOT_DEFINED"; /** * The entity 'unique_id' was not found. */ String ENTITY_NOT_FOUND = "ENTITY_NOT_FOUND"; /** * The parent of the entity to be created 'uniqueName' was not found. */ String PARENT_NOT_FOUND = "PARENT_NOT_FOUND"; /** * The operation 'action_type' is not supported for entity type * 'entity_type'. */ String OPERATION_NOT_SUPPORTED = "OPERATION_NOT_SUPPORTED"; /** * Mandatory property 'property_name' is missing. */ String MISSING_MANDATORY_PROPERTY = "MISSING_MANDATORY_PROPERTY"; /** * SerachControl is missing for the search call. */ String MISSING_SEARCH_CONTROL = "MISSING_SEARCH_CONTROL"; /** * cookie is missing from the PageControl data object. */ String MISSING_COOKIE = "MISSING_COOKIE"; /** * cookie specified in the PageControl data object is invalid. */ String INVALID_COOKIE = "INVALID_COOKIE"; /** * The number of search results 'result_size' exceeds the maximum search * result limit 'search_limit'. */ String EXCEED_MAX_TOTAL_SEARCH_LIMIT = "EXCEED_MAX_TOTAL_SEARCH_LIMIT"; /** * The syntax of the member DN 'unique_name'is invalid. Check if the special * characters are escaped. */ String INVALID_UNIQUE_NAME_SYNTAX = "INVALID_UNIQUE_NAME_SYNTAX"; /** * The syntax of the LDAP DN 'dn'is invalid. Check if the special * characters are escaped. */ String INVALID_DN_SYNTAX = "INVALID_DN_SYNTAX"; /** * The initialize property 'property_name'is invalid. */ String INVALID_INIT_PROPERTY = "INVALID_INIT_PROPERTY"; /** * The entity 'unique_name'has descendants. */ String ENTITY_HAS_DESCENDENTS = "ENTITY_HAS_DESCENDENTS"; /** * The following naming exception occured during processing: 'Root NamingException'. */ String NAMING_EXCEPTION = "NAMING_EXCEPTION"; /** * The following system exception occured during processing: 'root_exception'. */ String SYSTEM_EXCEPTION = "SYSTEM_EXCEPTION"; /** * The following SQL Exception occured during processing: 'Root SQLException'. */ String SQL_EXCEPTION = "SQL_EXCEPTION"; /** * The following generic Exception occured during processing: 'Root Exception'. */ String GENERIC = "GENERIC"; /** * The data type of Property 'property_name' is invalid. */ String INVALID_PROPERTY_DATA_TYPE = "INVALID_PROPERTY_DATA_TYPE"; /** * The sort keys are missing from the SortControl data object. */ String MISSING_SORT_KEY = "MISSING_SORT_KEY"; /** * The identifier is invalid */ String INVALID_IDENTIFIER = "INVALID_IDENTIFIER"; /** * The identifier of a entity is required */ String ENTITY_IDENTIFIER_NOT_SPECIFIED = "ENTITY_IDENTIFIER_NOT_SPECIFIED"; /** * specify multiple entities in one call is not allowed */ String ACTION_MULTIPLE_ENTITIES_SPECIFIED = "ACTION_MULTIPLE_ENTITIES_SPECIFIED"; /** * The class or interface ''{0}'' defined in configuration property ''{0}'' is not found. */ String CLASS_OR_INTERFACE_NOT_FOUND = "CLASS_OR_INTERFACE_NOT_FOUND"; /** * The virtual member manager model package with name space URI ''http://www.ibm.com/websphere/wim'' is not found in XSD file ''{0}'' defined in configuration property * ''xsdFileName''. */ String WIM_MODEL_PACKAGE_NOT_FOUND_IN_XSD = "WIM_MODEL_PACKAGE_NOT_FOUND_IN_XSD"; /** * The package name ''{0}'' defined in configuration property ''{0}'' is invalid. */ String INVALID_PACKAGE_NAME = "INVALID_PACKAGE_NAME"; /** * virtual member manager configuration XML file ''{0}'' is not found. */ String WIM_CONFIG_XML_FILE_NOT_FOUND = "WIM_CONFIG_XML_FILE_NOT_FOUND"; /** * Ticket for the asynchronous operation is invalid: {0} */ String INVALID_TICKET = "INVALID_TICKET"; /** * The method is not implemented. */ String METHOD_NOT_IMPLEMENTED = "METHOD_NOT_IMPLEMENTED"; /** * The required identifiers are missing */ String REQUIRED_IDENTIFIERS_MISSING = "REQUIRED_IDENTIFIERS_MISSING"; /** * The specified entity type is not supported. */ String ENTITY_TYPE_NOT_SUPPORTED = "ENTITY_TYPE_NOT_SUPPORTED"; /** * The specified attribute type is not supported. */ String ATTRIBUTE_NOT_SUPPORTED = "ATTRIBUTE_NOT_SUPPORTED"; /** * A required control object is missing from the datagraph. */ String MISSING_REQUIRED_CONTROL = "MISSING_REQUIRED_CONTROL"; /** * A required property in a control is not set. */ String MISSING_CONTROL_ATTRIBUTE = "MISSING_CONTROL_ATTRIBUTE"; /** * Login information for a user is not set. */ String LOGIN_INFORMATION_MISSING = "LOGIN_INFORMATION_MISSING"; /** * A search expression is not correctly formatted. */ String MALFORMED_SEARCH_EXPRESSION = "MALFORMED_SEARCH_EXPRESSION"; /** * An RDN style format is required but not set for the identifiers uniqueName */ String RDN_STYLE_FORMAT_REQUIRED = "RDN_STYLE_FORMAT_REQUIRED"; /** * An attribute for an 'entityType' in the wimconfig.xml is not set. */ String ENTITY_TYPE_CONFIGURATION_ATTRIBUTE_MISSING = "ENTITY_TYPE_CONFIGURATION_ATTRIBUTE_MISSING"; /** * The realm information in the datagraph does not match the realm of the repository. */ String INCORRECT_REALM = "INCORRECT_REALM"; /** * The realm name passed in {0} is invalid. */ String INVALID_REALM_NAME = "INVALID_REALM_NAME"; /** * The '{0}' base entry name specified in '{1}' is not valid. */ String INVALID_BASE_ENTRY_NAME = "INVALID_BASE_ENTRY_NAME"; /** * No repository configuration found for the base entry '{0}'. */ String REPOSITORY_NOT_FOUND_FOR_BASE_ENTRY = "REPOSITORY_NOT_FOUND_FOR_BASE_ENTRY"; /** * No repository configuration found for the realm '{0}'. */ String REPOSITORY_NOT_FOUND_FOR_REALM = "REPOSITORY_NOT_FOUND_FOR_REALM"; /** * Configuration file '{0}' is invalid. Root cause is '{1}'. */ String INVALID_WIM_CONFIG_XML_FILE = "INVALID_WIM_CONFIG_XML_FILE"; /** * Extension XML file ''{0}'' is invalid. Root cause is ''{1}''. */ String INVALID_WIM_EXTENSION_XML_FILE = "INVALID_WIM_EXTENSION_XML_FILE"; /** * The property "{0}" is not defined for entity type "{1}". */ String PROPERTY_NOT_DEFINED_FOR_ENTITY = "PROPERTY_NOT_DEFINED_FOR_ENTITY"; /** * The "expression" property is missing from the SearchControl data object. */ String MISSING_SEARCH_EXPRESSION = "MISSING_SEARCH_EXPRESSION"; /** * The specified entity is not in the scope of the realm. */ String ENTITY_NOT_IN_REALM_SCOPE = "ENTITY_NOT_IN_REALM_SCOPE"; /** * The default parent cannot be found for a particular entity type */ String DEFAULT_PARENT_NOT_FOUND = "DEFAULT_PARENT_NOT_FOUND"; /** * The operation "method_name" is not supported in repository "repos_id". */ String OPERATION_NOT_SUPPORTED_IN_REPOSITORY = "OPERATION_NOT_SUPPORTED_IN_REPOSITORY"; /** * Asynchronous operation is not supported by the repository, repos_id. */ String ASYNC_OPERATION_NOT_SUPPORTED_BY_REPOSITORY = "ASYNC_OPERATION_NOT_SUPPORTED_BY_REPOSITORY"; /** * The entity 'unique_name' already exist. */ String ENTITY_ALREADY_EXIST = "ENTITY_ALREADY_EXIST"; /** * Failed to create entity: 'reason' */ String ENTITY_CREATE_FAILED = "ENTITY_CREATE_FAILED"; /** * Failed to update entity 'uniqueName' : 'reason' */ String ENTITY_UPDATE_FAILED = "ENTITY_UPDATE_FAILED"; /** * Failed to delete entity 'uniqueName' : 'reason' */ String ENTITY_DELETE_FAILED = "ENTITY_DELETE_FAILED"; /** * Failed to get entity 'uniqueName' : 'reason' */ String ENTITY_GET_FAILED = "ENTITY_GET_FAILED"; /** * Failed to search entity : 'reason' */ String ENTITY_SEARCH_FAILED = "ENTITY_SEARCH_FAILED"; /** * Failed to read file 'fileName': 'reason' */ String ERROR_READING_FILE = "ERROR_READING_FILE"; /** * Failed to write to file 'fileName': 'reason' */ String ERROR_WRITING_FILE = "ERROR_WRITING_FILE"; /** * The directory 'dir_name' is not found. */ String DIRECTORY_NOT_FOUND = "DIRECTORY_NOT_FOUND"; /** * The repository adapter 'repositoryId' could not be initialized: 'reason'. */ String REPOSITORY_INITIALIZATION_FAILED = "REPOSITORY_INITIALIZATION_FAILED"; /** * The dataGraph could not be loaded: 'reason' */ String LOAD_DATAGRAPH_FAILED = "LOAD_DATAGRAPH_FAILED"; /** * The password match failed. */ String PASSWORD_MATCH_FAILED = "PASSWORD_MATCH_FAILED"; /** * The password check failed for principal name "{0}". Root cause is: "{1}". */ String PASSWORD_CHECKED_FAILED = "PASSWORD_CHECKED_FAILED"; /** * The password match failed for principal name {0}. */ String PASSWORD_MATCH_FAILED_FOR_PRINCIPALNAME = "PASSWORD_MATCH_FAILED_FOR_PRINCIPALNAME"; /** * Authentication is not supported by repository 'reposId'. */ String AUTHENTICATE_NOT_SUPPORTED = "AUTHENTICATE_NOT_SUPPORTED"; /** * Authentication with certificate is not supported by repository 'reposId'. */ String AUTHENTICATION_WITH_CERT_NOT_SUPPORTED = "AUTHENTICATION_WITH_CERT_NOT_SUPPORTED"; /** * The password is missing or empty. */ String MISSING_OR_EMPTY_PASSWORD = "MISSING_OR_EMPTY_PASSWORD"; /** * The search expression does not follow the supported search expression grammar */ String SEARCH_EXPRESSION_ERROR = "SEARCH_EXPRESSION_ERROR"; /** * Cannot search by a composite property */ String SEARCH_BY_COMPOSITE_PROPERTY_NOT_SUPPORTED = "SEARCH_BY_COMPOSITE_PROPERTY_NOT_SUPPORTED"; /** * Cannot search by a property type is "Object" */ String SEARCH_BY_LOB_PROPERTY_NOT_SUPPORTED = "SEARCH_BY_LOB_PROPERTY_NOT_SUPPORTED"; /** * The data type of the property is invalid. */ String PROPERTY_INVALID_DATA_TYPE = "PROPERTY_INVALID_DATA_TYPE"; /** * The specified property definition "{0}" with value "{1}" for property "{2}" is invalid. * */ String INVALID_PROPERTY_DEFINITION = "INVALID_PROPERTY_DEFINITION"; /** * The prefix "prefix" of name space "name_space" is duplicated with existing prefix. */ String DUPLICATE_NS_PREFIX = "DUPLICATE_NS_PREFIX"; /** * The name space URI "name_space" is duplicate. */ String DUPLICATE_NS_URI = "DUPLICATE_NS_URI"; /** * The name space URI can not be null or empty. */ String INVALID_NS_URI = "INVALID_NS_URI"; /** * The value of the property is invalid. */ String INVALID_PROPERTY_VALUE = "INVALID_PROPERTY_VALUE"; /** * */ String EXT_ID_HAS_MULTIPLE_VALUES = "EXT_ID_HAS_MULTIPLE_VALUES"; /** * The LDAP attribute used as an external identifier 'extid_attribute' * contained a null value for entity 'entity_dn'. */ String EXT_ID_VALUE_IS_NULL = "EXT_ID_VALUE_IS_NULL"; /** * Duplicate entries are found from the external identifier 'extId' in repository 'repos_id'. */ String DUPLICATE_EXTTERNAL_ID = "DUPLICATE_EXTTERNAL_ID"; /** * External name '{0}' is specified, but the external name control is not specified. */ String EXTERNAL_NAME_CONTROL_NOT_FOUND = "EXTERNAL_NAME_CONTROL_NOT_FOUND"; /** * Cannot construct uniqueName when create an entity */ String CAN_NOT_CONSTRUCT_UNIQUE_NAME = "CAN_NOT_CONSTRUCT_UNIQUE_NAME"; /** * Invalid value of property 'level', {0}, specified in {1}. */ String INVALID_LEVEL_IN_CONTROL = "INVALID_LEVEL_IN_CONTROL"; /** * The specified entity 'name' is not a group. */ String ENTITY_IS_NOT_A_GROUP = "ENTITY_IS_NOT_A_GROUP"; /** * virtual member manager Plug-in Manager being initialized. */ public final static String PLUGIN_MANAGER_INITIALIZED = "PLUGIN_MANAGER_INITIALIZED"; /** * virtual member manager Plug-in Manager is successfully loaded. */ public final static String PLUGIN_MANAGER_SUCCESSFULLY_LOADED = "PLUGIN_MANAGER_SUCCESSFULLY_LOADED"; /** * virtual member manager Plug-in Manager failure occurred while loading ''{0}''. Please check configuration file. */ public final static String PLUGIN_MANAGER_SUBSCRIBER_LOAD_FAILURE = "PLUGIN_MANAGER_SUBSCRIBER_LOAD_FAILURE"; /** * virtual member manager Plug-in Manager successfully loaded plug-in ''{0}''. */ public final static String PLUGIN_MANAGER_SUBSCRIBER_LOAD_SUCCESS = "PLUGIN_MANAGER_SUBSCRIBER_LOAD_SUCCESS"; /** * Classname: subscriber_classname not found for Topic-Subscriber subscriber_name */ public final static String PLUGIN_MANAGER_SUBSCRIBER_NOT_FOUND_ERROR = "PLUGIN_MANAGER_SUBSCRIBER_NOT_FOUND_ERROR"; /** * Duplicate definitions of InlineExit inlineexit_name defined. */ public final static String PLUGIN_MANAGER_MULTI_INLINE_DUPLICATE_NAME_ERROR = "PLUGIN_MANAGER_MULTI_INLINE_DUPLICATE_NAME_ERROR"; /** * Duplicate definitions of Topic-Emitters topicemitter_name defined. */ public final static String PLUGIN_MANAGER_MULTI_TOPIC_EMITTER_DUPLICATE_NAME_ERROR = "PLUGIN_MANAGER_MULTI_TOPIC_EMITTER_DUPLICATE_NAME_ERROR"; /** * exitpoint_name point of Topic-Emitter topicemitter_name has a noncompliant Topic-Subscriber topicsubscriber_name of SubscriberType subscribertype_name stored in the the * wrong subscriber list. */ public final static String PLUGIN_MANAGER_INVALID_SUBSCRIBER_TYPE_ERROR = "PLUGIN_MANAGER_INVALID_SUBSCRIBER_TYPE_ERROR"; /** * exitpoint_name point of Topic-Emitter topicemitter_name has an invalid topicsubscriber_name subscriber reference of subscribertype_name. */ public final static String PLUGIN_MANAGER_INVALID_SUBSCRIBER_REF_ERROR = "PLUGIN_MANAGER_INVALID_SUBSCRIBER_REF_ERROR"; /** * Topic-Emitter topicemitter_name is missing in the configuration file. */ public final static String PLUGIN_MANAGER_TOPIC_EMITTER_MISSING_ERROR = "PLUGIN_MANAGER_TOPIC_EMITTER_MISSING_ERROR"; /** * Critical exception has occurred inside a subscriber of plugin: {0} */ public final static String SUBSCRIBER_CRITICAL_EXCEPTION = "SUBSCRIBER_CRITICAL_EXCEPTION"; /** * Starting bootstrap sequence for the dynamic reload manager. */ public final static String DYNAMIC_RELOAD_START_BOOTSTRAP = "DYNAMIC_RELOAD_START_BOOTSTRAP"; /** * Waiting for notification that the server has finished starting... */ public final static String DYNAMIC_RELOAD_WAIT_NOTIF_SERVER_STARTED = "DYNAMIC_RELOAD_WAIT_NOTIF_SERVER_STARTED"; /** * Received notification that the server has finished starting */ public final static String DYNAMIC_RELOAD_RECEIVED_NOTIF_SERVER_STARTED = "DYNAMIC_RELOAD_RECEIVED_NOTIF_SERVER_STARTED"; /** * Initialization of the dynamic reload manager completed successfully. */ public final static String DYNAMIC_RELOAD_INIT_SUCCESS = "DYNAMIC_RELOAD_INIT_SUCCESS"; /** * Initialization of the dynamic reload manager failed. */ public final static String DYNAMIC_RELOAD_INIT_FAILURE = "DYNAMIC_RELOAD_INIT_FAILURE"; /** * An error occured while broadcasting an event from the deployment manager to managed nodes. */ public final static String DYNAMIC_RELOAD_EVENT_BROADCAST_ERROR = "DYNAMIC_RELOAD_EVENT_BROADCAST_ERROR"; /** * Managed node {0} is either unavailable or failed to process event (1). */ public final static String DYNAMIC_RELOAD_MANAGED_NODE_UNAVAILABLE = "DYNAMIC_RELOAD_MANAGED_NODE_UNAVAILABLE"; /** * Broadcasting event {0} to managed nodes. */ public final static String DYNAMIC_RELOAD_DMGR_BROADCAST_EVENT = "DYNAMIC_RELOAD_DMGR_BROADCAST_EVENT"; /** * Received event {0} from the deployment manager. */ public final static String DYNAMIC_RELOAD_MANAGED_NODE_RECEIVED_EVENT = "DYNAMIC_RELOAD_MANAGED_NODE_RECEIVED_EVENT"; /** * All updates must be performed at the deployment mananger and not at a managed node. */ public final static String DYNAMIC_RELOAD_INVALID_UPDATE_AT_MANAGED_NODE = "DYNAMIC_RELOAD_INVALID_UPDATE_AT_MANAGED_NODE"; /** * An error occurred while broadcasting an event from the admin agent to base profile. */ public final static String DYNAMIC_RELOAD_EVENT_BROADCAST_ERROR_TO_PROFILE = "DYNAMIC_RELOAD_EVENT_BROADCAST_ERROR_TO_PROFILE"; /** * Base profile {0} is either unavailable or failed to process event {1}. */ public final static String DYNAMIC_RELOAD_REGISTERED_PROFILE_UNAVAILABLE = "DYNAMIC_RELOAD_REGISTERED_PROFILE_UNAVAILABLE"; /** * Broadcasting event {0} to base profile {1}. */ public final static String DYNAMIC_RELOAD_AA_BROADCAST_EVENT_TO_PROFILE = "DYNAMIC_RELOAD_AA_BROADCAST_EVENT_TO_PROFILE"; /** * Received event {0} from the admin agent. */ public final static String DYNAMIC_RELOAD_REGISTERED_PROFILE_RECEIVED_EVENT = "DYNAMIC_RELOAD_REGISTERED_PROFILE_RECEIVED_EVENT"; /** * Requested update can not be performed at the admin agent. */ public final static String DYNAMIC_RELOAD_INVALID_UPDATE_AT_ADMIN_AGENT = "DYNAMIC_RELOAD_INVALID_UPDATE_AT_ADMIN_AGENT"; /** * Initialization of the MBean, {0}, completed successfully */ public final static String MBEAN_INIT_SUCCESS = "MBEAN_INIT_SUCCESS"; /** * Deactivation of the MBean, {0}, completed successfully */ public final static String MBEAN_DEACTIVATION_SUCCESS = "MBEAN_DEACTIVATION_SUCCESS"; /** * Initialization of the MBean, {0}, failed: {1} */ public final static String MBEAN_INIT_FAILURE = "MBEAN_INIT_FAILURE"; /** * Failed to get or call the MBean, {0}: {1} */ public final static String MBEAN_GET_CALL_FAILURE = "MBEAN_GET_CALL_FAILURE"; public static final String INVALID_BASE_ENTRY_DEFINITION = "INVALID_BASE_ENTRY_DEFINITION"; static final String INVALID_REALM_DEFINITION = "INVALID_REALM_DEFINITION"; static final String INVALID_PARTICIPATING_BASE_ENTRY_DEFINITION = "INVALID_PARTICIPATING_BASE_ENTRY_DEFINITION"; static final String INVALID_UR_ATTRIBUTE_MAPPING_DEFINITION = "INVALID_UR_ATTRIBUTE_MAPPING_DEFINITION"; static final String MISSING_BASE_ENTRY_IN_REALM = "MISSING_BASE_ENTRY_IN_REALM"; static final String TBS_CERTIFICATE_UNSUPPORTED = "TBS_CERTIFICATE_UNSUPPORTED"; static final String UNKNOWN_CERTIFICATE_ATTRIBUTE = "UNKNOWN_CERTIFICATE_ATTRIBUTE"; /** * The repository Id {0} specified is invalid. */ String INVALID_REPOSITORY_ID = "INVALID_REPOSITORY_ID"; /** * The principal name is missing or empty. */ String MISSING_OR_EMPTY_PRINCIPAL_NAME = "MISSING_OR_EMPTY_PRINCIPAL_NAME"; /** * No principal is found from the given principal name {0}. */ String PRINCIPAL_NOT_FOUND = "PRINCIPAL_NOT_FOUND"; /** * Multiple principals are found from the given principal name {0}. */ String MULTIPLE_PRINCIPALS_FOUND = "MULTIPLE_PRINCIPALS_FOUND"; /** * A search pattern 'pattern' is not valid. */ String INVALID_SEARCH_PATTERN = "INVALID_SEARCH_PATTERN"; /** * The database type 'dbType' is not supported. */ String DB_TYPE_NOT_SUPPORTED = "DB_TYPE_NOT_SUPPORTED"; /** * The entity type 'entity_type' in name space URI 'nsURI' is already defined. */ String ENTITY_TYPE_ALREADY_DEFINED = "ENTITY_TYPE_ALREADY_DEFINED"; /** * The property type 'propType' is already defined for entity type 'entityType." */ String PROPERTY_TYPE_ALREADY_DEFINED = "PROPERTY_TYPE_ALREADY_DEFINED"; /** * The LDAP entry 'dn' for the entity 'unique_name' is not found: */ String LDAP_ENTRY_NOT_FOUND = "LDAP_ENTRY_NOT_FOUND"; /** * The specified search expression 'search_expr" is invalid. */ String INVALID_SEARCH_EXPRESSION = "INVALID_SEARCH_EXPRESSION"; /** * Duplicate entity type 'entity_type' is defined in virtual member manager configuration XML file. */ String DUPLICATE_ENTITY_TYPE = "DUPLICATE_ENTITY_TYPE"; /** * The initial context pool size should be less the maximum context pool size. */ String INIT_POOL_SIZE_TOO_BIG = "INIT_POOL_SIZE_TOO_BIG"; /** * The preferred context pool size should be less the maximum context pool size. */ String PREF_POOL_SIZE_TOO_BIG = "PREF_POOL_SIZE_TOO_BIG"; /** * WebSphere variable, 'variable name', was not resolved. */ String WAS_VARIABLE_NOT_RESOLVED = "WAS_VARIABLE_NOT_RESOLVED"; /** * The reference type 'ref_type' is not found in the schema. */ String REFERENCE_TYPE_NOT_FOUND = "REFERENCE_TYPE_NOT_FOUND"; /** * Can not create multiple entity types in one call. */ String CAN_NOT_CREATE_MULTIPLE_ENTITY_TYPES = "CAN_NOT_CREATE_MULTIPLE_ENTITY_TYPES"; /** * Can not create multiple property types in one call. */ String CAN_NOT_CREATE_MULTIPLE_PROPERTY_TYPES = "CAN_NOT_CREATE_MULTIPLE_PROPERTY_TYPES"; /** * Can not create new entity type and new property type in one API call. */ String CAN_NOT_CREATE_BOTH_ENTITY_AND_PROPERTY = "CAN_NOT_CREATE_BOTH_ENTITY_AND_PROPERTY"; /** * The entity has two parameters that need to match but do not. */ String PARAMS_DO_NOT_MATCH = "PARAMS_DO_NOT_MATCH"; /** * No searchable attributes were specified in a search request. */ String SEARCH_ATTR_NOT_SPECIFIED = "SEARCH_ATTR_NOT_SPECIFIED"; /** * Too many attributes were specified in a search request. */ String SEARCH_PARAMETERS_OVER_SPECIFIED = "SEARCH_PARAMETERS_OVER_SPECIFIED"; /** * The entity with uniqueName '{0}' is not of type '{1}' */ String INCORRECT_ENTITY_TYPE = "INCORRECT_ENTITY_TYPE"; /** * The specified uniqueId property '{0}' of the parent is not valid. */ String INVALID_PARENT_UNIQUE_ID = "INVALID_PARENT_UNIQUE_ID"; /** * The format of value of the property '{0}' is invalid. */ String INVALID_PROPERTY_VALUE_FORMAT = "INVALID_PROPERTY_VALUE_FORMAT"; /** * The value '{0}' of 'countLimit' parameter in the SearchControl DataObject is greater than the value '{1}' of the 'searchLimit' parameter. */ String CANNOT_SPECIFY_COUNT_LIMIT = "CANNOT_SPECIFY_COUNT_LIMIT"; /** * The schema package with name space URI '{0}' is not found. */ String SCHEMA_PACKAGE_NOT_FOUND = "SCHEMA_PACKAGE_NOT_FOUND"; /** * Cannot create or update operational property '{0}'. */ String CANNOT_SPECIFIED_OPERATIONAL_PROPERTY_VALUE = "CANNOT_SPECIFIED_OPERATIONAL_PROPERTY_VALUE"; /** * The {0} repository ID is reserved. */ String REPOSITORY_ID_RESERVED = "REPOSITORY_ID_RESERVED"; /** * The {0} repository ID already exists. */ String REPOSITORY_ID_ALREADY_EXISTS = "REPOSITORY_ID_ALREADY_EXISTS"; /** * The {0} realm already exists. */ String REALM_ALREADY_EXISTS = "REALM_ALREADY_EXISTS"; /** * Supported entity type {0} already exists. */ String SUPPORTED_ENTITY_TYPE_ALREADY_EXISTS = "SUPPORTED_ENTITY_TYPE_ALREADY_EXISTS"; /** * RDN attribute {0} already exists. */ String RDN_ATTR_ALREADY_EXISTS = "RDN_ATTR_ALREADY_EXISTS"; /** * LDAP server with {0} primary host already exists. */ String PRIMARY_HOST_ALREADY_EXISTS = "PRIMARY_HOST_ALREADY_EXISTS"; /** * LDAP server with {0} backup host and {1} port already exists. */ String BACKUP_HOST_PORT_ALREADY_EXISTS = "BACKUP_HOST_PORT_ALREADY_EXISTS"; /** * LDAP entity type {0} already exists. */ String LDAP_ENTITY_TYPE_ALREADY_EXISTS = "LDAP_ENTITY_TYPE_ALREADY_EXISTS"; /** * LDAP dynamic group member attribute {0} already exists. */ String DYMANIC_GROUP_MEMBER_ATTR_ALREADY_EXISTS = "DYMANIC_GROUP_MEMBER_ATTR_ALREADY_EXISTS"; /** * LDAP group member attribute {0} already exists. */ String GROUP_MEMBER_ATTR_ALREADY_EXISTS = "GROUP_MEMBER_ATTR_ALREADY_EXISTS"; /** * LDAP group member attribute mapping for {0} already exists. */ String GROUP_MEMBER_ATTR_FOR_OBJECTCLASS_EXISTS = "GROUP_MEMBER_ATTR_FOR_OBJECTCLASS_EXISTS"; /** * LDAP server with {0} primary host is not found. */ String INVALID_PRIMARY_HOST = "INVALID_PRIMARY_HOST"; /** * LDAP server with {0} backup host and {1} port is not found. */ String INVALID_BACKUP_HOST_PORT = "INVALID_BACKUP_HOST_PORT"; /** * Supported entity type {0} is not found. */ String INVALID_SUPPORTED_ENTITY_TYPE = "INVALID_SUPPORTED_ENTITY_TYPE"; String INVALID_SUPPORTED_ENTITY_TYPE_DEFINITION = "INVALID_SUPPORTED_ENTITY_TYPE_DEFINITION"; /** * LDAP dynamic group member attribute {0} is not found. */ String INVALID_DYNAMIC_GROUP_MEMBER_ATTR = "INVALID_DYNAMIC_GROUP_MEMBER_ATTR"; /** * LDAP group member attribute {0} is not found. */ String INVALID_GROUP_MEMBER_ATTR = "INVALID_GROUP_MEMBER_ATTR"; /** * LDAP RDN Attribute {0} is not found. */ String INVALID_RDN_ATTR = "INVALID_RDN_ATTR"; /** * LDAP entity type {0} is not found. */ String INVALID_LDAP_ENTITY_TYPE = "INVALID_LDAP_ENTITY_TYPE"; /** * Login properties are not valid: {0} **/ String INVALID_LOGIN_PROPERTIES = "INVALID_LOGIN_PROPERTIES"; /** * Search filter is not valid: {0} **/ String INVALID_SEARCH_FILTER = "INVALID_SEARCH_FILTER"; /** * Search base is not valid: {0} **/ String INVALID_SEARCH_BASE = "INVALID_SEARCH_BASE"; /** * Search base is not valid: {0} **/ String NON_EXISTING_SEARCH_BASE = "NON_EXISTING_SEARCH_BASE"; /** * Object class(es) is not valid: {0} **/ String INVALID_OBJECT_CLASSES = "INVALID_OBJECT_CLASSES"; /** * Distinguished name [{0}] for base entry in the repository is not valid **/ String INVALID_BASE_ENTRY_NAME_IN_REPOSITORY = "INVALID_BASE_ENTRY_NAME_IN_REPOSITORY"; /** * The value for supportChangeLog parameter is invalid */ String INVALID_SUPPORT_CHANGE_LOG = "INVALID_SUPPORT_CHANGE_LOG"; /** * One or more of the required parameters are not specified. Required parameters are {0}. */ String REQUIRED_PARAMETERS_NOT_SPECIFIED = "REQUIRED_PARAMETERS_NOT_SPECIFIED"; /** * The {0} nonprofile repository, cannot be updated. */ String CONFIG_NON_PROFILE_REPO_CANNOT_BE_UPDATED = "CONFIG_NON_PROFILE_REPO_CANNOT_BE_UPDATED"; /** * A duplicate value is not allowed for parameter '{0}' */ String CONFIG_GROUP_SCOPE_CANNOT_BE_SET = "CONFIG_GROUP_SCOPE_CANNOT_BE_SET"; /** * The parameter value '{0}' is not correct for the parameter '{1}'. * The parameter must have one of the following values: '{2}'. */ String CONFIG_VALUE_NOT_VALID = "CONFIG_VALUE_NOT_VALID"; /** * Search 'principalName' with other properties is not supported. */ String CANNOT_SEARCH_PRINCIPAL_NAME_WITH_OTHER_PROPS = "CANNOT_SEARCH_PRINCIPAL_NAME_WITH_OTHER_PROPS"; /** * Updating 'propertyName' is not supported when ChangeSummary is on. */ String UPDATE_PROPERTY_NOT_SUPPORTED_WITH_CHANGESUMMARY = "UPDATE_PROPERTY_NOT_SUPPORTED_WITH_CHANGESUMMARY"; /** * Incorrect count limit '{0}' is specified in the SearchControl data object. */ String INCORRECT_COUNT_LIMIT = "INCORRECT_COUNT_LIMIT"; /** * The syntax of the certificate filter '{0}' is invalid. The correct syntax is: LDAP attribute=${Client certificate attribute} (for example, uid=${SubjectCN}). */ String INVALID_CERTIFICATE_FILTER = "INVALID_CERTIFICATE_FILTER"; /** * The DN field '{0}' is unknown. */ String UNKNOWN_DN_FIELD = "UNKNOWN_DN_FIELD"; /** * Async adapter can not be used in conjunction with Property Extension database or other synchronous/asynchronous adapters. */ String ASYNC_CALL_WITH_MULTIPLE_REPOSITORIES_NOT_SUPPORTED = "ASYNC_CALL_WITH_MULTIPLE_REPOSITORIES_NOT_SUPPORTED"; /** * Invalid value specified for parameter '{0}' */ String INVALID_PARAMETER_VALUE = "INVALID_PARAMETER_VALUE"; /** * Invalid value specified for parameter '{0}'. Warning */ String INVALID_PARAM_VALUE_WARN = "INVALID_PARAM_VALUE_WARN"; /** * The repository '{0}' is a read-only. It does not support a "write" operation. */ String CANNOT_WRITE_TO_READ_ONLY_REPOSITORY = "CANNOT_WRITE_TO_READ_ONLY_REPOSITORY"; /** * The initialization property '{0}' is missing from configuration. */ String MISSING_INI_PROPERTY = "MISSING_INI_PROPERTY"; /** * Could not register as WebSphere Application Server adminService notification listener. */ String ADMIN_SERVICE_REGISTRATION_FAILED = "ADMIN_SERVICE_REGISTRATION_FAILED"; /** * Can not create or update property '{0}' in repository '{1}'. */ String CAN_NOT_UPDATE_PROPERTY_IN_REPOSITORY = "CAN_NOT_UPDATE_PROPERTY_IN_REPOSITORY"; /** * Account {0} is stored in the file registry in temporary workspace. You must use the "$AdminConfig save" command to save it in the main repository. **/ String FILE_REGISTRY_ACCOUNT_ADDED = "FILE_REGISTRY_ACCOUNT_ADDED"; /** * The password is changed for {0} in the file registry in temporary workspace. You must use the "$AdminConfig save" command to save it in the main repository. **/ String FILE_REGISTRY_ACCOUNT_PASSWORD_CHANGED = "FILE_REGISTRY_ACCOUNT_PASSWORD_CHANGED"; /** * The realm {0} cannot be deleted because it is set as the default realm. **/ String CANNOT_DELETE_DEFAULT_REALM = "CANNOT_DELETE_DEFAULT_REALM"; /** * The realm {0} cannot be deleted because it is the only realm defined. There must always be at least 1 realm defined. **/ String CANNOT_DELETE_ONLY_REALM = "CANNOT_DELETE_ONLY_REALM"; /** * The base entry {0} could not be added to the realm {1} because a repository must * reference the base entry before it is added. **/ String BASE_ENTRY_CANNOT_BE_ADDED_TO_REALM = "BASE_ENTRY_CANNOT_BE_ADDED_TO_REALM"; /** * The base entry {0} could not be added to the realm {1} because * the base entry is already defined in a realm. **/ String DUPLICATE_BASE_ENTRY_IN_REALM = "DUPLICATE_BASE_ENTRY_IN_REALM"; /** * The base entry {0} could not be deleted because it is the last base entry in the realm {1} **/ String CANNOT_DELETE_ONLY_BASE_ENTRY_IN_REALM = "CANNOT_DELETE_ONLY_BASE_ENTRY_IN_REALM"; /** * The base entry {0} could not be added to the repository {1} because it is already defined in this or other repository. **/ String BASE_ENTRY_ALREADY_IN_REPOSITORY = "BASE_ENTRY_ALREADY_IN_REPOSITORY"; /** * The base entry {0} could not be deleted from the repository {1} because it * is the last base entry defined in the repository. **/ String CANNOT_DELETE_ONLY_BASE_ENTRY_IN_REPOSITORY = "CANNOT_DELETE_ONLY_BASE_ENTRY_IN_REPOSITORY"; /** * The base entry {0} could not be deleted from the repository because it is referenced by a realm. **/ String BASE_ENTRY_STILL_REFERENCED_BY_REALM = "BASE_ENTRY_STILL_REFERENCED_BY_REALM"; /** * The repository {0} could not be deleted because it has at least one base entry that is referenced by a realm. **/ String DELETE_REPOSITORY_PREREQUISITE_ERROR = "DELETE_REPOSITORY_PREREQUISITE_ERROR"; /** * The file {0} could not be found. **/ String FILE_NOT_FOUND = "FILE_NOT_FOUND"; /** * Adapter class name is missing or is not valid: {0} **/ String MISSING_OR_INVALID_ADAPTER_CLASS_NAME = "MISSING_OR_INVALID_ADAPTER_CLASS_NAME"; /** * Could not connect to the {0} repository using properties: {1} **/ String REPOSITORY_CONNECTION_FAILED = "REPOSITORY_CONNECTION_FAILED"; /** * Could not connect to {0} repository because connection data is not valid or is insufficient. **/ String MISSING_OR_INVALID_CONNECTION_DATA = "MISSING_OR_INVALID_CONNECTION_DATA"; /** * LDAP server is not configured for the repository {0}. */ String MISSING_LDAP_SERVER_CONFIGURATION = "MISSING_LDAP_SERVER_CONFIGURATION"; /** * LDAP group is not configured for the repository {0}. */ String MISSING_LDAP_GROUP_CONFIGURATION = "MISSING_LDAP_GROUP_CONFIGURATION"; /** * Realm configuration does not exist. */ String MISSING_REALM_CONFIGURATION = "MISSING_REALM_CONFIGURATION"; /** * Base entry {0} is not found in the {1} realm. **/ String BASE_ENTRY_NOT_FOUND_IN_REALM = "BASE_ENTRY_NOT_FOUND_IN_REALM"; /** * Base entry {0} is not found in the repository {1} **/ String BASE_ENTRY_NOT_FOUND_IN_REPOSITORY = "BASE_ENTRY_NOT_FOUND_IN_REPOSITORY"; /** * The configuration is not complete. Saving an incomplete configuration can cause startup problems. */ String CONFIG_NOT_COMPLETE = "CONFIG_NOT_COMPLETE"; /** * The configuration is saved in a temporary workspace. You must use the "$AdminConfig save" command to save it in the main repository. */ String CONFIG_SAVED_IN_WORKSPACE = "CONFIG_SAVED_IN_WORKSPACE"; /** * Each configured repository must contain at least one base entry. Please add a base entry before saving the configuration. */ String MUST_ADD_BASE_ENTRY_TO_REPOSITORY = "MUST_ADD_BASE_ENTRY_TO_REPOSITORY"; /** * Each configured repository must contain at least one base entry. Please add a base entry. */ String MISSING_BASE_ENTRY = "MISSING_BASE_ENTRY"; /** * Each configured realm must contain at least one participating base entry. Please add a base entry before saving the configuration. */ String MUST_ADD_BASE_ENTRY_TO_REALM = "MUST_ADD_BASE_ENTRY_TO_REALM"; /** * Each configured supported entity type must have at least one RDN property. Please add a valid RDN property before saving the configuration. */ String MUST_ADD_RDN_PROP_TO_SUPPORTED_ENTITY_TYPE = "MUST_ADD_RDN_PROP_TO_SUPPORTED_ENTITY_TYPE"; /** * Base entry specified is invalid: {0}. It must be a distinguished name. */ String BASE_ENTRY_MUST_BE_DN = "BASE_ENTRY_MUST_BE_DN"; /** * One or more of the related parameters are not specified. {0} is specified but {1} is not. */ String RELATED_PARAMETERS_NOT_SPECIFIED = "RELATED_PARAMETERS_NOT_SPECIFIED"; /** * The property {0} was not properly specified for setupIdMgrDB. **/ String DB_SETUP_PROPERTY_MISSING = "DB_SETUP_PROPERTY_MISSING"; /** * Command completed successfully. **/ String COMMAND_COMPLETED_SUCCESSFULLY = "COMMAND_COMPLETED_SUCCESSFULLY"; /** * Initialization of the authorization component completed successfully. **/ String AUTH_INIT_SUCCESS = "AUTH_INIT_SUCCESS"; /** * Initialization of the authorization component failed. **/ String AUTH_INIT_FAILURE = "AUTH_INIT_FAILURE"; /** * The {0} attribute may not be assigned to multiple groups. **/ String AUTH_ATTR_MULTIPLE_GROUP = "AUTH_ATTR_MULTIPLE_GROUP"; /** * An error occurred while performing an access verification for the {0} principal. **/ String AUTH_CHECK_FAILURE = "AUTH_CHECK_FAILURE"; /** * An unexpected error occurred while retrieving the caller's subject. **/ String AUTH_SUBJECT_FAILURE = "AUTH_SUBJECT_FAILURE"; /** * An unexpected error occurred while retrieving the subject's credentials. **/ String AUTH_SUBJECT_CRED_FAILURE = "AUTH_SUBJECT_CRED_FAILURE"; /** * The delegated administration view plug-in is either * missing or failed to return a value for the {0} entity. **/ String AUTH_VIEW_PLUGIN_FAILURE = "AUTH_VIEW_PLUGIN_FAILURE"; /** * The principal {0} is not authorized to perform the operation\n\t * {1} on {2} **/ String AUTH_ACCESS_FAILURE = "AUTH_ACCESS_FAILURE"; /** * The principal {0} does not have the role {1} required for the operation\n\t * {2} **/ String AUTH_ACCESS_ROLE_REQUIRED = "AUTH_ACCESS_ROLE_REQUIRED"; /** * An unexpected error occurred while looking up the {0} attribute * for the {1} entity to evaluate an access rule. **/ String AUTH_RULE_ATTR_FAILURE = "AUTH_RULE_ATTR_FAILURE"; /** * The {0} attribute for the {1} entity was not found to evaluate an access rule. **/ String AUTH_RULE_ATTR_MISSING = "AUTH_RULE_ATTR_MISSING"; /** * The dynamicUpdateConfig method of the ServiceProvider does not support an event with the type '{0}'. */ String DYNA_UPDATE_CONFIG_EVENT_NOT_SUPPORT = "DYNA_UPDATE_CONFIG_EVENT_NOT_SUPPORT"; /** * Cannot add a new realm through the dynamicUpdateConfig method of the ServiceProvider when there is no realm configured in vitural member manager. */ String DYNA_UPDATE_CONFIG_ADD_REALM_WITHOUT_REALM_CONFIG = "DYNA_UPDATE_CONFIG_ADD_REALM_WITHOUT_REALM_CONFIG"; /** * The DataObject type {0} for event type {1} is incorrect. */ String DYNA_UPDATE_CONFIG_WRONG_DATA_OBJECT_TYPE = "DYNA_UPDATE_CONFIG_WRONG_DATA_OBJECT_TYPE"; /** * The value for the dynamic configuration key {0} of event type {1} is missing. */ String DYNA_UPDATE_CONFIG_MISSING_VALUE = "DYNA_UPDATE_CONFIG_MISSING_VALUE"; /** * The default parent for entity type {0} in realm {1} already defined. */ String DEFAULT_PARENT_ALREADY_DEFINED = "DEFAULT_PARENT_ALREADY_DEFINED"; /** * Property extension repository has been already defined. */ String PROPERTY_EXTENSION_REPOSITORY_ALREADY_DEFINED = "PROPERTY_EXTENSION_REPOSITORY_ALREADY_DEFINED"; /** * The specified repository id {0} is not a LDAP repository. */ String NOT_LDAP_REPOSITORY = "NOT_LDAP_REPOSITORY"; /** * The dynamic configuration parameter {0} is missing. */ String MISSING_DYNA_CONFIG_PARAMETER = "MISSING_DYNA_CONFIG_PARAMETER"; /** * The write operations are not allowed on secondary LDAP server {0}. */ String WRITE_TO_SECONDARY_SERVERS_NOT_ALLOWED = "WRITE_TO_SECONDARY_SERVERS_NOT_ALLOWED"; /** * Entity DataObject is missing for operation {0}. */ String MISSING_ENTITY_DATA_OBJECT = "MISSING_ENTITY_DATA_OBJECT"; /** * The {0} search limit specified in the SearchControl data object is invalid. */ String INCORRECT_SEARCH_LIMIT = "INCORRECT_SEARCH_LIMIT"; /** * No database type was specified to be setup. Check DB, FED, and LA parameters. */ String DB_SETUP_NO_DB_SPECIFIED = "DB_SETUP_NO_DB_SPECIFIED"; /** * The {0} repository ID is not valid as repository for groups. */ String INVALID_REPOSITORY_FOR_GROUPS = "INVALID_REPOSITORY_FOR_GROUPS"; /** * The required parameter {0} is missing from realm {1}. */ String MISSING_REALM_RELATED_PARAMETER = "MISSING_REALM_RELATED_PARAMETER"; /** * The passed in DataObject type {0} is not valid for operation {1}. The correct DataObject type is {2}. */ String INVALID_DATA_OBJECT_TYPE = "INVALID_DATA_OBJECT_TYPE"; /** * Repository '{0}' is not a database repository and can not contain entities from other repository. */ String CANNOT_STORE_ENTITY_FROM_OTHER_REPOSITORY = "CANNOT_STORE_ENTITY_FROM_OTHER_REPOSITORY"; /** * Entity mapping repository is not defined in virtual member manager configuration. */ String ENTRY_MAPPING_REPOSITORY_NOT_DEFINED = "ENTRY_MAPPING_REPOSITORY_NOT_DEFINED"; /** * Property extension repository is not defined in virtual member manager configuration. */ String PROPERTY_EXTENSION_REPOSITORY_NOT_DEFINED = "PROPERTY_EXTENSION_REPOSITORY_NOT_DEFINED"; /** * The database migration task : {0} loading failed. */ String MIGRATION_DATABASE_LOADING = "MIGRATION_DATABASE_LOADING"; /** * At least one of the config path parameters for migrating wmm configuration task is missing. */ String MIGRATION_CONFIG_PATH_MISSING = "MIGRATION_CONFIG_PATH_MISSING"; /** * Database connection failed with database URL {0}. */ String DATABASE_CONNECTION = "DATABASE_CONNECTION"; /** * The {0} file is invalid. */ String MIGRATION_WMM_FILE_INVALID = "MIGRATION_WMM_FILE_INVALID"; /** * Migrating WMM failed due to: {0}. */ String MIGRATION_ERROR = "MIGRATION_ERROR"; /** * Command completed successfully. Invoke updateWMMReference command with reposType={0} to update reference properties. */ String INVOKE_UPDATE_WMM_REFERENCE_COMMAND = "INVOKE_UPDATE_WMM_REFERENCE_COMMAND"; /** * Initialization of component, {component_name}, failed: {reason} */ String COMPONENT_INITIALIZATION_FAILED = "COMPONENT_INITIALIZATION_FAILED"; /** * The user with uniqueName {0} cannot be deleted because it is the logged in user. */ String CANNOT_DELETE_LOGGED_IN_USER = "CANNOT_DELETE_LOGGED_IN_USER"; /** * To manage users and groups, either federated repositories must be the current realm definition or the * current realm definition configuration must match the federated repositories configuration. * If you use Lightweight Directory Access Protocol (LDAP), configure both the federated repositories * and standalone LDAP registry configurations to use the same LDAP server. */ String WAS_USER_REGISTRY_NOT_SUPPORTED = "WAS_USER_REGISTRY_NOT_SUPPORTED"; /** * WAS Primary Admin user Can Not be deleted */ String CANNOT_DELETE_PRIMARY_ADMIN = "CANNOT_DELETE_PRIMARY_ADMIN"; /** * can not find attribute mapping. */ String ATTRIBUTE_MAPPING_NOT_DEFINED = "ATTRIBUTE_MAPPING_NOT_DEFINED"; /** * there are more than one attribute configurations defined for {0}, please specify the entity type. */ String MORE_THAN_ONE_ATTRIBUTE_MAPPING = "MORE_THAN_ONE_ATTRIBUTE_MAPPING"; /** * attribute mapping for ''{0}'' already exist. */ String ATTRIBUTE_MAPPING_ALREADY_EXIST = "ATTRIBUTE_MAPPING_ALREADY_EXIST"; /** * The passed in DataObject is null. */ String INVALID_DATA_OBJECT = "INVALID_DATA_OBJECT"; /** * The wmmnode ''{0}'' failed to be migrated to virtual member manager realm. */ String BASE_ENTRY_MIGRATION_WARNING = "BASE_ENTRY_MIGRATION_WARNING"; /** * repositoriesForGroups is not configured for the repository {0}. */ String MISSING_REPOSITORIES_FOR_GROUPS_CONFIGURATION = "MISSING_REPOSITORIES_FOR_GROUPS_CONFIGURATION"; /** * Could not retrieve information associated with changelog in TDS repository */ String ERROR_IN_CHANGELOG_CONFIGURATION = "ERROR_IN_CHANGELOG_CONFIGURATION"; /** * NULL checkpoint value */ String NULL_CHECKPOINT_VALUE = "NULL_CHECKPOINT_VALUE"; /** * No change handler associated with repository type : {0} */ String NO_ASSOCIATED_CHANGE_HANDLER = "NO_ASSOCIATED_CHANGE_HANDLER"; /** * Invalid ChangeType */ String INVALID_CHANGETYPE = "INVALID_CHANGETYPE"; /* LI-80054-Start */ /** * Successfully added new property '' {0}'' to the entity ''{1}'' */ String EXTEND_SCHEMA_PROPERTY_EXTENSION_SUCCESSFUL = "EXTEND_SCHEMA_PROPERTY_EXTENSION_SUCCESSFUL"; /** * Command failed since a property doesn't exist in Look Aside Repository for the given applicable entity types. */ String EXTENDED_PROPERTY_NOT_DEFINED_FOR_ENTITY_TYPES = "EXTENDED_PROPERTY_NOT_DEFINED_FOR_ENTITY_TYPES"; /** * Command to add attribute to the entity has failed. */ String EXTEND_SCHEMA_PROPERTY_EXTENSION_FAILED = "EXTEND_SCHEMA_PROPERTY_EXTENSION_FAILED"; /** * Command failed since the Entity type ''{0}'' provided is an invalid entity type. */ String EXTEND_SCHEMA_PROPERTY_EXTENSION_INVALID_APPLICABLE_ENTITY_TYPE = "EXTEND_SCHEMA_PROPERTY_EXTENSION_INVALID_APPLICABLE_ENTITY_TYPE"; /** * Command failed since the Required Entity type ''{0}'' provided is an invalid entity type. */ String EXTEND_SCHEMA_PROPERTY_EXTENSION_INVALID_REQUIRED_ENTITY_TYPE = "EXTEND_SCHEMA_PROPERTY_EXTENSION_INVALID_REQUIRED_ENTITY_TYPE"; /** * Command failed since the data type of the attribute ''{0}'' provided as ''{1}'' provided is an invalid data type. */ String EXTEND_SCHEMA_PROPERTY_EXTENSION_INVALID_DATA_TYPE = "EXTEND_SCHEMA_PROPERTY_EXTENSION_INVALID_DATA_TYPE"; /** * Command failed since the Required Entity type ''{0}'' provided is not in the list of applicable entity types. */ String EXTEND_SCHEMA_PROPERTY_EXTENSION_INVALID_REQUIRED_NOTIN_APPLICABLE_ENTITY_TYPE = "EXTEND_SCHEMA_PROPERTY_EXTENSION_INVALID_REQUIRED_NOTIN_APPLICABLE_ENTITY_TYPE"; /** * Command failed since The namespace URI for the prefix, {0} is not defined. */ String INVALID_NS_PREFIX = "INVALID_NS_PREFIX"; /** * Command failed since the prefix {0} provided for the entity type is invalid. */ String INVALID_NS_PREFIX_FOR_ENTITY_TYPE_OR_PROPERTY = "INVALID_NS_PREFIX_FOR_ENTITY_TYPE_OR_PROPERTY"; /** * Command failed since prefix for the namespace URI '<Variable formatSpec="{0}">ns_URI</Variable>' is not provided. */ String NO_NS_PREFIX_FOR_NS_URI = "NO_NS_PREFIX_FOR_NS_URI"; /** * DB Login information for a user is not set. */ String INVALID_DB_CREDENTIALS = "INVALID_DB_CREDENTIALS"; /* LI-80054-End */ /** * The Custom Registry {0} is not supported by WebSphere Application Server. */ String MISSING_OR_INVALID_CUSTOM_REGISTRY_CLASS_NAME = "MISSING_OR_INVALID_CUSTOM_REGISTRY_CLASS_NAME"; /** * Exception is thrown from Custom Registry configured as Virtual Member Manager repository "{0}". */ String CUSTOM_REGISTRY_EXCEPTION = "CUSTOM_REGISTRY_EXCEPTION"; /** * Failure in generating the certificate. */ String CERTIFICATE_MAP_FAILED = "CERTIFICATE_MAP_FAILED"; /** * Failure to map certificate. */ String CERTIFICATE_GENERATE_FAILED = "CERTIFICATE_GENERATE_FAILED"; /** * Attribute mapping for <attribute_name> is not defined for one or more specified entity types. */ String ATTRIBUTE_MAPPING_NOT_DEFINED_FOR_ENTITY_TYPE = "ATTRIBUTE_MAPPING_NOT_DEFINED_FOR_ENTITY_TYPE"; /** * Attribute mapping for <attribute_name> already exists for one or more specified entity types. */ String ATTRIBUTE_MAPPING_ALREADY_EXISTS_FOR_ENTITY_TYPE = "ATTRIBUTE_MAPPING_ALREADY_EXISTS_FOR_ENTITY_TYPE"; /** * Common attribute mapping for <attribute_name> already exists. */ String COMMON_ATTRIBUTE_MAPPING_ALREADY_EXISTS = "COMMON_ATTRIBUTE_MAPPING_ALREADY_EXISTS"; /** * Common attribute mapping for <attribute_name> can not be added. */ String INVALID_COMMON_ATTRIBUTE_MAPPING = "INVALID_COMMON_ATTRIBUTE_MAPPING"; /** * Attribute or property name is required. */ String ATTR_OR_PROP_NAME_REQD = "ATTR_OR_PROP_NAME_REQD"; /** * WAS User Registry Attribute Name Mapping is invalid. */ String INVALID_USER_REGISTRY_ATTRIBUTE_NAME = "INVALID_USER_REGISTRY_ATTRIBUTE_NAME"; /** * Specified property can not be mapped. */ String PROPERTY_CAN_NOT_BE_MAPPED = "PROPERTY_CAN_NOT_BE_MAPPED"; /** * Source and Destination Domain Name cannot be same. */ String SOURCE_DEST_DOMAIN_CANNOT_BE_SAME = "SOURCE_DEST_CANNOT_HAVE_SAME_VALUE"; /** * Destination Domain Can not be Global/Admin */ String DEST_DOMAIN_CANNOT_BE_ADMIN_OR_GLOBAL = "DESTINATION_DOMAIN_CANNOT_BE_ADMIN_OR_GLOBAL"; /** * Command Failed To Execute Successfully */ String COULD_NOT_COPY_VMM_RELATED_FILES = "COULD_NOT_COPY_VMM_RELATED_FILES"; /** * Specified dbschema not available. */ String DBSCHEMA_NOT_AVAILABLE = "DBSCHEMA_NOT_AVAILABLE"; /** * Domain cannot be admin */ String DOMAIN_CANNOT_BE_ADMIN = "DOMAIN_CANNOT_BE_ADMIN"; /** * Specified tablespace prefix is invalid. */ String DB_TABLESPACE_PREFIX_INVALID = "DB_TABLESPACE_PREFIX_INVALID"; /** * Specified role name is invalid. */ String INVALID_ROLE_NAME = "INVALID_ROLE_NAME"; /** * Specified user or group id not unique. */ String USER_OR_GROUP_ID_NOT_UNIQUE = "USER_OR_GROUP_ID_NOT_UNIQUE"; /** * Specified user or group is already mapped to a role. */ String USER_OR_GROUP_ALREADY_MAPPED = "USER_OR_GROUP_ALREADY_MAPPED"; /** * /** * Could not connect to the LDAP Server specified. */ String CANNOT_CONNECT_LDAP_SERVER = "CANNOT_CONNECT_TO_LDAP_SERVER"; /** * The Userregistry is using current LDAP Server */ String CURRENT_LDAP_SERVER = "CURRENT_LDAP_SERVER"; /** * Repository Name must be either WIMLA or WIMDB in the file specified. */ String REPOSITORY_NAME_MUST_BE_EITHER_WIMLA_OR_WIMDB = "REPOSITORY_NAME_MUST_BE_EITHER_WIMLA_OR_WIMDB"; /** * Sort Control not valid */ String SORT_CONTROL_NOT_VALID = "SORT_CONTROL_NOT_VALID"; /** * The security domain 'domain_name' is not found. */ String DOMAIN_NOT_FOUND = "DOMAIN_NOT_FOUND"; /** * Deleted group member list. */ String DELETED_GROUPMEMBER = "DELETED_GROUPMEMBER"; /** * The Transaction was rolled back. */ String TRANSACTION_ROLLED_BACK = "TRANSACTION_ROLLED_BACK"; /** * Specified Entity type is invalid. */ String INVALID_ENTITY_TYPE = "INVALID_ENTITY_TYPE"; /** * Repository '{0}': Clear cache mode '{1}' passed in the Cache Control by user '{2}'. */ String CLEAR_ALL_CLEAR_CACHE_MODE = "CLEAR_ALL_CLEAR_CACHE_MODE"; /** * Repository '{0}': Unknown clear cache mode '{1}' passed in the Cache Control. */ String UNKNOWN_CLEAR_CACHE_MODE = "UNKNOWN_CLEAR_CACHE_MODE"; /** * Repository '{0}': Clear cache mode '{1}' is not supported for this operation. */ String UNSUPPORTED_CLEAR_CACHE_MODE = "UNSUPPORTED_CLEAR_CACHE_MODE"; /** * Specified default parent is not within realm scope. */ String DEFAULT_PARENT_NOT_IN_SCOPE = "DEFAULT_PARENT_NOT_IN_SCOPE"; /** * No mapping existing for specified entitytype in realm. */ String NO_PARENT_FOR_ENTITY_TYPE_IN_REALM = "NO_PARENT_FOR_ENTITY_TYPE_IN_REALM"; /** * Entity type name is not specified for property names. */ String ENTITY_TYPE_NAME_NOT_SPECIFIED = "ENTITY_TYPE_NAME_NOT_SPECIFIED"; /** * Value for timestamp format specified for LDAP adapter is invalid. */ String INVALID_TIMESTAMP_FORMAT = "INVALID_TIMESTAMP_FORMAT"; /** * The extended property has already been defined and will be ignored. */ String DUPLICATE_PROPERTY_EXTENDED = "DUPLICATE_PROPERTY_EXTENDED"; /** * The extended property cannot override a property on the entity. */ String DUPLICATE_PROPERTY_ENTITY = "DUPLICATE_PROPERTY_ENTITY"; /** * The LDAP registry will ignore the certificate authentication request since 'certificateMapeMode' is set to IGNORE. */ String LDAP_REGISTRY_CERT_IGNORED = "LDAP_REGISTRY_CERT_IGNORED"; /** * No custom X.509 certificate mapper implementation has been registered with the LDAP registry. */ String LDAP_REGISTRY_MAPPER_NOT_BOUND = "LDAP_REGISTRY_MAPPER_NOT_BOUND"; /** * The custom X.509 certificate mapper implementation has thrown a CertificateMapNotSupportedException. */ String LDAP_REGISTRY_CUSTOM_MAPPER_NOT_SUPPORTED = "LDAP_REGISTRY_CUSTOM_MAPPER_NOT_SUPPORTED"; /** * The custom X.509 certificate mapper implementation has thrown a CertificateMapFailedException. */ String LDAP_REGISTRY_CUSTOM_MAPPER_FAILED = "LDAP_REGISTRY_CUSTOM_MAPPER_FAILED"; /** * The custom X.509 certificate mapper implementation returned an invalid mapping value. */ String LDAP_REGISTRY_INVALID_MAPPING = "LDAP_REGISTRY_INVALID_MAPPING"; /** * CWIMK0011E: The user registry operation could not be completed. A valid user registry or repository was not found. */ String MISSING_REGISTRY_DEFINITION = "MISSING_REGISTRY_DEFINITION"; /** * The defined userFilter attribute will be ignored since there are loginProperty attributes defined. */ String LOGINPROPERTY_OVERRIDE_USERFILTER = "LOGINPROPERTY_OVERRIDE_USERFILTER"; /** * CWIML4553E: Kerberos login failed using Kerberos principal {0} and Kerberos credential cache (ccache) {1}. */ String KRB5_LOGIN_FAILED_CACHE = "KRB5_LOGIN_FAILED_CACHE"; /** * WIML4554E: Kerberos login failed using Kerberos principal {0} and Kerberos keytab {1}. */ String KRB5_LOGIN_FAILED_KEYTAB = "KRB5_LOGIN_FAILED_KEYTAB"; /** * CWIML4555E: Kerberos login failed using Kerberos principal {0} and the default Kerberos credential cache (ccache). */ String KRB5_LOGIN_FAILED_DEFAULT_CACHE = "KRB5_LOGIN_FAILED_DEFAULT_CACHE"; /** * CWIML4556E: Kerberos login failed using Kerberos principal {0} and the default Kerberos keytab. */ String KRB5_LOGIN_FAILED_DEFAULT_KEYTAB = "KRB5_LOGIN_FAILED_DEFAULT_KEYTAB"; /** * CWIML4557I: LDAPRegistry {0} configured with Kerberos credential cache (ccache) filename {1} and keytab filename {2}, using Kerberos credential cache (ccache) for Kerberos * bind authentication to LDAP server. */ String KRB5_TICKETCACHE_USED = "KRB5_TICKETCACHE_USED"; /** * CWIML4558E: The {0} Kerberos principal name is incorrectly formatted, or the realm name is missing, or a default realm name cannot be found. */ String INVALID_KRB5_PRINCIPAL = "INVALID_KRB5_PRINCIPAL"; /** * CWIML4559E: LDAPRegistry {0} could not read the Kerberos file {1}. */ String CANNOT_READ_KRB5_FILE = "CANNOT_READ_KRB5_FILE"; /** * CWIML4560E: The [{0}] attribute from the {1} element is configured to a file that does not exist at: {2} */ String KRB5_FILE_NOT_FOUND = "KRB5_FILE_NOT_FOUND"; /** * CWIML4561I: The LdapRegistry component is configured to use a {0} file located at {1} */ String KRB5_FILE_FOUND = "KRB5_FILE_FOUND"; /** * CWIML4518W: The {0} {1} value is malformed. The value must be a series of objectclass:attribute or *:attribute pairs, where each pair is separated by a semi-colon. */ String IDMAP_INVALID_FORMAT = "IDMAP_INVALID_FORMAT"; /** * CWIML4521E: The {0} LdapRegistry attempted to bind to the Ldap server using Kerberos credentials for {1} principal name, but the KerberosService * is not available. The bind authentication mechanism is {2}. */ String KRB5_SERVICE_NOT_AVAILABLE = "KRB5_SERVICE_NOT_AVAILABLE"; /** * CWIML4523E: The {0} value for {1} is invalid. It requires an attribute value assertion where the value assertion is =%v. For example, {2}. */ String FILTER_MISSING_PERCENT_V = "FILTER_MISSING_PERCENT_V"; }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.javaee.ddmodel/src.gen/com/ibm/ws/javaee/ddmodel/commonbnd/MessageDestinationRefType.java
3289
/******************************************************************************* * Copyright (c) 2017,2021 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 *******************************************************************************/ // NOTE: This is a generated file. Do not edit it directly. package com.ibm.ws.javaee.ddmodel.commonbnd; import com.ibm.ws.javaee.ddmodel.DDParser; public class MessageDestinationRefType extends com.ibm.ws.javaee.ddmodel.DDParser.ElementContentParsable implements com.ibm.ws.javaee.dd.commonbnd.MessageDestinationRef { public MessageDestinationRefType() { this(false); } public MessageDestinationRefType(boolean xmi) { this.xmi = xmi; } protected final boolean xmi; com.ibm.ws.javaee.ddmodel.StringType name; private com.ibm.ws.javaee.ddmodel.CrossComponentReferenceType bindingMessageDestinationRef; com.ibm.ws.javaee.ddmodel.StringType binding_name; @Override public java.lang.String getName() { return name != null ? name.getValue() : null; } @Override public java.lang.String getBindingName() { return binding_name != null ? binding_name.getValue() : null; } @Override public boolean isIdAllowed() { return true; } @Override public boolean handleAttribute(DDParser parser, String nsURI, String localName, int index) throws DDParser.ParseException { if (nsURI == null) { if (!xmi && "name".equals(localName)) { this.name = parser.parseStringAttributeValue(index); return true; } if ((xmi ? "jndiName" : "binding-name").equals(localName)) { this.binding_name = parser.parseStringAttributeValue(index); return true; } } return false; } @Override public boolean handleChild(DDParser parser, String localName) throws DDParser.ParseException { if (xmi && "bindingMessageDestinationRef".equals(localName)) { this.bindingMessageDestinationRef = new com.ibm.ws.javaee.ddmodel.CrossComponentReferenceType("bindingMessageDestinationRef", parser.getCrossComponentType()); parser.parse(bindingMessageDestinationRef); com.ibm.ws.javaee.dd.common.MessageDestinationRef referent = this.bindingMessageDestinationRef.resolveReferent(parser, com.ibm.ws.javaee.dd.common.MessageDestinationRef.class); if (referent != null) { this.name = parser.parseString(referent.getName()); } return true; } return false; } @Override public void describe(com.ibm.ws.javaee.ddmodel.DDParser.Diagnostics diag) { if (xmi) { diag.describeIfSet("bindingMessageDestinationRef", bindingMessageDestinationRef); } else { diag.describeIfSet("name", name); } diag.describeIfSet(xmi ? "jndiName" : "binding-name", binding_name); } }
epl-1.0
asupdev/asup
org.asup.os.type.dtaq.base/src/org/asup/os/type/dtaq/base/data/QueueSize.java
756
/** * Copyright (c) 2012, 2014 Sme.UP 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: * Mattia Rocchi - Initial API and implementation */ package org.asup.os.type.dtaq.base.data; import org.asup.il.data.QDataStructWrapper; import org.asup.il.data.QBinary; import org.asup.il.data.annotation.DataDef; public class QueueSize extends QDataStructWrapper { private static final long serialVersionUID = 1L; @DataDef() public QBinary maximumNumberOfEntries; @DataDef() public QBinary initialNumberOfEntries; }
epl-1.0
lhillah/pnmlframework
pnmlFw-PT-HLPNG/src/fr/lip6/move/pnml/pthlpng/hlcorestructure/ArcGraphics.java
6509
/** * Copyright 2009-2016 Université Paris Ouest and Sorbonne Universités, Univ. Paris 06 - CNRS UMR 7606 (LIP6) * * 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 * * Project leader / Initial Contributor: * Lom Messan Hillah - <lom-messan.hillah@lip6.fr> * * Contributors: * ${ocontributors} - <$oemails}> * * Mailing list: * lom-messan.hillah@lip6.fr */ /** * (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6/MoVe) * 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: * Lom HILLAH (LIP6) - Initial models and implementation * Rachid Alahyane (UPMC) - Infrastructure and continuous integration * Bastien Bouzerau (UPMC) - Architecture * Guillaume Giffo (UPMC) - Code generation refactoring, High-level API */ package fr.lip6.move.pnml.pthlpng.hlcorestructure; import java.nio.channels.FileChannel; import java.util.List; import org.apache.axiom.om.OMElement; import org.eclipse.emf.common.util.DiagnosticChain; import fr.lip6.move.pnml.framework.utils.IdRefLinker; import fr.lip6.move.pnml.framework.utils.exception.InnerBuildException; import fr.lip6.move.pnml.framework.utils.exception.InvalidIDException; import fr.lip6.move.pnml.framework.utils.exception.VoidRepositoryException; /** * <!-- begin-user-doc --> A representation of the model object '<em><b>Arc * Graphics</b></em>'. <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.ArcGraphics#getPositions * <em>Positions</em>}</li> * <li>{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.ArcGraphics#getLine * <em>Line</em>}</li> * <li>{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.ArcGraphics#getContainerArc * <em>Container Arc</em>}</li> * </ul> * </p> * * @see fr.lip6.move.pnml.pthlpng.hlcorestructure.HlcorestructurePackage#getArcGraphics() * @model annotation="http://www.pnml.org/models/HLAPI" * annotation="http://www.pnml.org/models/ToPNML tag='graphics' * kind='son'" * @generated */ public interface ArcGraphics extends Graphics { /** * Returns the value of the '<em><b>Positions</b></em>' containment reference * list. The list contents are of type * {@link fr.lip6.move.pnml.pthlpng.hlcorestructure.Position}. It is * bidirectional and its opposite is * '{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.Position#getContainerArcGraphics * <em>Container Arc Graphics</em>}'. <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Positions</em>' containment reference list isn't * clear, there really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Positions</em>' containment reference list. * @see fr.lip6.move.pnml.pthlpng.hlcorestructure.HlcorestructurePackage#getArcGraphics_Positions() * @see fr.lip6.move.pnml.pthlpng.hlcorestructure.Position#getContainerArcGraphics * @model opposite="containerArcGraphics" containment="true" * annotation="http://www.pnml.org/models/ToPNML kind='follow'" * @generated */ List<Position> getPositions(); /** * Returns the value of the '<em><b>Line</b></em>' containment reference. It is * bidirectional and its opposite is * '{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.Line#getContainerArcGraphics * <em>Container Arc Graphics</em>}'. <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Line</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Line</em>' containment reference. * @see #setLine(Line) * @see fr.lip6.move.pnml.pthlpng.hlcorestructure.HlcorestructurePackage#getArcGraphics_Line() * @see fr.lip6.move.pnml.pthlpng.hlcorestructure.Line#getContainerArcGraphics * @model opposite="containerArcGraphics" containment="true" ordered="false" * annotation="http://www.pnml.org/models/ToPNML kind='follow'" * @generated */ Line getLine(); /** * Sets the value of the * '{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.ArcGraphics#getLine * <em>Line</em>}' containment reference. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @param value the new value of the '<em>Line</em>' containment reference. * @see #getLine() * @generated */ void setLine(Line value); /** * Returns the value of the '<em><b>Container Arc</b></em>' container reference. * It is bidirectional and its opposite is * '{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.Arc#getArcgraphics * <em>Arcgraphics</em>}'. <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Container Arc</em>' container reference isn't * clear, there really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Container Arc</em>' container reference. * @see #setContainerArc(Arc) * @see fr.lip6.move.pnml.pthlpng.hlcorestructure.HlcorestructurePackage#getArcGraphics_ContainerArc() * @see fr.lip6.move.pnml.pthlpng.hlcorestructure.Arc#getArcgraphics * @model opposite="arcgraphics" transient="false" * @generated */ Arc getContainerArc(); /** * Sets the value of the * '{@link fr.lip6.move.pnml.pthlpng.hlcorestructure.ArcGraphics#getContainerArc * <em>Container Arc</em>}' container reference. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @param value the new value of the '<em>Container Arc</em>' container * reference. * @see #getContainerArc() * @generated */ void setContainerArc(Arc value); /** * Return the string containing the pnml output */ @Override public String toPNML(); /** * set values to conform PNML document */ @Override public void fromPNML(OMElement subRoot, IdRefLinker idr) throws InnerBuildException, InvalidIDException, VoidRepositoryException; /** * Write the PNML xml tree of this object into file */ @Override public void toPNML(FileChannel fc); @Override public boolean validateOCL(DiagnosticChain diagnostics); } // ArcGraphics
epl-1.0
debabratahazra/DS
designstudio/components/integrationfwk/ui/com.odcgroup.integrationfwk/src/com/odcgroup/integrationfwk/ui/model/Service.java
597
package com.odcgroup.integrationfwk.ui.model; import java.util.ArrayList; import java.util.List; public class Service { private final List<Operation> operations; private String componentService; public Service() { operations = new ArrayList<Operation>(); } public void addOperations(Operation operation) { operations.add(operation); } public String getComponentService() { return componentService; } public List<Operation> getOperations() { return operations; } public void setComponentService(String componentService) { this.componentService = componentService; } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/keybased/singletarget/singlekey/nonstringkeytype/Address.java
1448
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle 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 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings.keybased.singletarget.singlekey.nonstringkeytype; public class Address extends org.eclipse.persistence.testing.oxm.mappings.keybased.Address { public int id; public String street; public String city; public String country; public String zip; public Object getKey() { return id; } public boolean equals(Object obj) { if (obj == null || !(obj instanceof Address)) { return false; } Address tgtAddress = (Address) obj; return (tgtAddress.city.equals(city) && tgtAddress.country.equals(country) && tgtAddress.id==id && tgtAddress.street.equals(street) && tgtAddress.zip.equals(zip)); } }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NikoHomeControlCommunication.java
4490
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.nikohomecontrol.internal.protocol; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.nikohomecontrol.internal.protocol.nhc1.NikoHomeControlCommunication1; import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NikoHomeControlCommunication2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link NikoHomeControlCommunication} class is an abstract class representing the communication objects with the * Niko Home Control System. {@link NikoHomeControlCommunication1} or {@link NikoHomeControlCommunication2} should be * used for the respective version of Niko Home Control. * <ul> * <li>Start and stop communication with the Niko Home Control System. * <li>Read all setup and status information from the Niko Home Control Controller. * <li>Execute Niko Home Control commands. * <li>Listen to events from Niko Home Control. * </ul> * * @author Mark Herwege - Initial Contribution */ @NonNullByDefault public abstract class NikoHomeControlCommunication { private final Logger logger = LoggerFactory.getLogger(NikoHomeControlCommunication.class); protected final Map<String, NhcAction> actions = new ConcurrentHashMap<>(); protected final Map<String, NhcThermostat> thermostats = new ConcurrentHashMap<>(); protected final Map<String, NhcEnergyMeter> energyMeters = new ConcurrentHashMap<>(); protected final NhcControllerEvent handler; protected NikoHomeControlCommunication(NhcControllerEvent handler) { this.handler = handler; } /** * Start Communication with Niko Home Control system. */ public abstract void startCommunication(); /** * Stop Communication with Niko Home Control system. */ public abstract void stopCommunication(); /** * Close and restart communication with Niko Home Control system. */ public synchronized void restartCommunication() { stopCommunication(); logger.debug("restart communication from thread {}", Thread.currentThread().getId()); startCommunication(); } /** * Method to check if communication with Niko Home Control is active. * * @return True if active */ public abstract boolean communicationActive(); /** * Return all actions in the Niko Home Control Controller. * * @return <code>Map&ltString, {@link NhcAction}></code> */ public Map<String, NhcAction> getActions() { return actions; } /** * Return all thermostats in the Niko Home Control Controller. * * @return <code>Map&ltString, {@link NhcThermostat}></code> */ public Map<String, NhcThermostat> getThermostats() { return thermostats; } /** * Return all energyMeters meters in the Niko Home Control Controller. * * @return <code>Map&ltString, {@link NhcEnergyMeter}></code> */ public Map<String, NhcEnergyMeter> getEnergyMeters() { return energyMeters; } /** * Execute an action command by sending it to Niko Home Control. * * @param actionId * @param value */ public abstract void executeAction(String actionId, String value); /** * Execute a thermostat command by sending it to Niko Home Control. * * @param thermostatId * @param mode */ public abstract void executeThermostat(String thermostatId, String mode); /** * Execute a thermostat command by sending it to Niko Home Control. * * @param thermostatId * @param overruleTemp * @param overruleTime */ public abstract void executeThermostat(String thermostatId, int overruleTemp, int overruleTime); /** * Start retrieving energy meter data from Niko Home Control. * */ public void startEnergyMeter(String energyMeterId) { }; /** * Stop retrieving energy meter data from Niko Home Control. * */ public void stopEnergyMeter(String energyMeterId) { }; }
epl-1.0
asupdev/asup
org.asup.db.core.base/src/org/asup/db/core/base/BaseConnectionImpl.java
14231
/** * Copyright (c) 2012, 2014 Sme.UP 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: * Mattia Rocchi - Initial API and implementation */ package org.asup.db.core.base; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import org.asup.db.core.QCatalogContainer; import org.asup.db.core.QCatalogGenerationStrategy; import org.asup.db.core.QCatalogMetaData; import org.asup.db.core.QConnection; import org.asup.db.core.QConnectionDescription; import org.asup.db.core.QDatabaseContainer; import org.asup.db.syntax.QQueryParser; import org.asup.fw.core.FrameworkCoreUnexpectedConditionException; import org.asup.fw.core.QContext; import org.eclipse.datatools.modelbase.sql.schema.Schema; import org.eclipse.datatools.sqltools.parsers.sql.query.SQLQueryParseResult; public class BaseConnectionImpl implements QConnection, Connection { private QContext context; private QDatabaseContainer databaseContainer; private QQueryParser queryParser; private String virtualCatalog; private BaseCatalogConnection currentCatalogConnection; private List<BaseCatalogConnection> catalogConnections; public BaseConnectionImpl(QDatabaseContainer databaseContainer, QContext context) { this.context = context; this.databaseContainer = databaseContainer; this.queryParser = context.get(QQueryParser.class); this.catalogConnections = new ArrayList<BaseCatalogConnection>(); } public void abort(Executor executor) throws SQLException { getRawConnection().abort(executor); } public void clearWarnings() throws SQLException { getRawConnection().clearWarnings(); } @Override public void close() throws SQLException { for(BaseCatalogConnection catalogConnection: catalogConnections) { catalogConnection.close(); } this.catalogConnections.clear(); this.currentCatalogConnection = null; this.virtualCatalog = null; } @Override public void commit() throws SQLException { Connection connection = getRawConnection(); connection.commit(); } public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return getRawConnection().createArrayOf(typeName, elements); } public Blob createBlob() throws SQLException { return getRawConnection().createBlob(); } public Clob createClob() throws SQLException { return getRawConnection().createClob(); } public NClob createNClob() throws SQLException { return getRawConnection().createNClob(); } public SQLXML createSQLXML() throws SQLException { return getRawConnection().createSQLXML(); } @Override public BaseStatementImpl createStatement() throws SQLException { return createStatement(false); } @Override public BaseStatementImpl createStatement(boolean native_) throws SQLException { return createStatement(native_, false); } @Override public BaseStatementImpl createStatement(boolean native_, boolean updatable) throws SQLException { Statement sqlStatement = null; if(updatable) // connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); sqlStatement = getRawConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); else sqlStatement = getRawConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); BaseStatementImpl statement = new BaseStatementImpl(this, sqlStatement, native_); return statement; } public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return getRawConnection().createStatement(resultSetType, resultSetConcurrency); } public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return getRawConnection().createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return getRawConnection().createStruct(typeName, attributes); } public boolean getAutoCommit() throws SQLException { return getRawConnection().getAutoCommit(); } @Override public String getCatalog() throws SQLException { return virtualCatalog; } private BaseCatalogConnection getCatalogConnection() throws SQLException { if(currentCatalogConnection != null) return currentCatalogConnection; if(getCatalog() == null) { QCatalogContainer catalogContainer = this.databaseContainer.getDefaultCatalogContainer(); // search on connected catalog for(BaseCatalogConnection catalogConnection: catalogConnections) { if(catalogConnection.getCatalogContainer().equals(catalogContainer)) return catalogConnection; } currentCatalogConnection = new BaseCatalogConnection(catalogContainer); catalogConnections.add(currentCatalogConnection); } else { // search on connected catalog for(BaseCatalogConnection catalogConnection: catalogConnections) { if(getCatalog().equals(catalogConnection.getCatalogContainer().getName())) return catalogConnection; } for(QCatalogContainer catalogContainer: this.databaseContainer.getCatalogContainers()) { if(getCatalog().equals(catalogContainer.getName())) { currentCatalogConnection = new BaseCatalogConnection(catalogContainer); catalogConnections.add(currentCatalogConnection); break; } } } return currentCatalogConnection; } @Override public QCatalogGenerationStrategy getCatalogGenerationStrategy() { try { return getCatalogConnection().getCatalogGenerationStrategy(); } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public QCatalogMetaData getCatalogMetaData() { try { return getCatalogConnection().getCatalogMetaData(); } catch (SQLException e) { e.printStackTrace(); return null; } } public Properties getClientInfo() throws SQLException { return getRawConnection().getClientInfo(); } public String getClientInfo(String name) throws SQLException { return getRawConnection().getClientInfo(name); } @Override public QConnectionDescription getConnectionDescription() { QConnectionDescription connectionDescription = getContext().get(QConnectionDescription.class); if(connectionDescription == null) { final List<String> schemas = new ArrayList<String>(); for(Schema schema: getCatalogMetaData().getSchemas()) schemas.add(schema.getName()); connectionDescription = new QConnectionDescription() { @Override public List<String> getSchemas() { return schemas; } }; } return connectionDescription; } @Override public QContext getContext() { return context; } public int getHoldability() throws SQLException { return getRawConnection().getHoldability(); } @Override public String getID() { return context.getName(); } public DatabaseMetaData getMetaData() throws SQLException { return getRawConnection().getMetaData(); } public int getNetworkTimeout() throws SQLException { return getRawConnection().getNetworkTimeout(); } private Connection getRawConnection() throws SQLException { return getCatalogConnection().getRawConnection(); } public String getSchema() throws SQLException { return getRawConnection().getSchema(); } public int getTransactionIsolation() throws SQLException { return getRawConnection().getTransactionIsolation(); } public Map<String, Class<?>> getTypeMap() throws SQLException { return getRawConnection().getTypeMap(); } public SQLWarning getWarnings() throws SQLException { return getRawConnection().getWarnings(); } @Override public boolean isClosed() throws SQLException { try { if (getRawConnection() == null) return true; } catch (FrameworkCoreUnexpectedConditionException e) { return true; } return false; } public boolean isReadOnly() throws SQLException { return getRawConnection().isReadOnly(); } public boolean isValid(int timeout) throws SQLException { return getRawConnection().isValid(timeout); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return getRawConnection().isWrapperFor(iface); } public String nativeSQL(String sql) throws SQLException { return getRawConnection().nativeSQL(sql); } public CallableStatement prepareCall(String sql) throws SQLException { return getRawConnection().prepareCall(sql); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return getRawConnection().prepareCall(sql, resultSetType, resultSetConcurrency); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return getRawConnection().prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } public BasePreparedStatementImpl prepareStatement(String sql) throws SQLException { return prepareStatement(sql, false); } @Override public BasePreparedStatementImpl prepareStatement(String sql, boolean native_) throws SQLException { return prepareStatement(sql, native_, false); } @Override public BasePreparedStatementImpl prepareStatement(String sql, boolean native_, boolean updatable) throws SQLException { if(!native_) sql = translate(sql); PreparedStatement sqlPreparedStatement = null; if(updatable) sqlPreparedStatement = getRawConnection().prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); else sqlPreparedStatement = getRawConnection().prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); BasePreparedStatementImpl statement = new BasePreparedStatementImpl(this, sqlPreparedStatement, native_); return statement; } public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return getRawConnection().prepareStatement(sql, autoGeneratedKeys); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return getRawConnection().prepareStatement(sql, resultSetType, resultSetConcurrency); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return getRawConnection().prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return getRawConnection().prepareStatement(sql, columnIndexes); } public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return getRawConnection().prepareStatement(sql, columnNames); } public void releaseSavepoint(Savepoint savepoint) throws SQLException { getRawConnection().releaseSavepoint(savepoint); } @Override public void rollback() throws SQLException { Connection connection = getRawConnection(); connection.rollback(); } public void rollback(Savepoint savepoint) throws SQLException { getRawConnection().rollback(savepoint); } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { Connection connection = getRawConnection(); connection.setAutoCommit(autoCommit); } @Override public void setCatalog(String catalog) throws SQLException { if(catalog != null && catalog.equals(virtualCatalog)) return; virtualCatalog = catalog; currentCatalogConnection = null; getRawConnection(); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { getRawConnection().setClientInfo(properties); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { try { getRawConnection().setClientInfo(name, value); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setHoldability(int holdability) throws SQLException { getRawConnection().setHoldability(holdability); } public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { getRawConnection().setNetworkTimeout(executor, milliseconds); } public void setReadOnly(boolean readOnly) throws SQLException { getRawConnection().setReadOnly(readOnly); } public Savepoint setSavepoint() throws SQLException { return getRawConnection().setSavepoint(); } public Savepoint setSavepoint(String name) throws SQLException { return getRawConnection().setSavepoint(name); } public void setSchema(String schema) throws SQLException { getRawConnection().setSchema(schema); } public void setTransactionIsolation(int level) throws SQLException { getRawConnection().setTransactionIsolation(level); } public void setTypeMap(Map<String, Class<?>> map) throws SQLException { getRawConnection().setTypeMap(map); } @Override public String translate(String sql) throws SQLException { try { SQLQueryParseResult query = queryParser.parseQuery(sql); BaseCatalogConnection connection = getCatalogConnection(); sql = connection.getQueryWriter().writeQuery(query.getQueryStatement()); } catch (Exception e) { throw new SQLException(e); } return sql; } public <T> T unwrap(Class<T> iface) throws SQLException { return getRawConnection().unwrap(iface); } }
epl-1.0
DevBoost/CodeComposers
Plugins/de.devboost.codecomposers/src/de/devboost/codecomposers/util/Pair.java
2045
/******************************************************************************* * Copyright (c) 2006-2016 * Software Technology Group, Dresden University of Technology * DevBoost GmbH, Dresden, Amtsgericht Dresden, HRB 34001 * * 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: * Software Technology Group - TU Dresden, Germany; * DevBoost GmbH - Dresden, Germany * - initial API and implementation ******************************************************************************/ package de.devboost.codecomposers.util; /** * A typed pair of objects. Two pairs are equal if both the left and the right object are equal. * * @param <T1> * the type of the first (left) object * @param <T2> * the type of the second (right) object */ public class Pair<T1, T2> { private final T1 left; private final T2 right; public Pair(T1 left, T2 right) { super(); this.left = left; this.right = right; } public T1 getLeft() { return left; } public T2 getRight() { return right; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((left == null) ? 0 : left.hashCode()); result = prime * result + ((right == null) ? 0 : right.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair<?, ?> other = (Pair<?, ?>) obj; if (left == null) { if (other.left != null) return false; } else if (!left.equals(other.left)) return false; if (right == null) { if (other.right != null) return false; } else if (!right.equals(other.right)) return false; return true; } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.core/src/org/eclipse/jdt/internal/core/nd/java/NdConstantLong.java
1677
/******************************************************************************* * Copyright (c) 2015, 2016 Google, Inc 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: * Stefan Xenos (Google) - Initial implementation *******************************************************************************/ package org.eclipse.jdt.internal.core.nd.java; import org.eclipse.jdt.internal.compiler.impl.Constant; import org.eclipse.jdt.internal.compiler.impl.LongConstant; import org.eclipse.jdt.internal.core.nd.Nd; import org.eclipse.jdt.internal.core.nd.field.FieldLong; import org.eclipse.jdt.internal.core.nd.field.StructDef; public final class NdConstantLong extends NdConstant { public static final FieldLong VALUE; @SuppressWarnings("hiding") public static StructDef<NdConstantLong> type; static { type = StructDef.create(NdConstantLong.class, NdConstant.type); VALUE = type.addLong(); type.done(); } public NdConstantLong(Nd nd, long address) { super(nd, address); } protected NdConstantLong(Nd nd) { super(nd); } public static NdConstantLong create(Nd nd, long value) { NdConstantLong result = new NdConstantLong(nd); result.setValue(value); return result; } public void setValue(long value) { VALUE.put(getNd(), this.address, value); } public long getValue() { return VALUE.get(getNd(), this.address); } @Override public Constant getConstant() { return LongConstant.fromValue(getValue()); } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/directtofield/singleattribute/SingleAttributeTestCases.java
2327
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle 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 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings.directtofield.singleattribute; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.persistence.testing.oxm.mappings.directtofield.singleattribute.xmlattribute.DirectToXMLAttributeTestCases; import org.eclipse.persistence.testing.oxm.mappings.directtofield.singleattribute.xmlattribute.DirectToXMLAttributeNullTestCases; import org.eclipse.persistence.testing.oxm.mappings.directtofield.singleattribute.xmlelement.DirectToXMLElementTestCases; import org.eclipse.persistence.testing.oxm.mappings.directtofield.singleattribute.xmlelement.EmptyElementEmptyStringTestCases; import org.eclipse.persistence.testing.oxm.mappings.directtofield.singleattribute.xmlelementwithwhitespace.DirectToXMLElementWithWhitespaceTestCases; public class SingleAttributeTestCases extends TestCase { public static Test suite() { TestSuite suite = new TestSuite("Single Attribute Test Cases"); suite.addTestSuite(DirectToXMLAttributeTestCases.class); suite.addTestSuite(DirectToXMLAttributeNullTestCases.class); suite.addTestSuite(DirectToXMLElementTestCases.class); suite.addTestSuite(DirectToXMLElementWithWhitespaceTestCases.class); suite.addTestSuite(EmptyElementEmptyStringTestCases.class); return suite; } public static void main(String[] args) { String[] arguments = {"-c", "org.eclipse.persistence.testing.oxm.mappings.directtofield.SingleAttributeTestCases"}; junit.textui.TestRunner.main(arguments); } }
epl-1.0
sonatype/nexus-public
plugins/nexus-repository-maven/src/main/java/org/sonatype/nexus/repository/maven/internal/MavenIndexPublisher.java
13477
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.repository.maven.internal; import java.io.BufferedInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.TreeSet; import org.sonatype.goodies.common.ComponentSupport; import org.sonatype.nexus.repository.Repository; import org.sonatype.nexus.repository.maven.MavenIndexFacet; import org.sonatype.nexus.repository.maven.MavenPath; import org.sonatype.nexus.repository.maven.MavenPathParser; import org.sonatype.nexus.repository.maven.internal.filter.DuplicateDetectionStrategy; import org.sonatype.nexus.repository.proxy.ProxyFacet; import org.sonatype.nexus.repository.types.ProxyType; import org.sonatype.nexus.repository.view.ContentTypes; import org.sonatype.nexus.repository.view.Context; import org.sonatype.nexus.repository.view.Request; import org.sonatype.nexus.repository.view.payloads.StreamPayload; import com.google.common.base.Predicate; import com.google.common.io.Closer; import org.apache.maven.index.reader.ChunkReader; import org.apache.maven.index.reader.IndexReader; import org.apache.maven.index.reader.IndexWriter; import org.apache.maven.index.reader.Record; import org.apache.maven.index.reader.Record.Type; import org.apache.maven.index.reader.RecordCompactor; import org.apache.maven.index.reader.RecordExpander; import org.apache.maven.index.reader.ResourceHandler; import org.apache.maven.index.reader.WritableResourceHandler; import org.joda.time.DateTime; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.transform; import static java.util.Collections.singletonList; import static org.apache.maven.index.reader.Utils.allGroups; import static org.apache.maven.index.reader.Utils.descriptor; import static org.apache.maven.index.reader.Utils.rootGroup; import static org.apache.maven.index.reader.Utils.rootGroups; import static org.sonatype.nexus.repository.http.HttpMethods.GET; import static org.sonatype.nexus.repository.maven.internal.Constants.INDEX_MAIN_CHUNK_FILE_PATH; import static org.sonatype.nexus.repository.maven.internal.Constants.INDEX_PROPERTY_FILE_PATH; /** * General logic for Maven index publishing. * * @since 3.26 */ public abstract class MavenIndexPublisher extends ComponentSupport { private static final String INDEX_PROPERTY_FILE = "/" + INDEX_PROPERTY_FILE_PATH; private static final String INDEX_MAIN_CHUNK_FILE = "/" + INDEX_MAIN_CHUNK_FILE_PATH; private static final RecordExpander RECORD_EXPANDER = new RecordExpander(); protected static final RecordCompactor RECORD_COMPACTOR = new RecordCompactor(); /** * Gets the MavenPathParser for the specified repository. */ protected abstract MavenPathParser getMavenPathParser(final Repository repository); /** * * Returns a ResourceHandler implementation. */ protected abstract WritableResourceHandler getResourceHandler(final Repository repository); /** * Deletes the asset at the specified path. */ protected abstract boolean delete(Repository repository, String path) throws IOException; /** * Deletes index files from given repository, returns {@code true} if there was index in repository. */ public boolean unpublishIndexFiles(final Repository repository) throws IOException { checkNotNull(repository); return delete(repository, INDEX_PROPERTY_FILE) && delete(repository, INDEX_MAIN_CHUNK_FILE); } /** * Get group records from the specified repositories. */ protected abstract Iterable<Iterable<Record>> getGroupRecords( final List<Repository> repositories, final Closer closer) throws IOException; protected Iterable<Record> getRecords(final Repository repository, final Closer closer) throws IOException { ResourceHandler resourceHandler = closer.register(getResourceHandler(repository)); IndexReader indexReader = closer.register(new IndexReader(null, resourceHandler)); ChunkReader chunkReader = closer.register(indexReader.iterator().next()); return filter(transform(chunkReader, RECORD_EXPANDER::apply), new RecordTypeFilter(Type.ARTIFACT_ADD)); } /** * Publishes MI index into {@code target}, sourced from repository's own CMA structures. */ public abstract void publishHostedIndex( final Repository repository, final DuplicateDetectionStrategy<Record> duplicateDetectionStrategy) throws IOException; /** * Publishes the Maven index into {@code groupRepository}, sourced from {@code leafMembers} repositories. */ public void publishGroupIndex( final Repository groupRepository, final List<Repository> leafMembers, final DuplicateDetectionStrategy<Record> strategy) throws IOException { List<String> withoutIndex = new ArrayList<>(); for (Iterator<Repository> ri = leafMembers.iterator(); ri.hasNext(); ) { Repository leafMemberRepository = ri.next(); if (leafMemberRepository.facet(MavenIndexFacet.class).lastPublished() == null) { withoutIndex.add(leafMemberRepository.getName()); ri.remove(); } } if (!withoutIndex.isEmpty()) { log.info("Following members of group {} have no index, will not participate in merged index: {}", groupRepository.getName(), withoutIndex ); } publishMergedIndex(groupRepository, leafMembers, strategy); } /** * Publishes the Maven index for the specified proxy repository. */ public void publishProxyIndex( final Repository repository, final Boolean cacheFallback, final DuplicateDetectionStrategy<Record> strategy) throws IOException { if (!prefetchIndexFiles(repository)) { if (Boolean.TRUE.equals(cacheFallback)) { log.debug("No remote index found... generating partial index from caches"); publishHostedIndex(repository, strategy); } else { log.debug("No remote index found... nothing to publish"); } } } /** * Publishes MI index into {@code target}, sourced from {@code repositories} repositories. */ private void publishMergedIndex( final Repository target, final List<Repository> repositories, final DuplicateDetectionStrategy<Record> duplicateDetectionStrategy) throws IOException { checkNotNull(target); checkNotNull(repositories); Closer closer = Closer.create(); try (WritableResourceHandler resourceHandler = getResourceHandler(target); IndexWriter indexWriter = new IndexWriter(resourceHandler, target.getName(), false)) { indexWriter.writeChunk( transform( decorate( filter(concat(getGroupRecords(repositories, closer)), duplicateDetectionStrategy), target.getName() ), RECORD_COMPACTOR::apply ).iterator() ); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } /** * Returns the {@link DateTime} when index of the given repository was last published. */ public DateTime lastPublished(final Repository repository) throws IOException { checkNotNull(repository); try (ResourceHandler resourceHandler = getResourceHandler(repository)) { try (IndexReader indexReader = new IndexReader(null, resourceHandler)) { return new DateTime(indexReader.getPublishedTimestamp().getTime()); } } catch (IllegalArgumentException e) { // thrown by IndexReader when no index found log.debug("No index found in {}", repository, e); return null; } } /** * Prefetch proxy repository index files, if possible. Returns {@code true} if successful. Accepts only maven proxy * types. Returns {@code true} if successfully prefetched files (they exist on remote and are locally cached). */ public boolean prefetchIndexFiles(final Repository repository) throws IOException { checkNotNull(repository); checkArgument(ProxyType.NAME.equals(repository.getType().getValue())); MavenPathParser mavenPathParser = getMavenPathParser(repository); return prefetch(repository, INDEX_PROPERTY_FILE, mavenPathParser) && prefetch(repository, INDEX_MAIN_CHUNK_FILE, mavenPathParser); } /** * Primes proxy cache with given path and return {@code true} if succeeds. Accepts only maven proxy type. */ private static boolean prefetch( final Repository repository, final String path, final MavenPathParser mavenPathParser) throws IOException { MavenPath mavenPath = mavenPathParser.parsePath(path); Request getRequest = new Request.Builder() .action(GET) .path(path) .build(); Context context = new Context(repository, getRequest); context.getAttributes().set(MavenPath.class, mavenPath); return repository.facet(ProxyFacet.class).get(context) != null; } /** * This method is copied from MI and Plexus related methods, to produce exactly same (possibly buggy) extensions out * of a file path, as MI client will attempt to "fix" those. */ protected static String pathExtension(final String path) { String filename = path.toLowerCase(Locale.ENGLISH); if (filename.endsWith("tar.gz")) { return "tar.gz"; } else if (filename.endsWith("tar.bz2")) { return "tar.bz2"; } int lastSep = filename.lastIndexOf('/'); int lastDot; if (lastSep < 0) { lastDot = filename.lastIndexOf('.'); } else { lastDot = filename.substring(lastSep + 1).lastIndexOf('.'); if (lastDot >= 0) { lastDot += lastSep + 1; } } if (lastDot >= 0 && lastDot > lastSep) { return filename.substring(lastDot + 1); } return null; } /** * Method creating decorated {@link Iterable} of records where "decorated" means that special records * like descriptor, rootGroups and allGroups are automatically added as first and two last records (where group * related ones are being calculated during iterating over returned iterable). */ protected static Iterable<Record> decorate( final Iterable<Record> iterable, final String repositoryName) { final TreeSet<String> allGroups = new TreeSet<>(); final TreeSet<String> rootGroups = new TreeSet<>(); return transform( concat( singletonList(descriptor(repositoryName)), iterable, singletonList(allGroups(allGroups)), // placeholder, will be recreated at the end with proper content singletonList(rootGroups(rootGroups)) // placeholder, will be recreated at the end with proper content ), (Record rec) -> { if (Type.DESCRIPTOR == rec.getType()) { return rec; } else if (Type.ALL_GROUPS == rec.getType()) { return allGroups(allGroups); } else if (Type.ROOT_GROUPS == rec.getType()) { return rootGroups(rootGroups); } else { final String groupId = rec.get(Record.GROUP_ID); if (groupId != null) { allGroups.add(groupId); rootGroups.add(rootGroup(groupId)); } return rec; } } ); } protected static String determineContentType(final String name) { String contentType; if (name.endsWith(".properties")) { contentType = ContentTypes.TEXT_PLAIN; } else if (name.endsWith(".gz")) { contentType = ContentTypes.APPLICATION_GZIP; } else { throw new IllegalArgumentException("Unsupported MI index resource:" + name); } return contentType; } protected static StreamPayload createStreamPayload(final Path path, final String contentType) throws IOException { return new StreamPayload(() -> new BufferedInputStream(Files.newInputStream(path)), Files.size(path), contentType ); } /** * {@link Predicate} that filters {@link Record} based on allowed {@link Type}. */ protected static class RecordTypeFilter implements Predicate<Record> { private final List<Type> allowedTypes; public RecordTypeFilter(final Type... allowedTypes) { this.allowedTypes = Arrays.asList(allowedTypes); } @Override public boolean apply(final Record input) { return allowedTypes.contains(input.getType()); } } }
epl-1.0
acleasby/sblim2
src/main/java/org/sblim/slp/internal/msg/ServiceRegistration.java
5302
/** * (C) Copyright IBM Corp. 2007, 2009 * * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT. * * You can obtain a current copy of the Eclipse Public License from * http://www.opensource.org/licenses/eclipse-1.0.php * * @author : Endre Bak, IBM, ebak@de.ibm.com * * Change History * Flag Date Prog Description *------------------------------------------------------------------------------- * 1804402 2007-09-28 ebak IPv6 ready SLP * 1892103 2008-02-12 ebak SLP improvements * 2003590 2008-06-30 blaschke-oss Change licensing from CPL to EPL * 2524131 2009-01-21 raman_arora Upgrade client to JDK 1.5 (Phase 1) * 2531371 2009-02-10 raman_arora Upgrade client to JDK 1.5 (Phase 2) */ package org.sblim.slp.internal.msg; import java.io.IOException; import java.util.List; import org.sblim.slp.ServiceLocationAttribute; import org.sblim.slp.ServiceLocationException; import org.sblim.slp.ServiceURL; /* * 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Service * Location header (function = SrvReg = 3) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | * <URL-Entry> \ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | length of * service type string | <service-type> \ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | length of * <scope-list> | <scope-list> \ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | length of * attr-list string | <attr-list> \ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |# of * AttrAuths |(if present) Attribute Authentication Blocks...\ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ /** * ServiceRegistration message * */ public class ServiceRegistration extends SLPMessage { private ServiceURL iServURL; private List<String> iScopeList; private List<ServiceLocationAttribute> iAttrList; private List<?> iAuthBlockList; /** * parse * * @param pHdr * @param pInStr * @return SLPMessage * @throws ServiceLocationException * @throws IOException */ public static SLPMessage parse(MsgHeader pHdr, SLPInputStream pInStr) throws ServiceLocationException, IOException { ServiceURL url = pInStr.readURL(); pInStr.readServiceType(); // FIXME reading dummy SrvType. Correct? return new ServiceRegistration(pHdr, url, pInStr.readStringList(), pInStr .readAttributeList(), pInStr.readAuthBlockList()); } /** * Ctor. * * @param pServURL * @param pScopeList * - list of scope strings * @param pAttrList * - list of ServiceLocationAttributes * @param pAuthBlockList */ public ServiceRegistration(ServiceURL pServURL, List<String> pScopeList, List<ServiceLocationAttribute> pAttrList, List<?> pAuthBlockList) { super(SRV_REG); init(pServURL, pScopeList, pAttrList, pAuthBlockList); } /** * Ctor. * * @param pLangTag * @param pServURL * @param pScopeList * - list of scope strings * @param pAttrList * - list of ServiceLocationAttributes * @param pAuthBlockList */ public ServiceRegistration(String pLangTag, ServiceURL pServURL, List<String> pScopeList, List<ServiceLocationAttribute> pAttrList, List<?> pAuthBlockList) { super(SRV_REG, pLangTag); init(pServURL, pScopeList, pAttrList, pAuthBlockList); } /** * Ctor. * * @param pHeader * @param pServURL * @param pScopeList * - list of scope strings * @param pAttrList * - list of ServiceLocationAttributes * @param pAuthBlockList */ public ServiceRegistration(MsgHeader pHeader, ServiceURL pServURL, List<String> pScopeList, List<ServiceLocationAttribute> pAttrList, List<?> pAuthBlockList) { super(pHeader); init(pServURL, pScopeList, pAttrList, pAuthBlockList); } /** * getServiceURL * * @return ServiceURL */ public ServiceURL getServiceURL() { return this.iServURL; } /** * getScopeList * * @return List */ public List<String> getScopeList() { return this.iScopeList; } /** * getAttributeList * * @return List */ public List<ServiceLocationAttribute> getAttributeList() { return this.iAttrList; } /** * @param pOption */ @Override protected boolean serializeBody(SLPOutputStream pOutStr, SerializeOption pOption) { return pOutStr.write(this.iServURL) && pOutStr.write(this.iServURL.getServiceType()) && pOutStr.writeStringList(this.iScopeList) && pOutStr.writeAttributeList(this.iAttrList) && pOutStr.writeAuthBlockList(this.iAuthBlockList); } private void init(ServiceURL pServURL, List<String> pScopeList, List<ServiceLocationAttribute> pAttrList, List<?> pAuthBlockList) { this.iServURL = pServURL; this.iScopeList = pScopeList; this.iAttrList = pAttrList; this.iAuthBlockList = pAuthBlockList; } }
epl-1.0
ControlSystemStudio/cs-studio
thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/core/src/main/java/org/hibernate/cfg/ExtendsQueueEntry.java
1806
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA * */ package org.hibernate.cfg; import org.dom4j.Document; /** * Represents a mapping queued for delayed processing to await * processing of an extends entity upon which it depends. * * @author Steve Ebersole */ public class ExtendsQueueEntry { private final String explicitName; private final String mappingPackage; private final Document document; public ExtendsQueueEntry(String explicitName, String mappingPackage, Document document) { this.explicitName = explicitName; this.mappingPackage = mappingPackage; this.document = document; } public String getExplicitName() { return explicitName; } public String getMappingPackage() { return mappingPackage; } public Document getDocument() { return document; } }
epl-1.0
asupdev/asup
org.asup.os.type.jobd.base/src/org/asup/os/type/jobd/base/api/JobDescriptionDisplayer.java
3923
/** * Copyright (c) 2012, 2014 Sme.UP 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: * Mattia Rocchi - Initial API and implementation */ package org.asup.os.type.jobd.base.api; import java.io.IOException; import java.util.List; import javax.inject.Inject; import org.asup.fw.core.annotation.Supported; import org.asup.il.data.QCharacter; import org.asup.il.data.QDataStructWrapper; import org.asup.il.data.QEnum; import org.asup.il.data.annotation.DataDef; import org.asup.il.data.annotation.Entry; import org.asup.il.data.annotation.Program; import org.asup.il.data.annotation.Special; import org.asup.os.core.OperatingSystemRuntimeException; import org.asup.os.core.Scope; import org.asup.os.core.jobs.QJob; import org.asup.os.core.jobs.QJobLogManager; import org.asup.os.core.output.QObjectWriter; import org.asup.os.core.output.QOutputManager; import org.asup.os.core.resources.QResourceReader; import org.asup.os.type.QOperatingSystemTypeFactory; import org.asup.os.type.QTypedReference; import org.asup.os.type.jobd.QJobDescription; import org.asup.os.type.jobd.QJobDescriptionManager; import org.asup.os.type.lib.QLibrary; @Supported @Program(name = "QWDCDSG") public class JobDescriptionDisplayer { @Inject private QOutputManager outputManager; @Inject private QJobLogManager jobLogManager; @Inject private QJob job; @Inject private QJobDescriptionManager jobDescriptionManager; public @Entry void main( @Supported @DataDef(qualified = true) JobDescription jobDescription, @Supported @DataDef(length = 1) QEnum<OutputEnum, QCharacter> output) { QObjectWriter objectWriter = null; switch (output.asEnum()) { case PRINT: objectWriter = outputManager.getObjectWriter(job, output.getSpecialName()); break; case TERM_STAR: objectWriter = outputManager.getObjectWriter(job, output.asData().trimR()); break; } objectWriter.initialize(); // if (jobDescription.name.trimR().equals("*CURRENT")) { // writeLibraries(objectWriter, job.getLibraries()); // objectWriter.flush(); // return; // } QResourceReader<QJobDescription> resourceReader = null; String library = null; switch (jobDescription.library.asEnum()) { case LIBL: resourceReader = jobDescriptionManager.getResourceReader(job, Scope.LIBRARY_LIST); break; case CURLIB: resourceReader = jobDescriptionManager.getResourceReader(job, Scope.CURRENT_LIBRARY); break; case OTHER: library = jobDescription.library.asData().trimR(); resourceReader = jobDescriptionManager.getResourceReader(job, library); break; } QJobDescription qJobDescription = resourceReader.lookup(jobDescription.name.trimR()); if (qJobDescription == null) throw new OperatingSystemRuntimeException("Job description not found: " + jobDescription); writeLibraries(objectWriter, qJobDescription.getLibraries()); objectWriter.flush(); } private void writeLibraries(QObjectWriter objectWriter, List<String> libraries) { for (String library : libraries) { QTypedReference<QLibrary> qLibrary = QOperatingSystemTypeFactory.eINSTANCE.createTypedReference(); qLibrary.setName(library); try { objectWriter.write(qLibrary); } catch (IOException e) { jobLogManager.error(job, e.getMessage()); } } } public static class JobDescription extends QDataStructWrapper { private static final long serialVersionUID = 1L; @DataDef(length = 10) public QCharacter name; @DataDef(length = 10, value = "*LIBL") public QEnum<LibraryEnum, QCharacter> library; public static enum LibraryEnum { LIBL, CURLIB, OTHER } } public static enum OutputEnum { @Special(value = "*") TERM_STAR, @Special(value = "L") PRINT } }
epl-1.0
terry1013/Alesia
delete/gui/jtreetable/MyDataNode.java
1435
/******************************************************************************* * Copyright (C) 2017 terry. * 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: * terry - initial API and implementation ******************************************************************************/ package delete.gui.jtreetable; import java.util.*; public class MyDataNode { private String name; private String capital; private Date declared; private Integer area; private List<MyDataNode> children; public MyDataNode(String name, String capital, Date declared, Integer area, List<MyDataNode> children) { this.name = name; this.capital = capital; this.declared = declared; this.area = area; this.children = children; if (this.children == null) { this.children = Collections.emptyList(); } } public String getName() { return name; } public String getCapital() { return capital; } public Date getDeclared() { return declared; } public Integer getArea() { return area; } public List<MyDataNode> getChildren() { return children; } /** * Knotentext vom JTree. */ public String toString() { return name; } }
epl-1.0
oscarservice/oscar-old
src/main/java/org/oscarehr/common/model/ServiceSpecialists.java
2018
/** * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada */ package org.oscarehr.common.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @SuppressWarnings("serial") @Entity @Table(name = "serviceSpecialists") public class ServiceSpecialists extends AbstractModel<Integer> implements Serializable { private Integer serviceId=null; private Integer specId=null; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; public ServiceSpecialists() { } @Override public Integer getId() { return id; } public Integer getServiceId() { return serviceId; } public void setServiceId(Integer serviceId) { this.serviceId = serviceId; } public Integer getSpecId() { return specId; } public void setSpecId(Integer specId) { this.specId = specId; } }
gpl-2.0
rex-xxx/mt6572_x201
mediatek/packages/apps/MediatekDM/src/com/mediatek/MediatekDM/conn/DmDataConnection.java
18119
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * 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.mediatek.MediatekDM.conn; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.os.Bundle; import android.os.Handler; import android.util.Log; import com.mediatek.MediatekDM.DmApplication; import com.mediatek.MediatekDM.DmClient; import com.mediatek.MediatekDM.DmCommonFunction; import com.mediatek.MediatekDM.DmConst; import com.mediatek.MediatekDM.DmConst.TAG; import com.mediatek.MediatekDM.DmService; import com.mediatek.MediatekDM.data.IDmPersistentValues; import com.mediatek.MediatekDM.ext.MTKConnectivity; import com.mediatek.MediatekDM.ext.MTKOptions; import com.mediatek.MediatekDM.ext.MTKPhone; import com.mediatek.MediatekDM.option.Options; import com.mediatek.MediatekDM.session.SessionEventQueue; import com.mediatek.MediatekDM.util.ScreenLock; import junit.framework.Assert; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; public class DmDataConnection { public static final int GEMINI_SIM_1 = 0; public static final int GEMINI_SIM_2 = 1; private ConnectivityReceiver mConnectivityReceiver = null; private ConnectivityManager mConnMgr; private Context mContext; private DmDatabase mDmDatabase; private int simId = -1; private static Handler clientHandler = null; private static Handler serviceHandler = null; private static DmDataConnection instance = null; // extended message handler private Handler userMsgHandler = null; public void setUserHandler(Handler hd) { userMsgHandler = hd; } private DmDataConnection(Context context) { mContext = context; mConnMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); // register the CONNECTIVITY_ACTION receiver mConnectivityReceiver = new ConnectivityReceiver(); // init DmDatabase mDmDatabase = new DmDatabase(context); if (serviceHandler == null) { if (DmService.getServiceInstance() != null) { serviceHandler = DmService.getServiceInstance().mHandler; } } IntentFilter intent = new IntentFilter(); intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intent.addAction(DmConst.IntentAction.NET_DETECT_TIMEOUT); mContext.registerReceiver(mConnectivityReceiver, intent); } public static DmDataConnection getInstance(Context context) { if (instance == null) { instance = new DmDataConnection(context); } return instance; } public int startDmDataConnectivity() throws IOException { Assert.assertFalse("startDmDataConnectivity MUST NOT be called in direct internet conn.", Options.UseDirectInternet); // if gemini is set int result = -1; simId = DmCommonFunction.getRegisteredSimId(mContext); if (simId == -1) { Log.e(TAG.Connection, "Get Register SIM ID error in start data connection"); return result; } // for gemini if (MTKOptions.MTK_GEMINI_SUPPORT == true) { // begin for connectity gemini if (mDmDatabase.DmApnReady(simId) == false) { Log.e(TAG.Connection, "Dm apn table is not ready!"); return result; } result = beginDmDataConnectivityGemini(simId); } else { if (mDmDatabase.DmApnReady(GEMINI_SIM_1) == false) { Log.e(TAG.Connection, "Dm apn table is not ready!"); return result; } result = beginDmDataConnectivity(); } if (result == MTKPhone.APN_TYPE_NOT_AVAILABLE || result == MTKPhone.APN_REQUEST_FAILED) { Log.e(TAG.Connection, "start Dmdate Connectivity error"); } // for test begin if (result == MTKPhone.APN_ALREADY_ACTIVE) { Log.i(TAG.Connection, "DataConnection is already exist and send MSG_WAP_CONNECTION_SUCCESS to client"); notifyHandlers(IDmPersistentValues.MSG_WAP_CONNECTION_SUCCESS); } // for test end return result; } public void stopDmDataConnectivity() { Assert.assertFalse("stopDmDataConnectivity MUST NOT be called in direct internet conn.", Options.UseDirectInternet); Log.v(TAG.Connection, "stopDmDataConnectivity"); try { simId = DmCommonFunction.getRegisteredSimId(mContext); if (simId == -1) { Log.e(TAG.Connection, "Get Register SIM ID error in stop data connection"); return; } if (MTKOptions.MTK_GEMINI_SUPPORT == true) { // begin for connectity gemini endDmConnectivityGemini(simId); } else { endDmDataConnectivity(); } ScreenLock.releaseWakeLock(mContext); ScreenLock.enableKeyguard(mContext); } finally { Log.v(TAG.Connection, "stopUsingNetworkFeature end"); } } public class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (context == null || intent == null) { return; } if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { Log.d(TAG.Connection, "ConnectivityReceiver Receive android.net.conn.CONNECTIVITY_CHANGE"); Bundle bundle = intent.getExtras(); if (bundle != null) { NetworkInfo info = (NetworkInfo) bundle .get(ConnectivityManager.EXTRA_NETWORK_INFO); if (info == null) { Log.e(TAG.Connection, "[dm-conn]->Get NetworkInfo error"); return; } simId = DmCommonFunction.getRegisteredSimId(mContext); if (simId == -1) { Log.e(TAG.Connection, "[dm-conn]->Get Register SIM ID error in connetivity receiver"); return; } int networkSimId = MTKConnectivity.getSimId(info); int intentSimId = intent.getIntExtra(MTKConnectivity.EXTRA_SIM_ID, 0); int networkType = info.getType(); if (intentSimId == simId && networkType == MTKConnectivity.TYPE_MOBILE_DM) { Log.i(TAG.Connection, "[dm-conn]->type == " + info.getTypeName() + "(" + networkType + ")"); Log.i(TAG.Connection, "[dm-conn]->intent_sim_Id == " + intentSimId); Log.i(TAG.Connection, "[dm-conn]->network_sim_Id == " + networkSimId); Log.i(TAG.Connection, "[dm-conn]->registered_sim_Id == " + simId); State state = info.getState(); if (state == State.CONNECTED) { Log.i(TAG.Connection, "[dm-conn]->state == CONNECTED"); try { ensureRouteToHost(); // store CONNECTED event. DmApplication.getInstance().queueEvent( SessionEventQueue.EVENT_CONN_CONNECTED); Log.i(TAG.Connection, ">>sending msg WAP_CONN_SUCCESS"); notifyHandlers(IDmPersistentValues.MSG_WAP_CONNECTION_SUCCESS); } catch (Exception ex) { Log.e(TAG.Connection, "[dm-conn]->ensureRouteToHost() failed:", ex); } } else if (state == State.CONNECTING) { Log.i(TAG.Connection, "[dm-conn]->state == CONNECTING"); return; } else if (state == State.DISCONNECTED) { Log.i(TAG.Connection, "[dm-conn]->state == DISCONNECTED"); // store DISCONNECTED event. DmApplication.getInstance().queueEvent( SessionEventQueue.EVENT_CONN_DISCONNECTED); return; } } } } else if (intent.getAction().equalsIgnoreCase(DmConst.IntentAction.NET_DETECT_TIMEOUT)) { Log.i(TAG.Connection, "[dm-conn]->action == com.mediatek.MediatekDM.NETDETECTTIMEOUT"); Log.i(TAG.Connection, ">>>sending msg WAP_CONN_TIMEOUT"); notifyHandlers(IDmPersistentValues.MSG_WAP_CONNECTION_TIMEOUT); } } } private int beginDmDataConnectivity() throws IOException { int result = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, MTKPhone.FEATURE_ENABLE_DM); Log.i(TAG.Connection, "[dm-conn]->startUsingNetworkFeature: result=" + result); if (result == MTKPhone.APN_ALREADY_ACTIVE) { Log.i(TAG.Connection, "[dm-conn]->APN_ALREADY_ACTIVE"); ScreenLock.releaseWakeLock(mContext); ScreenLock.acquirePartialWakelock(mContext); ensureRouteToHost(); } else if (result == MTKPhone.APN_REQUEST_STARTED) { Log.i(TAG.Connection, "[dm-conn]->APN_REQUEST_STARTED, waiting for intent."); ScreenLock.releaseWakeLock(mContext); ScreenLock.acquirePartialWakelock(mContext); // mContext.registerReceiver(mConnectivityReceiver, new // IntentFilter( // ConnectivityManager.CONNECTIVITY_ACTION)); // mTelephonyManager=(TelephonyManager) // mContext.getSystemService(Service.TELEPHONY_SERVICE); } else if (result == MTKPhone.APN_REQUEST_FAILED) { Log.e(TAG.Connection, "[dm-conn]->APN_REQUEST_FAILED"); } else { throw new IOException("[dm-conn]:Cannot establish DM data connectivity"); } return result; } private void endDmDataConnectivity() { try { Log.v(TAG.Connection, "endDmDataConnectivity"); if (mConnMgr != null) { mConnMgr.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, MTKPhone.FEATURE_ENABLE_DM); } } finally { Log.v(TAG.Connection, "stopUsingNetworkFeature end"); } } private int beginDmDataConnectivityGemini(int simId) throws IOException { int result = MTKConnectivity.startUsingNetworkFeatureGemini(mConnMgr, ConnectivityManager.TYPE_MOBILE, MTKPhone.FEATURE_ENABLE_DM, simId); Log.i(TAG.Connection, "startDmDataConnectivityGemini: simId = " + simId + "\t result=" + result); if (result == MTKPhone.APN_ALREADY_ACTIVE) { Log.w(TAG.Connection, "The data connection is already exist, go ahead"); ScreenLock.releaseWakeLock(mContext); ScreenLock.acquirePartialWakelock(mContext); ensureRouteToHost(); } else if (result == MTKPhone.APN_REQUEST_STARTED) { Log.w(TAG.Connection, "The new data connection is started register and waiting for the intent"); ScreenLock.releaseWakeLock(mContext); ScreenLock.acquirePartialWakelock(mContext); // mContext.registerReceiver(mConnectivityReceiver, new // IntentFilter( // ConnectivityManager.CONNECTIVITY_ACTION)); // mContext.registerReceiver(mConnectivityReceiver, new // IntentFilter(DmConst.IntentAction.NET_DETECT_TIMEOUT)); // mTelephonyManager=(TelephonyManager) // mContext.getSystemService(Service.TELEPHONY_SERVICE); } else if (result == MTKPhone.APN_REQUEST_FAILED) { Log.e(TAG.Connection, "startUsingnetworkfeature failed"); } else { throw new IOException("Cannot establish Dm Data connectivity"); } return result; } // add for gemini private void endDmConnectivityGemini(int simId) { try { Log.i(TAG.Connection, "endDmDataConnectivityGemini: simId = " + simId); if (mConnMgr != null) { MTKConnectivity.stopUsingNetworkFeatureGemini(mConnMgr, ConnectivityManager.TYPE_MOBILE, MTKPhone.FEATURE_ENABLE_DM, simId); } } finally { Log.v(TAG.Connection, "stopUsingNetworkFeature end"); } } private void ensureRouteToHost() throws IOException { Log.v(TAG.Connection, "Begin ensureRouteToHost"); // call getApnInfoFromSettings String proxyAddr = mDmDatabase.getApnProxyFromSettings(); int inetAddr = lookupHost(proxyAddr); Log.i(TAG.Connection, "inetAddr = " + inetAddr); // get the addr form setting if (!mConnMgr.requestRouteToHost(MTKConnectivity.TYPE_MOBILE_DM, inetAddr)) { throw new IOException("Cannot establish route to proxy " + inetAddr); } } public static int lookupHost(String hostname) { InetAddress inetAddress; try { inetAddress = InetAddress.getByName(hostname); } catch (UnknownHostException e) { return -1; } byte[] addrBytes; int addr; addrBytes = inetAddress.getAddress(); addr = ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8) | (addrBytes[0] & 0xff); return addr; } private void notifyHandlers(int msgCode) { clientHandler = null; if (DmClient.getMdmClientInstance() != null) { clientHandler = DmClient.getMdmClientInstance().apnConnHandler; } // } if (serviceHandler == null) { if (DmService.getServiceInstance() != null) { serviceHandler = DmService.getServiceInstance().mHandler; } } if (clientHandler != null) { clientHandler.sendMessage(clientHandler.obtainMessage(msgCode)); } if (serviceHandler != null) { serviceHandler.sendMessage(serviceHandler.obtainMessage(msgCode)); } // extended message handler if (userMsgHandler != null) { userMsgHandler.sendMessage(userMsgHandler.obtainMessage(msgCode)); } } private void destroyDataConnection() { mContext.unregisterReceiver(mConnectivityReceiver); mContext = null; } public static void destroyInstance() { instance.destroyDataConnection(); serviceHandler = null; instance = null; } }
gpl-2.0
bayasist/vbox
out/linux.amd64/debug/obj/vboxjxpcom-gen/jxpcomgen/java/glue/IEventSourceChangedEvent.java
2545
/* * Copyright (C) 2010-2014 Oracle Corporation * * This file is part of the VirtualBox SDK, as available from * http://www.virtualbox.org. 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, in version 2.1 * as it comes in the "COPYING.LIB" file of the VirtualBox SDK distribution. * 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. * * IEventSourceChangedEvent.java * * DO NOT EDIT! This is a generated file. * Generated from: src/VBox/Main/idl/VirtualBox.xidl (VirtualBox's interface definitions in XML) * Generator: src/VBox/Main/glue/glue-java.xsl */ package org.virtualbox_4_3; import org.virtualbox_4_3.xpcom.*; import org.mozilla.interfaces.*; import java.util.List; public class IEventSourceChangedEvent extends IEvent { public IEventSourceChangedEvent(org.mozilla.interfaces.IEventSourceChangedEvent wrapped) { super(wrapped); } public org.mozilla.interfaces.IEventSourceChangedEvent getTypedWrapped() { return (org.mozilla.interfaces.IEventSourceChangedEvent) getWrapped(); } public org.virtualbox_4_3.IEventListener getListener() { try { org.mozilla.interfaces.IEventListener retVal = getTypedWrapped().getListener(); return (retVal != null) ? new org.virtualbox_4_3.IEventListener(retVal) : null; } catch (org.mozilla.xpcom.XPCOMException e) { throw new VBoxException(e.getMessage(), e); } } public Boolean getAdd() { try { boolean retVal = getTypedWrapped().getAdd(); return retVal; } catch (org.mozilla.xpcom.XPCOMException e) { throw new VBoxException(e.getMessage(), e); } } public static IEventSourceChangedEvent queryInterface(IUnknown obj) { nsISupports nsobj = obj != null ? (nsISupports)obj.getWrapped() : null; if (nsobj == null) return null; org.mozilla.interfaces.IEventSourceChangedEvent qiobj = Helper.queryInterface(nsobj, "{e7932cb8-f6d4-4ab6-9cbf-558eb8959a6a}", org.mozilla.interfaces.IEventSourceChangedEvent.class); return qiobj == null ? null : new IEventSourceChangedEvent(qiobj); } }
gpl-2.0
dlitz/resin
modules/resin/src/com/caucho/sql/PreparedStatementCacheItem.java
3875
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * Free SoftwareFoundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.sql; import com.caucho.util.CacheListener; import java.lang.ref.SoftReference; import java.sql.PreparedStatement; import java.util.logging.Level; import java.util.logging.Logger; /** * Represtents a prepared statement. */ class PreparedStatementCacheItem implements CacheListener { private final static Logger log = Logger.getLogger(PreparedStatementCacheItem.class.getName()); private PreparedStatementKey _key; private SoftReference<PreparedStatement> _pStmtRef; private ManagedConnectionImpl _mConn; private boolean _isActive; private boolean _isRemoved; PreparedStatementCacheItem(PreparedStatementKey key, PreparedStatement pStmt, ManagedConnectionImpl mConn) { if (pStmt == null) throw new NullPointerException(); _key = key; _pStmtRef = new SoftReference<PreparedStatement>(pStmt); _mConn = mConn; } /** * Activates the cache item. */ UserPreparedStatement toActive(UserConnection conn) { SoftReference<PreparedStatement> ref = _pStmtRef; if (ref == null) return null; PreparedStatement pStmt = ref.get(); if (pStmt == null) { _mConn.remove(_key); return null; } synchronized (this) { if (_isActive) return null; _isActive = true; } return new UserPreparedStatement(conn, pStmt, this); } void toIdle() { boolean doClose = false; synchronized (this) { if (_isRemoved) { _isRemoved = true; doClose = _isActive; } _isActive = false; } if (doClose) { try { PreparedStatement pStmt = _pStmtRef.get(); _pStmtRef = null; if (pStmt != null) pStmt.close(); } catch (Throwable e) { log.log(Level.FINE, e.toString(), e); } } } /** * Returns true for a removed item. */ boolean isRemoved() { return _isRemoved; } /** * Called when removed from the cache. */ public void removeEvent() { boolean doClose = false; synchronized (this) { if (! _isRemoved) { _isRemoved = true; doClose = ! _isActive; } } if (doClose) { try { PreparedStatement pStmt = _pStmtRef.get(); _pStmtRef = null; if (pStmt != null) pStmt.close(); } catch (Throwable e) { log.log(Level.FINE, e.toString(), e); } } } void destroy() { _isRemoved = true; SoftReference<PreparedStatement> ref = _pStmtRef; _pStmtRef = null; if (ref != null) { PreparedStatement pStmt = ref.get(); if (pStmt != null) { try { pStmt.close(); } catch (Throwable e) { log.log(Level.FINE, e.toString(), e); } } } } }
gpl-2.0
lostdj/Jaklin-OpenJFX
modules/graphics/src/main/java/com/sun/glass/ui/View.java
47159
/* * Copyright (c) 2010, 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.glass.ui; import com.sun.glass.events.MouseEvent; import com.sun.glass.events.ViewEvent; import java.lang.annotation.Native; import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; public abstract class View { //mymod @Native public final static int GESTURE_NO_VALUE = Integer.MAX_VALUE; @Native public final static double GESTURE_NO_DOUBLE_VALUE = Double.NaN; @Native public final static byte IME_ATTR_INPUT = 0x00; @Native public final static byte IME_ATTR_TARGET_CONVERTED = 0x01; @Native public final static byte IME_ATTR_CONVERTED = 0x02; @Native public final static byte IME_ATTR_TARGET_NOTCONVERTED = 0x03; @Native public final static byte IME_ATTR_INPUT_ERROR = 0x04; final static boolean accessible = AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> { String force = System.getProperty("glass.accessible.force"); if (force != null) return Boolean.parseBoolean(force); /* By default accessibility is enabled for Mac 10.9 or greater and Windows 7 or greater. */ try { String platform = Platform.determinePlatform(); String major = System.getProperty("os.version").replaceFirst("(\\d+)\\.\\d+.*", "$1"); String minor = System.getProperty("os.version").replaceFirst("\\d+\\.(\\d+).*", "$1"); int v = Integer.parseInt(major) * 100 + Integer.parseInt(minor); return (platform.equals(Platform.MAC) && v >= 1009) || (platform.equals(Platform.WINDOWS) && v >= 601); } catch (Exception e) { return false; } }); public static class EventHandler { public void handleViewEvent(View view, long time, int type) { } public void handleKeyEvent(View view, long time, int action, int keyCode, char[] keyChars, int modifiers) { } public void handleMenuEvent(View view, int x, int y, int xAbs, int yAbs, boolean isKeyboardTrigger) { } public void handleMouseEvent(View view, long time, int type, int button, int x, int y, int xAbs, int yAbs, int modifiers, boolean isPopupTrigger, boolean isSynthesized) { } /** * A Scroll event handler. * * The lines argument: * &gt; 0 - a number of lines to scroll per each 1.0 of deltaY scroll amount * == 0 - the scroll amount is in pixel units * &lt; 0 - the scrolling should be performed by pages. Each 1.0 of scroll amount * corresponds to exactly one page of scrollable content. * * Similarly, the chars argument specifies the number of characters * to scroll per 1.0 of the deltaX scrolling amount. * If the parameter is zero, the deltaX represents the number of * pixels to scroll. * * The defaultLines and defaultChars arguments contain the system-default * values of lines and chars. This can be used by the app to compute * the ratio of current settings and default settings and adjust the * pixel values accordingly. * * Multiplers are used when an app receives a non-zero unit values (i.e. * either the lines or chars are not zeroes), but wants instead get delta * values in pixels. In this case the app needs to multiply the deltas * on the provided multiplier parameter. */ public void handleScrollEvent(View view, long time, int x, int y, int xAbs, int yAbs, double deltaX, double deltaY, int modifiers, int lines, int chars, int defaultLines, int defaultChars, double xMultiplier, double yMultiplier) { } public void handleInputMethodEvent(long time, String text, int[] clauseBoundary, int[] attrBoundary, byte[] attrValue, int commitCount, int cursorPos) { } public double[] getInputMethodCandidatePos(int offset) { return null; } public void handleDragStart(View view, int button, int x, int y, int xAbs, int yAbs, ClipboardAssistance dropSourceAssistant) { } public void handleDragEnd(View view, int performedAction) { } public int handleDragEnter(View view, int x, int y, int xAbs, int yAbs, int recommendedDropAction, ClipboardAssistance dropTargetAssistant) { return recommendedDropAction; } public int handleDragOver(View view, int x, int y, int xAbs, int yAbs, int recommendedDropAction, ClipboardAssistance dropTargetAssistant) { return recommendedDropAction; } public void handleDragLeave(View view, ClipboardAssistance dropTargetAssistant) { } public int handleDragDrop(View view, int x, int y, int xAbs, int yAbs, int recommendedDropAction, ClipboardAssistance dropTargetAssistant) { return Clipboard.ACTION_NONE; } /** * Touch event handler. Called when touch event occures. * Always followed with one ore more #handleNextTouchEvent() calls * and a single #handleEndTouchEvent() call. * * @param isDirect if event reported by direct or indirect touch device; * touch screen is an example of direct touch device and * touch pad is an example of indirect one * @param touchEventCount indicates number of #handleNextTouchEvent() calls * that will follow this method call. */ public void handleBeginTouchEvent(View view, long time, int modifiers, boolean isDirect, int touchEventCount) { } /** * Touch event handler. Called for every touch point in some touch event. * * If the touch event has been emitted with direct touch device * (touch screen) then x and y arguments designate touch point position * relative to the top-left corner of the view and xAbs and yAbs * arguments designate position relative to the top-left corner of the * screen. Both positions are measured in pixels. * * If the touch event has been emitted with indirect touch device * (touch pad) then x and y arguments designate normalized touch point * position. It is measured between (0,0) and (10000,10000), where (0,0) * is the top-left and (10000,10000) is the bottom-right position on * the indirect touch input device (touch pad). xAbs and yAbs * arguments are equal values of x and y arguments respectively. * * @see #handleBeginTouchEvent(com.sun.glass.ui.View, long, int, boolean, int) * * @param type touch event type. One of constants declared in * #com.sun.glass.events.TouchEvent class. * @param touchId touch point identifier; * every touch point has its own unique identifier; * the identifier remains the same across multiple calls of * #handleNextTouchEvent method for the same touch point until * it is not released. * @param x the X coordinate of the touch point; * @param y the Y coordinate of the touch point; * @param xAbs absolute X coordinate of the touch point; * @param yAbs absolute Y coordinate of the touch point; */ public void handleNextTouchEvent(View view, long time, int type, long touchId, int x, int y, int xAbs, int yAbs) { } /** * Touch event handler. Called to notify that all #handleNextTouchEvent * methods corresponding to some touch event have been called already. * * @see #handleBeginTouchEvent(com.sun.glass.ui.View, long, int, boolean, int) */ public void handleEndTouchEvent(View view, long time) { } /** * Scroll gesture handler. * * If underlying system supports coordinates for gestures then x and y * arguments designate gesture position relative to the top-left * corner of the view and xAbs and yAbs designate gesture position * relative to the top-left corner of the screen. For gestures emitted * from direct touch input device (touch screen) positions are measured * in pixels. For gestures emitted from indirect touch input device * (touch pad) positions are normalized. For details of normalized * touch input position see #handleBeginTouchEvent method. * * If underlying system doesn't support coordinates for gestures then * x and y arguments designate mouse position relative to the top-left * corner of the view and xAbs and yAbs designate mouse position * relative to the top-left corner of the screen. Positions are measured * in pixels. * * If gesture handler is called to notify end of gesture, i.e. value of * type argument is equal to * com.sun.glass.events.GestureEvent.GESTURE_FINISHED constant then * x, y, xAbs and yAbs arguments may be set to View.GESTURE_NO_VALUE * constant indicating no data is available. This is implementation * specific behavior. * * Values of dx and dy arguments are always 0.0 if type argument * is set to com.sun.glass.events.GestureEvent.GESTURE_FINISHED * constant. * * For description of isDirect argument see #handleBeginTouchEvent * method. * * @param type gesture state. One of constants declared in * #com.sun.glass.events.GestureEvent class. * @param isInertia if gesture is caused by inertia. * @param touchCount number of touch points at * the moment of gesture execution; it is always set to * View.GESTURE_NO_VALUE constant if value of type argument is * set to com.sun.glass.events.GestureEvent.GESTURE_FINISHED * constant * @param x the X coordinate of the gesture; * @param y the Y coordinate of the gesture; * @param xAbs absolute X coordinate of the gesture; * @param yAbs absolute Y coordinate of the gesture; * @param dx horizontal scroll delta. Positive if scrolling from * left to right, non-positive otherwise * @param dy vertical scroll delta. Positive if scrolling from * up to down, non-positive otherwise * @param totaldx total horizontal scroll calculated from all * sequential scroll gestures, i.e. sum of all 'dx' values from * previous sequential calls to this method * @param totaldy total vertical scroll calculated from all * sequential scroll gestures, i.e. sum of all 'dy' values from * previous sequential calls to this method * @param multiplierX the X multiplier * @param multiplierY the Y multiplier * * Multiplers are used when an app receives a non-zero unit values (i.e. * either the lines or chars are not zeroes), but wants instead get delta * values in pixels. In this case the app needs to multiply the deltas * on the provided multiplier parameter. */ public void handleScrollGestureEvent(View view, long time, int type, int modifiers, boolean isDirect, boolean isInertia, int touchCount, int x, int y, int xAbs, int yAbs, double dx, double dy, double totaldx, double totaldy, double multiplierX, double multiplierY) { } /** * Zoom gesture handler. * * For description of isDirect argument see #handleBeginTouchEvent * method. * * For description of isInertia argument see #handleScrollGestureEvent * method. * * For description of type, x,y, xAbs and yAbs arguments * see #handleBeginTouchEvent method. * * If underlying system doesn't support measurement of expansion value * in zoom gestures then expansion and totalexpansion arguments are * always set to View.GESTURE_NO_DOUBLE_VALUE. * * If type argument is set to * com.sun.glass.events.GestureEvent.GESTURE_FINISHED constant value of * scale argument is always set to View.GESTURE_NO_DOUBLE_VALUE constant * and expansion argument is always 0.0. * * @param scale current zoom delta; the value is multiplicative * and not additive. * @param expansion current expansion delta. Measured in pixels on * direct touch input devices and normalized values on indirect * touch input devices. See #handleBeginTouchEvent for * description of units of indirect touch input devices. * @param totalscale total zoom calculated from all * sequential zoom gestures, i.e. sum of all 'scale' values from * previous sequential calls to this method * @param totalexpansion total expansion calculated from all * sequential zoom gestures, i.e. sum of all 'expansion' values * from previous sequential calls of this method */ public void handleZoomGestureEvent(View view, long time, int type, int modifiers, boolean isDirect, boolean isInertia, int x, int y, int xAbs, int yAbs, double scale, double expansion, double totalscale, double totalexpansion) { } /** * Rotation gesture handler. * * For description of isDirect argument see #handleBeginTouchEvent * method. * * For description of isInertia argument see #handleScrollGestureEvent * method. * * For description of type, x,y, xAbs and yAbs arguments * see #handleBeginTouchEvent method. * * @param dangle current angle delta in degrees. Positive for clockwise * rotation * @param totalangle total angle calculated from all * sequential rotation gestures, i.e. sum of all 'dangle' values * from previous sequential calls of this method */ public void handleRotateGestureEvent(View view, long time, int type, int modifiers, boolean isDirect, boolean isInertia, int x, int y, int xAbs, int yAbs, double dangle, double totalangle) { } /** * Swipe gesture handler. * * For description of isDirect argument see #handleBeginTouchEvent * method. * * For description of isInertia and touchCount arguments * see #handleScrollGestureEvent method. * * For description of type, x,y, xAbs and yAbs arguments * see #handleBeginTouchEvent method. * * @param dir gesture direction. * One of constants defined in com.sun.glass.events.SwipeGesture * class. */ public void handleSwipeGestureEvent(View view, long time, int type, int modifiers, boolean isDirect, boolean isInertia, int touchCount, int dir, int x, int y, int xAbs, int yAbs) { } public Accessible getSceneAccessible() { return null; } } public static long getMultiClickTime() { Application.checkEventThread(); return Application.GetApplication().staticView_getMultiClickTime(); } public static int getMultiClickMaxX() { Application.checkEventThread(); return Application.GetApplication().staticView_getMultiClickMaxX(); } public static int getMultiClickMaxY() { Application.checkEventThread(); return Application.GetApplication().staticView_getMultiClickMaxY(); } protected abstract void _enableInputMethodEvents(long ptr, boolean enable); protected void _finishInputMethodComposition(long ptr) { // Action needed only on Windows. } /* Read by the checkNotClosed method which could be called from lock/unlock on render thread */ private volatile long ptr; // Native handle (NSView*, or internal structure pointer) private Window window; // parent window private EventHandler eventHandler; private int width = -1; // not set private int height = -1; // not set private boolean isValid = false; // true between ViewEvent.Add & ViewEvent.REMOVE private boolean isVisible = false; private boolean inFullscreen = false; static final public class Capability { //mymod // we need these for native code @Native static final public int k3dKeyValue = 0; @Native static final public int kSyncKeyValue = 1; @Native static final public int k3dProjectionKeyValue = 2; @Native static final public int k3dProjectionAngleKeyValue = 3; @Native static final public int k3dDepthKeyValue = 4; @Native static final public int kHiDPIAwareKeyValue = 5; static final public Object k3dKey = Integer.valueOf(k3dKeyValue); // value must be Boolean static final public Object kSyncKey = Integer.valueOf(kSyncKeyValue); // value must be Boolean static final public Object k3dProjectionKey = Integer.valueOf(k3dProjectionKeyValue); // value must be Boolean static final public Object k3dProjectionAngleKey = Integer.valueOf(k3dProjectionAngleKeyValue); // value must be Float static final public Object k3dDepthKey = Integer.valueOf(k3dDepthKeyValue); // value must be Integer(depth), where depth = 0, 4, 8, 16, 32etc static final public Object kHiDPIAwareKey = Integer.valueOf(kHiDPIAwareKeyValue); // value must be Boolean; default = false (i.e. NOT HiDPI-aware) } protected abstract long _create(Map capabilities); protected View() { Application.checkEventThread(); this.ptr = _create(Application.GetApplication().getDeviceDetails()); if (this.ptr == 0L) { throw new RuntimeException("could not create platform view"); } } private void checkNotClosed() { if (this.ptr == 0L) { throw new IllegalStateException("The view has already been closed"); } } public boolean isClosed() { Application.checkEventThread(); return this.ptr == 0L; } protected abstract long _getNativeView(long ptr); /** * On Windows ptr is a pointer to a native structure. * However, for external clients of the API, a HWND has to be returned. * Hence the native method. */ public long getNativeView() { Application.checkEventThread(); checkNotClosed(); return _getNativeView(this.ptr); } /** Only used on Mac when run inside a plugin */ public int getNativeRemoteLayerId(String serverName) { Application.checkEventThread(); throw new RuntimeException("This operation is not supported on this platform"); } public Window getWindow() { Application.checkEventThread(); return this.window; } protected abstract int _getX(long ptr); /** X coordinate relative to the host (window or applet). */ public int getX() { Application.checkEventThread(); checkNotClosed(); return _getX(this.ptr); } protected abstract int _getY(long ptr); /** Y coordinate relative to the host (window or applet). */ public int getY() { Application.checkEventThread(); checkNotClosed(); return _getY(this.ptr); } public int getWidth() { Application.checkEventThread(); return this.width; } public int getHeight() { Application.checkEventThread(); return this.height; } protected abstract void _setParent(long ptr, long parentPtr); // Window calls the method from Window.setView() // package private void setWindow(Window window) { Application.checkEventThread(); checkNotClosed(); this.window = window; _setParent(this.ptr, window == null ? 0L : window.getNativeHandle()); this.isValid = this.ptr != 0 && window != null; } // package private void setVisible(boolean visible) { this.isVisible = visible; } protected abstract boolean _close(long ptr); public void close() { Application.checkEventThread(); if (this.ptr == 0) { return; } if (isInFullscreen()) { _exitFullscreen(this.ptr, false); } Window host = getWindow(); if (host != null) { host.setView(null); // will call this.setWindow(null) } this.isValid = false; _close(this.ptr); this.ptr = 0; } public EventHandler getEventHandler() { Application.checkEventThread(); return this.eventHandler; } public void setEventHandler(EventHandler eventHandler) { Application.checkEventThread(); this.eventHandler = eventHandler; } //-------- EVENTS --------// private void handleViewEvent(long time, int type) { if (this.eventHandler != null) { this.eventHandler.handleViewEvent(this, time, type); } } private void handleKeyEvent(long time, int action, int keyCode, char[] keyChars, int modifiers) { if (this.eventHandler != null) { this.eventHandler.handleKeyEvent(this, time, action, keyCode, keyChars, modifiers); } } private void handleMouseEvent(long time, int type, int button, int x, int y, int xAbs, int yAbs, int modifiers, boolean isPopupTrigger, boolean isSynthesized) { if (eventHandler != null) { eventHandler.handleMouseEvent(this, time, type, button, x, y, xAbs, yAbs, modifiers, isPopupTrigger, isSynthesized); } } private void handleMenuEvent(int x, int y, int xAbs, int yAbs, boolean isKeyboardTrigger) { if (this.eventHandler != null) { this.eventHandler.handleMenuEvent(this, x, y, xAbs, yAbs, isKeyboardTrigger); } } public void handleBeginTouchEvent(View view, long time, int modifiers, boolean isDirect, int touchEventCount) { if (eventHandler != null) { eventHandler.handleBeginTouchEvent(view, time, modifiers, isDirect, touchEventCount); } } public void handleNextTouchEvent(View view, long time, int type, long touchId, int x, int y, int xAbs, int yAbs) { if (eventHandler != null) { eventHandler.handleNextTouchEvent(view, time, type, touchId, x, y, xAbs, yAbs); } } public void handleEndTouchEvent(View view, long time) { if (eventHandler != null) { eventHandler.handleEndTouchEvent(view, time); } } public void handleScrollGestureEvent(View view, long time, int type, int modifiers, boolean isDirect, boolean isInertia, int touchCount, int x, int y, int xAbs, int yAbs, double dx, double dy, double totaldx, double totaldy, double multiplierX, double multiplierY) { if (eventHandler != null) { eventHandler.handleScrollGestureEvent(view, time, type, modifiers, isDirect, isInertia, touchCount, x, y, xAbs, yAbs, dx, dy, totaldx, totaldy, multiplierX, multiplierY); } } public void handleZoomGestureEvent(View view, long time, int type, int modifiers, boolean isDirect, boolean isInertia, int originx, int originy, int originxAbs, int originyAbs, double scale, double expansion, double totalscale, double totalexpansion) { if (eventHandler != null) { eventHandler.handleZoomGestureEvent(view, time, type, modifiers, isDirect, isInertia, originx, originy, originxAbs, originyAbs, scale, expansion, totalscale, totalexpansion); } } public void handleRotateGestureEvent(View view, long time, int type, int modifiers, boolean isDirect, boolean isInertia, int originx, int originy, int originxAbs, int originyAbs, double dangle, double totalangle) { if (eventHandler != null) { eventHandler.handleRotateGestureEvent(view, time, type, modifiers, isDirect, isInertia, originx, originy, originxAbs, originyAbs, dangle, totalangle); } } public void handleSwipeGestureEvent(View view, long time, int type, int modifiers, boolean isDirect, boolean isInertia, int touchCount, int dir, int originx, int originy, int originxAbs, int originyAbs) { if (eventHandler != null) { eventHandler.handleSwipeGestureEvent(view, time, type, modifiers, isDirect, isInertia, touchCount, dir, originx, originy, originxAbs, originyAbs); } } private void handleInputMethodEvent(long time, String text, int[] clauseBoundary, int[] attrBoundary, byte[] attrValue, int commitCount, int cursorPos) { if (this.eventHandler != null) { this.eventHandler.handleInputMethodEvent(time, text, clauseBoundary, attrBoundary, attrValue, commitCount, cursorPos); } } public void enableInputMethodEvents(boolean enable) { Application.checkEventThread(); checkNotClosed(); _enableInputMethodEvents(this.ptr, enable); } public void finishInputMethodComposition() { Application.checkEventThread(); checkNotClosed(); _finishInputMethodComposition(this.ptr); } private double[] getInputMethodCandidatePos(int offset) { if (this.eventHandler != null) { return this.eventHandler.getInputMethodCandidatePos(offset); } return null; } private void handleDragStart(int button, int x, int y, int xAbs, int yAbs, ClipboardAssistance dropSourceAssistant) { if (this.eventHandler != null) { this.eventHandler.handleDragStart(this, button, x, y, xAbs, yAbs, dropSourceAssistant); } } private void handleDragEnd(int performedAction) { if (this.eventHandler != null) { this.eventHandler.handleDragEnd(this, performedAction); } } private int handleDragEnter(int x, int y, int xAbs, int yAbs, int recommendedDropAction, ClipboardAssistance dropTargetAssistant) { if (this.eventHandler != null) { return this.eventHandler.handleDragEnter(this, x, y, xAbs, yAbs, recommendedDropAction, dropTargetAssistant); } else { return recommendedDropAction; } } private int handleDragOver(int x, int y, int xAbs, int yAbs, int recommendedDropAction, ClipboardAssistance dropTargetAssistant) { if (this.eventHandler != null) { return this.eventHandler.handleDragOver(this, x, y, xAbs, yAbs, recommendedDropAction, dropTargetAssistant); } else { return recommendedDropAction; } } private void handleDragLeave(ClipboardAssistance dropTargetAssistant) { if (this.eventHandler != null) { this.eventHandler.handleDragLeave(this, dropTargetAssistant); } } private int handleDragDrop(int x, int y, int xAbs, int yAbs, int recommendedDropAction, ClipboardAssistance dropTargetAssistant) { if (this.eventHandler != null) { return this.eventHandler.handleDragDrop(this, x, y, xAbs, yAbs, recommendedDropAction, dropTargetAssistant); } else { return Clipboard.ACTION_NONE; } } //-------- DRAWING --------// protected abstract void _scheduleRepaint(long ptr); /** marks native surface dirty, so the system itself will create repaint event * */ public void scheduleRepaint() { Application.checkEventThread(); checkNotClosed(); _scheduleRepaint(this.ptr); } protected abstract void _begin(long ptr); /** prepares to painting by locking native surface * * Called on the render thread */ public void lock() { checkNotClosed(); _begin(this.ptr); } protected abstract void _end(long ptr); /** ends painting by unlocking native surface and flushing * flushes surface (if flush == true) or discard it (flush == false) * * Called on the render thread */ public void unlock() { checkNotClosed(); _end(this.ptr); } protected abstract int _getNativeFrameBuffer(long ptr); /** * Called on the renderer thread and must be between lock and unlock */ public int getNativeFrameBuffer() { return _getNativeFrameBuffer(this.ptr); } protected abstract void _uploadPixels(long ptr, Pixels pixels); /** * This method dumps the pixels on to the view. * * NOTE: On MS Windows calling this method is REQUIRED for * transparent windows in order to update them. */ public void uploadPixels(Pixels pixels) { Application.checkEventThread(); checkNotClosed(); lock(); try { _uploadPixels(this.ptr, pixels); } finally { unlock(); } } //-------- FULLSCREEN --------// protected abstract boolean _enterFullscreen(long ptr, boolean animate, boolean keepRatio, boolean hideCursor); public boolean enterFullscreen(boolean animate, boolean keepRatio, boolean hideCursor) { Application.checkEventThread(); checkNotClosed(); return _enterFullscreen(this.ptr, animate, keepRatio, hideCursor); } protected abstract void _exitFullscreen(long ptr, boolean animate); public void exitFullscreen(boolean animate) { Application.checkEventThread(); checkNotClosed(); _exitFullscreen(this.ptr, animate); } public boolean isInFullscreen() { Application.checkEventThread(); return this.inFullscreen; } public boolean toggleFullscreen(boolean animate, boolean keepRatio, boolean hideCursor) { Application.checkEventThread(); checkNotClosed(); if (!this.inFullscreen) { enterFullscreen(animate, keepRatio, hideCursor); } else { exitFullscreen(animate); } _scheduleRepaint(this.ptr); return this.inFullscreen; } //-------- DELEGATE NOTIFICATIONS --------// protected void notifyView(int type) { // System.err.println(" notifyView: "+ViewEvent.getTypeString(type)+" on thread"+Thread.currentThread()); if (type == ViewEvent.REPAINT) { if (isValid) { handleViewEvent(System.nanoTime(), type); } } else { boolean synthesizeMOVE = false; switch (type) { case ViewEvent.REMOVE: isValid = false; synthesizeMOVE = true; break; case ViewEvent.ADD: isValid = true; synthesizeMOVE = true; break; case ViewEvent.FULLSCREEN_ENTER: this.inFullscreen = true; synthesizeMOVE = true; if (getWindow() != null) { getWindow().notifyFullscreen(true); } break; case ViewEvent.FULLSCREEN_EXIT: this.inFullscreen = false; synthesizeMOVE = true; if (getWindow() != null) { getWindow().notifyFullscreen(false); } break; case ViewEvent.MOVE: case ViewEvent.RESIZE: break; default: System.err.println("Unknown view event type: " + type); return; } handleViewEvent(System.nanoTime(), type); if (synthesizeMOVE) { // Generate MOVE event to update current insets. Native code may // send additional MOVE events when it detects insets change. handleViewEvent(System.nanoTime(), ViewEvent.MOVE); } } } protected void notifyResize(int width, int height) { if (this.width == width && this.height == height) { return; } this.width = width; this.height = height; handleViewEvent(System.nanoTime(), ViewEvent.RESIZE); } /* * x, y, width, heigth define the "dirty" rect */ protected void notifyRepaint(int x, int y, int width, int height) { notifyView(ViewEvent.REPAINT); } // ------------ MENU EVENT HANDLING ----------------- // protected void notifyMenu(int type, int button, int x, int y, int xAbs, int yAbs, int keyCode, char[] keyChars, int modifiers) { protected void notifyMenu(int x, int y, int xAbs, int yAbs, boolean isKeyboardTrigger) { handleMenuEvent(x, y, xAbs, yAbs, isKeyboardTrigger); } // ------------ MOUSE EVENTS HANDLING ----------------- // Synchronized on the Main thread of the underlying native system private static WeakReference<View> lastClickedView = null; private static int lastClickedButton; private static long lastClickedTime; private static int lastClickedX, lastClickedY; private static int clickCount; private static boolean dragProcessed = false; protected void notifyMouse(int type, int button, int x, int y, int xAbs, int yAbs, int modifiers, boolean isPopupTrigger, boolean isSynthesized) { // gznote: optimize - only call for undecorated Windows! if (this.window != null) { // handled by window (programmatical move/resize) if (this.window.handleMouseEvent(type, button, x, y, xAbs, yAbs)) { // The evnet has been processed by Glass return; } } long now = System.nanoTime(); if (type == MouseEvent.DOWN) { View lastClickedView = View.lastClickedView == null ? null : View.lastClickedView.get(); if (lastClickedView == this && lastClickedButton == button && (now - lastClickedTime) <= 1000000L*getMultiClickTime() && Math.abs(x - lastClickedX) <= getMultiClickMaxX() && Math.abs(y - lastClickedY) <= getMultiClickMaxY()) { clickCount++; } else { clickCount = 1; View.lastClickedView = new WeakReference<View>(this); lastClickedButton = button; lastClickedX = x; lastClickedY = y; } lastClickedTime = now; } handleMouseEvent(now, type, button, x, y, xAbs, yAbs, modifiers, isPopupTrigger, isSynthesized); if (type == MouseEvent.DRAG) { // Send the handleDragStart() only once per a drag gesture if (!dragProcessed) { notifyDragStart(button, x, y, xAbs, yAbs); dragProcessed = true; } } else { dragProcessed = false; } } // ------------- END OF MOUSE EVENTS ----------------- protected void notifyScroll(int x, int y, int xAbs, int yAbs, double deltaX, double deltaY, int modifiers, int lines, int chars, int defaultLines, int defaultChars, double xMultiplier, double yMultiplier) { if (this.eventHandler != null) { this.eventHandler.handleScrollEvent(this, System.nanoTime(), x, y, xAbs, yAbs, deltaX, deltaY, modifiers, lines, chars, defaultLines, defaultChars, xMultiplier, yMultiplier); } } protected void notifyKey(int type, int keyCode, char[] keyChars, int modifiers) { handleKeyEvent(System.nanoTime(), type, keyCode, keyChars, modifiers); } protected void notifyInputMethod(String text, int[] clauseBoundary, int[] attrBoundary, byte[] attrValue, int committedTextLength, int caretPos, int visiblePos) { handleInputMethodEvent(System.nanoTime(), text, clauseBoundary, attrBoundary, attrValue, committedTextLength, caretPos); } protected double[] notifyInputMethodCandidatePosRequest(int offset) { double[] ret = getInputMethodCandidatePos(offset); if (ret == null) { ret = new double[2]; ret[0] = 0.0; ret[1] = 0.0; } return ret; } private ClipboardAssistance dropSourceAssistant; protected void notifyDragStart(int button, int x, int y, int xAbs, int yAbs) { dropSourceAssistant = new ClipboardAssistance(Clipboard.DND) { @Override public void actionPerformed(int performedAction) { // on Windows called from DnD modal loop // on Mac the View is the drag delegate and calls notifyDragEnd directly notifyDragEnd(performedAction); } }; //DnD loop is inside dropSourceAssistant.flush() handleDragStart(button, x, y, xAbs, yAbs, dropSourceAssistant); //utilize dropSourceAssistant if DnD was not started. if (dropSourceAssistant != null) { dropSourceAssistant.close(); dropSourceAssistant = null; } } protected void notifyDragEnd(int performedAction) { handleDragEnd(performedAction); if (dropSourceAssistant != null) { dropSourceAssistant.close(); dropSourceAssistant = null; } } ClipboardAssistance dropTargetAssistant; // callback for native code protected int notifyDragEnter(int x, int y, int xAbs, int yAbs, int recommendedDropAction) { dropTargetAssistant = new ClipboardAssistance(Clipboard.DND) { @Override public void flush() { throw new UnsupportedOperationException("Flush is forbidden from target!"); } }; return handleDragEnter(x, y, xAbs, yAbs, recommendedDropAction, dropTargetAssistant); } // callback for native code protected int notifyDragOver(int x, int y, int xAbs, int yAbs, int recommendedDropAction) { return handleDragOver(x, y, xAbs, yAbs, recommendedDropAction, dropTargetAssistant); } // callback for native code protected void notifyDragLeave() { handleDragLeave(dropTargetAssistant); dropTargetAssistant.close(); } // callback for native code // gznote: should be renamed to notifyDragDrop/notifyDragPerformed to be consistent protected int notifyDragDrop(int x, int y, int xAbs, int yAbs, int recommendedDropAction) { int performedAction = handleDragDrop(x, y, xAbs, yAbs, recommendedDropAction, dropTargetAssistant); dropTargetAssistant.close(); return performedAction; } public void notifyBeginTouchEvent(int modifiers, boolean isDirect, int touchEventCount) { handleBeginTouchEvent(this, System.nanoTime(), modifiers, isDirect, touchEventCount); } public void notifyNextTouchEvent(int type, long touchId, int x, int y, int xAbs, int yAbs) { handleNextTouchEvent(this, System.nanoTime(), type, touchId, x, y, xAbs, yAbs); } public void notifyEndTouchEvent() { handleEndTouchEvent(this, System.nanoTime()); } public void notifyScrollGestureEvent(int type, int modifiers, boolean isDirect, boolean isInertia, int touchCount, int x, int y, int xAbs, int yAbs, double dx, double dy, double totaldx, double totaldy, double multiplierX, double multiplierY) { handleScrollGestureEvent(this, System.nanoTime(), type, modifiers, isDirect, isInertia, touchCount, x, y, xAbs, yAbs, dx, dy, totaldx, totaldy, multiplierX, multiplierY); } public void notifyZoomGestureEvent(int type, int modifiers, boolean isDirect, boolean isInertia, int originx, int originy, int originxAbs, int originyAbs, double scale, double expansion, double totalscale, double totalexpansion) { handleZoomGestureEvent(this, System.nanoTime(), type, modifiers, isDirect, isInertia, originx, originy, originxAbs, originyAbs, scale, expansion, totalscale, totalexpansion); } public void notifyRotateGestureEvent(int type, int modifiers, boolean isDirect, boolean isInertia, int originx, int originy, int originxAbs, int originyAbs, double dangle, double totalangle) { handleRotateGestureEvent(this, System.nanoTime(), type, modifiers, isDirect, isInertia, originx, originy, originxAbs, originyAbs, dangle, totalangle); } public void notifySwipeGestureEvent(int type, int modifiers, boolean isDirect, boolean isInertia, int touchCount, int dir, int originx, int originy, int originxAbs, int originyAbs) { handleSwipeGestureEvent(this, System.nanoTime(), type, modifiers, isDirect, isInertia, touchCount, dir, originx, originy, originxAbs, originyAbs); } /** * Returns the accessible object for the view. * This method is called by JNI code when the * platform requested the accessible peer for the view. * On Windows it happens on WM_GETOBJECT. * On Mac it happens on NSView#accessibilityAttributeNames. */ long getAccessible() { Application.checkEventThread(); checkNotClosed(); if (accessible) { Accessible acc = eventHandler.getSceneAccessible(); if (acc != null) { acc.setView(this); return acc.getNativeAccessible(); } } return 0L; } }
gpl-2.0
league/rngzip
libs/colloquial/com/colloquial/arithcode/PPMModel.java
10596
package com.colloquial.arithcode; /** Provides a cumulative, adaptive byte model implementing * prediction by partial matching up to a specified maximum context size. * Uses Method C for estimation. * * Constants that control behavior include the maximum total count before * rescaling, and the minimum count to retain after rescaling (an escape * is always maintained with a count of at least <code>1</code>). * <P> * For more details, see <a href="../../../tutorial.html">The Arithemtic Coding Tutorial</a>. * * @author <a href="http://www.colloquial.com/carp/">Bob Carpenter</a> * @version 1.1 * @since 1.0 */ public final class PPMModel implements ArithCodeModel { /** Construct a new model with the specified maximum length of * context to use for prediction. * @param maxContextLength Maximum length of context to use for prediction. */ public PPMModel(int maxContextLength) { _maxContextLength = maxContextLength; _buffer = new ByteBuffer(maxContextLength+1); } // specified in ArithCodeModel public boolean escaped(int symbol) { return (_contextNode != null && (symbol == ArithCodeModel.EOF || !_contextNode.hasDaughter(symbol))); } // specified in ArithCodeModel public void exclude(int i) { _excludedBytes.add(i); } // specified in ArithCodeModel public void interval(int symbol, int[] result) { if (symbol == ArithCodeModel.EOF) _backoffModel.interval(EOF,result,_excludedBytes); else if (symbol == ArithCodeModel.ESCAPE) intervalEscape(result); else intervalByte(symbol,result); } // specified in ArithCodeModel public int pointToSymbol(int count) { if (_contextNode != null) return _contextNode.pointToSymbol(count,_excludedBytes); return _backoffModel.pointToSymbol(count,_excludedBytes); } // specified in ArithCodeModel public int totalCount() { if (_contextNode == null) return _backoffModel.totalCount(_excludedBytes); return _contextNode.totalCount(_excludedBytes); } // specified in ArithCodeModel public void increment(int i) { increment(Converter.integerToByte(i)); } /** Exclude all of the bytes in the specified byte set. * @param bytesToExclude Set of bytes to exclude from outcome. * @since 1.1 */ public void exclude(ByteSet bytesToExclude) { _excludedBytes.add(bytesToExclude); } /** Count of bytes coded to use in pruning. */ // private int _byteCount; // implied = 0; uncomment for pruning /** Model to use for short contexts. */ private final ExcludingAdaptiveUnigramModel _backoffModel = new ExcludingAdaptiveUnigramModel(); /** Nodes at depth 1 in the model. All order 0 nodes are included in the unigram */ private final PPMNode[] _contexts = new PPMNode[256]; /** Maximum context length to search in trie. Maximum count will * be for maximum context length plus one. */ private final int _maxContextLength; /** Root of the trie structure of counts. Dummy byte as symbol. */ private final PPMNode _rootNode = new PPMNode((byte)'.'); /** Current context length. */ private int _contextLength; // implied = 0; /** Current context node. */ private PPMNode _contextNode; // = null; /** Bytes buffered for use as context. */ private final ByteBuffer _buffer; /** Storage for the excluded bytes */ private final ByteSet _excludedBytes = new ByteSet(); /** Returns interval for byte specified as an integer in 0 to 255 range. * @param i Integer specification of byte in 0 to 255 range. * @param result Array specifying cumulative probability for byte i. */ private void intervalByte(int i, int[] result) { if (_contextNode != null) _contextNode.interval(i,_excludedBytes,result); else _backoffModel.interval(i,result,_excludedBytes); increment(i); } /** Returns interval for escape in current context. * @param result Array for specifying cumulative probability for escape symbol in current context. */ private void intervalEscape(int[] result) { _contextNode.intervalEscape(_excludedBytes,result); if (_contextLength >= MIN_CONTEXT_LENGTH) for (PPMNode child = _contextNode._firstChild; child != null; child = child._nextSibling) _excludedBytes.add(child._byte); --_contextLength; // could decrement longer contexts more for a speedup in some cases getContextNodeLongToShort(); } // code used for pruning is edited out and marked as follows //PRUNE private void prune() { //PRUNE for (int i = 0; i < 256; ++i) if (_contexts[i] != null) _contexts[i] = _contexts[i].prune(); //PRUNE } /** Adds counts for given byte to model in current context and then updates the current context. * Rescales counts if necessary. Called by both encoding and deocding. * @param b Byte to add to model. */ private void increment(byte b) { _buffer.buffer(b); byte firstByte = _buffer.bytes()[_buffer.offset()]; if (_contexts[Converter.byteToInteger(firstByte)] == null) _contexts[Converter.byteToInteger(firstByte)] = new PPMNode(firstByte); if (_buffer.length() > 1) _contexts[Converter.byteToInteger(firstByte)].increment(_buffer.bytes(), _buffer.offset()+1, _buffer.length()-1); // _backoffModel.increment(Converter.byteToInteger(b)); // updates backoff model; best to exclude it by .1 b/B! _contextLength = Math.min(_maxContextLength,_buffer.length()); getContextNodeBinarySearch(); _excludedBytes.clear(); //PRUNE if (++_byteCount == PRUNE_INTERVAL) { _byteCount = 0; prune(); } // pruning } /** Use binary search to set the context node up to the currently * specified context length. May set it to <code>null</code> if * not found. */ private void getContextNodeBinarySearch() { int low = MIN_CONTEXT_LENGTH; int high = _contextLength; _contextLength = MIN_CONTEXT_LENGTH-1; // not sure we need this _contextNode = null; boolean isDeterministic = false; while (high >= low) { int contextLength = (high + low)/2; PPMNode contextNode = lookupNode(contextLength); if (contextNode == null || contextNode.isChildless(_excludedBytes)) { if (contextLength < high) high = contextLength; else --high; } else if (contextNode.isDeterministic(_excludedBytes)) { _contextLength = contextLength; _contextNode = contextNode; isDeterministic = true; if (contextLength < high) high = contextLength; else --high; } else if (!isDeterministic) { _contextLength = contextLength; _contextNode = contextNode; if (contextLength > low) low = contextLength; else ++low; } else { if (contextLength > low) low = contextLength; else ++low; } } } /* un-used variant lookung up context lengths by starting with shortest and * continuing to increase until found. private void getContextNodeShortToLong() { int maxContextLength = _contextLength; _contextNode = null; _contextLength = MIN_CONTEXT_LENGTH-1; for (int contextLength = MIN_CONTEXT_LENGTH; contextLength <= maxContextLength; ++contextLength) { PPMNode node = lookupNode(contextLength); if (node == null || node.isChildless(_excludedBytes)) { continue; // return; lose around .01 b/B total (not even average) with return, but 25% slower } _contextNode = node; _contextLength = contextLength; if (node.isDeterministic(_excludedBytes)) return; } } */ /** Starting at the longest context, count down in length to set * a valid context or give up. This version finds the shortest deterministic * context <= in length to the current context length, but if there is * no deterministic context, returns longest context length that exists * that is <= in length to the current context. * Could also implement this in short to long order */ private void getContextNodeLongToShort() { while (_contextLength >= MIN_CONTEXT_LENGTH) { _contextNode = lookupNode(_contextLength); if (_contextNode == null || _contextNode.isChildless(_excludedBytes)) { --_contextLength; continue; } while (_contextLength > MIN_CONTEXT_LENGTH && _contextNode.isDeterministic(_excludedBytes)) { // backoff to shortest deterministic node if context node is deterministic PPMNode backoffNode = lookupNode(_contextLength-1); if (backoffNode == null || !backoffNode.isDeterministic(_excludedBytes)) return; _contextNode = backoffNode; --_contextLength; } return; } _contextNode = null; } /** Returns node from the current byte buffer of * the specified context length, or null if there isn't one. * @param contextLength Number of bytes of context used. * @return Node found at that context. */ private PPMNode lookupNode(int contextLength) { PPMNode node = _contexts[Converter.byteToInteger(_buffer.bytes()[_buffer.offset()+_buffer.length()-contextLength])]; if (node == null) return (PPMNode) null; return lookup(node,_buffer.bytes(),_buffer.offset()+_buffer.length()-contextLength+1,contextLength-1); } /** Looks up a node from the given bytes, offset and length starting * from the specified node. * @param node Node from which to search. * @param bytes Sequence of bytes to search. * @param offset Offset into sequence of bytes of the first byte. * @param length Number of bytes to look up. * @return Node found for the given bytes. */ private static PPMNode lookup(PPMNode node, byte[] bytes, int offset, int length) { if (length == 0) return node; for (PPMNode child = node._firstChild; length > 0 && child != null; ) { if (bytes[offset]==child._byte) { if (length == 1) return child; node = child; child = child._firstChild; ++offset; --length; } else { child = child._nextSibling; } } return (PPMNode) null; } /** Minimum context length to look down sequence of nodes. * Shorter contexts use backoff model. */ private static final int MIN_CONTEXT_LENGTH = 1; /** Period between prunings in number of bytes. */ //PRUNE private static final int PRUNE_INTERVAL = 250000; // loses about 10% compression rate, saves lots of space }
gpl-2.0
nico202/ReGeX
app/src/main/java/com/phikal/regex/Activities/Settings/WordOptionFragment.java
3850
package com.phikal.regex.Activities.Settings; import android.app.Fragment; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import com.phikal.regex.Adapters.WordListAdapter; import com.phikal.regex.R; import com.phikal.regex.Utils.WordList; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class WordOptionFragment extends Fragment { public WordOptionFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_word_option, container, false); v.findViewById(R.id.add).setOnClickListener((_v) -> { try { URL url = new URL(((TextView) v.findViewById(R.id.new_url)).getText().toString()); ((TextView) v.findViewById(R.id.new_url)).setError(null); new WordInserter(url, (CursorAdapter) ((ListView) v.findViewById(R.id.word_list)).getAdapter()) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } catch (MalformedURLException mue) { ((TextView) v.findViewById(R.id.new_url)).setError(getResources().getString(R.string.url_error)); } }); ((ListView) v.findViewById(R.id.word_list)).setAdapter( WordListAdapter.genWordListAdapter(getActivity())); return v; } private class WordInserter extends AsyncTask<Void, String, Void> { final URL url; final BlockingQueue<String> bq; final ProgressDialog pd; final CursorAdapter ca; WordInserter(URL url, CursorAdapter ca) { this.url = url; this.ca = ca; this.bq = new LinkedBlockingQueue<>(); this.pd = new ProgressDialog(getActivity(), ProgressDialog.STYLE_SPINNER); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { new WordList(getActivity()).addFromQueue(url.toString(), bq); return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @Override protected void onPreExecute() { super.onPreExecute(); pd.setCancelable(false); pd.setMessage(getString(R.string.loading_words)); pd.show(); } @Override protected Void doInBackground(Void... params) { try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); for (String line; ((line = br.readLine())) != null; ) if ((line = line.trim()).matches("^\\w+$")) bq.put(line); br.close(); conn.disconnect(); } catch (IOException | InterruptedException ie) { ie.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); bq.add(WordList.DONE); pd.cancel(); ca.changeCursor(new WordList(getActivity()).getSources()); ca.notifyDataSetChanged(); } } }
gpl-2.0
Coolway99/ToS_Forum_Mafia_Note_Taker
main/ToS_Forum_Mafia_Note_Taker/src/main/MainRightClickMenu.java
10645
package main; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import javax.imageio.ImageIO; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import javax.swing.WindowConstants; public class MainRightClickMenu extends JPopupMenu { private static final long serialVersionUID = 2360564545515706123L; protected static JPopupMenu pop = new JPopupMenu(); private static PersonalActionListener listener = new PersonalActionListener(); public static PersonalMouseListener mouse = new PersonalMouseListener(); public static JFrame editFrame = new JFrame(); public static JTextArea editArea = new JTextArea(); public static JButton editSubmit = new JButton(); public static JButton editCancel = new JButton(); public static JPanel bbcPanel = new JPanel(); public static JButton bbcButtons[] = {new JButton("Colors"), new JButton("Size"), new JButton("b"), new JButton("i"), new JButton("u"), new JButton("s"), new JButton("[url=]") }; public static JButton colorButtons[][]; protected static MouseEvent eBox; private static GridBagLayout layout = new GridBagLayout(); public static JFrame colorFrame = new JFrame(); private static GridBagLayout colorFrameLayout = new GridBagLayout(); private static GridBagConstraints c; private static HashMap<Integer, HashMap<Boolean, String>> CodeList = new HashMap<>(); public static void initPopup(){ String[] FromList = {"\\[color=", "\\[/color\\]", "\\[size=", "\\[/size\\]", "\n", "\\[b\\]", "\\[/b\\]", "\\[i\\]", "\\[/i\\]", "\\[u\\]", "\\[/u\\]", "\\[s\\]", "\\[/s\\]", "\\[url=", "\\[/url\\]" }; String[] ToList = {"<font color=", "</font>", "<font size=", "</font>", "<br />", "<b>", "</b>", "<i>", "</i>", "<u>", "</u>", "<s>", "</s>", "<a href=\"", "</a>" }; for (int x = 0; x < FromList.length; x++) { CodeList.put(x, new HashMap<Boolean, String>()); CodeList.get(x).put(true, FromList[x]); CodeList.get(x).put(false, ToList[x]); } colorFrame.setLayout(colorFrameLayout); MenuInterface menuItem = new MenuInterface("Edit"); menuItem.addActionListener(listener); pop.add(menuItem); editFrame.setSize(600, 400); editArea.setLineWrap(true); editFrame.setLayout(layout); int rows[] = new int[10]; for (int x = 0; x < rows.length; x++) { rows[x] = (400 / rows.length); } int columns[] = new int[3]; for (int x = 0; x < columns.length; x++) { columns[x] = (600 / columns.length); } layout.rowHeights = rows; layout.columnWidths = columns; c = resetConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.gridheight = 9; editFrame.add(new JScrollPane(editArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER), c); c = resetConstraints(); c.gridx = 1; c.gridy = 9; c.gridwidth = 1; c.gridheight = 1; editFrame.add(editSubmit, c); c = resetConstraints(); c.gridx = 0; c.gridy = 9; c.gridwidth = 1; c.gridheight = 1; editFrame.add(editCancel, c); c = resetConstraints(); c.gridx = 2; c.gridy = 0; c.gridwidth = 1; c.gridheight = 10; bbcPanel.setLayout(new BoxLayout(bbcPanel, BoxLayout.Y_AXIS)); { class InsertListener implements ActionListener{ private final String b; private final String a; public InsertListener(String before, String after){ b = before; a = after; } @Override public void actionPerformed(ActionEvent e){ insertText(b, a); } } JButton b = bbcButtons[0]; b.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ colorFrame.setVisible(true); } }); b = bbcButtons[1]; b.addActionListener(new InsertListener("[size=", "[/size]")); b = bbcButtons[2]; b.addActionListener(new InsertListener("[b]", "[/b]")); b.setFont(b.getFont().deriveFont(Font.BOLD)); b = bbcButtons[3]; b.addActionListener(new InsertListener("[i]", "[/i]")); b.setFont(b.getFont().deriveFont(Font.ITALIC)); b = bbcButtons[4]; b.addActionListener(new InsertListener("[u]", "[/u]")); b = bbcButtons[5]; b.addActionListener(new InsertListener("[s]", "[/s]")); b = bbcButtons[6]; b.addActionListener(new InsertListener("[url=]", "[url]")); } for(JButton b : bbcButtons){ bbcPanel.add(b); } editFrame.add(bbcPanel, c); colorFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); editFrame.setLocationRelativeTo(null); editFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); editSubmit.setText("Submit"); editCancel.setText("Cancel"); editSubmit.addActionListener(new EditButtonActionListener()); editCancel.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ MainRightClickMenu.editFrame.setVisible(false); MainRightClickMenu.colorFrame.setVisible(false); Main.frame.setEnabled(true); Main.frame.requestFocus(); } }); try { final BufferedImage colors = ImageIO.read(Main.class.getClassLoader().getResource("assets/images/colors.png")); class ButtonListener implements ActionListener { private BufferedImage icon; public ButtonListener(BufferedImage icon){ this.icon = icon; } @Override public void actionPerformed(ActionEvent e){ insertText(String.format("[color=#%06X]", icon.getRGB(0, 0) - 0xFF000000), "[/color]"); } } colorButtons = new JButton[colors.getHeight()][colors.getWidth()]; rows = new int[colors.getHeight()]; for (int x = 0; x < rows.length; x++) { rows[x] = 16; } columns = new int[colors.getWidth()]; for (int x = 0; x < columns.length; x++) { columns[x] = 16; } colorFrameLayout.rowHeights = rows; colorFrameLayout.columnWidths = columns; for (int y = 0; y < colorButtons.length; y++) { for (int x = 0; x < colorButtons[0].length; x++) { final BufferedImage icon = colors.getSubimage(x, y, 1, 1); colorButtons[y][x] = new JButton(); colorButtons[y][x].addActionListener(new ButtonListener(icon)); c = resetConstraints(); c.gridx = x; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; colorFrame.add(colorButtons[y][x], c); } } colorFrame.pack(); Timer initIcons = new Timer("Color init icons", true); initIcons.schedule(new TimerTask(){ @Override public void run(){ for (int y = 0; y < colorButtons.length; y++) { for (int x = 0; x < colorButtons[0].length; x++) { final BufferedImage icon = colors.getSubimage(x, y, 1, 1); colorButtons[y][x].setBorder(null); colorButtons[y][x].setIcon(new ImageIcon(icon.getScaledInstance( colorButtons[y][x].getWidth(), colorButtons[y][x].getHeight(), Image.SCALE_FAST))); } } } }, 1000); } catch (IOException e) { e.printStackTrace(); } } private static GridBagConstraints resetConstraints(){ GridBagConstraints c = new GridBagConstraints(); c.weightx = 1.0; c.weighty = 1.0; c.fill = GridBagConstraints.BOTH; return c; } public static void insertText(String before, String after){ if (editArea.getSelectedText() == null) { editArea.replaceSelection(before + after); editArea.setCaretPosition(editArea.getCaretPosition() - after.length()); } else { editArea.replaceSelection(before + editArea.getSelectedText() + after); } editArea.requestFocus(); } public static String unParse(String in){ String B = in; for (int y = 0; y < CodeList.size(); y++) { String A[] = B.split(CodeList.get(y).get(true)); B = A[0]; for (int x = 1; x < A.length; x++) { B += CodeList.get(y).get(false); B += (CodeList.get(y).get(false).endsWith(">")) ? A[x] : (CodeList.get(y) .get(false).equals("<a href=\"") ? A[x].replaceFirst("\\]", "\">") : A[x].replaceFirst("\\]", ">")); } } return "<font face=\"arial\">" + B + "</font>"; } } class PersonalMouseListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e){ popup(e); } @Override public void mouseReleased(MouseEvent e){ popup(e); } public void popup(MouseEvent e){ if (e.isPopupTrigger()) { if (e.isPopupTrigger()) { MainRightClickMenu.pop.show(e.getComponent(), e.getX(), e.getY()); MainRightClickMenu.eBox = e; } } } } class PersonalActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e){ MenuInterface menu = (MenuInterface) e.getSource(); menu.doAction(e); } } class MenuInterface extends JMenuItem { private static final long serialVersionUID = -3707695245298165419L; public MenuInterface(String string){ super(string); } public void doAction(ActionEvent e){ if (!MainRightClickMenu.editFrame.isVisible()) { MainRightClickMenu.editFrame.setTitle(((MainTextPane) MainRightClickMenu.eBox .getSource()).fieldName); MainRightClickMenu.editArea .setText(((MainTextPane) MainRightClickMenu.eBox.getSource()).origString); MainRightClickMenu.editFrame.setVisible(true); MainRightClickMenu.editArea.requestFocus(); Main.frame.setEnabled(false); } } } class EditButtonActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e){ MainRightClickMenu.editFrame.setVisible(false); MainRightClickMenu.colorFrame.setVisible(false); ((MainTextPane) MainRightClickMenu.eBox.getSource()).origString = MainRightClickMenu.editArea.getText(); ((MainTextPane) MainRightClickMenu.eBox.getSource()).setText(MainRightClickMenu .unParse(MainRightClickMenu.editArea.getText())); Main.frame.setEnabled(true); Main.frame.requestFocus(); } }
gpl-2.0
StefanKopieczek/audinance
src/test/java/com/kopieczek/audinance/testutils/TestUtilities.java
3413
package com.kopieczek.audinance.testutils; import com.kopieczek.audinance.audiosources.DecodedSource; import com.kopieczek.audinance.audiosources.EncodedSource; import com.kopieczek.audinance.audiosources.NoMoreDataException; import com.kopieczek.audinance.formats.AudioFormat; import com.kopieczek.audinance.formats.DecodedAudio; import com.kopieczek.audinance.formats.InvalidAudioFormatException; import org.junit.Assert; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class TestUtilities { public static void assertDecodedAudioEqual(String message, DecodedAudio expected, DecodedAudio actual) { assertFormatsEqual(message + " audio formats are not equal", expected.getFormat(), actual.getFormat()); DecodedSource[] expectedChannels = expected.getChannels(); DecodedSource[] actualChannels = actual.getChannels(); double[][] expectedData = new double[expectedChannels.length][]; for (int ii = 0; ii < expectedChannels.length; ii++) { try { expectedData[ii] = getRawDataFromDecodedSource( expectedChannels[ii]); } catch (InvalidAudioFormatException e) { Assert.fail("Expected data invalid in channel " + ii); } } double[][] actualData = new double[actualChannels.length][]; for (int ii = 0; ii < actualChannels.length; ii++) { try { actualData[ii] = getRawDataFromDecodedSource( actualChannels[ii]); } catch (InvalidAudioFormatException e) { Assert.fail("Actual data invalid in channel " + ii); } } Assert.assertArrayEquals(message + "Audio data not equal.", expectedData, actualData); } private static double[] getRawDataFromDecodedSource( DecodedSource source) throws InvalidAudioFormatException { List<Double> rawData = new ArrayList<Double>(); int ii = 0; while (true) { try { rawData.add(source.getSample(ii)); } catch (NoMoreDataException e) { break; } ii++; } double[] result = new double[rawData.size()]; for (int jj = 0; jj < rawData.size(); jj++) { result[jj] = rawData.get(jj).doubleValue(); } return result; } private static void assertFormatsEqual(String message, AudioFormat expected, AudioFormat actual) { Assert.assertEquals(message + " Sample rates unequal.", expected.getSampleRate(), actual.getSampleRate()); Assert.assertEquals(message + " Number of channels differs.", expected.getSampleRate(), actual.getSampleRate()); // Catch changes in underlying equals() method not // updated here. Assert.assertEquals(message, expected, actual); } public static EncodedSource buildEncodedSource(int size, Consumer<ByteBuffer> bufferInitializer) { ByteBuffer bb = ByteBuffer.allocate(size); bufferInitializer.accept(bb); return new MockEncodedSource(bb.array()); } public static byte[] encode(String s) { return Charset.forName("ASCII").encode(s).array(); } }
gpl-2.0
neelance/jre4ruby
jre4ruby/src/share/sun/nio/cs/ext/MS950_HKSCS.java
3331
/* * Copyright 2002-2004 Sun Microsystems, Inc. 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package sun.nio.cs.ext; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import sun.nio.cs.HistoricallyNamedCharset; public class MS950_HKSCS extends Charset implements HistoricallyNamedCharset { public MS950_HKSCS() { super("x-MS950-HKSCS", ExtendedCharsets.aliasesFor("x-MS950-HKSCS")); } public String historicalName() { return "MS950_HKSCS"; } public boolean contains(Charset cs) { return ((cs.name().equals("US-ASCII")) || (cs instanceof MS950) || (cs instanceof MS950_HKSCS)); } public CharsetDecoder newDecoder() { return new Decoder(this); } public CharsetEncoder newEncoder() { return new Encoder(this); } private static class Decoder extends HKSCS.Decoder { private MS950.Decoder ms950Dec; /* * Note current decoder decodes 0x8BC2 --> U+F53A * ie. maps to Unicode PUA. * Unaccounted discrepancy between this mapping * inferred from MS950/windows-950 and the published * MS HKSCS mappings which maps 0x8BC2 --> U+5C22 * a character defined with the Unified CJK block */ protected char decodeDouble(int byte1, int byte2) { char c = super.decodeDouble(byte1, byte2); return (c != REPLACE_CHAR) ? c : ms950Dec.decodeDouble(byte1, byte2); } private Decoder(Charset cs) { super(cs); ms950Dec = new MS950.Decoder(cs); } } private static class Encoder extends HKSCS.Encoder { private MS950.Encoder ms950Enc; /* * Note current encoder encodes U+F53A --> 0x8BC2 * Published MS HKSCS mappings show * U+5C22 <--> 0x8BC2 */ protected int encodeDouble(char ch) { int r = super.encodeDouble(ch); return (r != 0) ? r : ms950Enc.encodeDouble(ch); } private Encoder(Charset cs) { super(cs); ms950Enc = new MS950.Encoder(cs); } } }
gpl-2.0
f1194361820/helper
frameworkex/frameworkex-bcl/src/test/java/com/fjn/helper/frameworkex/asm/test/GenerateClassTest.java
2430
/* * * Copyright 2018 FJN Corp. * * 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. * * Author Date Issue * fs1194361820@163.com 2015-01-01 Initial Version * */ package com.fjn.helper.frameworkex.asm.test; import static org.objectweb.asm.Opcodes.ACC_ABSTRACT; import static org.objectweb.asm.Opcodes.ACC_FINAL; import static org.objectweb.asm.Opcodes.ACC_INTERFACE; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACC_STATIC; import static org.objectweb.asm.Opcodes.V1_5; import java.io.File; import java.io.IOException; import java.io.PrintStream; import org.objectweb.asm.ClassWriter; /** * Generate a interface * <pre> * public interface HelloWorld { * public static final String VERSION="1.7"; * void sayHello(String message); * } * </pre> * @param args */ public class GenerateClassTest { public static void main(String[] args) throws IOException { ClassWriter writer = new ClassWriter(0); String className="com/fjn/helper/frameworkex/asm/test/HelloWorld"; writer.visit(V1_5, ACC_PUBLIC +ACC_ABSTRACT +ACC_INTERFACE, className, null, "java/lang/Object", null); writer.visitField(ACC_PUBLIC +ACC_FINAL+ ACC_STATIC, "VERSION", "Ljava/lang/String;", null, "1.7").visitEnd(); writer.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "sayHello", "(Ljava/lang/String;)V", null, null).visitEnd(); writer.visitEnd(); byte[] bytes= writer.toByteArray(); String classContent = new String(bytes); File f = new File("./target/test-classes/HelloWorld.class"); if(f.exists()){ f.delete(); } f.createNewFile(); PrintStream out =new PrintStream(f); System.setOut(out); System.out.print(classContent); out.flush(); out.close(); } }
gpl-2.0
liningwang/camera
map0802/src/com/wangln/model/GongGao.java
445
package com.wangln.model; import com.wangln.base.BaseModel; public class GongGao extends BaseModel{ private String title; private String content; public GongGao() { // TODO Auto-generated constructor stub } public String getTitle(){ return title; } public void setTitle(String title){ this.title = title; } public String getContent(){ return content; } public void setContent(String content){ this.content = content; } }
gpl-2.0
Norkart/NK-VirtualGlobe
Xj3D/parsetest/sai/external/TextureDemo1.java
5930
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Frame; import java.util.HashMap; import org.web3d.x3d.sai.BrowserFactory; import org.web3d.x3d.sai.ExternalBrowser; import org.web3d.x3d.sai.MFNode; import org.web3d.x3d.sai.SFImage; import org.web3d.x3d.sai.SFNode; import org.web3d.x3d.sai.X3DComponent; import org.web3d.x3d.sai.X3DFieldEvent; import org.web3d.x3d.sai.X3DFieldEventListener; import org.web3d.x3d.sai.X3DNode; import org.web3d.x3d.sai.X3DScene; /** * TextureDemo1 * * Create your very own animated texture by modifying it every frame. */ public class TextureDemo1 { public static void main(String[] args) { // Step One: Create the browser component HashMap requestedParameters = new HashMap(); requestedParameters.put("Xj3D_ConsoleShown", Boolean.TRUE); requestedParameters.put("Xj3D_LocationShown", Boolean.FALSE); X3DComponent comp = BrowserFactory .createX3DComponent(requestedParameters); ExternalBrowser browser = comp.getBrowser(); Frame f = new Frame(); f.setLayout(new BorderLayout()); f.setBackground(Color.blue); f.add((Component) comp, BorderLayout.CENTER); f.show(); f.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); f.setSize(400, 400); // Step Two: Initialize your scene browser.addBrowserListener(new GenericSAIBrowserListener()); // In this case we're building the scene the hard old way using // createX3DFromString because this was originally an EAI // demo that's been rewritten slightly for X3D. X3DScene scene = browser.createX3DFromString("PROFILE Interactive\n" + "DEF Root Transform {}"); X3DNode nodes[] = scene.getRootNodes(); System.out.println("Number of nodes from create:" + nodes.length); System.out.println("Replacing world..."); browser.replaceWorld(scene); System.out.println("World replaced."); X3DScene firstScene = browser.createX3DFromString("PROFILE Interchange\n" + "Viewpoint {}\n" + "Group {}\n" ); X3DNode levelOne[] = firstScene.getRootNodes(); for (int counter=0; counter<levelOne.length; counter++) firstScene.removeRootNode(levelOne[counter]); // No ROUTEs to transfer from the temporary scene. X3DScene secondScene = browser.createX3DFromString( "PROFILE Interactive\n" + "Transform {\n" + " children [\n" + " Shape {\n" + " appearance Appearance {\n" + " texture PixelTexture {\n" + " image 8 8 3\n" + "0x00FF00 0x00FF00 0x00FF00 0x00FF00 0x00FF00 0x0000FF 0x0000FF 0x0000FF\n" + "0x0000FF 0x00FF00 0x00FF00 0x00FF00 0x0000FF 0x0000FF 0x0000FF 0x0000FF\n" + "0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF\n" + "0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF\n" + "0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF\n" + "0x0000FF 0x0000FF 0x0000FF 0xFF0000 0xFF0000 0xFF0000 0x0000FF 0x0000FF\n" + "0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF\n" + "0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF 0x0000FF\n" + " }\n" + " material Material {\n" + " emissiveColor 1 0 0\n" + " }\n" + " }\n" + " geometry Box {}\n" + " }\n" + " ]\n" + "}"); X3DNode levelTwo[] = secondScene.getRootNodes(); for (int counter=0; counter<levelTwo.length; counter++) secondScene.removeRootNode(levelTwo[counter]); // No routes to transfer from the temporary scene // Construct the scene by adding the second set of nodes to the first // set and the third set of nodes to the second set. ((MFNode) nodes[0].getField("set_children")).setValue(levelOne.length, levelOne); ((MFNode) levelOne[1].getField("set_children")).setValue( levelTwo.length, levelTwo); // Walk down the fields to the image field of the pixel texture. X3DNode[] children = new X3DNode[((MFNode) levelTwo[0] .getField("children")).getSize()]; ((MFNode) (levelTwo[0].getField("children"))).getValue(children); X3DNode appearance = ((SFNode) (children[0].getField("appearance"))) .getValue(); X3DNode pixelTexture = ((SFNode) (appearance.getField("texture"))) .getValue(); SFImage imageField = (SFImage) (pixelTexture.getField("image")); imageField.addX3DEventListener(new SAIImageMutatorOne()); // The image mutator will manipulate the values it receives, but we // need // to trigger an event first. int pixels[] = new int[imageField.getComponents() * imageField.getHeight() * imageField.getWidth()]; imageField.getPixels(pixels); imageField.setValue(8, 8, 3, pixels); } } /** * A demo utility for PixelTexture. All this class does is wait for an event on * its SFImage input, do some preselected manipulation on that event's value, * and then send the event off to its output. A thread.sleep is thrown in to * avoid running too fast, but it would be much better to do this work in a * seperate process. */ class SAIImageMutatorOne implements X3DFieldEventListener { /** Buffer for the pixel data */ int pixels[]; public SAIImageMutatorOne() { pixels = new int[64]; } /** * Respond to the field changing. This demo depends on the fact that it can * modify the field that it is receiving an event from. This is not always * the case */ public void readableFieldChanged(X3DFieldEvent evt) { /** Get the event, change it, and then send a new value. */ SFImage src = (SFImage) (evt.getSource()); src.getPixels(pixels); int height = src.getHeight(); int width = src.getWidth(); int components = src.getComponents(); int pixelZero = pixels[0]; for (int counter = 1; counter < 64; counter++) { pixels[counter - 1] = pixels[counter]; } pixels[63] = pixelZero; src.setValue(height, width, components, pixels); } }
gpl-2.0
HackGunGame/HackGun
src/main/java/io/github/HackGunGame/main/Game.java
613
package io.github.HackGunGame.main; import com.jhilden13.java.advancedOutput.AdvancedOutput; import io.github.HackGunGame.resources.ProgramAttributes; import io.github.HackGunGame.script.Script; /** * Created by Josiah on 11/23/2015. */ public class Game { public static void init(String[] args) { long sMs = System.currentTimeMillis(); AdvancedOutput.init(ProgramAttributes.AID); Script.init(); AdvancedOutput.printLn(AdvancedOutput.level.INFO, "Finished Init in " + (System.currentTimeMillis() - sMs) + " miliseconds."); } public static void run() { } }
gpl-2.0
smeny/JPC
src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/vm/fsubr_ST7_ST3.java
2066
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package com.github.smeny.jpc.emulator.execution.opcodes.vm; import com.github.smeny.jpc.emulator.execution.*; import com.github.smeny.jpc.emulator.execution.decoder.*; import com.github.smeny.jpc.emulator.processor.*; import com.github.smeny.jpc.emulator.processor.fpu64.*; import static com.github.smeny.jpc.emulator.processor.Processor.*; public class fsubr_ST7_ST3 extends Executable { public fsubr_ST7_ST3(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double freg0 = cpu.fpu.ST(7); double freg1 = cpu.fpu.ST(3); if ((freg0 == Double.NEGATIVE_INFINITY && freg1 == Double.NEGATIVE_INFINITY) || (freg0 == Double.POSITIVE_INFINITY && freg1 == Double.POSITIVE_INFINITY)) cpu.fpu.setInvalidOperation(); cpu.fpu.setST(7, freg1-freg0); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
aosm/gcc_40
libjava/java/io/CharArrayWriter.java
8413
/* CharArrayWriter.java -- Write chars to a buffer Copyright (C) 1998, 1999, 2001, 2002 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. 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 GNU General Public License cover the whole combination. As a special 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 this 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 java.io; /** * This class allows data to be written to a char array buffer and * and then retrieved by an application. The internal char array * buffer is dynamically resized to hold all the data written. Please * be aware that writing large amounts to data to this stream will * cause large amounts of memory to be allocated. * <p> * The size of the internal buffer defaults to 32 and it is resized * in increments of 1024 chars. This behavior can be over-ridden by using the * following two properties: * <p> * <ul> * <li><xmp>gnu.java.io.CharArrayWriter.initialBufferSize</xmp></li> * <li><xmp>gnu.java.io.CharArrayWriter.bufferIncrementSize</xmp></li> * </ul> * <p> * There is a constructor that specified the initial buffer size and * that is the preferred way to set that value because it it portable * across all Java class library implementations. * <p> * * @author Aaron M. Renn (arenn@urbanophile.com) * @author Tom Tromey <tromey@cygnus.com> */ public class CharArrayWriter extends Writer { /** * The default initial buffer size */ private static final int DEFAULT_INITIAL_BUFFER_SIZE = 32; /** * This method initializes a new <code>CharArrayWriter</code> with * the default buffer size of 32 chars. If a different initial * buffer size is desired, see the constructor * <code>CharArrayWriter(int size)</code>. */ public CharArrayWriter () { this (DEFAULT_INITIAL_BUFFER_SIZE); } /** * This method initializes a new <code>CharArrayWriter</code> with * a specified initial buffer size. * * @param size The initial buffer size in chars */ public CharArrayWriter (int size) { super (); buf = new char[size]; } /** * Closes the stream. This method is guaranteed not to free the contents * of the internal buffer, which can still be retrieved. */ public void close () { } /** * This method flushes all buffered chars to the stream. */ public void flush () { } /** * This method discards all of the chars that have been written to the * internal buffer so far by setting the <code>count</code> variable to * 0. The internal buffer remains at its currently allocated size. */ public void reset () { synchronized (lock) { count = 0; } } /** * This method returns the number of chars that have been written to * the buffer so far. This is the same as the value of the protected * <code>count</code> variable. If the <code>reset</code> method is * called, then this value is reset as well. Note that this method does * not return the length of the internal buffer, but only the number * of chars that have been written to it. * * @return The number of chars in the internal buffer * * @see #reset() */ public int size () { return count; } /** * This method returns a char array containing the chars that have been * written to this stream so far. This array is a copy of the valid * chars in the internal buffer and its length is equal to the number of * valid chars, not necessarily to the the length of the current * internal buffer. Note that since this method allocates a new array, * it should be used with caution when the internal buffer is very large. */ public char[] toCharArray () { synchronized (lock) { char[] nc = new char[count]; System.arraycopy(buf, 0, nc, 0, count); return nc; } } /** * Returns the chars in the internal array as a <code>String</code>. The * chars in the buffer are converted to characters using the system default * encoding. There is an overloaded <code>toString()</code> method that * allows an application specified character encoding to be used. * * @return A <code>String</code> containing the data written to this * stream so far */ public String toString () { synchronized (lock) { return new String (buf, 0, count); } } /** * This method writes the writes the specified char into the internal * buffer. * * @param oneChar The char to be read passed as an int */ public void write (int oneChar) { synchronized (lock) { resize (1); buf[count++] = (char) oneChar; } } /** * This method writes <code>len</code> chars from the passed in array * <code>buf</code> starting at index <code>offset</code> into that buffer * * @param buffer The char array to write data from * @param offset The index into the buffer to start writing data from * @param len The number of chars to write */ public void write (char[] buffer, int offset, int len) { synchronized (lock) { if (len >= 0) resize (len); System.arraycopy(buffer, offset, buf, count, len); count += len; } } /** * This method writes <code>len</code> chars from the passed in * <code>String</code> <code>buf</code> starting at index * <code>offset</code> into the internal buffer. * * @param str The <code>String</code> to write data from * @param offset The index into the string to start writing data from * @param len The number of chars to write */ public void write (String str, int offset, int len) { synchronized (lock) { if (len >= 0) resize (len); str.getChars(offset, offset + len, buf, count); count += len; } } /** * This method writes all the chars that have been written to this stream * from the internal buffer to the specified <code>Writer</code>. * * @param out The <code>Writer</code> to write to * * @exception IOException If an error occurs */ public void writeTo (Writer out) throws IOException { synchronized (lock) { out.write(buf, 0, count); } } /** * This private method makes the buffer bigger when we run out of room * by allocating a larger buffer and copying the valid chars from the * old array into it. This is obviously slow and should be avoided by * application programmers by setting their initial buffer size big * enough to hold everything if possible. */ private void resize (int len) { if (count + len >= buf.length) { int newlen = buf.length * 2; if (count + len > newlen) newlen = count + len; char[] newbuf = new char[newlen]; System.arraycopy(buf, 0, newbuf, 0, count); buf = newbuf; } } /** * The internal buffer where the data written is stored */ protected char[] buf; /** * The number of chars that have been written to the buffer */ protected int count; }
gpl-2.0
fjoncourt/jfwknop
src/main/java/com/cipherdyne/gui/gpg/GpgKeySettingsController.java
2292
/* * JFwknop is developed primarily by the people listed in the file 'AUTHORS'. * Copyright (C) 2016 JFwknop developers and contributors. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.cipherdyne.gui.gpg; import com.cipherdyne.utils.GpgUtils; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; /** * */ public class GpgKeySettingsController { // GPG key settings view used by the controller private GpgKeySettingsView view; // GPG home directory to use to create the brand new GPG key private String gpgHomeDirectory; /** * Constructor * * @param parentWindow parent frame * @param gpgHomeDirectory GPG home directory */ public GpgKeySettingsController(JFrame parentWindow, String gpgHomeDirectory) { this.gpgHomeDirectory = gpgHomeDirectory; this.view = new GpgKeySettingsView(parentWindow); updateBtnBehaviour(); this.view.setVisible(true); } /** * Update button action listeners */ private void updateBtnBehaviour() { this.view.getBtnSubmit().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String userId = GpgKeySettingsController.this.view.getUserId().getText(); String passphrase = GpgKeySettingsController.this.view.getPassphrase().getText(); GpgUtils.createKey(gpgHomeDirectory, userId, passphrase); GpgKeySettingsController.this.view.dispose(); } }); } }
gpl-2.0
intelie/esper
esper/src/main/java/com/espertech/esper/epl/core/MethodPollingExecStrategy.java
5858
/************************************************************************************** * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * 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.core; import com.espertech.esper.client.EPException; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.EventType; import com.espertech.esper.epl.db.PollExecStrategy; import com.espertech.esper.event.EventAdapterService; import net.sf.cglib.reflect.FastMethod; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Viewable providing historical data from a database. */ public class MethodPollingExecStrategy implements PollExecStrategy { private static final Log log = LogFactory.getLog(MethodPollingExecStrategy.class); private final EventAdapterService eventAdapterService; private final FastMethod method; private boolean isArray; private boolean useMapType; private EventType eventType; /** * Ctor. * @param eventAdapterService for generating event beans * @param method the method to invoke * @param useMapType is true to indicate that Map-events are generated * @param eventType is the event type to use */ public MethodPollingExecStrategy(EventAdapterService eventAdapterService, FastMethod method, boolean useMapType, EventType eventType) { this.eventAdapterService = eventAdapterService; this.method = method; this.isArray = method.getReturnType().isArray(); this.useMapType = useMapType; this.eventType = eventType; } public void start() { } public void done() { } public void destroy() { } public List<EventBean> poll(Object[] lookupValues) { List<EventBean> rowResult = null; try { Object invocationResult = method.invoke(null, lookupValues); if (invocationResult != null) { if (isArray) { int length = Array.getLength(invocationResult); if (length > 0) { rowResult = new ArrayList<EventBean>(); for (int i = 0; i < length; i++) { Object value = Array.get(invocationResult, i); if (value == null) { log.warn("Expected non-null return result from method '" + method.getName() + "', but received null value"); continue; } EventBean event; if (useMapType) { if (!(value instanceof Map)) { log.warn("Expected Map-type return result from method '" + method.getName() + "', but received type '" + value.getClass() + "'"); continue; } Map mapValues = (Map) value; event = eventAdapterService.adaptorForTypedMap(mapValues, eventType); } else { event = eventAdapterService.adapterForBean(value); } rowResult.add(event); } } } else { rowResult = new LinkedList<EventBean>(); EventBean event; if (useMapType) { if (!(invocationResult instanceof Map)) { log.warn("Expected Map-type return result from method '" + method.getName() + "', but received type '" + invocationResult.getClass() + "'"); } else { Map mapValues = (Map) invocationResult; event = eventAdapterService.adaptorForTypedMap(mapValues, eventType); rowResult.add(event); } } else { event = eventAdapterService.adapterForBean(invocationResult); rowResult.add(event); } } } } catch (InvocationTargetException ex) { throw new EPException("Method '" + method.getName() + "' of class '" + method.getJavaMethod().getDeclaringClass().getName() + "' reported an exception: " + ex.getTargetException(), ex.getTargetException()); } return rowResult; } }
gpl-2.0
eshkinkot/midpssh
src/httpserver/midpssh/HttpFields.java
4934
/* This file is part of "MidpSSH". * Copyright (c) 2006 Karl von Randow. * * --LICENSE NOTICE-- * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * --LICENSE NOTICE-- * */ package midpssh; import java.io.EOFException; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; /** * * @author karl * @version */ public class HttpFields extends Object implements Serializable, Cloneable { private ArrayList fieldNames = new ArrayList(); private ArrayList fieldValues = new ArrayList(); /** Holds value of property firstLine. */ private String firstLine; /** Creates new HttpFields */ public HttpFields() { } public boolean read(HttpInputStream in) throws IOException { firstLine = in.readLineInclusive(); if (firstLine == null) throw new EOFException("EOF reading HTTP headers"); String trimmedFirstLine = HttpInputStream.trimNewline(firstLine); if (trimmedFirstLine.length() == 0) { firstLine = ""; return false; } // Sanity check, some servers don't return headers they just return body // straight away (eg. images on Tucows.com) if (firstLine.indexOf("HTTP/") == -1) { in.unreadLine(firstLine); firstLine = null; return true; } // Trim the newline characters firstLine = trimmedFirstLine; String line = in.readLine(); String key = null; StringBuffer value = null; // System.out.println(); // System.out.println( firstLine ); while (line != null && line.length() != 0) { // System.out.println( line ); if (line.startsWith(" ")) { if (value == null) { throw new IOException("Found header field continuation before a header field!: \"" + line + "\""); } // value.append( " " ); value.append(line); // .trim() } else { int colon = line.indexOf(":"); if (colon == -1) { if (value != null) { value.append(' '); value.append(line); } } else { if (key != null) { addField(key, value.toString().trim()); } key = line.substring(0, colon); value = new StringBuffer(); if (colon + 2 < line.length()) { value.append(line.substring(colon + 2)); // .trim() } } } line = in.readLine(); } if (key != null) { addField(key, value.toString().trim()); } if (line == null) throw new EOFException("EOF reading HTTP headers"); return true; } public String get(String fieldName) { return getField(fieldName); } public String getField(String fieldName) { int n = fieldNames.size(); for (int i = 0; i < n; i++) { String key = (String) fieldNames.get(i); if (key.equalsIgnoreCase(fieldName)) { return (String) fieldValues.get(i); } } return null; } public int getIntField(String fieldName) throws NumberFormatException { return getIntField(fieldName, -1); } public int getIntField(String fieldName, int defaultValue) throws NumberFormatException { String value = getField(fieldName); if (value != null) { value = value.trim(); try { return Integer.parseInt(value); } catch (NumberFormatException e) { // Try to get some numbers from the front as some spastic web // servers return something after the number, /* * eg. from * http://ad.nz.doubleclick.net/viewad/622507/asb_matrix_home_tile_260x80.gif * HTTP/1.0 200 OK Server: DCLK-HttpSvr Content-Type: image/gif * Content-Length: 7996Wed, 13 Aug 2003 04:51:35 GMT */ int iValue = -1; for (int i = 1; i <= value.length(); i++) { try { iValue = Integer.parseInt(value.substring(0, i)); } catch (NumberFormatException f) { // If possible return the last number that was valid if (i > 1) return iValue; // Otherwise throw the original exception break; } } throw e; } } else { return defaultValue; } } /** */ public void addField(String key, String value) { fieldNames.add(key); fieldValues.add(value); } /** * Getter for property firstLine. * * @return Value of property firstLine. */ public String getFirstLine() { return firstLine; } }
gpl-2.0
Shashi-Bhushan/General
algo-trials/src/main/java/in/shabhushan/algo_trials/PascalTriangle.java
793
package in.shabhushan.algo_trials; import java.util.ArrayList; import java.util.List; public class PascalTriangle { public static List<List<Integer>> getPascalTriangle(int depth) { List<List<Integer>> output = new ArrayList<>(); for (int i = 0; i < depth; i++) { List<Integer> list = new ArrayList<>(); list.add(1); output.add(list); } // for (int iter = 1; iter < depth; iter++) { int number = 1; for (int level = iter; level < depth; level++) { // get the list to add the number List<Integer> list = output.get(level); int lastNumber = list.get(list.size() - 1); list.add(number); number += lastNumber; } } System.out.println(depth + " " + output); return output; } }
gpl-2.0
hamsterxc/TheTaleClient
app/src/main/java/com/lonebytesoft/thetaleclient/api/dictionary/Habit.java
610
package com.lonebytesoft.thetaleclient.api.dictionary; /** * @author Hamster * @since 02.10.2014 */ public enum Habit { HONOR(0, "honor", "честь"), PEACEFULNESS(1, "peacefulness", "миролюбие"), ; public final int code; public final String name; public final String description; Habit(final int code, final String name, final String description) { this.code = code; this.name = name; this.description = description; } public int getCode() { return code; } public String getName() { return name; } }
gpl-2.0
smarr/Truffle
substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/heap/Target_java_lang_ref_PhantomReference.java
1832
/* * Copyright (c) 2021, 2021, 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.oracle.svm.core.heap; import java.lang.ref.PhantomReference; import com.oracle.svm.core.SubstrateUtil; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import com.oracle.svm.core.annotate.TargetElement; import com.oracle.svm.core.jdk.JDK17OrLater; @TargetClass(PhantomReference.class) public final class Target_java_lang_ref_PhantomReference<T> { @Substitute @TargetElement(onlyWith = JDK17OrLater.class) boolean refersTo0(Object obj) { return ReferenceInternals.refersTo(SubstrateUtil.cast(this, PhantomReference.class), obj); } }
gpl-2.0
Halcom/zanata-server
zanata-war/src/main/java/org/zanata/rest/editor/service/SuggestionsService.java
5648
/* * Copyright 2015, 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 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 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 GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General 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 org.zanata.rest.editor.service; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.googlecode.totallylazy.Option; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import org.apache.deltaspike.jpa.api.transaction.Transactional; import org.zanata.common.LocaleId; import org.zanata.model.HLocale; import org.zanata.rest.editor.dto.suggestion.Suggestion; import org.zanata.rest.editor.service.resource.SuggestionsResource; import org.zanata.service.LocaleService; import org.zanata.service.TranslationMemoryService; import org.zanata.webtrans.shared.model.TransMemoryQuery; import javax.annotation.Nullable; import javax.ws.rs.Path; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.Response; import java.util.List; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static org.zanata.webtrans.shared.rpc.HasSearchType.*; /** * @see org.zanata.rest.editor.service.resource.SuggestionsResource */ @RequestScoped @Named("editor.suggestionsService") @Path(SuggestionsResource.SERVICE_PATH) @Transactional(readOnly = true) public class SuggestionsService implements SuggestionsResource { public static final String SEARCH_TYPES = Joiner.on(", ").join(SearchType.values()); @Inject private TranslationMemoryService transMemoryService; @Inject private LocaleService localeService; @Override public Response query(List<String> query, String sourceLocaleString, String transLocaleString, String searchTypeString, long textFlowTargetId) { Option<SearchType> searchType = getSearchType(searchTypeString); if (searchType.isEmpty()) { return unknownSearchTypeResponse(searchTypeString); } Option<LocaleId> sourceLocale = getLocale(sourceLocaleString); if (sourceLocale.isEmpty()) { return Response.status(BAD_REQUEST) .entity(String.format("Unrecognized source locale: \"%s\"", sourceLocaleString)) .build(); } Option<LocaleId> transLocale = getLocale(transLocaleString); if (transLocale.isEmpty()) { return Response.status(BAD_REQUEST) .entity(String.format("Unrecognized translation locale: \"%s\"", transLocaleString)) .build(); } Optional<Long> tft; if (textFlowTargetId < 0) { tft = Optional.absent(); } else { tft = Optional.of(textFlowTargetId); } List<Suggestion> suggestions = transMemoryService.searchTransMemoryWithDetails(transLocale.get(), sourceLocale.get(), new TransMemoryQuery(query, searchType.get()), tft); // Wrap in generic entity to prevent type erasure, so that an // appropriate MessageBodyReader can be used. // see docs for GenericEntity GenericEntity<List<Suggestion>> entity = new GenericEntity<List<Suggestion>>(suggestions) {}; return Response.ok(entity).build(); } /** * Try to get a valid locale for a given string. * * @param localeString used to look up the locale * @return a wrapped LocaleId if the given string matches one, otherwise an empty option. */ private Option<LocaleId> getLocale(String localeString) { @Nullable HLocale hLocale = localeService.getByLocaleId(localeString); if (hLocale == null) { return Option.none(); } return Option.option(hLocale.getLocaleId()); } /** * Try to get a valid search type constant for a given string. * * @param searchTypeString used to look up the search type. Case insensitive. * @return A wrapped SearchType if the given string matches one, otherwise an empty option. */ private Option<SearchType> getSearchType(String searchTypeString) { for (SearchType type : SearchType.values()) { if (type.name().equalsIgnoreCase(searchTypeString)) { return Option.option(type); } } return Option.none(); } /** * Generate and build an error response that reports the search type being unrecognized. * * @param searchTypeString shown in the error message as the unrecognized string * @return a built Response. */ private Response unknownSearchTypeResponse(String searchTypeString) { String error = String.format("Unrecognized search type: \"%s\". Expected one of: %s", searchTypeString, SEARCH_TYPES); return Response.status(BAD_REQUEST).entity(error).build(); } }
gpl-2.0
Blackjak34/DoesNotCompute
src/main/java/com/github/blackjak34/compute/packet/MessageKeyTyped.java
616
package com.github.blackjak34.compute.packet; import io.netty.buffer.ByteBuf; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; public class MessageKeyTyped implements IMessage { private char keyTyped; @SuppressWarnings("unused") public MessageKeyTyped() {} public MessageKeyTyped(char keyTyped) { this.keyTyped = keyTyped; } public void fromBytes(ByteBuf buffer) { keyTyped = buffer.readChar(); } public void toBytes(ByteBuf buffer) { buffer.writeChar(keyTyped); } public char getKeyTyped() { return keyTyped; } }
gpl-2.0
AcademicTorrents/AcademicTorrents-Downloader
frostwire-merge/org/gudy/azureus2/ui/swt/views/peer/PeerFilesView.java
6475
/** * Copyright (C) Azureus Software, Inc, All Rights Reserved. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package org.gudy.azureus2.ui.swt.views.peer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.gudy.azureus2.core3.disk.DiskManagerFileInfo; import org.gudy.azureus2.core3.peer.PEPeer; import org.gudy.azureus2.core3.util.DisplayFormatters; import org.gudy.azureus2.plugins.ui.tables.TableCell; import org.gudy.azureus2.plugins.ui.tables.TableCellRefreshListener; import org.gudy.azureus2.plugins.ui.tables.TableColumn; import org.gudy.azureus2.ui.swt.views.table.CoreTableColumnSWT; import org.gudy.azureus2.ui.swt.views.table.TableViewSWT; import org.gudy.azureus2.ui.swt.views.table.impl.TableViewFactory; import org.gudy.azureus2.ui.swt.views.table.impl.TableViewTab; import com.aelitis.azureus.core.peermanager.piecepicker.util.BitFlags; import com.aelitis.azureus.ui.common.table.*; import com.aelitis.azureus.ui.common.table.impl.TableColumnManager; public class PeerFilesView extends TableViewTab<PeerFilesView.PeersFilesViewRow> implements TableDataSourceChangedListener, TableLifeCycleListener, TableRefreshListener { public static final String TABLEID_PEER_FILES = "PeerFiles"; boolean refreshing = false; private static final TableColumnCore[] basicItems = { new NameItem(), new PercentItem(), }; static{ TableColumnManager tcManager = TableColumnManager.getInstance(); tcManager.setDefaultColumnNames( TABLEID_PEER_FILES, basicItems ); } private TableViewSWT<PeersFilesViewRow> tv; private PEPeer current_peer; public PeerFilesView() { super( "PeerFilesView"); } public TableViewSWT<PeersFilesViewRow> initYourTableView() { tv = TableViewFactory.createTableViewSWT( PeersFilesViewRow.class, TABLEID_PEER_FILES, getPropertiesPrefix(), basicItems, "firstpiece", SWT.MULTI | SWT.FULL_SELECTION | SWT.VIRTUAL); tv.setRowDefaultIconSize(new Point(16, 16)); tv.addTableDataSourceChangedListener(this, true); tv.addRefreshListener(this, true); tv.addLifeCycleListener(this); return tv; } public void tableDataSourceChanged( Object newDataSource) { if ( newDataSource instanceof PEPeer ){ current_peer = (PEPeer)newDataSource; }if ( newDataSource instanceof Object[] ){ Object[] temp = (Object[])newDataSource; if ( temp.length > 0 && temp[0] instanceof PEPeer ){ current_peer = (PEPeer)temp[0]; }else{ current_peer = null; } }else{ current_peer = null; } } public void tableRefresh() { synchronized( this ){ if ( refreshing ){ return; } refreshing = true; } try{ PEPeer peer = current_peer; if ( peer == null ){ tv.removeAllTableRows(); }else{ if ( tv.getRowCount() == 0 ){ DiskManagerFileInfo[] files = peer.getManager().getDiskManager().getFiles(); PeersFilesViewRow[] rows = new PeersFilesViewRow[ files.length ]; for ( int i=0;i<files.length;i++ ){ rows[i] = new PeersFilesViewRow( files[i], peer ); } tv.addDataSources( rows ); tv.processDataSourceQueueSync(); }else{ TableRowCore[] rows = tv.getRows(); for ( TableRowCore row: rows ){ ((PeersFilesViewRow)row.getDataSource()).setPeer( peer ); } } } }finally{ synchronized( this ){ refreshing = false; } } } public void tableViewInitialized() { } public void tableViewTabInitComplete() { super.tableViewTabInitComplete(); } public void tableViewDestroyed() { } protected static class PeersFilesViewRow { private DiskManagerFileInfo file; private PEPeer peer; private PeersFilesViewRow( DiskManagerFileInfo _file, PEPeer _peer ) { file = _file; peer = _peer; } private DiskManagerFileInfo getFile() { return( file ); } private void setPeer( PEPeer _peer ) { peer = _peer; } private PEPeer getPeer() { return( peer ); } } private static class NameItem extends CoreTableColumnSWT implements TableCellRefreshListener { private NameItem() { super( "name", ALIGN_LEAD, POSITION_LAST, 300, TABLEID_PEER_FILES ); setType(TableColumn.TYPE_TEXT); } public void refresh( TableCell cell ) { PeersFilesViewRow row = (PeersFilesViewRow) cell.getDataSource(); String name = (row == null) ? "" : row.getFile().getFile(true).getName(); if (name == null) name = ""; cell.setText( name ); } } private static class PercentItem extends CoreTableColumnSWT implements TableCellRefreshListener { private PercentItem() { super( "%", ALIGN_TRAIL, POSITION_LAST, 60, TABLEID_PEER_FILES ); setRefreshInterval(INTERVAL_LIVE); setMinWidthAuto(true); } public void refresh( TableCell cell ) { PeersFilesViewRow row = (PeersFilesViewRow) cell.getDataSource(); if ( row == null ){ return; } DiskManagerFileInfo file = row.getFile(); PEPeer peer = row.getPeer(); BitFlags pieces = peer.getAvailable(); if( pieces == null ){ cell.setText( "" ); return; } boolean[] flags = pieces.flags; int first_piece = file.getFirstPieceNumber(); int last_piece = file.getLastPieceNumber(); int done = 0; for ( int i=first_piece;i<=last_piece;i++){ if ( flags[i] ){ done++; } } int percent = ( done * 1000 ) / (last_piece - first_piece + 1 ); cell.setText(percent < 0 ? "" : DisplayFormatters.formatPercentFromThousands((int) percent)); } } }
gpl-2.0
Bysmyyr/cpabe
jpbc/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/base/AbstractFieldOver.java
614
package it.unisa.dia.gas.plaf.jpbc.field.base; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.jpbc.FieldOver; import java.util.Random; /** * @author Angelo De Caro (angelo.decaro@gmail.com) */ public abstract class AbstractFieldOver<F extends Field, E extends Element> extends AbstractField<E> implements FieldOver<F, E> { protected F targetField; protected AbstractFieldOver(Random random, F targetField) { super(random); this.targetField = targetField; } public F getTargetField() { return targetField; } }
gpl-2.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/X_ASP_Module.java
4613
/****************************************************************************** * 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 ASP_Module * @author Adempiere (generated) * @version Release 3.5.4a - $Id$ */ public class X_ASP_Module extends PO implements I_ASP_Module, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_ASP_Module (Properties ctx, int ASP_Module_ID, String trxName) { super (ctx, ASP_Module_ID, trxName); /** if (ASP_Module_ID == 0) { setASP_Module_ID (0); setName (null); setValue (null); } */ } /** Load Constructor */ public X_ASP_Module (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 4 - System */ 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_ASP_Module[") .append(get_ID()).append("]"); return sb.toString(); } /** Set ASP Module. @param ASP_Module_ID ASP Module */ public void setASP_Module_ID (int ASP_Module_ID) { if (ASP_Module_ID < 1) set_ValueNoCheck (COLUMNNAME_ASP_Module_ID, null); else set_ValueNoCheck (COLUMNNAME_ASP_Module_ID, Integer.valueOf(ASP_Module_ID)); } /** Get ASP Module. @return ASP Module */ public int getASP_Module_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ASP_Module_ID); if (ii == null) return 0; return ii.intValue(); } /** 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 Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** 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 Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
gpl-2.0
hdadler/sensetrace-src
com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-arq/src/main/java/com/hp/hpl/jena/sparql/vocabulary/EARL.java
7203
/* * 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 com.hp.hpl.jena.sparql.vocabulary; import com.hp.hpl.jena.rdf.model.*; /** * Vocabulary definitions from EARL.rdf * Auto-generated by schemagen */ public class EARL { /** <p>The RDF model that holds the vocabulary terms</p> */ private static Model m_model = ModelFactory.createDefaultModel(); /** <p>The namespace of the vocabulary as a string</p> */ public static final String NS = "http://www.w3.org/ns/earl#"; /** <p>The namespace of the vocabulary as a string</p> * @see #NS */ public static String getURI() {return NS;} /** <p>The namespace of the vocabulary as a resource</p> */ public static final Resource NAMESPACE = m_model.createResource( NS ); /** <p>assertor of an assertion</p> */ public static final Property assertedBy = m_model.createProperty( "http://www.w3.org/ns/earl#assertedBy" ); /** <p>additional warnings or error messages in a human-readable form</p> */ public static final Property info = m_model.createProperty( "http://www.w3.org/ns/earl#info" ); /** <p>assertor that is primarily responsible for performing the test</p> */ public static final Property mainAssertor = m_model.createProperty( "http://www.w3.org/ns/earl#mainAssertor" ); /** <p>mode in which the test was performed</p> */ public static final Property mode = m_model.createProperty( "http://www.w3.org/ns/earl#mode" ); /** <p>outcome of performing the test</p> */ public static final Property outcome = m_model.createProperty( "http://www.w3.org/ns/earl#outcome" ); /** <p>location within a test subject that are most relevant to a test result</p> */ public static final Property pointer = m_model.createProperty( "http://www.w3.org/ns/earl#pointer" ); /** <p>result of an assertion</p> */ public static final Property result = m_model.createProperty( "http://www.w3.org/ns/earl#result" ); /** <p>test subject of an assertion</p> */ public static final Property subject = m_model.createProperty( "http://www.w3.org/ns/earl#subject" ); /** <p>test criterion of an assertion</p> */ public static final Property test = m_model.createProperty( "http://www.w3.org/ns/earl#test" ); /** <p>a statement that embodies the results of a test</p> */ public static final Resource Assertion = m_model.createResource( "http://www.w3.org/ns/earl#Assertion" ); /** <p>an entity such as a person, a software tool, an organization, or any other * grouping that carries out a test collectively</p> */ public static final Resource Assertor = m_model.createResource( "http://www.w3.org/ns/earl#Assertor" ); /** <p>the class of outcomes to denote an undetermined outcome</p> */ public static final Resource CannotTell = m_model.createResource( "http://www.w3.org/ns/earl#CannotTell" ); /** <p>the class of outcomes to denote failing a test</p> */ public static final Resource Fail = m_model.createResource( "http://www.w3.org/ns/earl#Fail" ); /** <p>the class of outcomes to denote the test is not applicable</p> */ public static final Resource NotApplicable = m_model.createResource( "http://www.w3.org/ns/earl#NotApplicable" ); /** <p>the class of outcomes to denote the test has not been carried out</p> */ public static final Resource NotTested = m_model.createResource( "http://www.w3.org/ns/earl#NotTested" ); /** <p>a discrete value that describes a resulting condition from carrying out the * test</p> */ public static final Resource OutcomeValue = m_model.createResource( "http://www.w3.org/ns/earl#OutcomeValue" ); /** <p>the class of outcomes to denote passing a test</p> */ public static final Resource Pass = m_model.createResource( "http://www.w3.org/ns/earl#Pass" ); /** <p>any piece of software such as an authoring tool, browser, or evaluation tool</p> */ public static final Resource Software = m_model.createResource( "http://www.w3.org/ns/earl#Software" ); /** <p>an atomic test, usually one that is a partial test for a requirement</p> */ public static final Resource TestCase = m_model.createResource( "http://www.w3.org/ns/earl#TestCase" ); /** <p>a testable statement, usually one that can be passed or failed</p> */ public static final Resource TestCriterion = m_model.createResource( "http://www.w3.org/ns/earl#TestCriterion" ); /** <p>describes how a test was carried out</p> */ public static final Resource TestMode = m_model.createResource( "http://www.w3.org/ns/earl#TestMode" ); /** <p>a higher-level requirement that is tested by executing one or more sub-tests</p> */ public static final Resource TestRequirement = m_model.createResource( "http://www.w3.org/ns/earl#TestRequirement" ); /** <p>the actual result of performing the test</p> */ public static final Resource TestResult = m_model.createResource( "http://www.w3.org/ns/earl#TestResult" ); /** <p>the class of things that have been tested against some test criterion</p> */ public static final Resource TestSubject = m_model.createResource( "http://www.w3.org/ns/earl#TestSubject" ); public static final Resource automatic = m_model.createResource( "http://www.w3.org/ns/earl#automatic" ); public static final Resource cantTell = m_model.createResource( "http://www.w3.org/ns/earl#cantTell" ); public static final Resource failed = m_model.createResource( "http://www.w3.org/ns/earl#failed" ); public static final Resource inapplicable = m_model.createResource( "http://www.w3.org/ns/earl#inapplicable" ); public static final Resource manual = m_model.createResource( "http://www.w3.org/ns/earl#manual" ); public static final Resource passed = m_model.createResource( "http://www.w3.org/ns/earl#passed" ); public static final Resource semiAuto = m_model.createResource( "http://www.w3.org/ns/earl#semiAuto" ); public static final Resource undisclosed = m_model.createResource( "http://www.w3.org/ns/earl#undisclosed" ); public static final Resource unknownMode = m_model.createResource( "http://www.w3.org/ns/earl#unknownMode" ); public static final Resource untested = m_model.createResource( "http://www.w3.org/ns/earl#untested" ); }
gpl-2.0
caipiao/Lottery
src/com/jeecms/common/page/Pagination.java
1396
package com.jeecms.common.page; import java.util.List; /** * 列表分页。包含list属性。 */ @SuppressWarnings("serial") public class Pagination extends SimplePage implements java.io.Serializable, Paginable { public Pagination() { } /** * 构造器 * * @param pageNo * 页码 * @param pageSize * 每页几条数据 * @param totalCount * 总共几条数据 */ public Pagination(int pageNo, int pageSize, int totalCount) { super(pageNo, pageSize, totalCount); } /** * 构造器 * * @param pageNo * 页码 * @param pageSize * 每页几条数据 * @param totalCount * 总共几条数据 * @param list * 分页内容 */ public Pagination(int pageNo, int pageSize, int totalCount, List<?> list) { super(pageNo, pageSize, totalCount); this.list = list; } /** * 第一条数据位置 * * @return */ public int getFirstResult() { return (pageNo - 1) * pageSize; } /** * 当前页的数据 */ private List<?> list; /** * 获得分页内容 * * @return */ public List<?> getList() { return list; } /** * 设置分页内容 * * @param list */ @SuppressWarnings("unchecked") public void setList(List list) { this.list = list; } }
gpl-2.0
algo3-2015-fiuba/algocraft
src/vistas/actores/jugadores/ActorJugadorTerran.java
585
package vistas.actores.jugadores; import java.awt.Graphics; import vistas.actores.Actor; import vistas.actores.construcciones.terran.ActorBaseTerran; public class ActorJugadorTerran extends ActorJugador { public ActorJugadorTerran() { this.nombre = "Unidad"; } @Override public void dibujar(Graphics g) { //Nunca deberia dibujarse //Quizas mostrar un icono en la parte superior } @Override public void dibujarBase(Graphics g, Object base) { Actor actorBaseTerran = new ActorBaseTerran(); actorBaseTerran.asignarEstado(base); actorBaseTerran.dibujar(g); } }
gpl-2.0
fprates/iocaste
src/runtime/lib/org/iocaste/runtime/common/page/StandardPageConfig.java
1533
package org.iocaste.runtime.common.page; import org.iocaste.runtime.common.application.Context; import org.iocaste.runtime.common.navcontrol.NavControl; import org.iocaste.runtime.common.style.ViewConfigStyle; public class StandardPageConfig extends AbstractViewConfig<Context> { /** * * @param context * @param page * @param name */ private final void config( Context context, AbstractPage page, String name) { ViewConfig extconfig; ViewConfigStyle style; AbstractPage child; extconfig = (child = page.getChild(name)).getConfig(); if (page.isSubPage(name) || (extconfig == null)) return; style = child.getConfigStyle(); if (style != null) { style.set(page.getStyleSheet()); style.execute(); } extconfig.run(context); } @Override protected void execute(Context context) { NavControl navcontrol; String submit; AbstractPage page; getTool("outercontent").style = "content_area"; getTool("content").attributes.put("style", "margin-top:3px"); page = context.getPage(); submit = page.getSubmit(); navcontrol = page.getNavControl(); if (submit != null) navcontrol.submit(submit); for (String action : page.getActions()) navcontrol.add(action); for (String key : page.getChildren()) config(context, page, key); } }
gpl-2.0
pascal888/UniParthenope-Widget
SendMail.java
2248
package Widget; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMail { private String username; private String password; private String destination; //Destinatario private String subject; //Oggetto della mail private String body_mail; //Corpo della mail Alert alert=new Alert(); //Creo una sessione per l'autenticazione public SendMail() { } // set nome utente public void setUserName(String user){ this.username=user; System.out.println("User impostato\n"); } // set della password public void setPassword(String password){ this.password=password; System.out.println("password impostato\n"); } //set del testo della mail public void setMessage(String text){ this.body_mail=text; System.out.println("messaggio impostato\n"); } // set dell'oggetto public void setSubject(String subject){ this.subject=subject; System.out.println("soggetto impostato\n"); } public void setDestination(String destination){ this.destination=destination; System.out.println("destinatario impostato\n"); } //Metodo per inviare mail public void send(){ Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.office365.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination)); message.setSubject(subject); message.setText(body_mail); Transport.send(message); System.out.println("Fatto"); alert.show_alert("Mail inviata correttamente"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
gpl-2.0
simplyianm/stanford-corenlp
src/main/java/edu/stanford/nlp/ie/QuantifiableEntityNormalizer.java
57729
package edu.stanford.nlp.ie; import edu.stanford.nlp.ie.pascal.ISODateInstance; import edu.stanford.nlp.ie.regexp.NumberSequenceClassifier; import edu.stanford.nlp.ling.CoreAnnotations.*; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.sequences.SeqClassifierFlags; import edu.stanford.nlp.stats.ClassicCounter; import edu.stanford.nlp.time.TimeAnnotations.*; import edu.stanford.nlp.time.Timex; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.util.EditDistance; import edu.stanford.nlp.util.Pair; import edu.stanford.nlp.util.StringUtils; import static java.lang.System.err; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Various methods for normalizing Money, Date, Percent, Time, and * Number, Ordinal amounts. * These matchers are generous in that they try to quantify something * that's already been labelled by an NER system; don't use them to make * classification decisions. This class has a twin in the pipeline world: * {@link edu.stanford.nlp.pipeline.QuantifiableEntityNormalizingAnnotator}. * Please keep the substantive content here, however, so as to lessen code * duplication. * <p> * <i>Implementation note:</i> The extensive test code for this class is * now in a separate JUnit Test class. This class depends on the background * symbol for NER being the default background symbol. This should be fixed * at some point. * * @author Chris Cox * @author Christopher Manning (extended for RTE) * @author Anna Rafferty */ public class QuantifiableEntityNormalizer { private static final boolean DEBUG = false; private static final boolean DEBUG2 = false; // String normlz functions public static String BACKGROUND_SYMBOL = SeqClassifierFlags.DEFAULT_BACKGROUND_SYMBOL; // this isn't a constant; it's set by the QuantifiableEntityNormalizingAnnotator private static final Pattern timePattern = Pattern.compile("([0-2]?[0-9])((?::[0-5][0-9]){0,2})([PpAa]\\.?[Mm]\\.?)?"); private static final Pattern moneyPattern = Pattern.compile("([$\u00A3\u00A5\u20AC#]?)(-?[0-9,]*)(\\.[0-9]*)?+"); private static final Pattern scorePattern = Pattern.compile(" *([0-9]+) *- *([0-9]+) *"); //Collections of entity types private static final Set<String> quantifiable; //Entity types that are quantifiable private static final Set<String> collapseBeforeParsing; private static final Set<String> timeUnitWords; private static final Map<String, Double> moneyMultipliers; private static final Map<String, Integer> moneyMultipliers2; private static final Map<String, Character> currencyWords; public static final ClassicCounter<String> wordsToValues; public static final ClassicCounter<String> ordinalsToValues; static { quantifiable = new HashSet<String>(); quantifiable.add("MONEY"); quantifiable.add("TIME"); quantifiable.add("DATE"); quantifiable.add("PERCENT"); quantifiable.add("NUMBER"); quantifiable.add("ORDINAL"); quantifiable.add("DURATION"); collapseBeforeParsing = new HashSet<String>(); collapseBeforeParsing.add("PERSON"); collapseBeforeParsing.add("ORGANIZATION"); collapseBeforeParsing.add("LOCATION"); timeUnitWords = new HashSet<String>(); timeUnitWords.add("second"); timeUnitWords.add("seconds"); timeUnitWords.add("minute"); timeUnitWords.add("minutes"); timeUnitWords.add("hour"); timeUnitWords.add("hours"); timeUnitWords.add("day"); timeUnitWords.add("days"); timeUnitWords.add("week"); timeUnitWords.add("weeks"); timeUnitWords.add("month"); timeUnitWords.add("months"); timeUnitWords.add("year"); timeUnitWords.add("years"); currencyWords = new HashMap<String,Character>(); currencyWords.put("dollars?", '$'); currencyWords.put("cents?", '$'); currencyWords.put("pounds?", '\u00A3'); currencyWords.put("pence|penny", '\u00A3'); currencyWords.put("yen", '\u00A5'); currencyWords.put("euros?", '\u20AC'); currencyWords.put("won", '\u20A9'); currencyWords.put("\\$", '$'); currencyWords.put("\u00A2", '$'); // cents currencyWords.put("\u00A3", '\u00A3'); // pounds currencyWords.put("#", '\u00A3'); // for Penn treebank currencyWords.put("\u00A5", '\u00A5'); // Yen currencyWords.put("\u20AC", '\u20AC'); // Euro currencyWords.put("\u20A9", '\u20A9'); // Won currencyWords.put("yuan", '\u5143'); // Yuan moneyMultipliers = new HashMap<String,Double>(); moneyMultipliers.put("trillion", 1000000000000.0); // can't be an integer moneyMultipliers.put("billion",1000000000.0); moneyMultipliers.put("bn",1000000000.0); moneyMultipliers.put("million", 1000000.0); moneyMultipliers.put("thousand", 1000.0); moneyMultipliers.put("hundred", 100.0); moneyMultipliers.put("b.", 1000000000.0); moneyMultipliers.put("m.", 1000000.0); moneyMultipliers.put(" m ",1000000.0); moneyMultipliers.put(" k ",1000.0); moneyMultipliers2 = new HashMap<String,Integer>(); moneyMultipliers2.put("[0-9](m)(?:[^a-zA-Z]|$)", 1000000); moneyMultipliers2.put("[0-9](b)(?:[^a-zA-Z]|$)", 1000000000); wordsToValues = new ClassicCounter<String>(); wordsToValues.setCount("zero", 0.0); wordsToValues.setCount("one", 1.0); wordsToValues.setCount("two", 2.0); wordsToValues.setCount("three", 3.0); wordsToValues.setCount("four", 4.0); wordsToValues.setCount("five", 5.0); wordsToValues.setCount("six", 6.0); wordsToValues.setCount("seven", 7.0); wordsToValues.setCount("eight", 8.0); wordsToValues.setCount("nine", 9.0); wordsToValues.setCount("ten", 10.0); wordsToValues.setCount("eleven", 11.0); wordsToValues.setCount("twelve", 12.0); wordsToValues.setCount("thirteen", 13.0); wordsToValues.setCount("fourteen", 14.0); wordsToValues.setCount("fifteen", 15.0); wordsToValues.setCount("sixteen", 16.0); wordsToValues.setCount("seventeen", 17.0); wordsToValues.setCount("eighteen", 18.0); wordsToValues.setCount("nineteen", 19.0); wordsToValues.setCount("twenty", 20.0); wordsToValues.setCount("thirty", 30.0); wordsToValues.setCount("forty", 40.0); wordsToValues.setCount("fifty", 50.0); wordsToValues.setCount("sixty", 60.0); wordsToValues.setCount("seventy", 70.0); wordsToValues.setCount("eighty", 80.0); wordsToValues.setCount("ninety", 90.0); wordsToValues.setCount("hundred", 100.0); wordsToValues.setCount("thousand", 1000.0); wordsToValues.setCount("million", 1000000.0); wordsToValues.setCount("billion", 1000000000.0); wordsToValues.setCount("bn", 1000000000.0); wordsToValues.setCount("trillion", 1000000000000.0); wordsToValues.setCount("dozen", 12.0); ordinalsToValues = new ClassicCounter<String>(); ordinalsToValues.setCount("zeroth", 0.0); ordinalsToValues.setCount("first", 1.0); ordinalsToValues.setCount("second", 2.0); ordinalsToValues.setCount("third", 3.0); ordinalsToValues.setCount("fourth", 4.0); ordinalsToValues.setCount("fifth", 5.0); ordinalsToValues.setCount("sixth", 6.0); ordinalsToValues.setCount("seventh", 7.0); ordinalsToValues.setCount("eighth", 8.0); ordinalsToValues.setCount("ninth", 9.0); ordinalsToValues.setCount("tenth", 10.0); ordinalsToValues.setCount("eleventh", 11.0); ordinalsToValues.setCount("twelfth", 12.0); ordinalsToValues.setCount("thirteenth", 13.0); ordinalsToValues.setCount("fourteenth", 14.0); ordinalsToValues.setCount("fifteenth", 15.0); ordinalsToValues.setCount("sixteenth", 16.0); ordinalsToValues.setCount("seventeenth", 17.0); ordinalsToValues.setCount("eighteenth", 18.0); ordinalsToValues.setCount("nineteenth", 19.0); ordinalsToValues.setCount("twentieth", 20.0); ordinalsToValues.setCount("twenty-first", 21.0); ordinalsToValues.setCount("twenty-second", 22.0); ordinalsToValues.setCount("twenty-third", 23.0); ordinalsToValues.setCount("twenty-fourth", 24.0); ordinalsToValues.setCount("twenty-fifth", 25.0); ordinalsToValues.setCount("twenty-sixth", 26.0); ordinalsToValues.setCount("twenty-seventh", 27.0); ordinalsToValues.setCount("twenty-eighth", 28.0); ordinalsToValues.setCount("twenty-ninth", 29.0); ordinalsToValues.setCount("thirtieth", 30.0); ordinalsToValues.setCount("thirty-first", 31.0); ordinalsToValues.setCount("fortieth", 40.0); ordinalsToValues.setCount("fiftieth", 50.0); ordinalsToValues.setCount("sixtieth", 60.0); ordinalsToValues.setCount("seventieth", 70.0); ordinalsToValues.setCount("eightieth", 80.0); ordinalsToValues.setCount("ninetieth", 90.0); ordinalsToValues.setCount("hundredth", 100.0); ordinalsToValues.setCount("thousandth", 1000.0); ordinalsToValues.setCount("millionth", 1000000.0); ordinalsToValues.setCount("billionth", 1000000000.0); ordinalsToValues.setCount("trillionth", 1000000000000.0); } private QuantifiableEntityNormalizer() {} // this is all static /** * This method returns the closest match in set such that the match * has more than three letters and differs from word only by one substitution, * deletion, or insertion. If not match exists, returns null. */ private static String getOneSubstitutionMatch(String word, Set<String> set) { // TODO (?) pass the EditDistance around more places to make this // more efficient. May not really matter. EditDistance ed = new EditDistance(); for(String cur : set) { if(isOneSubstitutionMatch(word, cur, ed)) return cur; } return null; } private static boolean isOneSubstitutionMatch(String word, String match, EditDistance ed) { if(word.equalsIgnoreCase(match)) return true; if(match.length() > 3) { if(ed.score(word, match) <= 1) return true; } return false; } /** Convert the content of a List of CoreMaps to a single * space-separated String. This grabs stuff based on the get(NamedEntityTagAnnotation.class) field. * [CDM: Changed to look at NamedEntityTagAnnotation not AnswerClass Jun 2010, hoping that will fix a bug.] * * @param l The List * @return one string containing all words in the list, whitespace separated */ public static <E extends CoreMap> String singleEntityToString(List<E> l) { String entityType = l.get(0).get(NamedEntityTagAnnotation.class); StringBuilder sb = new StringBuilder(); for (E w : l) { assert(w.get(NamedEntityTagAnnotation.class).equals(entityType)); sb.append(w.get(TextAnnotation.class)); sb.append(' '); } return sb.toString(); } /** * Currently this populates a List&lt;CoreLabel&gt; with words from the passed List, * but NER entities are collapsed and {@link CoreLabel} constituents of entities have * NER information in their "quantity" fields. * <p> * NOTE: This now seems to be used nowhere. The collapsing is done elsewhere. * That's probably appropriate; it doesn't seem like this should be part of * QuantifiableEntityNormalizer, since it's set to collapse non-quantifiable * entities.... * * @param l a list of CoreLabels with NER labels, * @return a Sentence where PERSON, ORG, LOC, entities are collapsed. */ public static List<CoreLabel> collapseNERLabels(List<CoreLabel> l){ if(DEBUG) { for (CoreLabel w: l) { System.err.println("<<"+w.get(TextAnnotation.class)+"::"+w.get(PartOfSpeechAnnotation.class)+"::"+w.get(NamedEntityTagAnnotation.class)+">>"); } } List<CoreLabel> s = new ArrayList<CoreLabel>(); String lastEntity = BACKGROUND_SYMBOL; StringBuilder entityStringCollector = null; //Iterate through each word.... for (CoreLabel w: l) { String entityType = w.get(NamedEntityTagAnnotation.class); //if we've just completed an entity and we're looking at a non-continuation, //we want to add that now. if (entityStringCollector != null && ! entityType.equals(lastEntity)) { CoreLabel nextWord = new CoreLabel(); nextWord.setWord(entityStringCollector.toString()); nextWord.set(PartOfSpeechAnnotation.class, "NNP"); nextWord.set(NamedEntityTagAnnotation.class, lastEntity); s.add(nextWord); if (DEBUG) { err.print("Quantifiable: Collapsing "); err.println(entityStringCollector.toString()); } entityStringCollector = null; } //If its not to be collapsed, toss it onto the sentence. if ( ! collapseBeforeParsing.contains(entityType)) { s.add(w); } else { //If it is to be collapsed.... //if its a continuation of the last entity, add it to the //current buffer. if (entityType.equals(lastEntity)){ assert entityStringCollector != null; entityStringCollector.append('_'); entityStringCollector.append(w.get(TextAnnotation.class)); } else { //and its NOT a continuation, make a new buffer. entityStringCollector = new StringBuilder(); entityStringCollector.append(w.get(TextAnnotation.class)); } } lastEntity=entityType; } // if the last token was a named-entity, we add it here. if (entityStringCollector!=null) { CoreLabel nextWord = new CoreLabel(); nextWord.setWord(entityStringCollector.toString()); nextWord.set(PartOfSpeechAnnotation.class, "NNP"); nextWord.set(NamedEntityTagAnnotation.class, lastEntity); s.add(nextWord); } for (CoreLabel w : s) { System.err.println("<<"+w.get(TextAnnotation.class)+"::"+w.get(PartOfSpeechAnnotation.class)+"::"+w.get(NamedEntityTagAnnotation.class)+">>"); } return s; } /** * Provided for backwards compatibility; see normalizedDateString(s, openRangeMarker) */ static String normalizedDateString(String s, Timex timexFromSUTime) { return normalizedDateString(s, ISODateInstance.NO_RANGE, timexFromSUTime); } /** * Returns a string that represents either a single date or a range of * dates. Representation pattern is roughly ISO8601, with some extensions * for greater expressivity; see {@link ISODateInstance} for details. * @param s Date string to normalize * @param openRangeMarker a marker for whether this date is not involved in * an open range, is involved in an open range that goes forever backward and * stops at s, or is involved in an open range that goes forever forward and * starts at s * @return A yyyymmdd format normalized date */ static String normalizedDateString(String s, String openRangeMarker, Timex timexFromSUTime) { if(timexFromSUTime != null) { if(timexFromSUTime.value() != null){ // fully disambiguated temporal return timexFromSUTime.value(); } else { // this is a relative date, e.g., "yesterday" return timexFromSUTime.altVal(); } } ISODateInstance d = new ISODateInstance(s, openRangeMarker); if (DEBUG2) err.println("normalizeDate: " + s + " to " + d.getDateString()); return (d.getDateString()); } /** * Tries to heuristically determine if the given word is a year */ static boolean isYear(CoreMap word) { String wordString = word.get(TextAnnotation.class); if(word.get(PartOfSpeechAnnotation.class) == null || word.get(PartOfSpeechAnnotation.class).equals("CD")) { //one possibility: it's a two digit year with an apostrophe: '90 if(wordString.length() == 3 && wordString.startsWith("'")) { if (DEBUG) { System.err.println("Found potential two digit year: " + wordString); } wordString = wordString.substring(1); try { Integer.parseInt(wordString); return true; } catch(Exception e) { return false; } } //if it is 4 digits, with first one <3 (usually we're not talking about //the far future, say it's a year if(wordString.length() == 4) { try { int num = Integer.parseInt(wordString); if(num < 3000) return true; } catch(Exception e) { return false; } } } return false; } private static final String dateRangeAfterOneWord = "after|since"; private static final String dateRangeBeforeOneWord = "before|until"; private static final List<Pair<String, String>> dateRangeBeforePairedOneWord; static { dateRangeBeforePairedOneWord = new ArrayList<Pair<String,String>>(); dateRangeBeforePairedOneWord.add(new Pair<String, String>("between", "and")); dateRangeBeforePairedOneWord.add(new Pair<String, String>("from", "to")); dateRangeBeforePairedOneWord.add(new Pair<String, String>("from", "-")); } private static final String datePrepositionAfterWord = "in|of"; /** * Takes the strings of the one previous and 3 next words to a date to * detect date range modifiers like "before" or "between \<date\> and \<date\> * @param <E> */ private static <E extends CoreMap> String detectDateRangeModifier(List<E> date, List<E> list, int beforeIndex, int afterIndex) { E prev = (beforeIndex >= 0) ? list.get(beforeIndex) : null; int sz = list.size(); E next = (afterIndex < sz) ? list.get(afterIndex) : null; E next2 = (afterIndex + 1 < sz) ? list.get(afterIndex + 1) : null; E next3 = (afterIndex + 2 < sz) ? list.get(afterIndex + 2) : null; if (DEBUG) { err.println("DateRange: previous: " + prev); err.println("Quantifiable: next: " + next + ' ' + next2 + ' ' + next3); } //sometimes the year gets tagged as CD but not as a date - if this happens, we want to add it in if (next != null && isYear(next)) { date.add(next); next.set(NamedEntityTagAnnotation.class, "DATE"); afterIndex++; } if (next2 != null && isYear(next2)) { date.add(next); assert(next != null); // keep the static analysis happy. next.set(NamedEntityTagAnnotation.class, "DATE"); date.add(next2); next2.set(NamedEntityTagAnnotation.class, "DATE"); afterIndex += 2; } //sometimes the date will be stated in a form like "June of 1984" -> we'd like this to be 198406 if(next != null && next.get(TextAnnotation.class).matches(datePrepositionAfterWord)) { //check if the next next word is a year or month if(next2 != null && (isYear(next2))) {//TODO: implement month! date.add(next); date.add(next2); afterIndex += 2; } } //String range = detectTwoSidedRangeModifier(date.get(0), list, beforeIndex, afterIndex); //if(range !=ISODateInstance.NO_RANGE) return range; //check if it's an open range - two sided ranges get checked elsewhere //based on the prev word if(prev != null) { String prevWord = prev.get(TextAnnotation.class).toLowerCase(); if(prevWord.matches(dateRangeBeforeOneWord)) { //we have an open range of the before type - e.g., Before June 6, John was 5 prev.set(PartOfSpeechAnnotation.class, "DATE_MOD"); return ISODateInstance.OPEN_RANGE_BEFORE; } else if(prevWord.matches(dateRangeAfterOneWord)) { //we have an open range of the after type - e.g., After June 6, John was 6 prev.set(PartOfSpeechAnnotation.class, "DATE_MOD"); return ISODateInstance.OPEN_RANGE_AFTER; } } return ISODateInstance.NO_RANGE; } /** * This should detect things like "between 5 and 5 million" and "from April 3 to June 6" * Each side of the range is tagged with the correct numeric quantity (e.g., 5/5x10E6 or * ****0403/****0606) and the other words (e.g., "between", "and", "from", "to") are * tagged as quantmod to avoid penalizing them for lack of alignment/matches. * * This method should be called after other collapsing is complete (e.g. 5 million should already be * concatenated) * @param <E> */ private static <E extends CoreMap> List<E> detectTwoSidedRangeModifier(E firstDate, List<E> list, int beforeIndex, int afterIndex, boolean concatenate) { E prev = (beforeIndex >= 0) ? list.get(beforeIndex) : null; //E cur = list.get(0); int sz = list.size(); E next = (afterIndex < sz) ? list.get(afterIndex) : null; E next2 = (afterIndex + 1 < sz) ? list.get(afterIndex + 1) : null; List<E> toRemove = new ArrayList<E>(); String curNER = (firstDate == null ? "" : firstDate.get(NamedEntityTagAnnotation.class)); if(curNER == null) curNER = ""; if(firstDate == null || firstDate.get(NormalizedNamedEntityTagAnnotation.class) == null) return toRemove; //TODO: make ranges actually work //first check if it's of the form "between <date> and <date>"/etc if (prev != null) { for (Pair<String, String> ranges : dateRangeBeforePairedOneWord) { if (prev.get(TextAnnotation.class).matches(ranges.first())) { if (next != null && next2 != null) { String nerNext2 = next2.get(NamedEntityTagAnnotation.class); if (next.get(TextAnnotation.class).matches(ranges.second()) && nerNext2 != null && nerNext2.equals(curNER)) { //Add rest in prev.set(PartOfSpeechAnnotation.class, "QUANT_MOD"); String rangeString; if(curNER.equals("DATE")) { ISODateInstance c = new ISODateInstance(new ISODateInstance(firstDate.get(NormalizedNamedEntityTagAnnotation.class)), new ISODateInstance(next2.get(NormalizedNamedEntityTagAnnotation.class))); rangeString = c.getDateString(); } else { rangeString = firstDate.get(NormalizedNamedEntityTagAnnotation.class) + '-' + next2.get(NormalizedNamedEntityTagAnnotation.class); } if (DEBUG) { System.err.println("#1: Changing normalized NER from " + firstDate.get(NormalizedNamedEntityTagAnnotation.class) + " to " + rangeString + " at index " + beforeIndex); } firstDate.set(NormalizedNamedEntityTagAnnotation.class, rangeString); if (DEBUG) { System.err.println("#2: Changing normalized NER from " + next2.get(NormalizedNamedEntityTagAnnotation.class) + " to " + rangeString + " at index " + afterIndex); } next2.set(NormalizedNamedEntityTagAnnotation.class, rangeString); next.set(NamedEntityTagAnnotation.class, nerNext2); if (DEBUG) { System.err.println("#3: Changing normalized NER from " + next.get(NormalizedNamedEntityTagAnnotation.class) + " to " + rangeString + " at index " + (afterIndex + 1)); } next.set(NormalizedNamedEntityTagAnnotation.class, rangeString); if (concatenate) { List<E> numberWords = new ArrayList<E>(); numberWords.add(firstDate); numberWords.add(next); numberWords.add(next2); concatenateNumericString(numberWords, toRemove); } } } } } } return toRemove; } /** * Concatenates separate words of a date or other numeric quantity into one node (e.g., 3 November -> 3_November) * Tag is CD or NNP, and other words are added to the remove list */ static <E extends CoreMap> void concatenateNumericString(List<E> words, List<E> toRemove) { if (words.size() <= 1) return; boolean first = true; StringBuilder newText = new StringBuilder(); E foundEntity = null; for (E word : words) { if (foundEntity == null && (word.get(PartOfSpeechAnnotation.class).equals("CD") || word.get(PartOfSpeechAnnotation.class).equals("NNP"))) { foundEntity = word; } if (first) { first = false; } else { newText.append('_'); } newText.append(word.get(TextAnnotation.class)); } if (foundEntity == null) { foundEntity = words.get(0);//if we didn't find one with the appropriate tag, just take the first one } toRemove.addAll(words); toRemove.remove(foundEntity); foundEntity.set(PartOfSpeechAnnotation.class, "CD"); // cdm 2008: is this actually good for dates?? String collapsed = newText.toString(); foundEntity.set(TextAnnotation.class, collapsed); foundEntity.set(OriginalTextAnnotation.class, collapsed); } public static String normalizedTimeString(String s, Timex timexFromSUTime) { return normalizedTimeString(s, null, timexFromSUTime); } public static String normalizedTimeString(String s, String ampm, Timex timexFromSUTime) { if(timexFromSUTime != null){ if(timexFromSUTime.value() != null){ // this timex is fully disambiguated return timexFromSUTime.value(); } else { // not disambiguated; contains some relative date return timexFromSUTime.altVal(); } } if (DEBUG2) err.println("normalizingTime: " + s); s = s.replaceAll("[ \t\n\0\f\r]", ""); Matcher m = timePattern.matcher(s); if (s.equalsIgnoreCase("noon")) { return "12:00pm"; } else if (s.equalsIgnoreCase("midnight")) { return "00:00am"; // or "12:00am" ? } else if (s.equalsIgnoreCase("morning")) { return "M"; } else if (s.equalsIgnoreCase("afternoon")) { return "A"; } else if (s.equalsIgnoreCase("evening")) { return "EN"; } else if (s.equalsIgnoreCase("night")) { return "N"; } else if (s.equalsIgnoreCase("day")) { return "D"; } else if (s.equalsIgnoreCase("suppertime")) { return "EN"; } else if (s.equalsIgnoreCase("lunchtime")) { return "MD"; } else if (s.equalsIgnoreCase("midday")) { return "MD"; } else if (s.equalsIgnoreCase("teatime")) { return "A"; } else if (s.equalsIgnoreCase("dinnertime")) { return "EN"; } else if (s.equalsIgnoreCase("dawn")) { return "EM"; } else if (s.equalsIgnoreCase("dusk")) { return "EN"; } else if (s.equalsIgnoreCase("sundown")) { return "EN"; } else if (s.equalsIgnoreCase("sunup")) { return "EM"; } else if (s.equalsIgnoreCase("daybreak")) { return "EM"; } else if (m.matches()) { if (DEBUG2) { err.printf("timePattern matched groups: |%s| |%s| |%s| |%s|\n", m.group(0), m.group(1), m.group(2), m.group(3)); } // group 1 is hours, group 2 is minutes and maybe seconds; group 3 is am/pm StringBuilder sb = new StringBuilder(); sb.append(m.group(1)); if (m.group(2) == null || "".equals(m.group(2))) { sb.append(":00"); } else { sb.append(m.group(2)); } if (m.group(3) != null) { String suffix = m.group(3); suffix = suffix.replaceAll("\\.", ""); suffix = suffix.toLowerCase(); sb.append(suffix); } else if (ampm != null) { sb.append(ampm); } else { // Do nothing; leave ambiguous // sb.append("pm"); } if (DEBUG2) { err.println("normalizedTimeString new str: " + sb.toString()); } return sb.toString(); } else if (DEBUG) { err.println("Quantifiable: couldn't normalize " + s); } return null; } /** * Heuristically decides if s is in American (42.33) or European (42,33) number format * and tries to turn European version into American. * */ private static String convertToAmerican(String s) { if(s.contains(",")) { //turn all but the last into blanks - this isn't really correct, but it's close enough for now while(s.indexOf(',') != s.lastIndexOf(',')) s = s.replaceFirst(",", ""); int place = s.lastIndexOf(','); //if it's american, should have at least three characters after it if (place >= s.length() - 3 && place != s.length() - 1) { s = s.substring(0, place) + '.' + s.substring(place + 1); } else { s = s.replace(",", ""); } } return s; } static String normalizedMoneyString(String s, Number numberFromSUTime) { //first, see if it looks like european style s = convertToAmerican(s); // clean up string s = s.replaceAll("[ \t\n\0\f\r,]", ""); s = s.toLowerCase(); if (DEBUG2) { err.println("normalizedMoneyString: Normalizing "+s); } double multiplier = 1.0; // do currency words char currencySign = '$'; for (String currencyWord : currencyWords.keySet()) { if (StringUtils.find(s, currencyWord)) { if (DEBUG2) { err.println("Found units: " + currencyWord); } if (currencyWord.equals("pence|penny") || currencyWord.equals("cents?") || currencyWord.equals("\u00A2")) { multiplier *= 0.01; } // if(DEBUG){err.println("Quantifiable: Found "+ currencyWord);} s = s.replaceAll(currencyWord, ""); currencySign = currencyWords.get(currencyWord); } } // process rest as number String value = normalizedNumberStringQuiet(s, multiplier, "", numberFromSUTime); if (value == null) { return null; } else { return currencySign + value; } } public static String normalizedNumberString(String s, String nextWord, Number numberFromSUTime) { if (DEBUG2) { err.println("normalizedNumberString: normalizing "+s); } return normalizedNumberStringQuiet(s, 1.0, nextWord, numberFromSUTime); } private static final Pattern allSpaces = Pattern.compile(" *"); public static String normalizedNumberStringQuiet(String s, double multiplier, String nextWord, Number numberFromSUTime) { // normalizations from SUTime take precedence, if available if(numberFromSUTime != null){ double v = Double.valueOf(numberFromSUTime.toString()); return Double.toString(v * multiplier); } // clean up string String origSClean = s.replaceAll("[\t\n\0\f\r]", ""); if (allSpaces.matcher(origSClean).matches()) { return s; } String[] origSSplit = origSClean.split(" "); s = s.replaceAll("[ \t\n\0\f\r]", ""); //see if it looks like european style s = convertToAmerican(s); // remove parenthesis around numbers // if PTBTokenized, this next bit should be a no-op // in some contexts parentheses might indicate a negative number, but ignore that. if (s.startsWith("(") && s.endsWith(")")) { s = s.substring(1, s.length() - 1); if (DEBUG2) err.println("Deleted (): " + s); } s = s.toLowerCase(); // get multipliers like "billion" boolean foundMultiplier = false; for (String moneyTag : moneyMultipliers.keySet()) { if (s.contains(moneyTag)) { // if (DEBUG) {err.println("Quantifiable: Found "+ moneyTag);} //special case check: m can mean either meters or million - if nextWord is high or long, we assume meters - this is a huge and bad hack!!! if(moneyTag.equals("m") && (nextWord.equals("high") || nextWord.equals("long") )) continue; s = s.replaceAll(moneyTag, ""); multiplier *= moneyMultipliers.get(moneyTag); foundMultiplier = true; } } for (String moneyTag : moneyMultipliers2.keySet()) { Matcher m = Pattern.compile(moneyTag).matcher(s); if (m.find()) { // if(DEBUG){err.println("Quantifiable: Found "+ moneyTag);} multiplier *= moneyMultipliers2.get(moneyTag); foundMultiplier = true; int start = m.start(1); int end = m.end(1); // err.print("Deleting from " + s); s = s.substring(0, start) + s.substring(end); // err.println("; Result is " + s); } } if(!foundMultiplier) { EditDistance ed = new EditDistance(); for (String moneyTag : moneyMultipliers.keySet()) { if(isOneSubstitutionMatch(origSSplit[origSSplit.length - 1], moneyTag, ed)) { s = s.replaceAll(moneyTag, ""); multiplier *= moneyMultipliers.get(moneyTag); } } } if (DEBUG2) err.println("Looking for number words in |" + s + "|; multiplier is " + multiplier); // handle numbers written in words String[] parts = s.split("[ -]"); boolean processed = false; double dd = 0.0; for (String part : parts) { if (wordsToValues.containsKey(part)) { dd += wordsToValues.getCount(part); processed = true; } else { String partMatch = getOneSubstitutionMatch(part, wordsToValues.keySet()); if(partMatch != null) { dd += wordsToValues.getCount(partMatch); processed = true; } } } if (processed) { dd *= multiplier; return Double.toString(dd); } // handle numbers written as numbers // s = s.replaceAll("-", ""); //This is bad: it lets 22-7 be the number 227! s = s.replaceAll("[A-Za-z]", ""); // handle scores or range Matcher m2 = scorePattern.matcher(s); if (m2.matches()) { double d1 = Double.parseDouble(m2.group(1)); double d2 = Double.parseDouble(m2.group(2)); return Double.toString(d1) + " - " + Double.toString(d2); } // check for hyphenated word like 4-Ghz: delete final - if (s.endsWith("-")) { s = s.substring(0, s.length() - 1); } Matcher m = moneyPattern.matcher(s); if (m.matches()) { if (DEBUG2) { err.println("Number matched with |" + m.group(2) + "| |" + m.group(3) + '|'); } try { double d = 0.0; if (m.group(2) != null && ! m.group(2).equals("")) { d = Double.parseDouble(m.group(2)); } if (m.group(3) != null && ! m.group(3).equals("")) { d += Double.parseDouble(m.group(3)); } if (d == 0.0 && multiplier != 1.0) { // we'd found a multiplier d = 1.0; } d *= multiplier; return Double.toString(d); } catch (Exception e) { if (DEBUG2) { e.printStackTrace(); } return null; } } else if (multiplier != 1.0) { // we found a multiplier, so we have something return Double.toString(multiplier); } else { return null; } } public static String normalizedOrdinalString(String s, Number numberFromSUTime) { if (DEBUG2) { err.println("normalizedOrdinalString: normalizing "+s); } return normalizedOrdinalStringQuiet(s, numberFromSUTime); } public static final Pattern numberPattern = Pattern.compile("([0-9.]+)"); public static String normalizedOrdinalStringQuiet(String s, Number numberFromSUTime) { // clean up string s = s.replaceAll("[ \t\n\0\f\r,]", ""); // remove parenthesis around numbers // if PTBTokenized, this next bit should be a no-op // in some contexts parentheses might indicate a negative number, but ignore that. if (s.startsWith("(") && s.endsWith(")")) { s = s.substring(1, s.length() - 1); if (DEBUG2) err.println("Deleted (): " + s); } s = s.toLowerCase(); if (DEBUG2) err.println("Looking for ordinal words in |" + s + '|'); if (Character.isDigit(s.charAt(0))) { Matcher matcher = numberPattern.matcher(s); matcher.find(); // just parse number part, assuming last two letters are st/nd/rd return normalizedNumberStringQuiet(matcher.group(), 1.0, "", numberFromSUTime); } else if (ordinalsToValues.containsKey(s)) { return Double.toString(ordinalsToValues.getCount(s)); } else { String val = getOneSubstitutionMatch(s, ordinalsToValues.keySet()); if(val != null) return Double.toString(ordinalsToValues.getCount(val)); else return null; } } public static String normalizedPercentString(String s, Number numberFromSUTime) { if (DEBUG2) { err.println("normalizedPercentString: " + s); } s = s.replaceAll("\\s", ""); s = s.toLowerCase(); if (s.contains("%") || s.contains("percent")) { s = s.replaceAll("percent|%", ""); } String norm = normalizedNumberStringQuiet(s, 1.0, "", numberFromSUTime); if (norm == null) { return null; } return '%' + norm; } /** Fetches the first encountered Number set by SUTime */ private static <E extends CoreMap> Number fetchNumberFromSUTime(List<E> l) { for(E e: l) { if(e.containsKey(NumericCompositeValueAnnotation.class)){ return e.get(NumericCompositeValueAnnotation.class); } } return null; } private static <E extends CoreMap> Timex fetchTimexFromSUTime(List<E> l) { for(E e: l) { if(e.containsKey(TimexAnnotation.class)){ return e.get(TimexAnnotation.class); } } return null; } private static <E extends CoreMap> List<E> processEntity(List<E> l, String entityType, String compModifier, String nextWord) { assert(quantifiable.contains(entityType)); if (DEBUG) { System.err.println("Quantifiable.processEntity: " + l); } String s; if (entityType.equals("TIME")) { s = timeEntityToString(l); } else { s = singleEntityToString(l); } Number numberFromSUTime = fetchNumberFromSUTime(l); Timex timexFromSUTime = fetchTimexFromSUTime(l); if (DEBUG) System.err.println("Quantifiable: working on " + s); String p = null; if (entityType.equals("NUMBER")) { p = ""; if (compModifier != null) { p = compModifier; } String q = normalizedNumberString(s, nextWord, numberFromSUTime); if (q != null) { p = p.concat(q); } else { p = null; } } else if (entityType.equals("ORDINAL")) { p = normalizedOrdinalString(s, numberFromSUTime); } else if (entityType.equals("DURATION")) { // SUTime marks some ordinals, e.g., "22nd time", as durations p = normalizedOrdinalString(s, numberFromSUTime); } else if (entityType.equals("MONEY")) { p = ""; if(compModifier!=null) { p = compModifier; } String q = normalizedMoneyString(s, numberFromSUTime); if (q != null) { p = p.concat(q); } else { p = null; } } else if (entityType.equals("DATE")) { p = normalizedDateString(s, timexFromSUTime); } else if (entityType.equals("TIME")) { p = ""; if (compModifier != null && ! compModifier.matches("am|pm")) { p = compModifier; } String q = normalizedTimeString(s, compModifier != null ? compModifier : "", timexFromSUTime); if (q != null && q.length() == 1 && !q.equals("D")) { p = p.concat(q); } else { p = q; } } else if (entityType.equals("PERCENT")) { p = ""; if (compModifier != null) { p = compModifier; } String q = normalizedPercentString(s, numberFromSUTime); if (q != null) { p = p.concat(q); } else { p = null; } } if (DEBUG) { err.println("Quantifiable: Processed '" + s + "' as '" + p + '\''); } int i = 0; for (E wi : l) { if (p != null) { if (DEBUG) { System.err.println("#4: Changing normalized NER from " + wi.get(NormalizedNamedEntityTagAnnotation.class) + " to " + p + " at index " + i); } wi.set(NormalizedNamedEntityTagAnnotation.class, p); } //currently we also write this into the answers; //wi.setAnswer(wi.get(AnswerAnnotation.class)+"("+p+")"); i++; } return l; } /** @param l The list of tokens in a time entity * @return the word in the time word list that should be normalized */ private static <E extends CoreMap> String timeEntityToString(List<E> l) { String entityType = l.get(0).get(AnswerAnnotation.class); int size = l.size(); for (E w : l) { assert(w.get(AnswerAnnotation.class) == null || w.get(AnswerAnnotation.class).equals(entityType)); Matcher m = timePattern.matcher(w.get(TextAnnotation.class)); if (m.matches()) return w.get(TextAnnotation.class); } if (DEBUG) { System.err.println("default: " + l.get(size-1).get(TextAnnotation.class)); } return l.get(size-1).get(TextAnnotation.class); } /** * Takes the output of an {@link AbstractSequenceClassifier} and marks up * each document by normalizing quantities. Each {@link CoreLabel} in any * of the documents which is normalizable will receive a "normalizedQuantity" * attribute. * * @param l a {@link List} of {@link List}s of {@link CoreLabel}s * @return The list with normalized entity fields filled in */ public static List<List<CoreLabel>> normalizeClassifierOutput(List<List<CoreLabel>> l){ for (List<CoreLabel> doc: l) { addNormalizedQuantitiesToEntities(doc); } return l; } private static final String lessEqualThreeWords = "no (?:more|greater|higher) than|as (?:many|much) as"; private static final String greaterEqualThreeWords = "no (?:less|fewer) than|as few as"; private static final String greaterThanTwoWords = "(?:more|greater|larger|higher) than"; private static final String lessThanTwoWords = "(?:less|fewer|smaller) than|at most"; private static final String lessEqualTwoWords = "no (?:more|greater)_than|or less|up to"; private static final String greaterEqualTwoWords = "no (?:less|fewer)_than|or more|at least"; private static final String approxTwoWords = "just (?:over|under)|or so"; private static final String greaterThanOneWord = "(?:above|over|more_than|greater_than)"; private static final String lessThanOneWord = "(?:below|under|less_than)"; private static final String lessEqualOneWord = "(?:up_to|within)"; // note that ones like "nearly" or "almost" can be above or below: // "almost 500 killed", "almost zero inflation" private static final String approxOneWord = "(?:approximately|estimated|nearly|around|about|almost|just_over|just_under)"; private static final String other = "other"; /** * Takes the strings of the three previous and next words to a quantity and * detects a * quantity modifier like "less than", "more than", etc. * Any of these words may be <code>null</code> or an empty String. */ private static <E extends CoreMap> String detectQuantityModifier(List<E> list, int beforeIndex, int afterIndex) { String prev = (beforeIndex >= 0) ? list.get(beforeIndex).get(TextAnnotation.class).toLowerCase(): ""; String prev2 = (beforeIndex - 1 >= 0) ? list.get(beforeIndex - 1).get(TextAnnotation.class).toLowerCase(): ""; String prev3 = (beforeIndex - 2 >= 0) ? list.get(beforeIndex - 2).get(TextAnnotation.class).toLowerCase(): ""; int sz = list.size(); String next = (afterIndex < sz) ? list.get(afterIndex).get(TextAnnotation.class).toLowerCase(): ""; String next2 = (afterIndex + 1 < sz) ? list.get(afterIndex + 1).get(TextAnnotation.class).toLowerCase(): ""; String next3 = (afterIndex + 2 < sz) ? list.get(afterIndex + 2).get(TextAnnotation.class).toLowerCase(): ""; if (DEBUG) { err.println("Quantifiable: previous: " + prev3 + ' ' + prev2+ ' ' + prev); err.println("Quantifiable: next: " + next + ' ' + next2 + ' ' + next3); } String longPrev = prev3 + ' ' + prev2 + ' ' + prev; if (longPrev.matches(lessEqualThreeWords)) { return "<="; } if (longPrev.matches(greaterEqualThreeWords)) { return ">="; } longPrev = prev2 + ' ' + prev; if (longPrev.matches(greaterThanTwoWords)) { return ">"; } if (longPrev.matches(lessEqualTwoWords)) { return "<="; } if (longPrev.matches(greaterEqualTwoWords)) { return ">="; } if (longPrev.matches(lessThanTwoWords)) { return "<"; } if (longPrev.matches(approxTwoWords)) { return "~"; } String longNext = next + ' ' + next2; if (longNext.matches(greaterEqualTwoWords)) { return ">="; } if (longNext.matches(lessEqualTwoWords)) { return "<="; } if (prev.matches(greaterThanOneWord)) { return ">"; } if (prev.matches(lessThanOneWord)) { return "<"; } if (prev.matches(lessEqualOneWord)) { return "<="; } if (prev.matches(approxOneWord)) { return "~"; } if (next.matches(other)) { return ">="; } if (DEBUG) { err.println("Quantifiable: not a quantity modifier"); } return null; } private static String earlyOneWord = "early"; private static String earlyTwoWords = "(?:dawn|eve|beginning) of"; private static String earlyThreeWords = "early in the"; private static String lateOneWord = "late"; private static String lateTwoWords = "late at|end of"; private static String lateThreeWords = "end of the"; private static String middleTwoWords = "(?:middle|midst) of"; private static String middleThreeWords = "(?:middle|midst) of the"; private static String amOneWord = "[Aa]\\.?[Mm]\\.?"; private static String pmOneWord = "[Pp]\\.?[Mm]\\.?"; private static String amThreeWords = "in the morning"; private static String pmTwoWords = "at night"; private static String pmThreeWords = "in the (?:afternoon|evening)"; /** * Takes the strings of the three previous words to a quantity and detects a * quantity modifier like "less than", "more than", etc. * Any of these words may be <code>null</code> or an empty String. */ private static <E extends CoreMap> String detectTimeOfDayModifier(List<E> list, int beforeIndex, int afterIndex) { String prev = (beforeIndex >= 0) ? list.get(beforeIndex).get(TextAnnotation.class).toLowerCase() : ""; String prev2 = (beforeIndex - 1 >= 0) ? list.get(beforeIndex - 1).get(TextAnnotation.class).toLowerCase() : ""; String prev3 = (beforeIndex - 2 >= 0) ? list.get(beforeIndex - 2).get(TextAnnotation.class).toLowerCase() : ""; int sz = list.size(); String next = (afterIndex < sz) ? list.get(afterIndex).get(TextAnnotation.class).toLowerCase() : ""; String next2 = (afterIndex + 1 < sz) ? list.get(afterIndex + 1).get(TextAnnotation.class).toLowerCase() : ""; String next3 = (afterIndex + 2 < sz) ? list.get(afterIndex + 2).get(TextAnnotation.class).toLowerCase() : ""; String longPrev = prev3 + ' ' + prev2 + ' ' + prev; if (longPrev.matches(earlyThreeWords)) { return "E"; } else if (longPrev.matches(lateThreeWords)) { return "L"; } else if (longPrev.matches(middleThreeWords)) { return "M"; } longPrev = prev2 + ' ' + prev; if (longPrev.matches(earlyTwoWords)) { return "E"; } else if (longPrev.matches(lateTwoWords)) { return "L"; } else if (longPrev.matches(middleTwoWords)) { return "M"; } if (prev.matches(earlyOneWord) || prev2.matches(earlyOneWord)) { return "E"; } else if (prev.matches(lateOneWord) || prev2.matches(lateOneWord)) { return "L"; } String longNext = next3 + ' ' + next2 + ' ' + next; if (longNext.matches(pmThreeWords)) { return "pm"; } if (longNext.matches(amThreeWords)) { return "am"; } longNext = next2 + ' ' + next; if (longNext.matches(pmTwoWords)) { return "pm"; } if (next.matches(amOneWord) || next2.matches("morning") || next3.matches("morning")) { return "am"; } if (next.matches(pmOneWord) || next2.matches("afternoon") || next3.matches("afternoon") || next2.matches("night") || next3.matches("night") || next2.matches("evening") || next3.matches("evening")) { return "pm"; } return ""; } /** * Identifies contiguous MONEY, TIME, DATE, or PERCENT entities * and tags each of their consitituents with a "normalizedQuantity" * label which contains the appropriate normalized string corresponding to * the full quantity. Quantities are not concatenated * * @param l A list of {@link CoreMap}s representing a single * document. Note: the Labels are updated in place. */ public static <E extends CoreMap> void addNormalizedQuantitiesToEntities(List<E> l) { addNormalizedQuantitiesToEntities(l, false); } /** * Identifies contiguous MONEY, TIME, DATE, or PERCENT entities * and tags each of their consitituents with a "normalizedQuantity" * label which contains the appropriate normalized string corresponding to * the full quantity. * * @param list A list of {@link CoreMap}s representing a single * document. Note: the Labels are updated in place. * @param concatenate true if quantities should be concatenated into one label, false otherwise */ public static <E extends CoreMap> void addNormalizedQuantitiesToEntities(List<E> list, boolean concatenate) { List<E> toRemove = new ArrayList<E>(); // list for storing those objects we're going to remove at the end (e.g., if concatenate, we replace 3 November with 3_November, have to remove one of the originals) String lastEntity = BACKGROUND_SYMBOL; String timeModifier = ""; int beforeIndex = -1; ArrayList<E> collector = new ArrayList<E>(); for (int i = 0, sz = list.size(); i < sz; i++) { E wi = list.get(i); if (DEBUG) { System.err.println("addNormalizedQuantitiesToEntities: wi is " + wi + "; collector is " + collector); } // repairs commas in between dates... String constant first in equals() in case key has null value.... if ((i+1) < sz && ",".equals(wi.get(TextAnnotation.class)) && "DATE".equals(lastEntity)) { E nextWord = list.get(i+1); String nextNER = nextWord.get(NamedEntityTagAnnotation.class); if (nextNER != null && nextNER.equals("DATE")) { wi.set(NamedEntityTagAnnotation.class, "DATE"); } } //repairs mistagged multipliers after a numeric quantity String curWord = (wi.get(TextAnnotation.class) != null ? wi.get(TextAnnotation.class) : ""); String nextWord = ""; if ((i+1) < sz) { nextWord = list.get(i+1).get(TextAnnotation.class); if(nextWord == null) nextWord = ""; } if (!curWord.equals("") && (moneyMultipliers.containsKey(curWord) || (getOneSubstitutionMatch(curWord, moneyMultipliers.keySet()) != null)) && lastEntity != null && (lastEntity.equals("MONEY") || lastEntity.equals("NUMBER"))) { wi.set(NamedEntityTagAnnotation.class, lastEntity); } //repairs four digit ranges (2002-2004) that have not been tagged as years - maybe bad? (empirically useful) if (curWord.contains("-")) { String[] sides = curWord.split("-"); if (sides.length == 2) { try { int first = Integer.parseInt(sides[0]); int second = Integer.parseInt(sides[1]); //they're both integers, see if they're both between 1000-3000 (likely years) if (1000 <= first && first <= 3000 && 1000 <= second && second <= 3000) { wi.set(NamedEntityTagAnnotation.class, "DATE"); String dateStr = new ISODateInstance(new ISODateInstance(sides[0]), new ISODateInstance(sides[1])).getDateString(); if (DEBUG) { System.err.println("#5: Changing normalized NER from " + wi.get(NormalizedNamedEntityTagAnnotation.class) + " to " + dateStr + " at index " + i); } wi.set(NormalizedNamedEntityTagAnnotation.class, dateStr); continue; } } catch (Exception e) { // they weren't numbers. } } } // Marks time units as NUMBER if they are preceded by a CD tag. e.g. "two years" or "5 minutes" String prevTag = (i-1 > 0 ? list.get(i-1).get(PartOfSpeechAnnotation.class) : null); if ( timeUnitWords.contains(curWord) && (wi.get(NamedEntityTagAnnotation.class) == null || !wi.get(NamedEntityTagAnnotation.class).equals("DATE")) && (prevTag != null && prevTag.equals("CD")) ) { wi.set(NamedEntityTagAnnotation.class, "NUMBER"); } String currEntity = wi.get(NamedEntityTagAnnotation.class); if (currEntity != null && currEntity.equals("TIME")) { if (timeModifier.equals("")) { timeModifier = detectTimeOfDayModifier(list, i-1, i+1); } } // if the current wi is a non-continuation and the last one was a // quantity, we close and process the last segment. if ((currEntity == null || ! currEntity.equals(lastEntity)) && quantifiable.contains(lastEntity)) { String compModifier = null; // special handling of TIME if (lastEntity.equals("TIME")) { processEntity(collector, lastEntity, timeModifier, nextWord); } else if (lastEntity.equals(("DATE"))) { //detect date range modifiers by looking at nearby words compModifier = detectDateRangeModifier(collector, list, beforeIndex, i); if (!compModifier.equals(ISODateInstance.BOUNDED_RANGE)) processEntity(collector, lastEntity, compModifier, nextWord); //now repair this date if it's more than one word //doesn't really matter which one we keep ideally we should be doing lemma/etc matching anyway //but we vaguely try to deal with this by choosing the NNP or the CD if (concatenate) concatenateNumericString(collector, toRemove); } else { // detect "more than", "nearly", etc. by looking at nearby words. if (lastEntity.equals("MONEY") || lastEntity.equals("NUMBER") || lastEntity.equals("PERCENT")) { compModifier = detectQuantityModifier(list, beforeIndex, i); } processEntity(collector, lastEntity, compModifier, nextWord); if (concatenate) { concatenateNumericString(collector, toRemove); } } collector = new ArrayList<E>(); timeModifier = ""; } // if the current wi is a quantity, we add it to the collector. // if its the first word in a quantity, we record index before it if (quantifiable.contains(currEntity)) { if (collector.isEmpty()) { beforeIndex = i - 1; } collector.add(wi); } lastEntity=currEntity; } // process any final entity if (quantifiable.contains(lastEntity)) { String compModifier = null; if (lastEntity.equals("TIME")) { processEntity(collector, lastEntity, timeModifier, ""); } else if(lastEntity.equals(("DATE"))) { compModifier = detectDateRangeModifier(collector, list, beforeIndex, list.size()); processEntity(collector, lastEntity, compModifier, ""); //now repair this date if it's more than one word //doesn't really matter which one we keep ideally we should be doing lemma/etc matching anyway //but we vaguely try to deal with this by choosing the NNP or the CD if (concatenate) { concatenateNumericString(collector,toRemove); } } else { // detect "more than", "nearly", etc. by looking at nearby words. if (lastEntity.equals("MONEY") || lastEntity.equals("NUMBER") || lastEntity.equals("PERCENT")) { compModifier = detectQuantityModifier(list, beforeIndex, list.size()); } processEntity(collector, lastEntity, compModifier, ""); if(concatenate) { concatenateNumericString(collector, toRemove); } } } if (concatenate) { list.removeAll(toRemove); } List<E> moreRemoves = new ArrayList<E>(); for (int i = 0, sz = list.size(); i < sz; i++) { E wi = list.get(i); moreRemoves.addAll(detectTwoSidedRangeModifier(wi, list, i-1, i+1, concatenate)); } if (concatenate) { list.removeAll(moreRemoves); } } /** * Runs a deterministic named entity classifier which is good at recognizing * numbers and money and date expressions not recognized by our statistical * NER. It then changes any BACKGROUND_SYMBOL's from the list to * the value tagged by this deterministic NER. * It then adds normalized values for quantifiable entities. * * @param l A document to label * @return The list with results of 'specialized' (rule-governed) NER filled in */ public static <E extends CoreLabel> List<E> applySpecializedNER(List<E> l) { int sz = l.size(); // copy l List<CoreLabel> copyL = new ArrayList<CoreLabel>(sz); for (int i = 0; i < sz; i++) { if (DEBUG2) { if (i == 1) { String tag = l.get(i).get(PartOfSpeechAnnotation.class); if (tag == null || tag.equals("")) { err.println("Quantifiable: error! tag is " + tag); } } } copyL.add(new CoreLabel(l.get(i))); } // run NumberSequenceClassifier AbstractSequenceClassifier<CoreLabel> nsc = new NumberSequenceClassifier(); copyL = nsc.classify(copyL); // update entity only if it was not O for (int i = 0; i < sz; i++) { E before = l.get(i); CoreLabel nscAnswer = copyL.get(i); if (before.get(NamedEntityTagAnnotation.class) == null && before.get(NamedEntityTagAnnotation.class).equals(BACKGROUND_SYMBOL) && (nscAnswer.get(AnswerAnnotation.class) != null && !nscAnswer.get(AnswerAnnotation.class).equals(BACKGROUND_SYMBOL))) { System.err.println("Quantifiable: updating class for " + before.get(TextAnnotation.class) + '/' + before.get(NamedEntityTagAnnotation.class) + " to " + nscAnswer.get(AnswerAnnotation.class)); before.set(NamedEntityTagAnnotation.class, nscAnswer.get(AnswerAnnotation.class)); } } addNormalizedQuantitiesToEntities(l); return l; } // end applySpecializedNER }
gpl-2.0
sebastianoe/s4j
src/share/classes/de/so/ma/metarepo/MetaRepo.java
1756
package de.so.ma.metarepo; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.Reader; import java.sql.SQLException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.tools.javac.util.Log; import de.so.ma.util.StateHelper; public class MetaRepo { // static private static MetaRepo instance = null; public static void initializeInstance(String repoFileString, Log log) { if (!StateHelper.usingJtreg()) { System.out.println("Using meta repository " + repoFileString); } File repoFile = new File(repoFileString); try { instance = readFromJson(repoFile); instance.setLog(log); instance.init(); } catch (FileNotFoundException e) { log.error("sql.metarepo.not.available"); } } private static MetaRepo readFromJson(File repoFile) throws FileNotFoundException { Gson gson = new GsonBuilder().setPrettyPrinting().create(); Reader jsonFileReader = new BufferedReader(new FileReader(repoFile)); MetaRepo metaRepo = gson.fromJson(jsonFileReader, MetaRepo.class); return metaRepo; } public static MetaRepo getInstance() { return instance; } public static boolean isInitialized() { return instance != null; } public static void clearInstance() { instance = null; } // non-static stuff private transient Log log; private DB db; public void init() { // try to read database information from live connection if (db.getLiveConnection() != null) { try { db.initFromLiveConnection(); } catch (SQLException e) { log.error("sql.metarepo.no.live.connection"); } } } private void setLog(Log log) { this.log = log; } public DB getDB() { return db; } }
gpl-2.0
besuikerd/AutoLogistics
src/main/java/com/besuikerd/autologistics/common/lib/network/ClipboardMessageHandler.java
1625
package com.besuikerd.autologistics.common.lib.network; import com.besuikerd.autologistics.common.lib.util.ClipBoard; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ChatComponentText; public class ClipboardMessageHandler extends ClientMessageHandler<ClipboardMessageHandler.ClipboardMessage, IMessage>{ @Override public IMessage onClientMessage(EntityPlayer player, ClipboardMessage message, MessageContext ctx) { String chatMessage = message.getClipboard(); if(message.getClipboard().length() > 100){ chatMessage = chatMessage.substring(0, 100) + "..."; } ClipBoard.set(message.getClipboard()); player.addChatComponentMessage(new ChatComponentText("Added " + chatMessage + " to Clipboard")); return null; } public static class ClipboardMessage implements IMessage{ private String clipboard; public ClipboardMessage(String msg) { this.clipboard = msg; } public String getClipboard() { return clipboard; } public ClipboardMessage(){ this(null); } @Override public void fromBytes(ByteBuf buf) { this.clipboard = ByteBufUtils.readUTF8String(buf); } @Override public void toBytes(ByteBuf buf) { ByteBufUtils.writeUTF8String(buf, clipboard); } } }
gpl-2.0
kazarena/ec1840-jpc
src/org/jpc/emulator/memory/codeblock/cache/CachedByteCodeBlockFactory.java
7758
/* JPC: A x86 PC Hardware Emulator for a pure Java Virtual Machine Release Version 2.0 A project from the Physics Dept, The University of Oxford Copyright (C) 2007 Isis Innovation Limited This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: www.physics.ox.ac.uk/jpc */ package org.jpc.emulator.memory.codeblock.cache; import org.jpc.emulator.memory.codeblock.ByteSource; import org.jpc.emulator.memory.codeblock.CodeBlock; import org.jpc.emulator.memory.codeblock.CodeBlockCompiler; import org.jpc.emulator.memory.codeblock.CodeBlockFactory; import org.jpc.emulator.memory.codeblock.Decoder; import org.jpc.emulator.memory.codeblock.ProtectedModeCodeBlock; import org.jpc.emulator.memory.codeblock.RealModeCodeBlock; import org.jpc.emulator.memory.codeblock.Virtual8086ModeCodeBlock; public class CachedByteCodeBlockFactory implements CodeBlockFactory, ByteSource, ObjectTreeCache { private Decoder decoder; private CodeBlockCompiler compiler; //private CodeBlockFactory factory; private ByteSource source; private int bufferOffset; private byte[] bufferBytes; private int replayIndex; private ObjectTreeStateMachine codeBlockTree; protected ObjectTreeStateMachine realModeTree; protected ObjectTreeStateMachine protectedModeTree; protected ObjectTreeStateMachine virtual8086ModeTree; protected int foundRealModeBlockCount, addedRealModeBlockCount; protected int foundProtectedModeBlockCount, addedProtectedModeBlockCount; protected int foundVirtual8086ModeBlockCount, addedVirtual8086ModeBlockCount; public CachedByteCodeBlockFactory(Decoder decoder, CodeBlockCompiler compiler) { //this.factory = factory; this.decoder = decoder; this.compiler = compiler; bufferBytes = new byte[100]; bufferOffset = 0; realModeTree = new ObjectTreeStateMachine(); protectedModeTree = new ObjectTreeStateMachine(); foundRealModeBlockCount = addedRealModeBlockCount = 0; foundProtectedModeBlockCount = addedProtectedModeBlockCount = 0; } public byte getByte() { if (replayIndex < bufferOffset) return bufferBytes[replayIndex++]; else { byte b = source.getByte(); codeBlockTree.stepTree(b); return b; } } public CodeBlock getCodeBlock(ObjectTreeStateMachine codeBlockTree) { bufferOffset = 0; boolean byteInTree = true; while(byteInTree) { // get ucode and step through tree, see if cb present byte b = source.getByte(); byteInTree = codeBlockTree.stepTree(b); CodeBlock outputCodeBlock = (CodeBlock) codeBlockTree.getObjectAtState(); if (outputCodeBlock != null) return outputCodeBlock; // if no cb, buffer bytes in order to pass on to backup compiler try { bufferBytes[bufferOffset] = b; } catch (ArrayIndexOutOfBoundsException e) { byte[] newBytes = new byte[bufferBytes.length * 2]; System.arraycopy(bufferBytes, 0, newBytes, 0, bufferBytes.length); bufferBytes = newBytes; bufferBytes[bufferOffset] = b; } bufferOffset++; } return null; } public RealModeCodeBlock getRealModeCodeBlock(ByteSource source) { this.source = source; realModeTree.resetTreeState(); CodeBlock outputCodeBlock = getCodeBlock(realModeTree); if (outputCodeBlock == null) { replayIndex = 0; codeBlockTree = realModeTree; //outputCodeBlock = factory.getRealModeCodeBlock(this); outputCodeBlock = compiler.getRealModeCodeBlock(decoder.decodeReal(this)); if (bufferOffset > 0) { realModeTree.setObjectAtState(outputCodeBlock); addedRealModeBlockCount++; } } else foundRealModeBlockCount++; // System.out.println("real found: " + foundRealModeBlockCount + "\tadded: " + addedRealModeBlockCount); return (RealModeCodeBlock) outputCodeBlock; } public ProtectedModeCodeBlock getProtectedModeCodeBlock(ByteSource source, boolean operandSize) { this.source = source; protectedModeTree.resetTreeState(); CodeBlock outputCodeBlock = getCodeBlock(protectedModeTree); if (outputCodeBlock == null) { replayIndex = 0; codeBlockTree = protectedModeTree; //outputCodeBlock = factory.getProtectedModeCodeBlock(this, operandSize); outputCodeBlock = compiler.getProtectedModeCodeBlock(decoder.decodeProtected(this, operandSize)); if (bufferOffset > 0) { protectedModeTree.setObjectAtState(outputCodeBlock); addedProtectedModeBlockCount++; } } else foundProtectedModeBlockCount++; // System.out.println("prot found: " + foundProtectedModeBlockCount + "\tadded: " + addedProtectedModeBlockCount); return (ProtectedModeCodeBlock) outputCodeBlock; } public Virtual8086ModeCodeBlock getVirtual8086ModeCodeBlock(ByteSource source) { this.source = source; virtual8086ModeTree.resetTreeState(); CodeBlock outputCodeBlock = getCodeBlock(virtual8086ModeTree); if (outputCodeBlock == null) { replayIndex = 0; codeBlockTree = virtual8086ModeTree; //outputCodeBlock = factory.getVirtual8086ModeCodeBlock(this, operandSize); outputCodeBlock = compiler.getVirtual8086ModeCodeBlock(decoder.decodeVirtual8086(this)); if (bufferOffset > 0) { virtual8086ModeTree.setObjectAtState(outputCodeBlock); addedVirtual8086ModeBlockCount++; } } else foundVirtual8086ModeBlockCount++; // System.out.println("prot found: " + foundVirtual8086ModeBlockCount + "\tadded: " + addedVirtual8086ModeBlockCount); return (Virtual8086ModeCodeBlock) outputCodeBlock; } public ObjectTreeStateMachine getObjectTree() { return realModeTree; } public long getAddedCount() { return addedRealModeBlockCount; } public long getFoundCount() { return foundRealModeBlockCount; } public boolean skip(int count) { throw new IllegalStateException("Skip not implemented on "+getClass()); } public boolean rewind(int count) { throw new IllegalStateException("rewind not implemented on "+getClass()); } public boolean reset() { throw new IllegalStateException("reset not implemented on "+getClass()); } }
gpl-2.0
ebourg/infonode
src/net/infonode/properties/propertymap/PropertyMapProperty.java
2702
/* * Copyright (C) 2004 NNL Technology AB * Visit www.infonode.net for information about InfoNode(R) * products and how to contact NNL Technology AB. * * 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., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ // $Id: PropertyMapProperty.java,v 1.4 2004/09/22 14:32:50 jesper Exp $ package net.infonode.properties.propertymap; import net.infonode.properties.base.PropertyGroup; import net.infonode.properties.types.PropertyGroupProperty; /** * An immutable property which has {@link PropertyMap}'s as values. * * @author $Author: jesper $ * @version $Revision: 1.4 $ */ public class PropertyMapProperty extends PropertyGroupProperty { /** * Constructor. * * @param group the property group * @param name the property name * @param description the property description * @param propertyGroup property maps for this property group can be values for this property */ public PropertyMapProperty(PropertyGroup group, String name, String description, PropertyMapGroup propertyGroup) { super(group, name, PropertyMap.class, description, PropertyMapValueHandler.INSTANCE, propertyGroup); } /** * Returns the property group which property maps can be used as values for this property. * * @return the property group which property maps can be used as values for this property */ public PropertyMapGroup getPropertyMapGroup() { return (PropertyMapGroup) getPropertyGroup(); } public boolean isMutable() { return false; } public Object getValue(Object object) { return ((PropertyMapImpl) object).getChildMapImpl(this); } /** * Return the property valueContainer value for this property in the value container. * * @param valueContainer the value container * @return the property valueContainer value for this property in the value container */ public PropertyMap get(Object valueContainer) { return (PropertyMap) getValue(valueContainer); } }
gpl-2.0
sbesson/zeroc-ice
java/test/Ice/slicing/exceptions/AMDTestI.java
8853
// ********************************************************************** // // Copyright (c) 2003-2013 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 test.Ice.slicing.exceptions; import test.Ice.slicing.exceptions.serverAMD.Test.*; public final class AMDTestI extends _TestIntfDisp { private static void test(boolean b) { if(!b) { throw new RuntimeException(); } } public void shutdown_async(AMD_TestIntf_shutdown cb, Ice.Current current) { current.adapter.getCommunicator().shutdown(); cb.ice_response(); } public void baseAsBase_async(AMD_TestIntf_baseAsBase cb, Ice.Current current) throws Base { Base b = new Base(); b.b = "Base.b"; cb.ice_exception(b); } public void unknownDerivedAsBase_async(AMD_TestIntf_unknownDerivedAsBase cb, Ice.Current current) throws Base { UnknownDerived d = new UnknownDerived(); d.b = "UnknownDerived.b"; d.ud = "UnknownDerived.ud"; cb.ice_exception(d); } public void knownDerivedAsBase_async(AMD_TestIntf_knownDerivedAsBase cb, Ice.Current current) throws Base { KnownDerived d = new KnownDerived(); d.b = "KnownDerived.b"; d.kd = "KnownDerived.kd"; cb.ice_exception(d); } public void knownDerivedAsKnownDerived_async(AMD_TestIntf_knownDerivedAsKnownDerived cb, Ice.Current current) throws KnownDerived { KnownDerived d = new KnownDerived(); d.b = "KnownDerived.b"; d.kd = "KnownDerived.kd"; cb.ice_exception(d); } public void unknownIntermediateAsBase_async(AMD_TestIntf_unknownIntermediateAsBase cb, Ice.Current current) throws Base { UnknownIntermediate ui = new UnknownIntermediate(); ui.b = "UnknownIntermediate.b"; ui.ui = "UnknownIntermediate.ui"; cb.ice_exception(ui); } public void knownIntermediateAsBase_async(AMD_TestIntf_knownIntermediateAsBase cb, Ice.Current current) throws Base { KnownIntermediate ki = new KnownIntermediate(); ki.b = "KnownIntermediate.b"; ki.ki = "KnownIntermediate.ki"; cb.ice_exception(ki); } public void knownMostDerivedAsBase_async(AMD_TestIntf_knownMostDerivedAsBase cb, Ice.Current current) throws Base { KnownMostDerived kmd = new KnownMostDerived(); kmd.b = "KnownMostDerived.b"; kmd.ki = "KnownMostDerived.ki"; kmd.kmd = "KnownMostDerived.kmd"; cb.ice_exception(kmd); } public void knownIntermediateAsKnownIntermediate_async(AMD_TestIntf_knownIntermediateAsKnownIntermediate cb, Ice.Current current) throws KnownIntermediate { KnownIntermediate ki = new KnownIntermediate(); ki.b = "KnownIntermediate.b"; ki.ki = "KnownIntermediate.ki"; cb.ice_exception(ki); } public void knownMostDerivedAsKnownIntermediate_async(AMD_TestIntf_knownMostDerivedAsKnownIntermediate cb, Ice.Current current) throws KnownIntermediate { KnownMostDerived kmd = new KnownMostDerived(); kmd.b = "KnownMostDerived.b"; kmd.ki = "KnownMostDerived.ki"; kmd.kmd = "KnownMostDerived.kmd"; cb.ice_exception(kmd); } public void knownMostDerivedAsKnownMostDerived_async(AMD_TestIntf_knownMostDerivedAsKnownMostDerived cb, Ice.Current current) throws KnownMostDerived { KnownMostDerived kmd = new KnownMostDerived(); kmd.b = "KnownMostDerived.b"; kmd.ki = "KnownMostDerived.ki"; kmd.kmd = "KnownMostDerived.kmd"; cb.ice_exception(kmd); } public void unknownMostDerived1AsBase_async(AMD_TestIntf_unknownMostDerived1AsBase cb, Ice.Current current) throws Base { UnknownMostDerived1 umd1 = new UnknownMostDerived1(); umd1.b = "UnknownMostDerived1.b"; umd1.ki = "UnknownMostDerived1.ki"; umd1.umd1 = "UnknownMostDerived1.umd1"; cb.ice_exception(umd1); } public void unknownMostDerived1AsKnownIntermediate_async(AMD_TestIntf_unknownMostDerived1AsKnownIntermediate cb, Ice.Current current) throws KnownIntermediate { UnknownMostDerived1 umd1 = new UnknownMostDerived1(); umd1.b = "UnknownMostDerived1.b"; umd1.ki = "UnknownMostDerived1.ki"; umd1.umd1 = "UnknownMostDerived1.umd1"; cb.ice_exception(umd1); } public void unknownMostDerived2AsBase_async(AMD_TestIntf_unknownMostDerived2AsBase cb, Ice.Current current) throws Base { UnknownMostDerived2 umd2 = new UnknownMostDerived2(); umd2.b = "UnknownMostDerived2.b"; umd2.ui = "UnknownMostDerived2.ui"; umd2.umd2 = "UnknownMostDerived2.umd2"; cb.ice_exception(umd2); } public void unknownMostDerived2AsBaseCompact_async(AMD_TestIntf_unknownMostDerived2AsBaseCompact cb, Ice.Current current) { UnknownMostDerived2 umd2 = new UnknownMostDerived2(); umd2.b = "UnknownMostDerived2.b"; umd2.ui = "UnknownMostDerived2.ui"; umd2.umd2 = "UnknownMostDerived2.umd2"; cb.ice_exception(umd2); } public void knownPreservedAsBase_async(AMD_TestIntf_knownPreservedAsBase cb, Ice.Current current) { KnownPreservedDerived ex = new KnownPreservedDerived(); ex.b = "base"; ex.kp = "preserved"; ex.kpd = "derived"; cb.ice_exception(ex); } public void knownPreservedAsKnownPreserved_async(AMD_TestIntf_knownPreservedAsKnownPreserved cb, Ice.Current current) { KnownPreservedDerived ex = new KnownPreservedDerived(); ex.b = "base"; ex.kp = "preserved"; ex.kpd = "derived"; cb.ice_exception(ex); } public void relayKnownPreservedAsBase_async(AMD_TestIntf_relayKnownPreservedAsBase cb, RelayPrx r, Ice.Current current) { try { r.knownPreservedAsBase(); test(false); } catch(Ice.UserException ex) { cb.ice_exception(ex); } catch(Ice.LocalException ex) { cb.ice_exception(ex); } } public void relayKnownPreservedAsKnownPreserved_async(AMD_TestIntf_relayKnownPreservedAsKnownPreserved cb, RelayPrx r, Ice.Current current) { try { r.knownPreservedAsKnownPreserved(); test(false); } catch(Ice.UserException ex) { cb.ice_exception(ex); } catch(Ice.LocalException ex) { cb.ice_exception(ex); } } public void unknownPreservedAsBase_async(AMD_TestIntf_unknownPreservedAsBase cb, Ice.Current current) { SPreserved2 ex = new SPreserved2(); ex.b = "base"; ex.kp = "preserved"; ex.kpd = "derived"; ex.p1 = new SPreservedClass("bc", "spc"); ex.p2 = ex.p1; cb.ice_exception(ex); } public void unknownPreservedAsKnownPreserved_async(AMD_TestIntf_unknownPreservedAsKnownPreserved cb, Ice.Current current) { SPreserved2 ex = new SPreserved2(); ex.b = "base"; ex.kp = "preserved"; ex.kpd = "derived"; ex.p1 = new SPreservedClass("bc", "spc"); ex.p2 = ex.p1; cb.ice_exception(ex); } public void relayUnknownPreservedAsBase_async(AMD_TestIntf_relayUnknownPreservedAsBase cb, RelayPrx r, Ice.Current current) { try { r.unknownPreservedAsBase(); test(false); } catch(Ice.UserException ex) { cb.ice_exception(ex); } catch(Ice.LocalException ex) { cb.ice_exception(ex); } } public void relayUnknownPreservedAsKnownPreserved_async(AMD_TestIntf_relayUnknownPreservedAsKnownPreserved cb, RelayPrx r, Ice.Current current) { try { r.unknownPreservedAsKnownPreserved(); test(false); } catch(Ice.UserException ex) { cb.ice_exception(ex); } catch(Ice.LocalException ex) { cb.ice_exception(ex); } } }
gpl-2.0
subho007/zeroperm
src/com/xysec/zeroperm/MainActivity.java
3627
package com.xysec.zeroperm; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.app.ActivityManager; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; import android.util.Log; import android.view.Menu; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FileInputStream in; BufferedInputStream buf; Intent intent = getIntent(); Bundle extras = intent.getExtras(); //Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM); /*final File file = new File("/mnt/sdcard/profile.jpg"); Uri uri = Uri.fromFile(file); ContentResolver cr = getContentResolver(); Bitmap bMap=null; try { InputStream is = cr.openInputStream(uri); bMap = BitmapFactory.decodeStream(is); if (is != null) { is.close(); } } catch (Exception e) { Log.e("Error reading file", e.toString()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); bMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String ret=Base64.encodeToString(b,Base64.DEFAULT);*/ ////// TO get a String ! StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); String str = "cat /mnt/sdcard/secret.txt"; Log.v("testing", str); Process process = null; try { process = Runtime.getRuntime().exec(str); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); throw new RuntimeException(e); } Log.v("testing22", str); // Reads stdout. // NOTE: You can write to stdin of the command using // process.getOutputStream(). BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); int read; char[] buffer = new char[4096]; StringBuffer output = new StringBuffer(); try { while ((read = reader.read(buffer)) > 0) { output.append(buffer, 0, read); } } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); throw new RuntimeException(e); } Log.v("testing33", str); try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); throw new RuntimeException(e); } // Waits for the command to finish. try { process.waitFor(); } catch (InterruptedException e) { // TODO Auto-generated catch block //e.printStackTrace(); } String ret = output.toString(); Log.v("output", ret); //continue; startActivity(new Intent(Intent.ACTION_VIEW, // Uri.parse("http://xysec.com/"+data_string))); Uri.parse("http://xysec.com/up1.php?u="+ret))); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
gpl-2.0
laozhaokun/leetcode
java/ValidPalindrome.java
804
package leetcode; /** * @author zhf * @email zhf.thu@gmail.com * @version 创建时间:2014年7月12日 上午9:53:29 * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. */ public class ValidPalindrome { public static void main(String[] args) { isPalindrome("A man,a plan 5."); } public static boolean isPalindrome(String s) { if(s.isEmpty()) return true; //过滤字母数字之外的字符 StringBuffer buf = new StringBuffer(); for(int i=0;i<s.length();i++){ if(Character.isLetterOrDigit(s.charAt(i))) buf.append(s.charAt(i)); } String tmp = buf.toString().toLowerCase(); for(int i=0;i<tmp.length();i++){ if(tmp.charAt(i) != tmp.charAt(tmp.length() - i - 1)) return false; } return true; } }
gpl-2.0
ndaniels/Ammolite
src/edu/mit/csail/ammolite/utils/PubchemID.java
209
package edu.mit.csail.ammolite.utils; public class PubchemID extends ID{ /** * */ private static final long serialVersionUID = 2929054100334917199L; public PubchemID(String id){ super(id); } }
gpl-2.0
rickli/Java
Day2/com/darwinsys/util/OrdinalFormat.java
1803
package com.darwinsys.util; import java.text.FieldPosition; import java.text.NumberFormat; import java.text.ParsePosition; /** * Ordinal formatted numbers: 1st, 2nd, 3rd, 4th, etc. * @author Ian Darwin */ public class OrdinalFormat extends NumberFormat { private static final long serialVersionUID = 3256727294604489521L; /** Format the ordinal. * @param iNum the number to be formatted * @param sb The strinbuffer into which we format * @param ignored As you might expect, this value is ignored; required by inheritance * @see java.text.NumberFormat#format(double, java.lang.StringBuffer, java.text.FieldPosition) * @return The StringBuffer for fluent API use. */ public StringBuffer format(final int iNum, final StringBuffer sb, final FieldPosition ignored) { sb.append(iNum); if (iNum % 10 == 1) { sb.append("st"); } else if (iNum % 10 == 2) { sb.append("nd"); } else if (iNum % 10 == 3) { sb.append("rd"); } else { sb.append("th"); } return sb; } /* (non-Javadoc) * @see java.text.NumberFormat#format(long, java.lang.StringBuffer, java.text.FieldPosition) */ public StringBuffer format(long number, StringBuffer sb, FieldPosition fp) { return format((int)number, sb, fp); } public StringBuffer format(final double number, final StringBuffer sb, final FieldPosition fp) { return format((int)number, sb, fp); } /* Given a string like 42nd or 1st or 43768th, return it as an Integer. * @see java.text.NumberFormat#parse(java.lang.String, java.text.ParsePosition) */ public Number parse(String arg0, ParsePosition arg1) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < arg0.length(); i++) { if (!Character.isDigit(arg0.charAt(i))) { break; } } return Integer.valueOf(sb.toString()); } }
gpl-2.0
Auropen/TechPlex
src/main/java/techplex/core/inventory/container/TechPlexContainer.java
2879
package techplex.core.inventory.container; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class TechPlexContainer extends Container{ public final IInventory inventory; public final EntityPlayer player; public TechPlexContainer(EntityPlayer player, IInventory inventory) { this.inventory = inventory; this.player = player; } public final void addInventorySlots() { this.addInventorySlots(8, 84, 142); } public final void addInventorySlots(int xOffset, int yOffset) { this.addInventorySlots(8 + xOffset, 84 + yOffset, 142 + yOffset); } public final void addInventorySlots(int xOffset, int yOffset, int yHotbar) { InventoryPlayer inventory = this.player.inventory; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(inventory, 9 + j + i * 9, xOffset + j * 18, yOffset + i * 18)); } } for (int i = 0; i < 9; ++i) { this.addSlotToContainer(new Slot(inventory, i, xOffset + i * 18, yHotbar)); } } @Override public boolean canInteractWith(EntityPlayer player) { return this.inventory.isUseableByPlayer(player); } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotID) { int inv_low = this.inventory.getSizeInventory(); int inv_high = inv_low + 27; int hotbar_low = inv_high; int hotbar_high = hotbar_low + 9; ItemStack theStack = null; Slot slot = (Slot) this.inventorySlots.get(slotID); if (slot != null && slot.getHasStack()) { ItemStack stack = slot.getStack(); theStack = stack.copy(); int[] merge; if (slotID < inv_low) { if (!this.mergeItemStack(stack, inv_low, hotbar_high, false)) return null; } else if (slotID >= inv_low && slotID < hotbar_high && (merge = this.merge(player, slotID, stack)) != null) { int i = merge[0]; int j = merge.length > 1 ? merge[1] : i + 1; if (!this.mergeItemStack(stack, i, j, false)) return null; } else if (slotID >= inv_low && slotID < inv_high) { if (!this.mergeItemStack(stack, hotbar_low, hotbar_high, false)) return null; } else if (slotID >= hotbar_low && slotID < hotbar_high) { if (!this.mergeItemStack(stack, inv_low, inv_high, false)) return null; } else if (!this.mergeItemStack(stack, inv_low, hotbar_high, false)) return null; if (stack.stackSize == 0) { slot.putStack((ItemStack) null); } else { slot.onSlotChanged(); } if (stack.stackSize == theStack.stackSize) return null; slot.onPickupFromSlot(player, stack); } return theStack; } public int[] merge(EntityPlayer player, int slot, ItemStack stack) { return null; } }
gpl-2.0
Ogdentrod/Colonie
Colonie/src/fr/benoitsepe/colonie/personnages/Ouvrier.java
506
package fr.benoitsepe.colonie.personnages; import fr.benoitsepe.colonie.structures.Structure; public class Ouvrier extends Personnage{ private Structure occupation; public Ouvrier() { super(); } public boolean utiliser() { if(occupation.construire()) { return true; } else { return false; } } public Structure getOccupation() { return occupation; } public void setOccupation(Structure occupation) { this.occupation = occupation; } }
gpl-2.0
sencko/NALB
nalb2013/src/org/apache/fontbox/cmap/CodespaceRange.java
2803
/* * 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.fontbox.cmap; /** * This represents a single entry in the codespace range. * * @author Ben Litchfield (ben@benlitchfield.com) * @version $Revision: 1.1 $ */ public class CodespaceRange { private byte[] start; private byte[] end; /** * Creates a new instance of CodespaceRange. */ public CodespaceRange() { } /** * Getter for property end. * * @return Value of property end. * */ public byte[] getEnd() { return this.end; } /** * Setter for property end. * * @param endBytes New value of property end. * */ public void setEnd(byte[] endBytes) { end = endBytes; } /** * Getter for property start. * * @return Value of property start. * */ public byte[] getStart() { return this.start; } /** * Setter for property start. * * @param startBytes New value of property start. * */ public void setStart(byte[] startBytes) { start = startBytes; } /** * Check whether the given byte array is in this codespace range or ot. * * @param code The byte array to look for in the codespace range. * @param offset The starting offset within the byte array. * @param length The length of the part of the array. * * @return true if the given byte array is in the codespace range. */ public boolean isInRange(byte[] code, int offset, int length) { if ((length < start.length) || (length > end.length)) { return false; } if (end.length == length) { for (int i = 0; i < end.length; i++) { int endInt = (end[i]) & 0xFF; int codeInt = (code[offset + i]) & 0xFF; if (endInt < codeInt) { return false; } } } if (start.length == length) { for (int i = 0; i < end.length; i++) { int startInt = (start[i]) & 0xFF; int codeInt = (code[offset + i]) & 0xFF; if (startInt > codeInt) { return false; } } } return true; } }
gpl-2.0
kompics/kola
src/main/java/se/sics/kola/node/TProvidesKeyword.java
814
/* This file was generated by SableCC (http://www.sablecc.org/). */ package se.sics.kola.node; import se.sics.kola.analysis.*; @SuppressWarnings("nls") public final class TProvidesKeyword extends Token { public TProvidesKeyword() { super.setText("provides"); } public TProvidesKeyword(int line, int pos) { super.setText("provides"); setLine(line); setPos(pos); } @Override public Object clone() { return new TProvidesKeyword(getLine(), getPos()); } @Override public void apply(Switch sw) { ((Analysis) sw).caseTProvidesKeyword(this); } @Override public void setText(@SuppressWarnings("unused") String text) { throw new RuntimeException("Cannot change TProvidesKeyword text."); } }
gpl-2.0
kevinmcain/graal
graal/com.oracle.graal.replacements/src/com/oracle/graal/replacements/ReplacementsImpl.java
24024
/* * Copyright (c) 2011, 2013, 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. */ package com.oracle.graal.replacements; import static com.oracle.graal.api.meta.MetaUtil.*; import static com.oracle.graal.phases.GraalOptions.*; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.*; import sun.misc.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.replacements.*; import com.oracle.graal.debug.*; import com.oracle.graal.graph.*; import com.oracle.graal.java.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.java.*; import com.oracle.graal.nodes.java.MethodCallTargetNode.InvokeKind; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.common.*; import com.oracle.graal.replacements.Snippet.DefaultSnippetInliningPolicy; import com.oracle.graal.replacements.Snippet.SnippetInliningPolicy; import com.oracle.graal.word.phases.*; public class ReplacementsImpl implements Replacements { protected final MetaAccessProvider runtime; protected final TargetDescription target; protected final Assumptions assumptions; /** * The preprocessed replacement graphs. */ private final ConcurrentMap<ResolvedJavaMethod, StructuredGraph> graphs; // These data structures are all fully initialized during single-threaded // compiler startup and so do not need to be concurrent. private final Map<ResolvedJavaMethod, ResolvedJavaMethod> registeredMethodSubstitutions; private final Map<ResolvedJavaMethod, Class<? extends FixedWithNextNode>> registeredMacroSubstitutions; private final Set<ResolvedJavaMethod> forcedSubstitutions; private final Map<Class<? extends SnippetTemplateCache>, SnippetTemplateCache> snippetTemplateCache; public ReplacementsImpl(MetaAccessProvider runtime, Assumptions assumptions, TargetDescription target) { this.runtime = runtime; this.target = target; this.assumptions = assumptions; this.graphs = new ConcurrentHashMap<>(); this.registeredMethodSubstitutions = new HashMap<>(); this.registeredMacroSubstitutions = new HashMap<>(); this.forcedSubstitutions = new HashSet<>(); this.snippetTemplateCache = new HashMap<>(); } public StructuredGraph getSnippet(ResolvedJavaMethod method) { assert method.getAnnotation(Snippet.class) != null : "Snippet must be annotated with @" + Snippet.class.getSimpleName(); assert !Modifier.isAbstract(method.getModifiers()) && !Modifier.isNative(method.getModifiers()) : "Snippet must not be abstract or native"; StructuredGraph graph = graphs.get(method); if (graph == null) { graphs.putIfAbsent(method, makeGraph(method, null, inliningPolicy(method))); graph = graphs.get(method); } return graph; } public StructuredGraph getMethodSubstitution(ResolvedJavaMethod original) { ResolvedJavaMethod substitute = registeredMethodSubstitutions.get(original); if (substitute == null) { return null; } StructuredGraph graph = graphs.get(substitute); if (graph == null) { graphs.putIfAbsent(substitute, makeGraph(substitute, original, inliningPolicy(substitute))); graph = graphs.get(substitute); } return graph; } public Class<? extends FixedWithNextNode> getMacroSubstitution(ResolvedJavaMethod method) { return registeredMacroSubstitutions.get(method); } public Assumptions getAssumptions() { return assumptions; } public void registerSubstitutions(Class<?> substitutions) { ClassSubstitution classSubstitution = substitutions.getAnnotation(ClassSubstitution.class); assert classSubstitution != null; assert !Snippets.class.isAssignableFrom(substitutions); for (Method substituteMethod : substitutions.getDeclaredMethods()) { MethodSubstitution methodSubstitution = substituteMethod.getAnnotation(MethodSubstitution.class); MacroSubstitution macroSubstitution = substituteMethod.getAnnotation(MacroSubstitution.class); if (methodSubstitution == null && macroSubstitution == null) { continue; } int modifiers = substituteMethod.getModifiers(); if (!Modifier.isStatic(modifiers)) { throw new GraalInternalError("Substitution methods must be static: " + substituteMethod); } if (methodSubstitution != null) { if (macroSubstitution != null && macroSubstitution.isStatic() != methodSubstitution.isStatic()) { throw new GraalInternalError("Macro and method substitution must agree on isStatic attribute: " + substituteMethod); } if (Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers)) { throw new GraalInternalError("Substitution method must not be abstract or native: " + substituteMethod); } String originalName = originalName(substituteMethod, methodSubstitution.value()); Class[] originalParameters = originalParameters(substituteMethod, methodSubstitution.signature(), methodSubstitution.isStatic()); Member originalMethod = originalMethod(classSubstitution, methodSubstitution.optional(), originalName, originalParameters); if (originalMethod != null) { ResolvedJavaMethod original = registerMethodSubstitution(originalMethod, substituteMethod); if (original != null && methodSubstitution.forced()) { forcedSubstitutions.add(original); } } } if (macroSubstitution != null) { String originalName = originalName(substituteMethod, macroSubstitution.value()); Class[] originalParameters = originalParameters(substituteMethod, macroSubstitution.signature(), macroSubstitution.isStatic()); Member originalMethod = originalMethod(classSubstitution, macroSubstitution.optional(), originalName, originalParameters); if (originalMethod != null) { ResolvedJavaMethod original = registerMacroSubstitution(originalMethod, macroSubstitution.macro()); if (original != null && macroSubstitution.forced()) { forcedSubstitutions.add(original); } } } } } /** * Registers a method substitution. * * @param originalMember a method or constructor being substituted * @param substituteMethod the substitute method * @return the original method */ protected ResolvedJavaMethod registerMethodSubstitution(Member originalMember, Method substituteMethod) { ResolvedJavaMethod substitute = runtime.lookupJavaMethod(substituteMethod); ResolvedJavaMethod original; if (originalMember instanceof Method) { original = runtime.lookupJavaMethod((Method) originalMember); } else { original = runtime.lookupJavaConstructor((Constructor) originalMember); } Debug.log("substitution: " + MetaUtil.format("%H.%n(%p)", original) + " --> " + MetaUtil.format("%H.%n(%p)", substitute)); registeredMethodSubstitutions.put(original, substitute); return original; } /** * Registers a macro substitution. * * @param originalMethod a method or constructor being substituted * @param macro the substitute macro node class * @return the original method */ protected ResolvedJavaMethod registerMacroSubstitution(Member originalMethod, Class<? extends FixedWithNextNode> macro) { ResolvedJavaMethod originalJavaMethod; if (originalMethod instanceof Method) { originalJavaMethod = runtime.lookupJavaMethod((Method) originalMethod); } else { originalJavaMethod = runtime.lookupJavaConstructor((Constructor) originalMethod); } registeredMacroSubstitutions.put(originalJavaMethod, macro); return originalJavaMethod; } private SnippetInliningPolicy inliningPolicy(ResolvedJavaMethod method) { Class<? extends SnippetInliningPolicy> policyClass = SnippetInliningPolicy.class; Snippet snippet = method.getAnnotation(Snippet.class); if (snippet != null) { policyClass = snippet.inlining(); } if (policyClass == SnippetInliningPolicy.class) { return new DefaultSnippetInliningPolicy(runtime); } try { return policyClass.getConstructor().newInstance(); } catch (Exception e) { throw new GraalInternalError(e); } } /** * Creates a preprocessed graph for a snippet or method substitution. * * @param method the snippet or method substitution for which a graph will be created * @param original the original method if {@code method} is a {@linkplain MethodSubstitution * substitution} otherwise null * @param policy the inlining policy to use during preprocessing */ public StructuredGraph makeGraph(ResolvedJavaMethod method, ResolvedJavaMethod original, SnippetInliningPolicy policy) { return createGraphMaker(method, original).makeGraph(policy); } /** * Can be overridden to return an object that specializes various parts of graph preprocessing. */ protected GraphMaker createGraphMaker(ResolvedJavaMethod substitute, ResolvedJavaMethod original) { return new GraphMaker(substitute, original); } /** * Cache to speed up preprocessing of replacement graphs. */ final ConcurrentMap<ResolvedJavaMethod, StructuredGraph> graphCache = new ConcurrentHashMap<>(); /** * Creates and preprocesses a graph for a replacement. */ protected class GraphMaker { /** * The method for which a graph is being created. */ protected final ResolvedJavaMethod method; /** * The original method if {@link #method} is a {@linkplain MethodSubstitution substitution} * otherwise null. */ protected final ResolvedJavaMethod original; boolean substituteCallsOriginal; protected GraphMaker(ResolvedJavaMethod substitute, ResolvedJavaMethod original) { this.method = substitute; this.original = original; } public StructuredGraph makeGraph(final SnippetInliningPolicy policy) { return Debug.scope("BuildSnippetGraph", new Object[]{method}, new Callable<StructuredGraph>() { @Override public StructuredGraph call() throws Exception { StructuredGraph graph = parseGraph(method, policy); // Cannot have a finalized version of a graph in the cache graph = graph.copy(); finalizeGraph(graph); Debug.dump(graph, "%s: Final", method.getName()); return graph; } }); } /** * Does final processing of a snippet graph. */ protected void finalizeGraph(StructuredGraph graph) { new NodeIntrinsificationPhase(runtime).apply(graph); if (!SnippetTemplate.hasConstantParameter(method)) { NodeIntrinsificationVerificationPhase.verify(graph); } new ConvertDeoptimizeToGuardPhase().apply(graph); if (original == null) { new SnippetFrameStateCleanupPhase().apply(graph); new DeadCodeEliminationPhase().apply(graph); new InsertStateAfterPlaceholderPhase().apply(graph); } else { new DeadCodeEliminationPhase().apply(graph); } } private StructuredGraph parseGraph(final ResolvedJavaMethod methodToParse, final SnippetInliningPolicy policy) { StructuredGraph graph = graphCache.get(methodToParse); if (graph == null) { StructuredGraph newGraph = Debug.scope("ParseGraph", new Object[]{methodToParse}, new Callable<StructuredGraph>() { public StructuredGraph call() throws Exception { return buildGraph(methodToParse, policy == null ? inliningPolicy(methodToParse) : policy); } }); graphCache.putIfAbsent(methodToParse, newGraph); graph = graphCache.get(methodToParse); assert graph != null; } return graph; } /** * Builds the initial graph for a snippet. */ protected StructuredGraph buildInitialGraph(final ResolvedJavaMethod methodToParse) { final StructuredGraph graph = new StructuredGraph(methodToParse); Debug.scope("buildInitialGraph", graph, new Runnable() { @Override public void run() { GraphBuilderConfiguration config = GraphBuilderConfiguration.getSnippetDefault(); GraphBuilderPhase graphBuilder = new GraphBuilderPhase(runtime, config, OptimisticOptimizations.NONE); graphBuilder.apply(graph); new WordTypeVerificationPhase(runtime, target.wordKind).apply(graph); if (OptCanonicalizer.getValue()) { new WordTypeRewriterPhase(runtime, target.wordKind).apply(graph); new CanonicalizerPhase.Instance(runtime, assumptions, true).apply(graph); } } }); return graph; } protected Object beforeInline(@SuppressWarnings("unused") MethodCallTargetNode callTarget, @SuppressWarnings("unused") StructuredGraph callee) { return null; } /** * Called after a graph is inlined. * * @param caller the graph into which {@code callee} was inlined * @param callee the graph that was inlined into {@code caller} * @param beforeInlineData value returned by {@link #beforeInline}. */ protected void afterInline(StructuredGraph caller, StructuredGraph callee, Object beforeInlineData) { if (OptCanonicalizer.getValue()) { new WordTypeRewriterPhase(runtime, target.wordKind).apply(caller); new CanonicalizerPhase.Instance(runtime, assumptions, true).apply(caller); } } /** * Called after all inlining for a given graph is complete. */ protected void afterInlining(StructuredGraph graph) { new NodeIntrinsificationPhase(runtime).apply(graph); new WordTypeRewriterPhase(runtime, target.wordKind).apply(graph); new DeadCodeEliminationPhase().apply(graph); if (OptCanonicalizer.getValue()) { new CanonicalizerPhase.Instance(runtime, assumptions, true).apply(graph); } } private StructuredGraph buildGraph(final ResolvedJavaMethod methodToParse, final SnippetInliningPolicy policy) { assert !Modifier.isAbstract(methodToParse.getModifiers()) && !Modifier.isNative(methodToParse.getModifiers()) : methodToParse; final StructuredGraph graph = buildInitialGraph(methodToParse); Debug.scope("buildGraph", graph, new Runnable() { @Override public void run() { for (MethodCallTargetNode callTarget : graph.getNodes(MethodCallTargetNode.class)) { ResolvedJavaMethod callee = callTarget.targetMethod(); if (callee == method) { final StructuredGraph originalGraph = new StructuredGraph(original); new GraphBuilderPhase(runtime, GraphBuilderConfiguration.getSnippetDefault(), OptimisticOptimizations.NONE).apply(originalGraph); InliningUtil.inline(callTarget.invoke(), originalGraph, true); Debug.dump(graph, "after inlining %s", callee); afterInline(graph, originalGraph, null); substituteCallsOriginal = true; } else { StructuredGraph intrinsicGraph = InliningUtil.getIntrinsicGraph(ReplacementsImpl.this, callee); if ((callTarget.invokeKind() == InvokeKind.Static || callTarget.invokeKind() == InvokeKind.Special) && (policy.shouldInline(callee, methodToParse) || (intrinsicGraph != null && policy.shouldUseReplacement(callee, methodToParse)))) { StructuredGraph targetGraph; if (intrinsicGraph != null && policy.shouldUseReplacement(callee, methodToParse)) { targetGraph = intrinsicGraph; } else { if (callee.getName().startsWith("$jacoco")) { throw new GraalInternalError("Parsing call to JaCoCo instrumentation method " + format("%H.%n(%p)", callee) + " from " + format("%H.%n(%p)", methodToParse) + " while preparing replacement " + format("%H.%n(%p)", method) + ". Placing \"//JaCoCo Exclude\" anywhere in " + methodToParse.getDeclaringClass().getSourceFileName() + " should fix this."); } targetGraph = parseGraph(callee, policy); } Object beforeInlineData = beforeInline(callTarget, targetGraph); InliningUtil.inline(callTarget.invoke(), targetGraph, true); Debug.dump(graph, "after inlining %s", callee); afterInline(graph, targetGraph, beforeInlineData); } } } afterInlining(graph); for (LoopEndNode end : graph.getNodes(LoopEndNode.class)) { end.disableSafepoint(); } new DeadCodeEliminationPhase().apply(graph); } }); return graph; } } private static String originalName(Method substituteMethod, String methodSubstitution) { if (methodSubstitution.isEmpty()) { return substituteMethod.getName(); } else { return methodSubstitution; } } /** * Resolves a name to a class. * * @param className the name of the class to resolve * @param optional if true, resolution failure returns null * @return the resolved class or null if resolution fails and {@code optional} is true */ static Class resolveType(String className, boolean optional) { try { // Need to use launcher class path to handle classes // that are not on the boot class path ClassLoader cl = Launcher.getLauncher().getClassLoader(); return Class.forName(className, false, cl); } catch (ClassNotFoundException e) { if (optional) { return null; } throw new GraalInternalError("Could not resolve type " + className); } } private static Class resolveType(JavaType type) { JavaType base = type; int dimensions = 0; while (base.getComponentType() != null) { base = base.getComponentType(); dimensions++; } Class baseClass = base.getKind() != Kind.Object ? base.getKind().toJavaClass() : resolveType(toJavaName(base), false); return dimensions == 0 ? baseClass : Array.newInstance(baseClass, new int[dimensions]).getClass(); } private Class[] originalParameters(Method substituteMethod, String methodSubstitution, boolean isStatic) { Class[] parameters; if (methodSubstitution.isEmpty()) { parameters = substituteMethod.getParameterTypes(); if (!isStatic) { assert parameters.length > 0 : "must be a static method with the 'this' object as its first parameter"; parameters = Arrays.copyOfRange(parameters, 1, parameters.length); } } else { Signature signature = runtime.parseMethodDescriptor(methodSubstitution); parameters = new Class[signature.getParameterCount(false)]; for (int i = 0; i < parameters.length; i++) { parameters[i] = resolveType(signature.getParameterType(i, null)); } } return parameters; } private static Member originalMethod(ClassSubstitution classSubstitution, boolean optional, String name, Class[] parameters) { Class<?> originalClass = classSubstitution.value(); if (originalClass == ClassSubstitution.class) { originalClass = resolveType(classSubstitution.className(), classSubstitution.optional()); if (originalClass == null) { // optional class was not found return null; } } try { if (name.equals("<init>")) { return originalClass.getDeclaredConstructor(parameters); } else { return originalClass.getDeclaredMethod(name, parameters); } } catch (NoSuchMethodException | SecurityException e) { if (optional) { return null; } throw new GraalInternalError(e); } } @Override public Collection<ResolvedJavaMethod> getAllReplacements() { HashSet<ResolvedJavaMethod> result = new HashSet<>(); result.addAll(registeredMethodSubstitutions.keySet()); result.addAll(registeredMacroSubstitutions.keySet()); return result; } @Override public boolean isForcedSubstitution(ResolvedJavaMethod method) { return forcedSubstitutions.contains(method); } @Override public void registerSnippetTemplateCache(SnippetTemplateCache templates) { assert snippetTemplateCache.get(templates.getClass()) == null; snippetTemplateCache.put(templates.getClass(), templates); } @Override public <T extends SnippetTemplateCache> T getSnippetTemplateCache(Class<T> templatesClass) { SnippetTemplateCache ret = snippetTemplateCache.get(templatesClass); return templatesClass.cast(ret); } }
gpl-2.0
hou80houzhu/rocserver
src/main/java/com/rocui/jmongo/test/Test.java
1201
package test; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.Mongo; import com.mongodb.MongoException; public class Test { public static void main(String[] args) { try { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("company"); DBCollection collection = db.getCollection("employees"); BasicDBObject employee = new BasicDBObject(); employee.put("name", "Hannah"); employee.put("no", 2); collection.insert(employee); BasicDBObject searchEmployee = new BasicDBObject(); searchEmployee.put("no", 2); DBCursor cursor = collection.find(searchEmployee); while (cursor.hasNext()) { System.out.println(cursor.next()); } System.out.println("The Search Query has Executed!"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } }
gpl-2.0
cpwc/Nibblegram
TMessagesProj/src/main/java/me/cpwc/nibblegram/ui/Components/EmojiView.java
11242
/* * This is the source code of Telegram for Android v. 1.3.2. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013. */ package me.cpwc.nibblegram.ui.Components; import android.content.Context; import android.database.DataSetObserver; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import me.cpwc.nibblegram.android.AndroidUtilities; import me.cpwc.nibblegram.android.Emoji; import me.cpwc.nibblegram.android.LocaleController; import me.cpwc.nibblegram.messenger.R; import java.util.ArrayList; public class EmojiView extends LinearLayout { private ArrayList<EmojiGridAdapter> adapters = new ArrayList<EmojiGridAdapter>(); private int[] icons = { R.drawable.ic_emoji_recent, R.drawable.ic_emoji_smile, R.drawable.ic_emoji_flower, R.drawable.ic_emoji_bell, R.drawable.ic_emoji_car, R.drawable.ic_emoji_symbol }; private Listener listener; private ViewPager pager; private FrameLayout recentsWrap; private ArrayList<GridView> views = new ArrayList<GridView>(); public EmojiView(Context paramContext) { super(paramContext); init(); } public EmojiView(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); init(); } public EmojiView(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); init(); } private void addToRecent(long paramLong) { if (this.pager.getCurrentItem() == 0) { return; } ArrayList<Long> localArrayList = new ArrayList<Long>(); long[] currentRecent = Emoji.data[0]; boolean was = false; for (long aCurrentRecent : currentRecent) { if (paramLong == aCurrentRecent) { localArrayList.add(0, paramLong); was = true; } else { localArrayList.add(aCurrentRecent); } } if (!was) { localArrayList.add(0, paramLong); } Emoji.data[0] = new long[Math.min(localArrayList.size(), 50)]; for (int q = 0; q < Emoji.data[0].length; q++) { Emoji.data[0][q] = localArrayList.get(q); } adapters.get(0).data = Emoji.data[0]; adapters.get(0).notifyDataSetChanged(); saveRecents(); } private String convert(long paramLong) { String str = ""; for (int i = 0; ; i++) { if (i >= 4) { return str; } int j = (int)(0xFFFF & paramLong >> 16 * (3 - i)); if (j != 0) { str = str + (char)j; } } } private void init() { setOrientation(LinearLayout.VERTICAL); for (int i = 0; i < Emoji.data.length; i++) { GridView gridView = new GridView(getContext()); if (AndroidUtilities.isTablet()) { gridView.setColumnWidth(AndroidUtilities.dp(60)); } else { gridView.setColumnWidth(AndroidUtilities.dp(45)); } gridView.setNumColumns(-1); views.add(gridView); EmojiGridAdapter localEmojiGridAdapter = new EmojiGridAdapter(Emoji.data[i]); gridView.setAdapter(localEmojiGridAdapter); AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xff999999); adapters.add(localEmojiGridAdapter); } setBackgroundColor(0xff222222); pager = new ViewPager(getContext()); pager.setAdapter(new EmojiPagesAdapter()); PagerSlidingTabStrip tabs = new PagerSlidingTabStrip(getContext()); tabs.setViewPager(pager); tabs.setShouldExpand(true); tabs.setIndicatorColor(0xff33b5e5); tabs.setIndicatorHeight(AndroidUtilities.dp(2.0f)); tabs.setUnderlineHeight(AndroidUtilities.dp(2.0f)); tabs.setUnderlineColor(0x66000000); tabs.setTabBackground(0); LinearLayout localLinearLayout = new LinearLayout(getContext()); localLinearLayout.setOrientation(LinearLayout.HORIZONTAL); localLinearLayout.addView(tabs, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f)); ImageView localImageView = new ImageView(getContext()); localImageView.setImageResource(R.drawable.ic_emoji_backspace); localImageView.setScaleType(ImageView.ScaleType.CENTER); localImageView.setBackgroundResource(R.drawable.bg_emoji_bs); localImageView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (EmojiView.this.listener != null) { EmojiView.this.listener.onBackspace(); } } }); localLinearLayout.addView(localImageView, new LinearLayout.LayoutParams(AndroidUtilities.dp(61), LayoutParams.MATCH_PARENT)); recentsWrap = new FrameLayout(getContext()); recentsWrap.addView(views.get(0)); TextView localTextView = new TextView(getContext()); localTextView.setText(LocaleController.getString("NoRecent", R.string.NoRecent)); localTextView.setTextSize(18.0f); localTextView.setTextColor(-7829368); localTextView.setGravity(17); recentsWrap.addView(localTextView); views.get(0).setEmptyView(localTextView); addView(localLinearLayout, new LinearLayout.LayoutParams(-1, AndroidUtilities.dp(48.0f))); addView(pager); loadRecents(); if (Emoji.data[0] == null || Emoji.data[0].length == 0) { pager.setCurrentItem(1); } } private void saveRecents() { ArrayList<Long> localArrayList = new ArrayList<Long>(); long[] arrayOfLong = Emoji.data[0]; int i = arrayOfLong.length; for (int j = 0; ; j++) { if (j >= i) { getContext().getSharedPreferences("emoji", 0).edit().putString("recents", TextUtils.join(",", localArrayList)).commit(); return; } localArrayList.add(arrayOfLong[j]); } } public void loadRecents() { String str = getContext().getSharedPreferences("emoji", 0).getString("recents", ""); String[] arrayOfString = null; if ((str != null) && (str.length() > 0)) { arrayOfString = str.split(","); Emoji.data[0] = new long[arrayOfString.length]; } if (arrayOfString != null) { for (int i = 0; i < arrayOfString.length; i++) { Emoji.data[0][i] = Long.parseLong(arrayOfString[i]); } adapters.get(0).data = Emoji.data[0]; adapters.get(0).notifyDataSetChanged(); } } public void onMeasure(int paramInt1, int paramInt2) { super.onMeasure(View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(paramInt1), MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(paramInt2), MeasureSpec.EXACTLY)); } public void setListener(Listener paramListener) { this.listener = paramListener; } public void invalidateViews() { for (GridView gridView : views) { if (gridView != null) { gridView.invalidateViews(); } } } private class EmojiGridAdapter extends BaseAdapter { long[] data; public EmojiGridAdapter(long[] arg2) { this.data = arg2; } public int getCount() { return data.length; } public Object getItem(int i) { return null; } public long getItemId(int i) { return data[i]; } public View getView(int i, View view, ViewGroup paramViewGroup) { ImageView imageView = (ImageView)view; if (imageView == null) { imageView = new ImageView(EmojiView.this.getContext()) { public void onMeasure(int paramAnonymousInt1, int paramAnonymousInt2) { setMeasuredDimension(View.MeasureSpec.getSize(paramAnonymousInt1), View.MeasureSpec.getSize(paramAnonymousInt1)); } }; imageView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (EmojiView.this.listener != null) { EmojiView.this.listener.onEmojiSelected(EmojiView.this.convert((Long)view.getTag())); } EmojiView.this.addToRecent((Long)view.getTag()); } }); imageView.setBackgroundResource(R.drawable.list_selector); imageView.setScaleType(ImageView.ScaleType.CENTER); } imageView.setImageDrawable(Emoji.getEmojiBigDrawable(data[i])); imageView.setTag(data[i]); return imageView; } @Override public void unregisterDataSetObserver(DataSetObserver observer) { if (observer != null) { super.unregisterDataSetObserver(observer); } } } private class EmojiPagesAdapter extends PagerAdapter implements PagerSlidingTabStrip.IconTabProvider { public void destroyItem(ViewGroup paramViewGroup, int paramInt, Object paramObject) { View localObject; if (paramInt == 0) { localObject = recentsWrap; } else { localObject = views.get(paramInt); } paramViewGroup.removeView(localObject); } public int getCount() { return views.size(); } public int getPageIconResId(int paramInt) { return icons[paramInt]; } public Object instantiateItem(ViewGroup paramViewGroup, int paramInt) { View localObject; if (paramInt == 0) { localObject = recentsWrap; } else { localObject = views.get(paramInt); } paramViewGroup.addView(localObject); return localObject; } public boolean isViewFromObject(View paramView, Object paramObject) { return paramView == paramObject; } @Override public void unregisterDataSetObserver(DataSetObserver observer) { if (observer != null) { super.unregisterDataSetObserver(observer); } } } public static abstract interface Listener { public abstract void onBackspace(); public abstract void onEmojiSelected(String paramString); } }
gpl-2.0
lockland/MonsterCar
src/model/entidade/Manutencao.java
1259
package model.entidade; /** * @author Lockland */ public class Manutencao { private int id; private String descricao; private String codComprovante; private String data; public Manutencao(int id, String descricao, String codComprovante, String data) { this.id = id; this.descricao = descricao; this.codComprovante = codComprovante; this.data = data; } public Manutencao(String descricao, String codComprovante, String data) { this.id = 0; this.descricao = descricao; this.codComprovante = codComprovante; this.data = data; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getData() { return data; } public String getDescricao() { return descricao; } public String getCodComprovante() { return codComprovante; } @Override public String toString() { return this.getClass().getSimpleName() + "{" + "id=" + id + ", descricao=" + descricao + ", codComprovante=" + codComprovante + ", data=" + data + '}'; } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/src/share/classes/javax/swing/plaf/metal/MetalTitlePane.java
33403
/* * Copyright 2000-2006 Sun Microsystems, Inc. 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package javax.swing.plaf.metal; import sun.swing.SwingUtilities2; import sun.awt.SunToolkit; import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.InternalFrameEvent; import javax.swing.plaf.*; import javax.swing.plaf.basic.*; import java.util.Locale; import javax.accessibility.*; /** * Class that manages a JLF awt.Window-descendant class's title bar. * <p> * This class assumes it will be created with a particular window * decoration style, and that if the style changes, a new one will * be created. * * @author Terry Kellerman * @since 1.4 */ class MetalTitlePane extends JComponent { private static final Border handyEmptyBorder = new EmptyBorder(0,0,0,0); private static final int IMAGE_HEIGHT = 16; private static final int IMAGE_WIDTH = 16; /** * PropertyChangeListener added to the JRootPane. */ private PropertyChangeListener propertyChangeListener; /** * JMenuBar, typically renders the system menu items. */ private JMenuBar menuBar; /** * Action used to close the Window. */ private Action closeAction; /** * Action used to iconify the Frame. */ private Action iconifyAction; /** * Action to restore the Frame size. */ private Action restoreAction; /** * Action to restore the Frame size. */ private Action maximizeAction; /** * Button used to maximize or restore the Frame. */ private JButton toggleButton; /** * Button used to maximize or restore the Frame. */ private JButton iconifyButton; /** * Button used to maximize or restore the Frame. */ private JButton closeButton; /** * Icon used for toggleButton when window is normal size. */ private Icon maximizeIcon; /** * Icon used for toggleButton when window is maximized. */ private Icon minimizeIcon; /** * Image used for the system menu icon */ private Image systemIcon; /** * Listens for changes in the state of the Window listener to update * the state of the widgets. */ private WindowListener windowListener; /** * Window we're currently in. */ private Window window; /** * JRootPane rendering for. */ private JRootPane rootPane; /** * Room remaining in title for bumps. */ private int buttonsWidth; /** * Buffered Frame.state property. As state isn't bound, this is kept * to determine when to avoid updating widgets. */ private int state; /** * MetalRootPaneUI that created us. */ private MetalRootPaneUI rootPaneUI; // Colors private Color inactiveBackground = UIManager.getColor("inactiveCaption"); private Color inactiveForeground = UIManager.getColor("inactiveCaptionText"); private Color inactiveShadow = UIManager.getColor("inactiveCaptionBorder"); private Color activeBumpsHighlight = MetalLookAndFeel.getPrimaryControlHighlight(); private Color activeBumpsShadow = MetalLookAndFeel.getPrimaryControlDarkShadow(); private Color activeBackground = null; private Color activeForeground = null; private Color activeShadow = null; // Bumps private MetalBumps activeBumps = new MetalBumps( 0, 0, activeBumpsHighlight, activeBumpsShadow, MetalLookAndFeel.getPrimaryControl() ); private MetalBumps inactiveBumps = new MetalBumps( 0, 0, MetalLookAndFeel.getControlHighlight(), MetalLookAndFeel.getControlDarkShadow(), MetalLookAndFeel.getControl() ); public MetalTitlePane(JRootPane root, MetalRootPaneUI ui) { this.rootPane = root; rootPaneUI = ui; state = -1; installSubcomponents(); determineColors(); installDefaults(); setLayout(createLayout()); } /** * Uninstalls the necessary state. */ private void uninstall() { uninstallListeners(); window = null; removeAll(); } /** * Installs the necessary listeners. */ private void installListeners() { if (window != null) { windowListener = createWindowListener(); window.addWindowListener(windowListener); propertyChangeListener = createWindowPropertyChangeListener(); window.addPropertyChangeListener(propertyChangeListener); } } /** * Uninstalls the necessary listeners. */ private void uninstallListeners() { if (window != null) { window.removeWindowListener(windowListener); window.removePropertyChangeListener(propertyChangeListener); } } /** * Returns the <code>WindowListener</code> to add to the * <code>Window</code>. */ private WindowListener createWindowListener() { return new WindowHandler(); } /** * Returns the <code>PropertyChangeListener</code> to install on * the <code>Window</code>. */ private PropertyChangeListener createWindowPropertyChangeListener() { return new PropertyChangeHandler(); } /** * Returns the <code>JRootPane</code> this was created for. */ public JRootPane getRootPane() { return rootPane; } /** * Returns the decoration style of the <code>JRootPane</code>. */ private int getWindowDecorationStyle() { return getRootPane().getWindowDecorationStyle(); } public void addNotify() { super.addNotify(); uninstallListeners(); window = SwingUtilities.getWindowAncestor(this); if (window != null) { if (window instanceof Frame) { setState(((Frame)window).getExtendedState()); } else { setState(0); } setActive(window.isActive()); installListeners(); updateSystemIcon(); } } public void removeNotify() { super.removeNotify(); uninstallListeners(); window = null; } /** * Adds any sub-Components contained in the <code>MetalTitlePane</code>. */ private void installSubcomponents() { int decorationStyle = getWindowDecorationStyle(); if (decorationStyle == JRootPane.FRAME) { createActions(); menuBar = createMenuBar(); add(menuBar); createButtons(); add(iconifyButton); add(toggleButton); add(closeButton); } else if (decorationStyle == JRootPane.PLAIN_DIALOG || decorationStyle == JRootPane.INFORMATION_DIALOG || decorationStyle == JRootPane.ERROR_DIALOG || decorationStyle == JRootPane.COLOR_CHOOSER_DIALOG || decorationStyle == JRootPane.FILE_CHOOSER_DIALOG || decorationStyle == JRootPane.QUESTION_DIALOG || decorationStyle == JRootPane.WARNING_DIALOG) { createActions(); createButtons(); add(closeButton); } } /** * Determines the Colors to draw with. */ private void determineColors() { switch (getWindowDecorationStyle()) { case JRootPane.FRAME: activeBackground = UIManager.getColor("activeCaption"); activeForeground = UIManager.getColor("activeCaptionText"); activeShadow = UIManager.getColor("activeCaptionBorder"); break; case JRootPane.ERROR_DIALOG: activeBackground = UIManager.getColor( "OptionPane.errorDialog.titlePane.background"); activeForeground = UIManager.getColor( "OptionPane.errorDialog.titlePane.foreground"); activeShadow = UIManager.getColor( "OptionPane.errorDialog.titlePane.shadow"); break; case JRootPane.QUESTION_DIALOG: case JRootPane.COLOR_CHOOSER_DIALOG: case JRootPane.FILE_CHOOSER_DIALOG: activeBackground = UIManager.getColor( "OptionPane.questionDialog.titlePane.background"); activeForeground = UIManager.getColor( "OptionPane.questionDialog.titlePane.foreground"); activeShadow = UIManager.getColor( "OptionPane.questionDialog.titlePane.shadow"); break; case JRootPane.WARNING_DIALOG: activeBackground = UIManager.getColor( "OptionPane.warningDialog.titlePane.background"); activeForeground = UIManager.getColor( "OptionPane.warningDialog.titlePane.foreground"); activeShadow = UIManager.getColor( "OptionPane.warningDialog.titlePane.shadow"); break; case JRootPane.PLAIN_DIALOG: case JRootPane.INFORMATION_DIALOG: default: activeBackground = UIManager.getColor("activeCaption"); activeForeground = UIManager.getColor("activeCaptionText"); activeShadow = UIManager.getColor("activeCaptionBorder"); break; } activeBumps.setBumpColors(activeBumpsHighlight, activeBumpsShadow, activeBackground); } /** * Installs the fonts and necessary properties on the MetalTitlePane. */ private void installDefaults() { setFont(UIManager.getFont("InternalFrame.titleFont", getLocale())); } /** * Uninstalls any previously installed UI values. */ private void uninstallDefaults() { } /** * Returns the <code>JMenuBar</code> displaying the appropriate * system menu items. */ protected JMenuBar createMenuBar() { menuBar = new SystemMenuBar(); menuBar.setFocusable(false); menuBar.setBorderPainted(true); menuBar.add(createMenu()); return menuBar; } /** * Closes the Window. */ private void close() { Window window = getWindow(); if (window != null) { window.dispatchEvent(new WindowEvent( window, WindowEvent.WINDOW_CLOSING)); } } /** * Iconifies the Frame. */ private void iconify() { Frame frame = getFrame(); if (frame != null) { frame.setExtendedState(state | Frame.ICONIFIED); } } /** * Maximizes the Frame. */ private void maximize() { Frame frame = getFrame(); if (frame != null) { frame.setExtendedState(state | Frame.MAXIMIZED_BOTH); } } /** * Restores the Frame size. */ private void restore() { Frame frame = getFrame(); if (frame == null) { return; } if ((state & Frame.ICONIFIED) != 0) { frame.setExtendedState(state & ~Frame.ICONIFIED); } else { frame.setExtendedState(state & ~Frame.MAXIMIZED_BOTH); } } /** * Create the <code>Action</code>s that get associated with the * buttons and menu items. */ private void createActions() { closeAction = new CloseAction(); if (getWindowDecorationStyle() == JRootPane.FRAME) { iconifyAction = new IconifyAction(); restoreAction = new RestoreAction(); maximizeAction = new MaximizeAction(); } } /** * Returns the <code>JMenu</code> displaying the appropriate menu items * for manipulating the Frame. */ private JMenu createMenu() { JMenu menu = new JMenu(""); if (getWindowDecorationStyle() == JRootPane.FRAME) { addMenuItems(menu); } return menu; } /** * Adds the necessary <code>JMenuItem</code>s to the passed in menu. */ private void addMenuItems(JMenu menu) { Locale locale = getRootPane().getLocale(); JMenuItem mi = menu.add(restoreAction); int mnemonic = MetalUtils.getInt("MetalTitlePane.restoreMnemonic", -1); if (mnemonic != -1) { mi.setMnemonic(mnemonic); } mi = menu.add(iconifyAction); mnemonic = MetalUtils.getInt("MetalTitlePane.iconifyMnemonic", -1); if (mnemonic != -1) { mi.setMnemonic(mnemonic); } if (Toolkit.getDefaultToolkit().isFrameStateSupported( Frame.MAXIMIZED_BOTH)) { mi = menu.add(maximizeAction); mnemonic = MetalUtils.getInt("MetalTitlePane.maximizeMnemonic", -1); if (mnemonic != -1) { mi.setMnemonic(mnemonic); } } menu.add(new JSeparator()); mi = menu.add(closeAction); mnemonic = MetalUtils.getInt("MetalTitlePane.closeMnemonic", -1); if (mnemonic != -1) { mi.setMnemonic(mnemonic); } } /** * Returns a <code>JButton</code> appropriate for placement on the * TitlePane. */ private JButton createTitleButton() { JButton button = new JButton(); button.setFocusPainted(false); button.setFocusable(false); button.setOpaque(true); return button; } /** * Creates the Buttons that will be placed on the TitlePane. */ private void createButtons() { closeButton = createTitleButton(); closeButton.setAction(closeAction); closeButton.setText(null); closeButton.putClientProperty("paintActive", Boolean.TRUE); closeButton.setBorder(handyEmptyBorder); closeButton.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, "Close"); closeButton.setIcon(UIManager.getIcon("InternalFrame.closeIcon")); if (getWindowDecorationStyle() == JRootPane.FRAME) { maximizeIcon = UIManager.getIcon("InternalFrame.maximizeIcon"); minimizeIcon = UIManager.getIcon("InternalFrame.minimizeIcon"); iconifyButton = createTitleButton(); iconifyButton.setAction(iconifyAction); iconifyButton.setText(null); iconifyButton.putClientProperty("paintActive", Boolean.TRUE); iconifyButton.setBorder(handyEmptyBorder); iconifyButton.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, "Iconify"); iconifyButton.setIcon(UIManager.getIcon("InternalFrame.iconifyIcon")); toggleButton = createTitleButton(); toggleButton.setAction(restoreAction); toggleButton.putClientProperty("paintActive", Boolean.TRUE); toggleButton.setBorder(handyEmptyBorder); toggleButton.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, "Maximize"); toggleButton.setIcon(maximizeIcon); } } /** * Returns the <code>LayoutManager</code> that should be installed on * the <code>MetalTitlePane</code>. */ private LayoutManager createLayout() { return new TitlePaneLayout(); } /** * Updates state dependant upon the Window's active state. */ private void setActive(boolean isActive) { Boolean activeB = isActive ? Boolean.TRUE : Boolean.FALSE; closeButton.putClientProperty("paintActive", activeB); if (getWindowDecorationStyle() == JRootPane.FRAME) { iconifyButton.putClientProperty("paintActive", activeB); toggleButton.putClientProperty("paintActive", activeB); } // Repaint the whole thing as the Borders that are used have // different colors for active vs inactive getRootPane().repaint(); } /** * Sets the state of the Window. */ private void setState(int state) { setState(state, false); } /** * Sets the state of the window. If <code>updateRegardless</code> is * true and the state has not changed, this will update anyway. */ private void setState(int state, boolean updateRegardless) { Window w = getWindow(); if (w != null && getWindowDecorationStyle() == JRootPane.FRAME) { if (this.state == state && !updateRegardless) { return; } Frame frame = getFrame(); if (frame != null) { JRootPane rootPane = getRootPane(); if (((state & Frame.MAXIMIZED_BOTH) != 0) && (rootPane.getBorder() == null || (rootPane.getBorder() instanceof UIResource)) && frame.isShowing()) { rootPane.setBorder(null); } else if ((state & Frame.MAXIMIZED_BOTH) == 0) { // This is a croak, if state becomes bound, this can // be nuked. rootPaneUI.installBorder(rootPane); } if (frame.isResizable()) { if ((state & Frame.MAXIMIZED_BOTH) != 0) { updateToggleButton(restoreAction, minimizeIcon); maximizeAction.setEnabled(false); restoreAction.setEnabled(true); } else { updateToggleButton(maximizeAction, maximizeIcon); maximizeAction.setEnabled(true); restoreAction.setEnabled(false); } if (toggleButton.getParent() == null || iconifyButton.getParent() == null) { add(toggleButton); add(iconifyButton); revalidate(); repaint(); } toggleButton.setText(null); } else { maximizeAction.setEnabled(false); restoreAction.setEnabled(false); if (toggleButton.getParent() != null) { remove(toggleButton); revalidate(); repaint(); } } } else { // Not contained in a Frame maximizeAction.setEnabled(false); restoreAction.setEnabled(false); iconifyAction.setEnabled(false); remove(toggleButton); remove(iconifyButton); revalidate(); repaint(); } closeAction.setEnabled(true); this.state = state; } } /** * Updates the toggle button to contain the Icon <code>icon</code>, and * Action <code>action</code>. */ private void updateToggleButton(Action action, Icon icon) { toggleButton.setAction(action); toggleButton.setIcon(icon); toggleButton.setText(null); } /** * Returns the Frame rendering in. This will return null if the * <code>JRootPane</code> is not contained in a <code>Frame</code>. */ private Frame getFrame() { Window window = getWindow(); if (window instanceof Frame) { return (Frame)window; } return null; } /** * Returns the <code>Window</code> the <code>JRootPane</code> is * contained in. This will return null if there is no parent ancestor * of the <code>JRootPane</code>. */ private Window getWindow() { return window; } /** * Returns the String to display as the title. */ private String getTitle() { Window w = getWindow(); if (w instanceof Frame) { return ((Frame)w).getTitle(); } else if (w instanceof Dialog) { return ((Dialog)w).getTitle(); } return null; } /** * Renders the TitlePane. */ public void paintComponent(Graphics g) { // As state isn't bound, we need a convenience place to check // if it has changed. Changing the state typically changes the if (getFrame() != null) { setState(getFrame().getExtendedState()); } JRootPane rootPane = getRootPane(); Window window = getWindow(); boolean leftToRight = (window == null) ? rootPane.getComponentOrientation().isLeftToRight() : window.getComponentOrientation().isLeftToRight(); boolean isSelected = (window == null) ? true : window.isActive(); int width = getWidth(); int height = getHeight(); Color background; Color foreground; Color darkShadow; MetalBumps bumps; if (isSelected) { background = activeBackground; foreground = activeForeground; darkShadow = activeShadow; bumps = activeBumps; } else { background = inactiveBackground; foreground = inactiveForeground; darkShadow = inactiveShadow; bumps = inactiveBumps; } g.setColor(background); g.fillRect(0, 0, width, height); g.setColor( darkShadow ); g.drawLine ( 0, height - 1, width, height -1); g.drawLine ( 0, 0, 0 ,0); g.drawLine ( width - 1, 0 , width -1, 0); int xOffset = leftToRight ? 5 : width - 5; if (getWindowDecorationStyle() == JRootPane.FRAME) { xOffset += leftToRight ? IMAGE_WIDTH + 5 : - IMAGE_WIDTH - 5; } String theTitle = getTitle(); if (theTitle != null) { FontMetrics fm = SwingUtilities2.getFontMetrics(rootPane, g); g.setColor(foreground); int yOffset = ( (height - fm.getHeight() ) / 2 ) + fm.getAscent(); Rectangle rect = new Rectangle(0, 0, 0, 0); if (iconifyButton != null && iconifyButton.getParent() != null) { rect = iconifyButton.getBounds(); } int titleW; if( leftToRight ) { if (rect.x == 0) { rect.x = window.getWidth() - window.getInsets().right-2; } titleW = rect.x - xOffset - 4; theTitle = SwingUtilities2.clipStringIfNecessary( rootPane, fm, theTitle, titleW); } else { titleW = xOffset - rect.x - rect.width - 4; theTitle = SwingUtilities2.clipStringIfNecessary( rootPane, fm, theTitle, titleW); xOffset -= SwingUtilities2.stringWidth(rootPane, fm, theTitle); } int titleLength = SwingUtilities2.stringWidth(rootPane, fm, theTitle); SwingUtilities2.drawString(rootPane, g, theTitle, xOffset, yOffset ); xOffset += leftToRight ? titleLength + 5 : -5; } int bumpXOffset; int bumpLength; if( leftToRight ) { bumpLength = width - buttonsWidth - xOffset - 5; bumpXOffset = xOffset; } else { bumpLength = xOffset - buttonsWidth - 5; bumpXOffset = buttonsWidth + 5; } int bumpYOffset = 3; int bumpHeight = getHeight() - (2 * bumpYOffset); bumps.setBumpArea( bumpLength, bumpHeight ); bumps.paintIcon(this, g, bumpXOffset, bumpYOffset); } /** * Actions used to <code>close</code> the <code>Window</code>. */ private class CloseAction extends AbstractAction { public CloseAction() { super(UIManager.getString("MetalTitlePane.closeTitle", getLocale())); } public void actionPerformed(ActionEvent e) { close(); } } /** * Actions used to <code>iconfiy</code> the <code>Frame</code>. */ private class IconifyAction extends AbstractAction { public IconifyAction() { super(UIManager.getString("MetalTitlePane.iconifyTitle", getLocale())); } public void actionPerformed(ActionEvent e) { iconify(); } } /** * Actions used to <code>restore</code> the <code>Frame</code>. */ private class RestoreAction extends AbstractAction { public RestoreAction() { super(UIManager.getString ("MetalTitlePane.restoreTitle", getLocale())); } public void actionPerformed(ActionEvent e) { restore(); } } /** * Actions used to <code>restore</code> the <code>Frame</code>. */ private class MaximizeAction extends AbstractAction { public MaximizeAction() { super(UIManager.getString("MetalTitlePane.maximizeTitle", getLocale())); } public void actionPerformed(ActionEvent e) { maximize(); } } /** * Class responsible for drawing the system menu. Looks up the * image to draw from the Frame associated with the * <code>JRootPane</code>. */ private class SystemMenuBar extends JMenuBar { public void paint(Graphics g) { if (isOpaque()) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); } if (systemIcon != null) { g.drawImage(systemIcon, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null); } else { Icon icon = UIManager.getIcon("InternalFrame.icon"); if (icon != null) { icon.paintIcon(this, g, 0, 0); } } } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); return new Dimension(Math.max(IMAGE_WIDTH, size.width), Math.max(size.height, IMAGE_HEIGHT)); } } private class TitlePaneLayout implements LayoutManager { public void addLayoutComponent(String name, Component c) {} public void removeLayoutComponent(Component c) {} public Dimension preferredLayoutSize(Container c) { int height = computeHeight(); return new Dimension(height, height); } public Dimension minimumLayoutSize(Container c) { return preferredLayoutSize(c); } private int computeHeight() { FontMetrics fm = rootPane.getFontMetrics(getFont()); int fontHeight = fm.getHeight(); fontHeight += 7; int iconHeight = 0; if (getWindowDecorationStyle() == JRootPane.FRAME) { iconHeight = IMAGE_HEIGHT; } int finalHeight = Math.max( fontHeight, iconHeight ); return finalHeight; } public void layoutContainer(Container c) { boolean leftToRight = (window == null) ? getRootPane().getComponentOrientation().isLeftToRight() : window.getComponentOrientation().isLeftToRight(); int w = getWidth(); int x; int y = 3; int spacing; int buttonHeight; int buttonWidth; if (closeButton != null && closeButton.getIcon() != null) { buttonHeight = closeButton.getIcon().getIconHeight(); buttonWidth = closeButton.getIcon().getIconWidth(); } else { buttonHeight = IMAGE_HEIGHT; buttonWidth = IMAGE_WIDTH; } // assumes all buttons have the same dimensions // these dimensions include the borders x = leftToRight ? w : 0; spacing = 5; x = leftToRight ? spacing : w - buttonWidth - spacing; if (menuBar != null) { menuBar.setBounds(x, y, buttonWidth, buttonHeight); } x = leftToRight ? w : 0; spacing = 4; x += leftToRight ? -spacing -buttonWidth : spacing; if (closeButton != null) { closeButton.setBounds(x, y, buttonWidth, buttonHeight); } if( !leftToRight ) x += buttonWidth; if (getWindowDecorationStyle() == JRootPane.FRAME) { if (Toolkit.getDefaultToolkit().isFrameStateSupported( Frame.MAXIMIZED_BOTH)) { if (toggleButton.getParent() != null) { spacing = 10; x += leftToRight ? -spacing -buttonWidth : spacing; toggleButton.setBounds(x, y, buttonWidth, buttonHeight); if (!leftToRight) { x += buttonWidth; } } } if (iconifyButton != null && iconifyButton.getParent() != null) { spacing = 2; x += leftToRight ? -spacing -buttonWidth : spacing; iconifyButton.setBounds(x, y, buttonWidth, buttonHeight); if (!leftToRight) { x += buttonWidth; } } } buttonsWidth = leftToRight ? w - x : x; } } /** * PropertyChangeListener installed on the Window. Updates the necessary * state as the state of the Window changes. */ private class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent pce) { String name = pce.getPropertyName(); // Frame.state isn't currently bound. if ("resizable".equals(name) || "state".equals(name)) { Frame frame = getFrame(); if (frame != null) { setState(frame.getExtendedState(), true); } if ("resizable".equals(name)) { getRootPane().repaint(); } } else if ("title".equals(name)) { repaint(); } else if ("componentOrientation" == name) { revalidate(); repaint(); } else if ("iconImage" == name) { updateSystemIcon(); revalidate(); repaint(); } } } /** * Update the image used for the system icon */ private void updateSystemIcon() { Window window = getWindow(); if (window == null) { systemIcon = null; return; } java.util.List<Image> icons = window.getIconImages(); assert icons != null; if (icons.size() == 0) { systemIcon = null; } else if (icons.size() == 1) { systemIcon = icons.get(0); } else { systemIcon = SunToolkit.getScaledIconImage(icons, IMAGE_WIDTH, IMAGE_HEIGHT); } } /** * WindowListener installed on the Window, updates the state as necessary. */ private class WindowHandler extends WindowAdapter { public void windowActivated(WindowEvent ev) { setActive(true); } public void windowDeactivated(WindowEvent ev) { setActive(false); } } }
gpl-2.0
iprem/Hackerrank
CountingSort2/src/CountingSort2.java
431
import java.util.Scanner; public class CountingSort2 { private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[100]; for(int i= 0; i< n;i ++){ a[sc.nextInt()]++; } for(int i =0;i < 100; i++){ for(int j = 0; j<a[i]; j++) System.out.print(i+ " "); } } }
gpl-2.0
joshmoore/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/agents/fsimporter/util/ThumbnailLabel.java
6056
/* * org.openmicroscopy.shoola.agents.fsimporter.util.ThumbnailLabel * *------------------------------------------------------------------------------ * Copyright (C) 2006-2011 University of Dundee. All rights reserved. * * * 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 org.openmicroscopy.shoola.agents.fsimporter.util; //Java imports import java.awt.Color; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.border.Border; //Third-party libraries //Application-internal dependencies import org.openmicroscopy.shoola.agents.events.iviewer.ViewImage; import org.openmicroscopy.shoola.agents.events.iviewer.ViewImageObject; import org.openmicroscopy.shoola.agents.fsimporter.IconManager; import org.openmicroscopy.shoola.agents.fsimporter.ImporterAgent; import org.openmicroscopy.shoola.agents.util.ui.RollOverThumbnailManager; import org.openmicroscopy.shoola.env.data.model.ThumbnailData; import org.openmicroscopy.shoola.env.event.EventBus; import org.openmicroscopy.shoola.util.image.geom.Factory; import pojos.ImageData; import pojos.PlateData; /** * Component displaying the thumbnail. * * @author Jean-Marie Burel &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a> * @author Donald MacDonald &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a> * @version 3.0 * <small> * (<b>Internal version:</b> $Revision: $Date: $) * </small> * @since 3.0-Beta4 */ class ThumbnailLabel extends JLabel { /** Bound property indicating to browse the specified plate. */ static final String BROWSE_PLATE_PROPERTY = "browsePlate"; /** The border of the thumbnail label. */ private static final Border LABEL_BORDER = BorderFactory.createLineBorder(Color.black, 1); /** The text displayed in the tool tip when the image has been imported. */ static final String IMAGE_LABEL_TOOLTIP = "Click to view the image."; /** The text displayed in the tool tip when the plate has been imported. */ static final String PLATE_LABEL_TOOLTIP = "Double-Click to browse the plate."; /** The thumbnail or the image to host. */ private Object data; /** Posts an event to view the object. */ private void view() { EventBus bus = ImporterAgent.getRegistry().getEventBus(); if (data instanceof ThumbnailData) { ThumbnailData thumbnail = (ThumbnailData) data; if (thumbnail.getImage() != null) bus.post(new ViewImage(new ViewImageObject( thumbnail.getImage()), null)); } else if (data instanceof ImageData) { ImageData image = (ImageData) data; bus.post(new ViewImage(new ViewImageObject(image), null)); } else if (data instanceof PlateData) { firePropertyChange(BROWSE_PLATE_PROPERTY, null, data); } } /** Rolls over the node. */ private void rollOver() { if (data instanceof ThumbnailData) { ThumbnailData thumbnail = (ThumbnailData) data; RollOverThumbnailManager.rollOverDisplay(thumbnail.getThumbnail(), getBounds(), getLocationOnScreen(), toString()); } } /** * Sets the thumbnail to view. * * @param data The value to set. */ private void setThumbnail(ThumbnailData data) { if (data == null) return; BufferedImage img = Factory.magnifyImage(0.25, data.getThumbnail()); ImageIcon icon = null; if (img != null) icon = new ImageIcon(img); this.data = data; setToolTipText(IMAGE_LABEL_TOOLTIP); setBorder(LABEL_BORDER); if (icon != null) { setIcon(icon); } addMouseListener(new MouseAdapter() { /** * Views the image. * @see MouseListener#mousePressed(MouseEvent) */ public void mousePressed(MouseEvent e) { if (e.getClickCount() == 1) view(); } /** * Removes the zooming window from the display. * @see MouseListener#mouseExited(MouseEvent) */ public void mouseExited(MouseEvent e) { RollOverThumbnailManager.stopOverDisplay(); } /** * Zooms the thumbnail. * @see MouseListener#mouseEntered(MouseEvent) */ public void mouseEntered(MouseEvent e) { rollOver(); } }); } /** Creates a default new instance. */ ThumbnailLabel() {} /** * Creates a new instance. * * @param icon The icon to display. */ ThumbnailLabel(Icon icon) { super(icon); } /** * Sets the object that has been imported. * * @param data The imported image. */ void setData(Object data) { if (data == null) return; this.data = data; if (data instanceof ImageData) { setToolTipText(IMAGE_LABEL_TOOLTIP); } else if (data instanceof PlateData) { setToolTipText(PLATE_LABEL_TOOLTIP); IconManager icons = IconManager.getInstance(); setIcon(icons.getIcon(IconManager.PLATE)); } else if (data instanceof ThumbnailData) { setThumbnail((ThumbnailData) data); return; } addMouseListener(new MouseAdapter() { /** * Views the image. * @see MouseListener#mousePressed(MouseEvent) */ public void mousePressed(MouseEvent e) { if (e.getClickCount() == 1) view(); } }); } }
gpl-2.0
vishwaAbhinav/OpenNMS
opennms-webapp/target/generated-sources/castor/org/opennms/netmgt/config/attrsummary/descriptors/SummaryDescriptor.java
6038
/* * This class was automatically generated with * <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML * Schema. * $Id$ */ package org.opennms.netmgt.config.attrsummary.descriptors; //---------------------------------/ //- Imported classes and packages -/ //---------------------------------/ import org.opennms.netmgt.config.attrsummary.Summary; /** * Class SummaryDescriptor. * * @version $Revision$ $Date$ */ @SuppressWarnings("all") public class SummaryDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl { //--------------------------/ //- Class/Member Variables -/ //--------------------------/ /** * Field _elementDefinition. */ private boolean _elementDefinition; /** * Field _nsPrefix. */ private java.lang.String _nsPrefix; /** * Field _nsURI. */ private java.lang.String _nsURI; /** * Field _xmlName. */ private java.lang.String _xmlName; /** * Field _identity. */ private org.exolab.castor.xml.XMLFieldDescriptor _identity; //----------------/ //- Constructors -/ //----------------/ public SummaryDescriptor() { super(); _nsURI = "http://xmlns.opennms.org/xsd/attr-summary"; _xmlName = "summary"; _elementDefinition = true; //-- set grouping compositor setCompositorAsSequence(); org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null; org.exolab.castor.mapping.FieldHandler handler = null; org.exolab.castor.xml.FieldValidator fieldValidator = null; //-- initialize attribute descriptors //-- initialize element descriptors //-- _resourceList desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.attrsummary.Resource.class, "_resourceList", "resource", org.exolab.castor.xml.NodeType.Element); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { Summary target = (Summary) object; return target.getResource(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { Summary target = (Summary) object; target.addResource( (org.opennms.netmgt.config.attrsummary.Resource) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException { try { Summary target = (Summary) object; target.removeAllResource(); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return new org.opennms.netmgt.config.attrsummary.Resource(); } }; desc.setSchemaType("org.opennms.netmgt.config.attrsummary.Resource"); desc.setHandler(handler); desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/attr-summary"); desc.setMultivalued(true); addFieldDescriptor(desc); addSequenceElement(desc); //-- validation code for: _resourceList fieldValidator = new org.exolab.castor.xml.FieldValidator(); fieldValidator.setMinOccurs(0); { //-- local scope } desc.setValidator(fieldValidator); } //-----------/ //- Methods -/ //-----------/ /** * Method getAccessMode. * * @return the access mode specified for this class. */ @Override() public org.exolab.castor.mapping.AccessMode getAccessMode( ) { return null; } /** * Method getIdentity. * * @return the identity field, null if this class has no * identity. */ @Override() public org.exolab.castor.mapping.FieldDescriptor getIdentity( ) { return _identity; } /** * Method getJavaClass. * * @return the Java class represented by this descriptor. */ @Override() public java.lang.Class<?> getJavaClass( ) { return org.opennms.netmgt.config.attrsummary.Summary.class; } /** * Method getNameSpacePrefix. * * @return the namespace prefix to use when marshaling as XML. */ @Override() public java.lang.String getNameSpacePrefix( ) { return _nsPrefix; } /** * Method getNameSpaceURI. * * @return the namespace URI used when marshaling and * unmarshaling as XML. */ @Override() public java.lang.String getNameSpaceURI( ) { return _nsURI; } /** * Method getValidator. * * @return a specific validator for the class described by this * ClassDescriptor. */ @Override() public org.exolab.castor.xml.TypeValidator getValidator( ) { return this; } /** * Method getXMLName. * * @return the XML Name for the Class being described. */ @Override() public java.lang.String getXMLName( ) { return _xmlName; } /** * Method isElementDefinition. * * @return true if XML schema definition of this Class is that * of a global * element or element with anonymous type definition. */ public boolean isElementDefinition( ) { return _elementDefinition; } }
gpl-2.0
sfaci/java-hibernate
HibernateRelacionNaN/src/org/sfsoft/hibernate/gui/JEnemigo.java
5100
package org.sfsoft.hibernate.gui; import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JLabel; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.JComboBox; import org.sfsoft.hibernate.Arma; import javax.swing.JList; import javax.swing.JScrollPane; /** * Dialogo con el que el usuario introduce información sobre un Enemigo * para insertar o modificar * @author Santiago Faci * @version curso 2014-2015 */ public class JEnemigo extends JDialog { private final JPanel contentPanel = new JPanel(); private JTextField txtNombre; private JTextField txtVida; private JTextField txtPuntos; private JLabel lblNewLabel; private JLabel lblNewLabel_1; private JLabel lblNewLabel_2; private JLabel lblNewLabel_3; private String nombre; private int vida; private int puntos; private List<Arma> armas; private JScrollPane scrollPane; private JListArma listaArmas; /** * Getters y setters para obtener y fijar información en la ventana * @return */ public String getNombre() { return nombre; } public void setNombre(String nombre) { this.txtNombre.setText(nombre); } public int getVida() { return vida; } public void setVida(int vida) { this.txtVida.setText(String.valueOf(vida)); } public int getPuntos() { return puntos; } public void setPuntos(int puntos) { this.txtPuntos.setText(String.valueOf(puntos)); } public List<Arma> getArmas() { return armas; } public void setArmas(List<Arma> armas) { listaArmas.setArmasSeleccionadas(armas); } /** * Se invoca cuando el usuario ha pulsado en Aceptar. Recoge y valida la información de las cajas de texto * y cierra la ventana */ private void aceptar() { if (txtNombre.getText().equals("")) return; try { if (txtVida.getText().equals("")) txtVida.setText("0"); if (txtPuntos.getText().equals("")) txtPuntos.setText("0"); nombre = txtNombre.getText(); vida = Integer.parseInt(txtVida.getText()); puntos = Integer.parseInt(txtPuntos.getText()); armas = listaArmas.getArmasSeleccionadas(); setVisible(false); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null, "Comprueba que los datos son correctos", "Enemigo", JOptionPane.ERROR_MESSAGE); } } /** * Invocado cuando el usuario cancela. Simplemente cierra la ventana */ private void cancelar() { setVisible(false); } private void inicializar() { listaArmas.listar(); } /** * Constructor. Crea la ventana */ public JEnemigo() { setModal(true); setTitle("Enemigo"); setBounds(100, 100, 284, 355); setLocationRelativeTo(null); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); txtNombre = new JTextField(); txtNombre.setBounds(100, 22, 138, 20); contentPanel.add(txtNombre); txtNombre.setColumns(10); txtVida = new JTextField(); txtVida.setBounds(100, 64, 60, 20); contentPanel.add(txtVida); txtVida.setColumns(10); txtPuntos = new JTextField(); txtPuntos.setBounds(100, 106, 60, 20); contentPanel.add(txtPuntos); txtPuntos.setColumns(10); lblNewLabel = new JLabel("Nombre"); lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel.setBounds(10, 25, 46, 14); contentPanel.add(lblNewLabel); lblNewLabel_1 = new JLabel("Vida"); lblNewLabel_1.setBounds(10, 67, 46, 14); contentPanel.add(lblNewLabel_1); lblNewLabel_2 = new JLabel("Puntos"); lblNewLabel_2.setBounds(10, 109, 46, 14); contentPanel.add(lblNewLabel_2); lblNewLabel_3 = new JLabel("Arma"); lblNewLabel_3.setBounds(10, 151, 46, 14); contentPanel.add(lblNewLabel_3); scrollPane = new JScrollPane(); scrollPane.setBounds(104, 151, 156, 125); contentPanel.add(scrollPane); listaArmas = new JListArma(); scrollPane.setViewportView(listaArmas); inicializar(); { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { aceptar(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cancelar(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } } }
gpl-2.0
glasnosh/Ithaca
maquina_1_verificadora/analizar_espejo.java
3843
/* * "analizar_espejo.java" * Crea una ventana de diálogo donde se muestra la imagen especular de la malla y se la analiza * * * Copyright (C) 2005, 2006 Jose Manuel Martínez García <glasnosh@gmail.com> * * This program is "Open Source" software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (explicitly version 2 * of the License). */ import java.lang.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /* * La estructura de componentes es: * * ________________________________ * | ____________________________ | * | | | | * | | Imagen "espejo " | | * | | JPanel | | * | | | | * | | | | * | |__________________________| | * | ___________________________| | * | | JTextField - Formula | | * | |__________________________| | * | ____________________________ | * | | | | * | | JTextArea explicacion | | * | | del mundo | | * | |__________________________| | * | _________________ | * | |JButton cerrar | | * |______________________________| * * */ class analizar_espejo extends JDialog{ JTextField campo_texto_formula; JTextArea area_texto_explicacion; JButton boton_cerrar; String formula; malla mimalla; public analizar_espejo(JFrame f, String formula, malla mimalla){//constructor super(f,"Modelo Espejo",true); this.formula = formula; malla malla_espejo = (new intercambiador_malla()).espejo(mimalla); //le damos la vuelta a la malla (espejo) tablero_espejo te1 = new tablero_espejo(malla_espejo); //dibujo del tablero espejo (es un jpanel) campo_texto_formula = new JTextField(20); campo_texto_formula.setText(formula); campo_texto_formula.setMargin(new Insets(10,10,10,10)); campo_texto_formula.setEditable(false); campo_texto_formula.setBackground(Color.white); campo_texto_formula.setForeground(Color.black); area_texto_explicacion = new JTextArea(" \nEste es un mundo espejo del original. \nLa malla es una imagen especular donde en las \n fórmulas han cambiado los valores de verdad \n en relación a las posiciones \"izquierda\" y \"derecha\"."); area_texto_explicacion.setEditable(false); boton_cerrar = new JButton("Cerrar"); JPanel panel_boton_cerrar = new JPanel(new BorderLayout()); //para que este a la derecha anidamos dos paneles panel_boton_cerrar.add(BorderLayout.EAST, boton_cerrar); JPanel panel_abajo = new JPanel(new BorderLayout()); panel_abajo.add(BorderLayout.NORTH,campo_texto_formula); panel_abajo.add(BorderLayout.SOUTH,panel_boton_cerrar); panel_abajo.add(BorderLayout.CENTER,area_texto_explicacion); JPanel panel_ppal = new JPanel(new GridLayout(2,1)); panel_ppal.add(te1); panel_ppal.add(panel_abajo); hilo_analizador hilo_x = new hilo_analizador(malla_espejo,campo_texto_formula,1); //analisis hilo_x.run(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ setVisible(false); }}); boton_cerrar.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e4) { setVisible(false); } }); getContentPane().add(panel_ppal); setSize(470,400); setLocationRelativeTo(null); setResizable(false); setVisible(true); malla_espejo = (new intercambiador_malla()).espejo(malla_espejo); //me he hecho un pequeño lio con el paso de variables. Esto se hace para que la malla vuelva a estar en su sitio, sino queda del reves en el original al pasar los parametros por referencia }//constructor }//class
gpl-2.0
Songbird0/TheBareMinimum
src/fr/songbird/survivalDevKit/Corrector.java
6229
package fr.songbird.survivalDevKit; import java.io.*; import net.wytrem.logging.*; /** * I'm happy to present you my primitive Corrector ! * He can to correct words that your file contains ! (he's not case sensitive currently) * @author songbird * @version 0.4_2-ALPHA * */ public class Corrector { //###### PRIVATE VARIABLES ###### private final static BasicLogger logger = LoggerFactory.getLogger(Corrector.class); private char commonCharacterWOTF = 0; private char commonCharacterIKB = 0; private File orthographyFile = null; private String pertinentWord = null; private String fileDirectory = null; private CheckEntry checkWOTF = new CheckEntry(); private CheckEntry checkIKB = new CheckEntry(); private String inputKeyBoard = null; private int dominantOccurrenceLetterWOTF = 0; private int dominantOccurrenceLetterIKB = 0; private boolean stopResearch = false; //###### PUBLIC VARIABLES ###### //###### CONSTRUCTOR ###### public Corrector(String fileName, String[] directoriesName){ File directoriesPath = new File(fileDirectory = Downloader.buildOnlyPath(new String(System.getProperty("user.home")+File.separator), directoriesName)); directoriesPath.mkdirs(); orthographyFile = new File(fileDirectory+fileName); } //###### PRIVATE METHODS ###### private void setDominantOccurrenceLetterWOTF(int DOLW){ this.dominantOccurrenceLetterWOTF = DOLW; } private void setDominantOccurrenceLetterIKB(int DOLI){ this.dominantOccurrenceLetterIKB = DOLI; } private void searchCoherentSetKeyValue(char[] wordOfTheFile, char[] inputKeyBoard){ //Cette methode renverra une chaine de caractere (le mot suggere) this.pertinentWord = new String(wordOfTheFile); this.inputKeyBoard = new String(inputKeyBoard); int dominantOccurrenceLetterWOTF = checkWOTF.getOccurrenceDominantLetter(pertinentWord.toCharArray()); setDominantOccurrenceLetterWOTF(dominantOccurrenceLetterWOTF); int dominantOccurrenceLetterIKB = checkIKB.getOccurrenceDominantLetter(this.inputKeyBoard.toCharArray()); setDominantOccurrenceLetterIKB(dominantOccurrenceLetterIKB); if(!areIdentical(pertinentWord, this.inputKeyBoard)){ if(checkWOTF.capableToBeSuggested(wordOfTheFile, inputKeyBoard) && this.dominantOccurrenceLetterWOTF == this.dominantOccurrenceLetterIKB){ //System.out.println("Capable to be suggested"); if(identicalDominantLetter(wordOfTheFile, inputKeyBoard, this.dominantOccurrenceLetterWOTF, this.dominantOccurrenceLetterIKB)){ System.out.println("Vous avez saisi le mot '"+this.inputKeyBoard+"' mais il ne semble pas correct.\nVous vouliez dire '"+this.pertinentWord+"' ?"); stopResearch = true; } } } else{ System.out.println("Rien a suggerer, les deux mots sont identiques."); stopResearch = true; } } /** * On cherche si le nombre d'occurrences identiques vaut aussi pour la lettre, les deux mots peuvent avoir autant d'occurrences, mais pas la meme lettre * @param WOTF * @param IKB * @param dominantOccurrenceLetterWOTF * @param dominantOccurrenceLetterIKB * @param instanceWOTF * @param instanceIKB * @return */ private boolean identicalDominantLetter(char[] WOTF, char[] IKB, int dominantOccurrenceLetterWOTF, int dominantOccurrenceLetterIKB){ for(Character caract : WOTF){ if(checkWOTF.getCharacterAsciiSetKey(caract).get() == dominantOccurrenceLetterWOTF){ commonCharacterWOTF = caract; //System.out.println("[WOTF]: "+caract+" est la lettre dominante."); } else{ commonCharacterWOTF = 0; } } for(Character caract : IKB){ if(checkIKB.getCharacterAsciiSetKey(caract).get() == dominantOccurrenceLetterIKB){ //System.out.println("[IKB]: "+caract+" est la lettre dominante."); commonCharacterIKB = caract; } else{ commonCharacterIKB = 0; } } if((commonCharacterWOTF != 0 && commonCharacterIKB != 0) && commonCharacterWOTF == commonCharacterIKB){ return true; } return false; } private boolean areIdentical(String WOTF, String IKB){ return WOTF.equals(IKB); } //###### PUBLIC METHODS ###### public void readOrthographyFile(String word){ BufferedReader buff = null; if(orthographyFile.exists()){ try{ buff = new BufferedReader(new InputStreamReader(new FileInputStream(orthographyFile))); while((pertinentWord = buff.readLine()) != null && stopResearch == false){ searchCoherentSetKeyValue(pertinentWord.toCharArray(), word.toCharArray()); //System.out.println("tracker rearOrthographyFile"); checkWOTF.getCurrentInstanceCharacterAsciiSet().clear(); checkWOTF.getCurrentInstanceAsciiCode().clear(); } }catch(IOException ioexception0){ ioexception0.printStackTrace(); }catch(Exception exception1){ exception1.printStackTrace(); } finally{ try { buff.close(); } catch (IOException exception2) { exception2.printStackTrace(); } } } else{ try { logger.warning("Le fichier d'orthographe n'est pas present !\nUn fichier vide a ete cree, veuillez le completer !"); orthographyFile.createNewFile(); } catch (IOException exception3) { exception3.printStackTrace(); } } } public boolean readOrthographyFile(String word, boolean toSearchIdenticalWord){ BufferedReader buff = null; boolean isFound = false; if(orthographyFile.exists()){ try{ buff = new BufferedReader(new InputStreamReader(new FileInputStream(orthographyFile))); while((pertinentWord = buff.readLine()) != null){ if(areIdentical(pertinentWord, word)){ System.out.println(pertinentWord+" et "+word+" sont identiques."); return isFound = true; } } }catch(IOException ioexception0){ ioexception0.printStackTrace(); }catch(Exception exception1){ exception1.printStackTrace(); } finally{ try { buff.close(); } catch (IOException exception2) { exception2.printStackTrace(); } } } else{ try { logger.warning("Le fichier d'orthographe n'est pas present !\nUn fichier vide a ete cree, veuillez le completer !"); orthographyFile.createNewFile(); } catch (IOException exception3) { exception3.printStackTrace(); } } return isFound; } }
gpl-2.0
asifdahir/nscloud
automationTest/src/test/java/com/owncloud/android/test/ui/testSuites/LogoutTestSuite.java
2567
/** * ownCloud Android client application * * @author purigarcia * Copyright (C) 2015 ownCloud Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * 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, see <http://www.gnu.org/licenses/>. * */ package com.nscloud.android.test.ui.testSuites; import static org.junit.Assert.*; import io.appium.java_client.android.AndroidDriver; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import com.nscloud.android.test.ui.actions.Actions; import com.nscloud.android.test.ui.groups.NoIgnoreTestCategory; import com.nscloud.android.test.ui.groups.SmokeTestCategory; import com.nscloud.android.test.ui.models.LoginForm; import com.nscloud.android.test.ui.models.FileListView; import com.nscloud.android.test.ui.models.MenuList; import com.nscloud.android.test.ui.models.SettingsView; public class LogoutTestSuite{ AndroidDriver driver; Common common; @Rule public TestName name = new TestName(); @Before public void setUp() throws Exception { common=new Common(); driver=common.setUpCommonDriver(); } @Test @Category({NoIgnoreTestCategory.class, SmokeTestCategory.class}) public void testLogout () throws Exception { FileListView fileListView = Actions.login(Config.URL, Config.user, Config.password, Config.isTrusted, driver); common.assertIsInFileListView(); MenuList menulist = fileListView.clickOnMenuButton(); SettingsView settingsView = menulist.clickOnSettingsButton(); settingsView.tapOnAccountElement(1,1, 1000); LoginForm loginForm = settingsView.clickOnDeleteAccountElement(); assertEquals("Server address https://…", loginForm.gethostUrlInput().getText()); assertEquals("Username", loginForm.getUserNameInput().getText()); assertEquals("", loginForm.getPasswordInput().getText()); } @After public void tearDown() throws Exception { common.takeScreenShotOnFailed(name.getMethodName()); //driver.removeApp("com.owncloud.android"); driver.quit(); } }
gpl-2.0
Tusamarco/stresstool
src/net/tc/jsonparser/StructureDefinitionParser.java
372
package net.tc.jsonparser; import java.io.FileReader; import java.util.Map; import org.json.simple.parser.JSONParser; import net.tc.data.db.Schema; import net.tc.data.db.Table; public interface StructureDefinitionParser { public Schema parseSchema(JSONParser parser, FileReader fr, Map tableInstances); public Table parseTable(JSONParser parser,FileReader fr); }
gpl-2.0
jackyhong/esper
esper/src/main/java/com/espertech/esper/epl/core/EngineImportServiceImpl.java
27141
/************************************************************************************** * 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.core; import com.espertech.esper.client.*; import com.espertech.esper.client.annotation.BuiltinAnnotation; import com.espertech.esper.client.hook.AggregationFunctionFactory; import com.espertech.esper.collection.Pair; import com.espertech.esper.epl.agg.access.AggregationStateType; import com.espertech.esper.epl.approx.CountMinSketchAggType; import com.espertech.esper.epl.expression.accessagg.ExprAggCountMinSketchNode; import com.espertech.esper.epl.expression.accessagg.ExprAggMultiFunctionLinearAccessNode; import com.espertech.esper.epl.expression.accessagg.ExprAggMultiFunctionSortedMinMaxByNode; import com.espertech.esper.epl.expression.core.ExprCurrentEvaluationContextNode; import com.espertech.esper.epl.expression.core.ExprNode; import com.espertech.esper.epl.expression.methodagg.*; import com.espertech.esper.type.MinMaxTypeEnum; import com.espertech.esper.util.JavaClassHelper; import com.espertech.esper.util.MethodResolver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.MathContext; import java.util.*; /** * Implementation for engine-level imports. */ public class EngineImportServiceImpl implements EngineImportService { private static final Log log = LogFactory.getLog(EngineImportServiceImpl.class); private final List<String> imports; private final Map<String, ConfigurationPlugInAggregationFunction> aggregationFunctions; private final List<Pair<Set<String>, ConfigurationPlugInAggregationMultiFunction>> aggregationAccess; private final Map<String, EngineImportSingleRowDesc> singleRowFunctions; private final Map<String, ConfigurationMethodRef> methodInvocationRef; private final boolean allowExtendedAggregationFunc; private final boolean isUdfCache; private final boolean isDuckType; private final boolean sortUsingCollator; private final MathContext optionalDefaultMathContext; private final TimeZone timeZone; /** * Ctor * @param allowExtendedAggregationFunc true to allow non-SQL standard builtin agg functions. */ public EngineImportServiceImpl(boolean allowExtendedAggregationFunc, boolean isUdfCache, boolean isDuckType, boolean sortUsingCollator, MathContext optionalDefaultMathContext, TimeZone timeZone) { imports = new ArrayList<String>(); aggregationFunctions = new HashMap<String, ConfigurationPlugInAggregationFunction>(); aggregationAccess = new ArrayList<Pair<Set<String>, ConfigurationPlugInAggregationMultiFunction>>(); singleRowFunctions = new HashMap<String, EngineImportSingleRowDesc>(); methodInvocationRef = new HashMap<String, ConfigurationMethodRef>(); this.allowExtendedAggregationFunc = allowExtendedAggregationFunc; this.isUdfCache = isUdfCache; this.isDuckType = isDuckType; this.sortUsingCollator = sortUsingCollator; this.optionalDefaultMathContext = optionalDefaultMathContext; this.timeZone = timeZone; } public boolean isUdfCache() { return isUdfCache; } public boolean isDuckType() { return isDuckType; } public ConfigurationMethodRef getConfigurationMethodRef(String className) { return methodInvocationRef.get(className); } /** * Adds cache configs for method invocations for from-clause. * @param configs cache configs */ public void addMethodRefs(Map<String, ConfigurationMethodRef> configs) { methodInvocationRef.putAll(configs); } public void addImport(String importName) throws EngineImportException { if(!isClassName(importName) && !isPackageName(importName)) { throw new EngineImportException("Invalid import name '" + importName + "'"); } if (log.isDebugEnabled()) { log.debug("Adding import " + importName); } imports.add(importName); } public void addAggregation(String functionName, ConfigurationPlugInAggregationFunction aggregationDesc) throws EngineImportException { validateFunctionName("aggregation function", functionName); if(aggregationDesc.getFactoryClassName() == null || !isClassName(aggregationDesc.getFactoryClassName())) { throw new EngineImportException("Invalid class name for aggregation factory '" + aggregationDesc.getFactoryClassName() + "'"); } aggregationFunctions.put(functionName.toLowerCase(), aggregationDesc); } public void addSingleRow(String functionName, String singleRowFuncClass, String methodName, ConfigurationPlugInSingleRowFunction.ValueCache valueCache, ConfigurationPlugInSingleRowFunction.FilterOptimizable filterOptimizable, boolean rethrowExceptions) throws EngineImportException { validateFunctionName("single-row", functionName); if(!isClassName(singleRowFuncClass)) { throw new EngineImportException("Invalid class name for aggregation '" + singleRowFuncClass + "'"); } singleRowFunctions.put(functionName.toLowerCase(), new EngineImportSingleRowDesc(singleRowFuncClass, methodName, valueCache, filterOptimizable, rethrowExceptions)); } public AggregationFunctionFactory resolveAggregationFactory(String name) throws EngineImportUndefinedException, EngineImportException { ConfigurationPlugInAggregationFunction desc = aggregationFunctions.get(name); if (desc == null) { desc = aggregationFunctions.get(name.toLowerCase()); } if (desc == null || desc.getFactoryClassName() == null) { throw new EngineImportUndefinedException("A function named '" + name + "' is not defined"); } String className = desc.getFactoryClassName(); Class clazz; try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); clazz = Class.forName(className, true, cl); } catch (ClassNotFoundException ex) { throw new EngineImportException("Could not load aggregation factory class by name '" + className + "'", ex); } Object object; try { object = clazz.newInstance(); } catch (InstantiationException e) { throw new EngineImportException("Error instantiating aggregation factory class by name '" + className + "'", e); } catch (IllegalAccessException e) { throw new EngineImportException("Illegal access instatiating aggregation factory class by name '" + className + "'", e); } if (!(object instanceof AggregationFunctionFactory)) { throw new EngineImportException("Aggregation class by name '" + className + "' does not implement AggregationFunctionFactory"); } return (AggregationFunctionFactory) object; } public void addAggregationMultiFunction(ConfigurationPlugInAggregationMultiFunction desc) throws EngineImportException { LinkedHashSet<String> orderedImmutableFunctionNames = new LinkedHashSet<String>(); for (String functionName : desc.getFunctionNames()) { orderedImmutableFunctionNames.add(functionName.toLowerCase()); validateFunctionName("aggregation multi-function", functionName.toLowerCase()); } if(!isClassName(desc.getMultiFunctionFactoryClassName())) { throw new EngineImportException("Invalid class name for aggregation multi-function factory '" + desc.getMultiFunctionFactoryClassName() + "'"); } aggregationAccess.add(new Pair<Set<String>, ConfigurationPlugInAggregationMultiFunction>(orderedImmutableFunctionNames, desc)); } public ConfigurationPlugInAggregationMultiFunction resolveAggregationMultiFunction(String name) { for (Pair<Set<String>, ConfigurationPlugInAggregationMultiFunction> config : aggregationAccess) { if (config.getFirst().contains(name.toLowerCase())) { return config.getSecond(); } } return null; } public Pair<Class, EngineImportSingleRowDesc> resolveSingleRow(String name) throws EngineImportException, EngineImportUndefinedException { EngineImportSingleRowDesc pair = singleRowFunctions.get(name); if (pair == null) { pair = singleRowFunctions.get(name.toLowerCase()); } if (pair == null) { throw new EngineImportUndefinedException("A function named '" + name + "' is not defined"); } Class clazz; try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); clazz = Class.forName(pair.getClassName(), true, cl); } catch (ClassNotFoundException ex) { throw new EngineImportException("Could not load single-row function class by name '" + pair.getClassName() + "'", ex); } return new Pair<Class, EngineImportSingleRowDesc>(clazz, pair); } public Method resolveMethod(String className, String methodName, Class[] paramTypes, boolean[] allowEventBeanType, boolean[] allowEventBeanCollType) throws EngineImportException { Class clazz; try { clazz = resolveClassInternal(className, false); } catch (ClassNotFoundException e) { throw new EngineImportException("Could not load class by name '" + className + "', please check imports", e); } try { return MethodResolver.resolveMethod(clazz, methodName, paramTypes, false, allowEventBeanType, allowEventBeanCollType); } catch (EngineNoSuchMethodException e) { throw convert(clazz, methodName, paramTypes, e, false); } } public Constructor resolveCtor(Class clazz, Class[] paramTypes) throws EngineImportException { try { return MethodResolver.resolveCtor(clazz, paramTypes); } catch (EngineNoSuchCtorException e) { throw convert(clazz, paramTypes, e); } } public Method resolveMethod(String className, String methodName) throws EngineImportException { Class clazz; try { clazz = resolveClassInternal(className, false); } catch (ClassNotFoundException e) { throw new EngineImportException("Could not load class by name '" + className + "', please check imports", e); } return resolveMethodInternal(clazz, methodName, MethodModifiers.REQUIRE_STATIC_AND_PUBLIC); } public Method resolveNonStaticMethod(Class clazz, String methodName) throws EngineImportException { return resolveMethodInternal(clazz, methodName, MethodModifiers.REQUIRE_NONSTATIC_AND_PUBLIC); } public Class resolveClass(String className) throws EngineImportException { Class clazz; try { clazz = resolveClassInternal(className, false); } catch (ClassNotFoundException e) { throw new EngineImportException("Could not load class by name '" + className + "', please check imports", e); } return clazz; } public Class resolveAnnotation(String className) throws EngineImportException { Class clazz; try { clazz = resolveClassInternal(className, true); } catch (ClassNotFoundException e) { throw new EngineImportException("Could not load annotation class by name '" + className + "', please check imports", e); } return clazz; } /** * Finds a class by class name using the auto-import information provided. * @param className is the class name to find * @return class * @throws ClassNotFoundException if the class cannot be loaded */ protected Class resolveClassInternal(String className, boolean requireAnnotation) throws ClassNotFoundException { // Attempt to retrieve the class with the name as-is try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return Class.forName(className, true, cl); } catch(ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug("Class not found for resolving from name as-is '" + className + "'"); } } // Try all the imports for(String importName : imports) { boolean isClassName = isClassName(importName); boolean containsPackage = importName.indexOf('.') != -1; String classNameWithDot = "." + className; String classNameWithDollar = "$" + className; // Import is a class name if(isClassName) { if ((containsPackage && importName.endsWith(classNameWithDot)) || (containsPackage && importName.endsWith(classNameWithDollar)) || (!containsPackage && importName.equals(className)) || (!containsPackage && importName.endsWith(classNameWithDollar))) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return Class.forName(importName, true, cl); } String prefixedClassName = importName + '$' + className; try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class clazz = Class.forName(prefixedClassName, true, cl); if (!requireAnnotation || clazz.isAnnotation()) { return clazz; } } catch(ClassNotFoundException e){ if (log.isDebugEnabled()) { log.debug("Class not found for resolving from name '" + prefixedClassName + "'"); } } } else { if (requireAnnotation && importName.equals(Configuration.ANNOTATION_IMPORT)) { Class clazz = BuiltinAnnotation.BUILTIN.get(className.toLowerCase()); if (clazz != null) { return clazz; } } // Import is a package name String prefixedClassName = getPackageName(importName) + '.' + className; try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class clazz = Class.forName(prefixedClassName, true, cl); if (!requireAnnotation || clazz.isAnnotation()) { return clazz; } } catch(ClassNotFoundException e){ if (log.isDebugEnabled()) { log.debug("Class not found for resolving from name '" + prefixedClassName + "'"); } } } } // try to resolve from method references for (String name : methodInvocationRef.keySet()) { if (JavaClassHelper.isSimpleNameFullyQualfied(className, name)) { try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class clazz = Class.forName(name, true, cl); if (!requireAnnotation || clazz.isAnnotation()) { return clazz; } } catch (ClassNotFoundException e1) { if (log.isDebugEnabled()) { log.debug("Class not found for resolving from method invocation ref:" + name); } } } } // No import worked, the class isn't resolved throw new ClassNotFoundException("Unknown class " + className); } public Method resolveMethod(Class clazz, String methodName, Class[] paramTypes, boolean[] allowEventBeanType, boolean[] allowEventBeanCollType) throws EngineImportException { try { return MethodResolver.resolveMethod(clazz, methodName, paramTypes, true, allowEventBeanType, allowEventBeanType); } catch (EngineNoSuchMethodException e) { throw convert(clazz, methodName, paramTypes, e, true); } } private EngineImportException convert(Class clazz, String methodName, Class[] paramTypes, EngineNoSuchMethodException e, boolean isInstance) { String expected = JavaClassHelper.getParameterAsString(paramTypes); String message = "Could not find "; if (!isInstance) { message += "static "; } else { message += "enumeration method, date-time method or instance "; } if (paramTypes.length > 0) { message += "method named '" + methodName + "' in class '" + JavaClassHelper.getClassNameFullyQualPretty(clazz) + "' with matching parameter number and expected parameter type(s) '" + expected + "'"; } else { message += "method named '" + methodName + "' in class '" + JavaClassHelper.getClassNameFullyQualPretty(clazz) + "' taking no parameters"; } if (e.getNearestMissMethod() != null) { message += " (nearest match found was '" + e.getNearestMissMethod().getName(); if (e.getNearestMissMethod().getParameterTypes().length == 0) { message += "' taking no parameters"; } else { message += "' taking type(s) '" + JavaClassHelper.getParameterAsString(e.getNearestMissMethod().getParameterTypes()) + "'"; } message += ")"; } return new EngineImportException(message, e); } private EngineImportException convert(Class clazz, Class[] paramTypes, EngineNoSuchCtorException e) { String expected = JavaClassHelper.getParameterAsString(paramTypes); String message = "Could not find constructor "; if (paramTypes.length > 0) { message += "in class '" + JavaClassHelper.getClassNameFullyQualPretty(clazz) + "' with matching parameter number and expected parameter type(s) '" + expected + "'"; } else { message += "in class '" + JavaClassHelper.getClassNameFullyQualPretty(clazz) + "' taking no parameters"; } if (e.getNearestMissCtor() != null) { message += " (nearest matching constructor "; if (e.getNearestMissCtor().getParameterTypes().length == 0) { message += "taking no parameters"; } else { message += "taking type(s) '" + JavaClassHelper.getParameterAsString(e.getNearestMissCtor().getParameterTypes()) + "'"; } message += ")"; } return new EngineImportException(message, e); } public ExprNode resolveSingleRowExtendedBuiltin(String name) { String nameLowerCase = name.toLowerCase(); if (nameLowerCase.equals("current_evaluation_context")) { return new ExprCurrentEvaluationContextNode(); } return null; } public ExprNode resolveAggExtendedBuiltin(String name, boolean isDistinct) { if (!allowExtendedAggregationFunc) { return null; } String nameLowerCase = name.toLowerCase(); if (nameLowerCase.equals("first")) { return new ExprAggMultiFunctionLinearAccessNode(AggregationStateType.FIRST); } if (nameLowerCase.equals("last")) { return new ExprAggMultiFunctionLinearAccessNode(AggregationStateType.LAST); } if (nameLowerCase.equals("window")) { return new ExprAggMultiFunctionLinearAccessNode(AggregationStateType.WINDOW); } if (nameLowerCase.equals("firstever")) { return new ExprFirstEverNode(isDistinct); } if (nameLowerCase.equals("lastever")) { return new ExprLastEverNode(isDistinct); } if (nameLowerCase.equals("countever")) { return new ExprCountEverNode(isDistinct); } if (nameLowerCase.equals("minever")) { return new ExprMinMaxAggrNode(isDistinct, MinMaxTypeEnum.MIN, false, true); } if (nameLowerCase.equals("maxever")) { return new ExprMinMaxAggrNode(isDistinct, MinMaxTypeEnum.MAX, false, true); } if (nameLowerCase.equals("fminever")) { return new ExprMinMaxAggrNode(isDistinct, MinMaxTypeEnum.MIN, true, true); } if (nameLowerCase.equals("fmaxever")) { return new ExprMinMaxAggrNode(isDistinct, MinMaxTypeEnum.MAX, true, true); } if (nameLowerCase.equals("rate")) { return new ExprRateAggNode(isDistinct); } if (nameLowerCase.equals("nth")) { return new ExprNthAggNode(isDistinct); } if (nameLowerCase.equals("leaving")) { return new ExprLeavingAggNode(isDistinct); } if (nameLowerCase.equals("maxby")) { return new ExprAggMultiFunctionSortedMinMaxByNode(true, false, false); } if (nameLowerCase.equals("maxbyever")) { return new ExprAggMultiFunctionSortedMinMaxByNode(true, true, false); } if (nameLowerCase.equals("minby")) { return new ExprAggMultiFunctionSortedMinMaxByNode(false, false, false); } if (nameLowerCase.equals("minbyever")) { return new ExprAggMultiFunctionSortedMinMaxByNode(false, true, false); } if (nameLowerCase.equals("sorted")) { return new ExprAggMultiFunctionSortedMinMaxByNode(false, false, true); } CountMinSketchAggType cmsType = CountMinSketchAggType.fromNameMayMatch(nameLowerCase); if (cmsType != null) { return new ExprAggCountMinSketchNode(isDistinct, cmsType); } return null; } public MathContext getDefaultMathContext() { return optionalDefaultMathContext; } public TimeZone getTimeZone() { return timeZone; } public boolean isSortUsingCollator() { return sortUsingCollator; } /** * For testing, returns imports. * @return returns auto-import list as array */ protected String[] getImports() { return imports.toArray(new String[imports.size()]); } private static boolean isFunctionName(String functionName) { String classNameRegEx = "\\w+"; return functionName.matches(classNameRegEx); } private static boolean isClassName(String importName) { String classNameRegEx = "(\\w+\\.)*\\w+(\\$\\w+)?"; return importName.matches(classNameRegEx); } private static boolean isPackageName(String importName) { String classNameRegEx = "(\\w+\\.)+\\*"; return importName.matches(classNameRegEx); } // Strip off the final ".*" private static String getPackageName(String importName) { return importName.substring(0, importName.length() - 2); } private void validateFunctionName(String functionType, String functionName) throws EngineImportException { String functionNameLower = functionName.toLowerCase(); if (aggregationFunctions.containsKey(functionNameLower)) { throw new EngineImportException("Aggregation function by name '" + functionName + "' is already defined"); } if (singleRowFunctions.containsKey(functionNameLower)) { throw new EngineImportException("Single-row function by name '" + functionName + "' is already defined"); } for (Pair<Set<String>, ConfigurationPlugInAggregationMultiFunction> pairs : aggregationAccess) { if (pairs.getFirst().contains(functionNameLower)) { throw new EngineImportException("Aggregation multi-function by name '" + functionName + "' is already defined"); } } if(!isFunctionName(functionName)) { throw new EngineImportException("Invalid " + functionType + " name '" + functionName + "'"); } } private Method resolveMethodInternal(Class clazz, String methodName, MethodModifiers methodModifiers) throws EngineImportException { Method methods[] = clazz.getMethods(); Method methodByName = null; // check each method by name for (Method method : methods) { if (method.getName().equals(methodName)) { if (methodByName != null) { throw new EngineImportException("Ambiguous method name: method by name '" + methodName + "' is overloaded in class '" + clazz.getName() + "'"); } int modifiers = method.getModifiers(); boolean isPublic = Modifier.isPublic(modifiers); boolean isStatic = Modifier.isStatic(modifiers); if (methodModifiers.acceptsPublicFlag(isPublic) && methodModifiers.acceptsStaticFlag(isStatic)) { methodByName = method; } } } if (methodByName == null) { throw new EngineImportException("Could not find " + methodModifiers.getText() + " method named '" + methodName + "' in class '" + clazz.getName() + "'"); } return methodByName; } private enum MethodModifiers { REQUIRE_STATIC_AND_PUBLIC("public static", true), REQUIRE_NONSTATIC_AND_PUBLIC("public non-static", false); private final String text; private final boolean requiredStaticFlag; MethodModifiers(String text, boolean requiredStaticFlag) { this.text = text; this.requiredStaticFlag = requiredStaticFlag; } public boolean acceptsPublicFlag(boolean isPublic) { return isPublic; } public boolean acceptsStaticFlag(boolean isStatic) { return requiredStaticFlag == isStatic; } public String getText() { return text; } } }
gpl-2.0
thirdy/poe-merchant
src/main/java/net/poemerchant/util/NashornUtils.java
2568
package net.poemerchant.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import jdk.nashorn.api.scripting.ScriptObjectMirror; import net.poemerchant.ex.PoEMerchantRuntimeException; import com.google.common.base.Predicate; import com.google.common.base.Predicates; public class NashornUtils { public static <T> T evalFunc(String js, String functionIdentifier, String... params) { ScriptEngine engine = new ScriptEngineManager() .getEngineByName("nashorn"); try { Object eval = engine.eval(js); Invocable invocable = (Invocable) engine; T result = (T) invocable.invokeFunction(functionIdentifier, params); return result; } catch (ScriptException e) { throw new PoEMerchantRuntimeException(e); } catch (NoSuchMethodException e) { throw new PoEMerchantRuntimeException(e); } } public static <T> T evalJSArray(String raw) { String js = "var func1 = function() { " + "return " + raw + ";" + "}"; return evalFunc(js, "func1"); } public static Map<String, Object> evalJSArrayToMap(String raw, Predicate<Object> isNeeded) { ScriptObjectMirror evalJSArray = evalJSArray(raw); return somToMap(evalJSArray, isNeeded); } public static Map<String, Object> evalJSArrayToMap(String raw) { return evalJSArrayToMap(raw, Predicates.alwaysTrue()); } public static Map<String, Object> somToMap(ScriptObjectMirror scriptObjectMirror, Predicate<Object> filter) { Map<String, Object> map = new HashMap<String, Object>(); Set<Entry<String, Object>> entrySet = scriptObjectMirror.entrySet(); for (Iterator<Entry<String, Object>> iter = entrySet.iterator(); iter.hasNext();) { Entry<String, Object> entry = iter.next(); if (filter != null && filter.apply(entry.getKey())) { continue; } Object obj = entry.getValue(); if (obj.getClass().equals(ScriptObjectMirror.class)) { ScriptObjectMirror som = (ScriptObjectMirror) obj; if (som.getClassName().equals("Array")) { obj = somToArray(som); } } map.put(entry.getKey(), obj); } return map; } public static Object[] somToArray(ScriptObjectMirror som) { Set<Entry<String, Object>> arrayEntries = som.entrySet(); Object[] obj = new Object[arrayEntries.size()]; int idx = 0; for (Entry<String, Object> entry : arrayEntries) { obj[idx] = entry.getValue(); idx++; } return obj; } }
gpl-2.0
aktion-hip/vif
org.hip.viffw/src/org/hip/kernel/bom/impl/PreparedInsertStatement.java
6272
/** This package is part of the servlet framework used for the application VIF. Copyright (C) 2001-2014, Benno Luthiger 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. 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 org.hip.kernel.bom.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.hip.kernel.bom.DomainObject; import org.hip.kernel.bom.GettingException; import org.hip.kernel.bom.model.MappingDef; import org.hip.kernel.bom.model.ObjectDef; import org.hip.kernel.exc.DefaultExceptionHandler; import org.hip.kernel.exc.VError; import org.hip.kernel.sys.VSys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** This is the prepared insert Statement. * * @author Benno Luthiger */ public class PreparedInsertStatement extends SqlPreparedStatement { private static final Logger LOG = LoggerFactory.getLogger(PreparedInsertStatement.class); private transient int numberOfAffected; /** PreparedInsertStatement constructor, initializes the home and prepares the insert statement. * * @param inHome org.hip.kernel.bom.impl.DomainObjectHomeImpl */ public PreparedInsertStatement(final DomainObjectHomeImpl inHome) { super(); home = inHome; initConnection(); prepareStatement(); } /** This method executes the insert.<br> * The method is named "executeUpdate" because it calls the method java.sql.PreparedStatement.executeUpdate(), which * updates the table, i.e. executes a SQL INSERT, UPDATE or DELETE statement.<br> * NOTE: If auto commit is on, the connection is closed. Else the connection has to be committed (or rollbacked) and * is closed then. Be CAREFUL to close the Connection in case of failure. Also be careful to close the statement. * * @return Collection of auto-generated keys (Long) of the new entries created by this InsertStatement. * @exception java.sql.SQLException */ public Collection<Long> executeUpdate() throws SQLException { try { final Collection<Long> outAutoKeys = new ArrayList<Long>(); numberOfAffected = statement.executeUpdate(); try (ResultSet lResult = statement.getGeneratedKeys()) { while (lResult.next()) { outAutoKeys.add(Long.valueOf(lResult.getLong(1))); } return outAutoKeys; } } catch (final SQLException exc) { LOG.error("Error encountered with '{}'!", sqlString, exc); throw exc; } finally { traceWarnings(connection); if (!connection.isClosed()) { if (connection.getAutoCommit()) { connection.close(); } } } } /** Returns the number of rows affected by this insert. * * @return int */ public int getNumberOfAffected() { return numberOfAffected; } /** Prepares the statement by creating the SQL string. */ public final void prepareStatement() { final List<String> lSQLs = home.createPreparedInserts2(); if (lSQLs.isEmpty()) { throw new VError("Table not defined for : " + home.toString()); } if (lSQLs.size() > 1) { // NOPMD by lbenno throw new VError("More than one table defined for : " + home.toString()); } sqlString = lSQLs.get(0); try { statement = connection.prepareStatement(sqlString, Statement.RETURN_GENERATED_KEYS); } catch (final SQLException exc) { throw new VError("SQL error while preparing statement : " + exc.toString(), exc); } } /** This method sets the values of the prepared statement according to the values of the DomainObject. This method * was inspired by the DomainObjectImpl.createInsertString() method. * * @param inObject org.hip.kernel.bom.DomainObject */ public void setValues(final DomainObject inObject) { // check existence of statement if (VSys.assertNotNull(this, "setValues", statement)) { return; } if (inObject.getHome() != home) { throw new VError("The object " + inObject.toString() + " can not be used with this statement which has been prepared with " + home.toString()); } final ObjectDef lDef = home.getObjectDef(); final String lTable = getTablename(lDef); int i = 0; // NOPMD by lbenno for (final MappingDef lMappingDef : lDef.getMappingDefsForTable2(lTable)) { i++; // Now we get the value final String lPropertyName = lMappingDef.getPropertyDef().getName(); Object lValue = null; try { lValue = inObject.get(lPropertyName); } catch (final GettingException exc) { DefaultExceptionHandler.instance().handle(exc); } try { if (lValue == null) { final String lValueType = lMappingDef.getPropertyDef().getValueType(); statement.setNull(i, convertToSqlType(lValueType)); } else { setValueToStatement(lValue, i); } // else } // try catch (final SQLException exc) { throw new VError("SQL Error while settings values in a prepared insert statement : " + exc.toString(), exc); } // catch } } }
gpl-2.0
ridethepenguin/coursera
POSA-14/W7-A6-VulnCheck/iRemember/peers/LoginActivityStudent2.java
3629
package edu.vuum.mocca.ui; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import edu.vuum.mocca.R; import edu.vuum.mocca.storage.StorageUtilities; /** * The activity that allows the user to provide login information. */ public class LoginActivity extends StoryActivityBase{ // A tag used for debugging with Logcat static final String LOG_TAG = LoginActivity.class.getCanonicalName(); // The edit texts used EditText mLoginId; EditText mPassword; // Make sure we use maximum security to store login credentials static final int MAX_SECURITY = Integer.MAX_VALUE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Setup the UI setContentView(R.layout.login_activity); // Line 36 //Find the edit texts mLoginId = (EditText) findViewById(R.id.username); mPassword = (EditText) findViewById(R.id.password); } /** * Get the file used for storing login credentials */ public static File getLoginFile (Context context) { return StorageUtilities.getOutputMediaFile(context, // Line 48 StorageUtilities.MEDIA_TYPE_TEXT, // changed this from MAX_SECURITY to StorageUtilities.SECURITY_PRIVATE, because the StorageUtilities // only checks for the StorageUtilities.SECURITY_PRIVATE or StorageUtilities.SECURITY_PUBLIC values wich // are different from MAX_SECURITY // default is the insecure location used! StorageUtilities.SECURITY_PRIVATE, "login.txt"); } /** * Returns the last LoginId input into this activity, or 0 if none is set. */ public static long getLoginId(Context context) { // Get the output file for the login information File loginFile = getLoginFile(context); // Line 59 String out = null; // If it already exists, read the login ID and return it if (loginFile != null && loginFile.exists()) { try { Scanner sc = new Scanner(loginFile); out = sc.nextLine(); sc.close(); return Long.parseLong(out); } catch (Exception e) { // This should never really happen Log.e(LOG_TAG, "Unable to get LoginID from file"); // Line 72 } } return 0; } /** * Returns the last password input into this activity, or null if one has not been set */ public static String getPassword(Context context) { // Get the output file for the login information File loginFile = getLoginFile(context); String out = null; // If it already exists, read the login information from the file and display it if (loginFile != null && loginFile.exists()) { try { Scanner sc = new Scanner(loginFile); // Line 91 sc.nextLine(); out = sc.nextLine(); sc.close(); return out; } catch (Exception e) { // This should never really happen Log.e(LOG_TAG, "Unable to get password from file."); } } return out; } /** * The login button was clicked. */ public void loginClicked(View v){ // Save the input login information in a file so that the rest of the app can access it. File loginFile = getLoginFile(this); try { BufferedWriter writer = new BufferedWriter(new FileWriter(loginFile)); // Line 113 writer.write(mLoginId.getText().toString()); writer.newLine(); writer.write(mPassword.getText().toString()); writer.newLine(); writer.close(); } catch (Exception e) { Log.e(LOG_TAG, "Problem in loginClicked"); } finally { openListStoryActivity(); // Line 123 } } }
gpl-2.0
deNULL/Wire-Desktop
src/tl/MessageMediaUnsupported.java
963
package tl; import java.nio.ByteBuffer; public class MessageMediaUnsupported extends tl.TMessageMedia { public MessageMediaUnsupported(ByteBuffer buffer) throws Exception { bytes = TL.readString(buffer); } public MessageMediaUnsupported(byte[] bytes) { this.bytes = bytes; } public ByteBuffer writeTo(ByteBuffer buffer, boolean boxed) throws Exception { int oldPos = buffer.position(); if (boxed) { buffer.putInt(0x29632a36); } TL.writeString(buffer, bytes, false); if (oldPos + length() + (boxed ? 4 : 0) != buffer.position()) { System.err.println("Invalid length at MessageMediaUnsupported: expected " + (length() + (boxed ? 4 : 0)) + " bytes, got " + (buffer.position() - oldPos)); } return buffer; } public int length() throws Exception { return TL.length(bytes); } public String toString() { return "(messageMediaUnsupported bytes:" + TL.toString(bytes) + ")"; } }
gpl-2.0
mcxr4299/SurveyHelper
app/src/main/java/net/mccode/surveyhelper/SettingsFragment.java
6295
package net.mccode.surveyhelper; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import android.support.annotation.NonNull; import android.util.Log; import android.view.MenuItem; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import net.mccode.surveyhelper.utils.CommonUtils; public class SettingsFragment extends PreferenceFragment { private static final String TAG = "SettingsTAG"; private ProgressDialog progressDialog; private Handler updateHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); setHasOptionsMenu(true); updateHandler = new UpdateHandler(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: getActivity().finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, @NonNull Preference preference) { switch(preference.getKey()) { case "check_update": progressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.checking_update), true, true); new Thread(new CheckUpdate(updateHandler)).start(); return true; case "about_me": new AlertDialog.Builder(getActivity()) .setIcon(R.mipmap.ic_launcher) .setTitle(String.format( getResources().getString(R.string.text_now_version), CommonUtils.getVersionName(getActivity()) )) .setMessage(R.string.text_about_me) .setPositiveButton(R.string.btn_ok, null) .show(); return true; default: return false; } } /** * 对比版本号,提示是否更新 * @param newVersionCode 最新版本号 * @param newVersionName 最新版本名 */ private void update(int newVersionCode, String newVersionName) { if(progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss(); int versionCode = CommonUtils.getVersionCode(getActivity()); if(versionCode < newVersionCode) { String text = String.format( getResources().getString(R.string.text_need_update), newVersionName ); DialogInterface.OnClickListener okListener; // 确定按钮点击监听器 okListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent( Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.update_url)) ); startActivity(i); } }; new AlertDialog.Builder(getActivity()) .setTitle(R.string.text_title_update) .setMessage(text) .setPositiveButton(R.string.btn_ok, okListener) .setNegativeButton(R.string.btn_cancel, null) .show(); } else { Toast.makeText(getActivity(), R.string.text_latest_version, Toast.LENGTH_SHORT) .show(); } } private class UpdateHandler extends Handler { @Override public void handleMessage(Message msg) { update(msg.getData().getInt("code"), msg.getData().getString("name") ); } }; private class CheckUpdate implements Runnable { private static final String URL = "http://mccode.net/api/surveyVersion.php"; private Handler handler; public CheckUpdate(Handler handler) { this.handler = handler; } public void run() { HttpGet get = new HttpGet(URL); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(get); if(response.getStatusLine().getStatusCode() != 200) { Log.w(TAG, "版本号获取响应错误"); return; } JSONObject json = new JSONObject(EntityUtils.toString( response.getEntity(), "utf-8")); int code = json.getInt("code"); if(code == 0) { // 获取json中版本发送消息给主线程 Bundle bundle = new Bundle(); bundle.putInt("code", json.getInt("surveyVersionCode")); bundle.putString("name", json.getString("surveyVersionName")); Message msg = new Message(); msg.setData(bundle); handler.sendMessage(msg); } else { Log.w(TAG, "服务器端版本查询错误" + Integer.toString(code) + json.getString("msg")); } } catch (IOException e) { Log.w(TAG, "版本号获取连接失败"); } catch (JSONException e) { Log.w(TAG, "JSON解析失败"); } } } }
gpl-2.0
lclsdu/CS
jspxcms/src/com/jspxcms/core/web/directive/CommentListDirective.java
728
package com.jspxcms.core.web.directive; import java.io.IOException; import java.util.Map; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; /** * CommentListDirective * * @author liufang * */ public class CommentListDirective extends AbstractCommentListPageDirective implements TemplateDirectiveModel { @SuppressWarnings("rawtypes") public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { super.doExecute(env, params, loopVars, body, false); } }
gpl-2.0
s2sprodotti/SDS
SistemaDellaSicurezza/src/com/apconsulting/luna/ejb/SediLesione/SediLesioneBean.java
12129
/** ======================================================================== */ /** */ /** @copyright Copyright (c) 2010-2015, S2S s.r.l. */ /** @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 */ /** @version 6.0 */ /** This file is part of SdS - Sistema della Sicurezza . */ /** SdS - Sistema della Sicurezza 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. */ /** SdS - Sistema della Sicurezza 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 SdS - Sistema della Sicurezza . If not, see <http://www.gnu.org/licenses/gpl-2.0.html> GNU Public License v.2 */ /** */ /** ======================================================================== */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.apconsulting.luna.ejb.SediLesione; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Collection; import javax.ejb.CreateException; import javax.ejb.EJBException; import javax.ejb.FinderException; import javax.ejb.NoSuchEntityException; import s2s.ejb.pseudoejb.BMPConnection; import s2s.ejb.pseudoejb.BMPEntityBean; import s2s.ejb.pseudoejb.EntityContextWrapper; /** * * @author Dario */ public class SediLesioneBean extends BMPEntityBean implements ISediLesione, ISediLesioneHome { //<comment description="Member Variables"> long COD_SED_LES; //1 String NOM_SED_LES; //2 String TPL_SED_LES; //3 //</comment> ////////////////////// CONSTRUCTOR/////////////////// private static SediLesioneBean ys = null; private SediLesioneBean() { // } public static SediLesioneBean getInstance() { if (ys == null) { ys = new SediLesioneBean(); } return ys; } ////////////////////////////ATTENTION!!/////////////////////////////////////////////////////////////// //<comment description="Zdes opredeliayutsia metody EJB objecta kotorie budut rabotat v JSP Containere (Zaglushki)"/> // (Home Intrface) create() public ISediLesione create(String strNOM_SED_LES, String strTPL_SED_LES) throws CreateException { SediLesioneBean bean = new SediLesioneBean(); try { Object primaryKey = bean.ejbCreate(strNOM_SED_LES, strTPL_SED_LES); bean.setEntityContext(new EntityContextWrapper(primaryKey)); bean.ejbPostCreate(strNOM_SED_LES, strTPL_SED_LES); return bean; } catch (Exception ex) { throw new javax.ejb.CreateException(ex.getMessage()); } } // (Home Intrface) remove() @Override public void remove(Object primaryKey) { SediLesioneBean iSediLesioneBean = new SediLesioneBean(); try { Object obj = iSediLesioneBean.ejbFindByPrimaryKey((Long) primaryKey); iSediLesioneBean.setEntityContext(new EntityContextWrapper(obj)); iSediLesioneBean.ejbActivate(); iSediLesioneBean.ejbLoad(); iSediLesioneBean.ejbRemove(); } catch (Exception ex) { throw new EJBException(ex); } } // (Home Intrface) findByPrimaryKey() public ISediLesione findByPrimaryKey(Long primaryKey) throws FinderException { SediLesioneBean bean = new SediLesioneBean(); try { bean.setEntityContext(new EntityContextWrapper(primaryKey)); bean.ejbActivate(); bean.ejbLoad(); return bean; } catch (Exception ex) { throw new javax.ejb.FinderException(ex.getMessage()); } } // (Home Intrface) findAll() public Collection findAll() throws FinderException { try { return this.ejbFindAll(); } catch (Exception ex) { throw new javax.ejb.FinderException(ex.getMessage()); } } public Collection getANA_SED_LES_TAB_ByNOM_View() { return (new SediLesioneBean()).ejbGetANA_SED_LES_TAB_ByNOM_View(); } public Collection findEx(String NOM, long iOrderBy) { return (new SediLesioneBean()).ejbfindEx(NOM, iOrderBy); } /////////////////////ATTENTION!!//////////////////////////////////////////////////////////////////////////// //<comment description="Zdes opredeliayutsia metody home intefeisa kotorie budut rabotat v EJB Containere"/> //</ISediLesioneHome-implementation> public Long ejbCreate(String strNOM_SED_LES, String strTPL_SED_LES) { this.NOM_SED_LES = strNOM_SED_LES; this.TPL_SED_LES = strTPL_SED_LES; this.COD_SED_LES = NEW_ID(); // unic ID BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("INSERT INTO ana_sed_les_tab (cod_sed_les,nom_sed_les,tpl_sed_les) VALUES(?,?,?)"); ps.setLong(1, COD_SED_LES); ps.setString(2, NOM_SED_LES); ps.setString(3, TPL_SED_LES); ps.executeUpdate(); return new Long(COD_SED_LES); } catch (Exception ex) { throw new EJBException(ex); } finally { bmp.close(); } } //------------------------------------------------------- public void ejbPostCreate(String strNOM_SED_LES, String strTPL_SED_LES) { } //-------------------------------------------------- public Collection ejbFindAll() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT cod_sed_les FROM ana_sed_les_tab "); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { al.add(new Long(rs.getLong(1))); } return al; } catch (Exception ex) { throw new EJBException(ex); } finally { bmp.close(); } } //----------------------------------------------------------- public Long ejbFindByPrimaryKey(Long primaryKey) { return primaryKey; } //---------------------------------------------------------- public void ejbActivate() { this.COD_SED_LES = ((Long) this.getEntityKey()).longValue(); } //---------------------------------------------------------- public void ejbPassivate() { this.COD_SED_LES = -1; } //---------------------------------------------------------- public void ejbLoad() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT * FROM ana_sed_les_tab WHERE cod_sed_les=?"); ps.setLong(1, COD_SED_LES); ResultSet rs = ps.executeQuery(); if (rs.next()) { this.NOM_SED_LES = rs.getString("NOM_SED_LES"); this.TPL_SED_LES = rs.getString("TPL_SED_LES"); } else { throw new NoSuchEntityException("SediLesione con ID= non è trovata"); } } catch (Exception ex) { throw new EJBException(ex); } finally { bmp.close(); } } //---------------------------------------------------------- public void ejbRemove() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("DELETE FROM ana_sed_les_tab WHERE cod_sed_les=?"); ps.setLong(1, COD_SED_LES); if (ps.executeUpdate() == 0) { throw new NoSuchEntityException("SediLesione con ID= non è trovata"); } } catch (Exception ex) { throw new EJBException(ex); } finally { bmp.close(); } } //---------------------------------------------------------- public void ejbStore() { if (!isModified()) { return; } BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("UPDATE ana_sed_les_tab SET nom_sed_les=?, tpl_sed_les=? WHERE cod_sed_les=?"); ps.setString(1, NOM_SED_LES); ps.setString(2, TPL_SED_LES); ps.setLong(3, COD_SED_LES); if (ps.executeUpdate() == 0) { throw new NoSuchEntityException("SediLesione con ID= non è trovata"); } } catch (Exception ex) { throw new EJBException(ex); } finally { bmp.close(); } } //------------------------------------------------------------- /////////////////////////////////ATTENTION!!////////////////////////////// //<comment description="Zdes opredeliayutsia metody (remote) interfeisa"/> //<comment description="setter/getters"> //1 public void setNOM_SED_LES(String newNOM_SED_LES) { if (NOM_SED_LES.equals(newNOM_SED_LES)) { return; } NOM_SED_LES = newNOM_SED_LES; setModified(); } public String getNOM_SED_LES() { return NOM_SED_LES; } //2 public void setTPL_SED_LES(String newTPL_SED_LES) { if (TPL_SED_LES.equals(newTPL_SED_LES)) { return; } TPL_SED_LES = newTPL_SED_LES; setModified(); } public String getTPL_SED_LES() { return TPL_SED_LES; } //3 public long getCOD_SED_LES() { return COD_SED_LES; } //============================================ //</comment> // Views by Pogrebnoy Yura public Collection ejbGetANA_SED_LES_TAB_ByNOM_View() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT cod_sed_les, nom_sed_les, tpl_sed_les FROM ana_sed_les_tab ORDER BY nom_sed_les"); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { ANA_SED_LES_TAB_ByNOM_View obj = new ANA_SED_LES_TAB_ByNOM_View(); obj.COD_SED_LES = rs.getLong(1); obj.NOM_SED_LES = rs.getString(2); obj.TPL_SED_LES = rs.getString(3); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { throw new EJBException(ex); } finally { bmp.close(); } } public Collection ejbfindEx(String NOM, long iOrderBy) { String Sql = "SELECT cod_sed_les, nom_sed_les, tpl_sed_les FROM ana_sed_les_tab "; if (NOM != null) { Sql += " WHERE UPPER(nom_sed_les) LIKE ? "; } Sql += " ORDER BY nom_sed_les"; BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement(Sql); if (NOM != null) { ps.setString(1, NOM.toUpperCase() + "%"); } ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { findEx_sed_les obj = new findEx_sed_les(); obj.COD_SED_LES = rs.getLong(1); obj.NOM_SED_LES = rs.getString(2); obj.TPL_SED_LES = rs.getString(3); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { throw new EJBException(ex); } finally { bmp.close(); } } ///////////ATTENTION!!//////////////////////////////////////////// }//<comment description="end of implementation SediLesioneBean"/>
gpl-2.0
smarr/GraalCompiler
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/java/MonitorEnterNode.java
2761
/* * Copyright (c) 2009, 2015, 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. */ package com.oracle.graal.nodes.java; import jdk.internal.jvmci.meta.LocationIdentity; import com.oracle.graal.graph.IterableNodeType; import com.oracle.graal.graph.NodeClass; import com.oracle.graal.nodeinfo.NodeInfo; import com.oracle.graal.nodes.ValueNode; import com.oracle.graal.nodes.extended.MonitorEnter; import com.oracle.graal.nodes.memory.MemoryCheckpoint; import com.oracle.graal.nodes.spi.Lowerable; import com.oracle.graal.nodes.spi.LoweringTool; import com.oracle.graal.nodes.spi.Virtualizable; import com.oracle.graal.nodes.spi.VirtualizerTool; import com.oracle.graal.nodes.virtual.VirtualObjectNode; /** * The {@code MonitorEnterNode} represents the acquisition of a monitor. */ @NodeInfo public final class MonitorEnterNode extends AccessMonitorNode implements Virtualizable, Lowerable, IterableNodeType, MonitorEnter, MemoryCheckpoint.Single { public static final NodeClass<MonitorEnterNode> TYPE = NodeClass.create(MonitorEnterNode.class); public MonitorEnterNode(ValueNode object, MonitorIdNode monitorId) { super(TYPE, object, monitorId); } @Override public LocationIdentity getLocationIdentity() { return LocationIdentity.any(); } @Override public void lower(LoweringTool tool) { tool.getLowerer().lower(this, tool); } @Override public void virtualize(VirtualizerTool tool) { ValueNode alias = tool.getAlias(object()); if (alias instanceof VirtualObjectNode) { VirtualObjectNode virtual = (VirtualObjectNode) alias; if (virtual.hasIdentity()) { tool.addLock(virtual, getMonitorId()); tool.delete(); } } } }
gpl-2.0
guru-digital/sstemplate-netbeans
src/org/netbeans/modules/php/sstemplate/editor/lexer/SSTemplateTokenId.java
3089
/** * Silverstripe Template for Netbeans * * Copyright (c) 2015 Corey Sewell * * For warranty and licensing information, view the LICENSE file. */ package org.netbeans.modules.php.sstemplate.editor.lexer; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import org.netbeans.api.lexer.InputAttributes; import org.netbeans.api.lexer.Language; import org.netbeans.api.lexer.LanguagePath; import org.netbeans.api.lexer.Token; import org.netbeans.api.lexer.TokenId; import org.netbeans.spi.lexer.LanguageEmbedding; import org.netbeans.spi.lexer.LanguageHierarchy; import org.netbeans.spi.lexer.Lexer; import org.netbeans.spi.lexer.LexerRestartInfo; public enum SSTemplateTokenId implements TokenId { T_SSTEMPLATE_NAME(null, "sstemplate_name"), T_SSTEMPLATE_STRING(null, "sstemplate_string"), T_SSTEMPLATE_NUMBER(null, "sstemplate_number"), T_SSTEMPLATE_OPERATOR(null, "sstemplate_operator"), T_SSTEMPLATE_PUNCTUATION(null, "sstemplate_punctuation"), T_SSTEMPLATE_WHITESPACE(null, "sstemplate_whitespace"), T_SSTEMPLATE_FUNCTION(null, "sstemplate_function"), T_SSTEMPLATE_INSTRUCTION(null, "sstemplate_instruction"), T_SSTEMPLATE_VARIABLE(null, "sstemplate_variable"), T_SSTEMPLATE_COMMENT(null, "sstemplate_comment"), T_SSTEMPLATE_OTHER(null, "sstemplate_other"); private final String fixedText; private final String primaryCategory; SSTemplateTokenId(String fixedText, String primaryCategory) { this.fixedText = fixedText; this.primaryCategory = primaryCategory; } public String fixedText() { return fixedText; } @Override public String primaryCategory() { return primaryCategory; } private static final Language<SSTemplateTokenId> language = new LanguageHierarchy<SSTemplateTokenId>() { @Override protected Collection<SSTemplateTokenId> createTokenIds() { return EnumSet.allOf(SSTemplateTokenId.class); } @Override protected Map<String, Collection<SSTemplateTokenId>> createTokenCategories() { Map<String, Collection<SSTemplateTokenId>> cats = new HashMap<String, Collection<SSTemplateTokenId>>(); return cats; } @Override protected Lexer<SSTemplateTokenId> createLexer(LexerRestartInfo<SSTemplateTokenId> info) { return SSTemplateLexer.create(info); } @Override protected String mimeType() { return "text/sstemplate-markup"; } @Override protected LanguageEmbedding<?> embedding(Token<SSTemplateTokenId> token, LanguagePath languagePath, InputAttributes inputAttributes) { return null; } }.language(); public static Language<SSTemplateTokenId> language() { return language; } }
gpl-2.0
liuyuan216/prism
src/explicit/STPGModelChecker.java
32121
//============================================================================== // // Copyright (c) 2002- // Authors: // * Dave Parker <david.parker@comlab.ox.ac.uk> (University of Oxford) // * Vojtech Forejt <vojtech.forejt@cs.ox.ac.uk> (University of Oxford) // //------------------------------------------------------------------------------ // // This file is part of PRISM. // // PRISM 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. // // PRISM 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 PRISM; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //============================================================================== package explicit; import java.util.BitSet; import java.util.List; import java.util.Map; import parser.ast.Expression; import prism.PrismComponent; import prism.PrismException; import prism.PrismFileLog; import prism.PrismLog; import prism.PrismUtils; import explicit.rewards.STPGRewards; /** * Explicit-state model checker for two-player stochastic games (STPGs). */ public class STPGModelChecker extends ProbModelChecker { /** * Create a new STPGModelChecker, inherit basic state from parent (unless null). */ public STPGModelChecker(PrismComponent parent) throws PrismException { super(parent); } // Model checking functions @Override protected StateValues checkProbPathFormulaLTL(Model model, Expression expr, boolean qual, MinMax minMax, BitSet statesOfInterest) throws PrismException { throw new PrismException("LTL model checking not yet supported for stochastic games"); } // Numerical computation functions /** * Compute next=state probabilities. * i.e. compute the probability of being in a state in {@code target} in the next step. * @param stpg The STPG * @param target Target states * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) */ public ModelCheckerResult computeNextProbs(STPG stpg, BitSet target, boolean min1, boolean min2) throws PrismException { ModelCheckerResult res = null; int n; double soln[], soln2[]; long timer; timer = System.currentTimeMillis(); // Store num states n = stpg.getNumStates(); // Create/initialise solution vector(s) soln = Utils.bitsetToDoubleArray(target, n); soln2 = new double[n]; // Next-step probabilities stpg.mvMultMinMax(soln, min1, min2, soln2, null, false, null); // Return results res = new ModelCheckerResult(); res.soln = soln2; res.numIters = 1; res.timeTaken = timer / 1000.0; return res; } /** * Compute reachability probabilities. * i.e. compute the min/max probability of reaching a state in {@code target}. * @param stpg The STPG * @param target Target states * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) */ public ModelCheckerResult computeReachProbs(STPG stpg, BitSet target, boolean min1, boolean min2) throws PrismException { return computeReachProbs(stpg, null, target, min1, min2, null, null); } /** * Compute until probabilities. * i.e. compute the min/max probability of reaching a state in {@code target}, * while remaining in those in @{code remain}. * @param stpg The STPG * @param remain Remain in these states (optional: null means "all") * @param target Target states * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) */ public ModelCheckerResult computeUntilProbs(STPG stpg, BitSet remain, BitSet target, boolean min1, boolean min2) throws PrismException { return computeReachProbs(stpg, remain, target, min1, min2, null, null); } /** * Compute reachability/until probabilities. * i.e. compute the min/max probability of reaching a state in {@code target}, * while remaining in those in @{code remain}. * @param stpg The STPG * @param remain Remain in these states (optional: null means "all") * @param target Target states * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) * @param init Optionally, an initial solution vector (may be overwritten) * @param known Optionally, a set of states for which the exact answer is known * Note: if 'known' is specified (i.e. is non-null, 'init' must also be given and is used for the exact values. */ public ModelCheckerResult computeReachProbs(STPG stpg, BitSet remain, BitSet target, boolean min1, boolean min2, double init[], BitSet known) throws PrismException { ModelCheckerResult res = null; BitSet no, yes; int i, n, numYes, numNo; long timer, timerProb0, timerProb1; boolean genAdv; // Check for some unsupported combinations if (solnMethod == SolnMethod.VALUE_ITERATION && valIterDir == ValIterDir.ABOVE && !(precomp && prob0)) { throw new PrismException("Precomputation (Prob0) must be enabled for value iteration from above"); } // Are we generating an optimal adversary? genAdv = exportAdv; // Start probabilistic reachability timer = System.currentTimeMillis(); if (verbosity >= 1) mainLog.println("\nStarting probabilistic reachability..."); // Check for deadlocks in non-target state (because breaks e.g. prob1) stpg.checkForDeadlocks(target); // Store num states n = stpg.getNumStates(); // Optimise by enlarging target set (if more info is available) if (init != null && known != null) { BitSet targetNew = new BitSet(n); for (i = 0; i < n; i++) { targetNew.set(i, target.get(i) || (known.get(i) && init[i] == 1.0)); } target = targetNew; } // Precomputation timerProb0 = System.currentTimeMillis(); if (precomp && prob0) { no = prob0(stpg, remain, target, min1, min2); } else { no = new BitSet(); } timerProb0 = System.currentTimeMillis() - timerProb0; timerProb1 = System.currentTimeMillis(); if (precomp && prob1 && !genAdv) { yes = prob1(stpg, remain, target, min1, min2); } else { yes = (BitSet) target.clone(); } timerProb1 = System.currentTimeMillis() - timerProb1; // Print results of precomputation numYes = yes.cardinality(); numNo = no.cardinality(); if (verbosity >= 1) mainLog.println("target=" + target.cardinality() + ", yes=" + numYes + ", no=" + numNo + ", maybe=" + (n - (numYes + numNo))); // Compute probabilities switch (solnMethod) { case VALUE_ITERATION: res = computeReachProbsValIter(stpg, no, yes, min1, min2, init, known); break; case GAUSS_SEIDEL: res = computeReachProbsGaussSeidel(stpg, no, yes, min1, min2, init, known); break; default: throw new PrismException("Unknown STPG solution method " + solnMethod); } // Finished probabilistic reachability timer = System.currentTimeMillis() - timer; if (verbosity >= 1) mainLog.println("Probabilistic reachability took " + timer / 1000.0 + " seconds."); // Update time taken res.timeTaken = timer / 1000.0; res.timeProb0 = timerProb0 / 1000.0; res.timePre = (timerProb0 + timerProb1) / 1000.0; return res; } /** * Prob0 precomputation algorithm. * i.e. determine the states of an STPG which, with min/max probability 0, * reach a state in {@code target}, while remaining in those in @{code remain}. * {@code min}=true gives Prob0E, {@code min}=false gives Prob0A. * @param stpg The STPG * @param remain Remain in these states (optional: null means "all") * @param target Target states * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) */ public BitSet prob0(STPG stpg, BitSet remain, BitSet target, boolean min1, boolean min2) { int n, iters; BitSet u, soln, unknown; boolean u_done; long timer; // Start precomputation timer = System.currentTimeMillis(); if (verbosity >= 1) mainLog.println("Starting Prob0 (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")..."); // Special case: no target states if (target.cardinality() == 0) { soln = new BitSet(stpg.getNumStates()); soln.set(0, stpg.getNumStates()); return soln; } // Initialise vectors n = stpg.getNumStates(); u = new BitSet(n); soln = new BitSet(n); // Determine set of states actually need to perform computation for unknown = new BitSet(); unknown.set(0, n); unknown.andNot(target); if (remain != null) unknown.and(remain); // Fixed point loop iters = 0; u_done = false; // Least fixed point - should start from 0 but we optimise by // starting from 'target', thus bypassing first iteration u.or(target); soln.or(target); while (!u_done) { iters++; // Single step of Prob0 stpg.prob0step(unknown, u, min1, min2, soln); // Check termination u_done = soln.equals(u); // u = soln u.clear(); u.or(soln); } // Negate u.flip(0, n); // Finished precomputation timer = System.currentTimeMillis() - timer; if (verbosity >= 1) { mainLog.print("Prob0 (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")"); mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds."); } return u; } /** * Prob1 precomputation algorithm. * i.e. determine the states of an STPG which, with min/max probability 1, * reach a state in {@code target}, while remaining in those in @{code remain}. * @param stpg The STPG * @param remain Remain in these states (optional: null means "all") * @param target Target states * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) */ public BitSet prob1(STPG stpg, BitSet remain, BitSet target, boolean min1, boolean min2) { int n, iters; BitSet u, v, soln, unknown; boolean u_done, v_done; long timer; // Start precomputation timer = System.currentTimeMillis(); if (verbosity >= 1) mainLog.println("Starting Prob1 (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")..."); // Special case: no target states if (target.cardinality() == 0) { return new BitSet(stpg.getNumStates()); } // Initialise vectors n = stpg.getNumStates(); u = new BitSet(n); v = new BitSet(n); soln = new BitSet(n); // Determine set of states actually need to perform computation for unknown = new BitSet(); unknown.set(0, n); unknown.andNot(target); if (remain != null) unknown.and(remain); // Nested fixed point loop iters = 0; u_done = false; // Greatest fixed point u.set(0, n); while (!u_done) { v_done = false; // Least fixed point - should start from 0 but we optimise by // starting from 'target', thus bypassing first iteration v.clear(); v.or(target); soln.clear(); soln.or(target); while (!v_done) { iters++; // Single step of Prob1 stpg.prob1step(unknown, u, v, min1, min2, soln); // Check termination (inner) v_done = soln.equals(v); // v = soln v.clear(); v.or(soln); } // Check termination (outer) u_done = v.equals(u); // u = v u.clear(); u.or(v); } // Finished precomputation timer = System.currentTimeMillis() - timer; if (verbosity >= 1) { mainLog.print("Prob1 (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")"); mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds."); } return u; } /** * Compute reachability probabilities using value iteration. * @param stpg The STPG * @param no Probability 0 states * @param yes Probability 1 states * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) * @param init Optionally, an initial solution vector (will be overwritten) * @param known Optionally, a set of states for which the exact answer is known * Note: if 'known' is specified (i.e. is non-null, 'init' must also be given and is used for the exact values. */ protected ModelCheckerResult computeReachProbsValIter(STPG stpg, BitSet no, BitSet yes, boolean min1, boolean min2, double init[], BitSet known) throws PrismException { ModelCheckerResult res = null; BitSet unknown; int i, n, iters; double soln[], soln2[], tmpsoln[], initVal; int adv[] = null; boolean genAdv, done; long timer; // Are we generating an optimal adversary? genAdv = exportAdv; // Start value iteration timer = System.currentTimeMillis(); if (verbosity >= 1) mainLog.println("Starting value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")..."); // Store num states n = stpg.getNumStates(); // Create solution vector(s) soln = new double[n]; soln2 = (init == null) ? new double[n] : init; // Initialise solution vectors. Use (where available) the following in order of preference: // (1) exact answer, if already known; (2) 1.0/0.0 if in yes/no; (3) passed in initial value; (4) initVal // where initVal is 0.0 or 1.0, depending on whether we converge from below/above. initVal = (valIterDir == ValIterDir.BELOW) ? 0.0 : 1.0; if (init != null) { if (known != null) { for (i = 0; i < n; i++) soln[i] = soln2[i] = known.get(i) ? init[i] : yes.get(i) ? 1.0 : no.get(i) ? 0.0 : init[i]; } else { for (i = 0; i < n; i++) soln[i] = soln2[i] = yes.get(i) ? 1.0 : no.get(i) ? 0.0 : init[i]; } } else { for (i = 0; i < n; i++) soln[i] = soln2[i] = yes.get(i) ? 1.0 : no.get(i) ? 0.0 : initVal; } // Determine set of states actually need to compute values for unknown = new BitSet(); unknown.set(0, n); unknown.andNot(yes); unknown.andNot(no); if (known != null) unknown.andNot(known); // Create/initialise adversary storage if (genAdv) { adv = new int[n]; for (i = 0; i < n; i++) { adv[i] = -1; } } // Start iterations iters = 0; done = false; while (!done && iters < maxIters) { iters++; // Matrix-vector multiply and min/max ops stpg.mvMultMinMax(soln, min1, min2, soln2, unknown, false, genAdv ? adv : null); // Check termination done = PrismUtils.doublesAreClose(soln, soln2, termCritParam, termCrit == TermCrit.ABSOLUTE); // Swap vectors for next iter tmpsoln = soln; soln = soln2; soln2 = tmpsoln; } // Finished value iteration timer = System.currentTimeMillis() - timer; if (verbosity >= 1) { mainLog.print("Value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")"); mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds."); } // Non-convergence is an error (usually) if (!done && errorOnNonConverge) { String msg = "Iterative method did not converge within " + iters + " iterations."; msg += "\nConsider using a different numerical method or increasing the maximum number of iterations"; throw new PrismException(msg); } // Print adversary if (genAdv) { PrismLog out = new PrismFileLog(exportAdvFilename); for (i = 0; i < n; i++) { out.println(i + " " + (adv[i] != -1 ? stpg.getAction(i, adv[i]) : "-")); } out.println(); out.close(); } // Return results res = new ModelCheckerResult(); res.soln = soln; res.numIters = iters; res.timeTaken = timer / 1000.0; return res; } /** * Compute reachability probabilities using Gauss-Seidel. * @param stpg The STPG * @param no Probability 0 states * @param yes Probability 1 states * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) * @param init Optionally, an initial solution vector (will be overwritten) * @param known Optionally, a set of states for which the exact answer is known * Note: if 'known' is specified (i.e. is non-null, 'init' must also be given and is used for the exact values. */ protected ModelCheckerResult computeReachProbsGaussSeidel(STPG stpg, BitSet no, BitSet yes, boolean min1, boolean min2, double init[], BitSet known) throws PrismException { ModelCheckerResult res; BitSet unknown; int i, n, iters; double soln[], initVal, maxDiff; boolean done; long timer; // Start value iteration timer = System.currentTimeMillis(); if (verbosity >= 1) mainLog.println("Starting value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")..."); // Store num states n = stpg.getNumStates(); // Create solution vector soln = (init == null) ? new double[n] : init; // Initialise solution vector. Use (where available) the following in order of preference: // (1) exact answer, if already known; (2) 1.0/0.0 if in yes/no; (3) passed in initial value; (4) initVal // where initVal is 0.0 or 1.0, depending on whether we converge from below/above. initVal = (valIterDir == ValIterDir.BELOW) ? 0.0 : 1.0; if (init != null) { if (known != null) { for (i = 0; i < n; i++) soln[i] = known.get(i) ? init[i] : yes.get(i) ? 1.0 : no.get(i) ? 0.0 : init[i]; } else { for (i = 0; i < n; i++) soln[i] = yes.get(i) ? 1.0 : no.get(i) ? 0.0 : init[i]; } } else { for (i = 0; i < n; i++) soln[i] = yes.get(i) ? 1.0 : no.get(i) ? 0.0 : initVal; } // Determine set of states actually need to compute values for unknown = new BitSet(); unknown.set(0, n); unknown.andNot(yes); unknown.andNot(no); if (known != null) unknown.andNot(known); // Start iterations iters = 0; done = false; while (!done && iters < maxIters) { iters++; // Matrix-vector multiply and min/max ops maxDiff = stpg.mvMultGSMinMax(soln, min1, min2, unknown, false, termCrit == TermCrit.ABSOLUTE); // Check termination done = maxDiff < termCritParam; } // Finished Gauss-Seidel timer = System.currentTimeMillis() - timer; if (verbosity >= 1) { mainLog.print("Value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")"); mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds."); } // Non-convergence is an error (usually) if (!done && errorOnNonConverge) { String msg = "Iterative method did not converge within " + iters + " iterations."; msg += "\nConsider using a different numerical method or increasing the maximum number of iterations"; throw new PrismException(msg); } // Return results res = new ModelCheckerResult(); res.soln = soln; res.numIters = iters; res.timeTaken = timer / 1000.0; return res; } /** * Construct strategy information for min/max reachability probabilities. * (More precisely, list of indices of player 1 choices resulting in min/max.) * (Note: indices are guaranteed to be sorted in ascending order.) * @param stpg The STPG * @param state The state to generate strategy info for * @param target The set of target states to reach * @param min1 Min or max probabilities for player 1 (true=min, false=max) * @param min2 Min or max probabilities for player 2 (true=min, false=max) * @param lastSoln Vector of probabilities from which to recompute in one iteration */ public List<Integer> probReachStrategy(STPG stpg, int state, BitSet target, boolean min1, boolean min2, double lastSoln[]) throws PrismException { double val = stpg.mvMultMinMaxSingle(state, lastSoln, min1, min2); return stpg.mvMultMinMaxSingleChoices(state, lastSoln, min1, min2, val); } /** * Compute bounded reachability probabilities. * i.e. compute the min/max probability of reaching a state in {@code target} within k steps. * @param stpg The STPG * @param target Target states * @param k Bound * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) */ public ModelCheckerResult computeBoundedReachProbs(STPG stpg, BitSet target, int k, boolean min1, boolean min2) throws PrismException { return computeBoundedReachProbs(stpg, null, target, k, min1, min2, null, null); } /** * Compute bounded until probabilities. * i.e. compute the min/max probability of reaching a state in {@code target}, * within k steps, and while remaining in states in @{code remain}. * @param stpg The STPG * @param remain Remain in these states (optional: null means "all") * @param target Target states * @param k Bound * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) */ public ModelCheckerResult computeBoundedUntilProbs(STPG stpg, BitSet remain, BitSet target, int k, boolean min1, boolean min2) throws PrismException { return computeBoundedReachProbs(stpg, remain, target, k, min1, min2, null, null); } /** * Compute bounded reachability/until probabilities. * i.e. compute the min/max probability of reaching a state in {@code target}, * within k steps, and while remaining in states in @{code remain}. * @param stpg The STPG * @param remain Remain in these states (optional: null means "all") * @param target Target states * @param k Bound * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound) * @param min2 Min or max probabilities for player 2 (true=min, false=max) * @param init Initial solution vector - pass null for default * @param results Optional array of size k+1 to store (init state) results for each step (null if unused) */ public ModelCheckerResult computeBoundedReachProbs(STPG stpg, BitSet remain, BitSet target, int k, boolean min1, boolean min2, double init[], double results[]) throws PrismException { // TODO: implement until ModelCheckerResult res = null; int i, n, iters; double soln[], soln2[], tmpsoln[]; long timer; // Start bounded probabilistic reachability timer = System.currentTimeMillis(); if (verbosity >= 1) mainLog.println("\nStarting bounded probabilistic reachability..."); // Store num states n = stpg.getNumStates(); // Create solution vector(s) soln = new double[n]; soln2 = (init == null) ? new double[n] : init; // Initialise solution vectors. Use passed in initial vector, if present if (init != null) { for (i = 0; i < n; i++) soln[i] = soln2[i] = target.get(i) ? 1.0 : init[i]; } else { for (i = 0; i < n; i++) soln[i] = soln2[i] = target.get(i) ? 1.0 : 0.0; } // Store intermediate results if required // (compute min/max value over initial states for first step) if (results != null) { results[0] = Utils.minMaxOverArraySubset(soln2, stpg.getInitialStates(), min2); } // Start iterations iters = 0; while (iters < k) { iters++; // Matrix-vector multiply and min/max ops stpg.mvMultMinMax(soln, min1, min2, soln2, target, true, null); // Store intermediate results if required // (compute min/max value over initial states for this step) if (results != null) { results[iters] = Utils.minMaxOverArraySubset(soln2, stpg.getInitialStates(), min2); } // Swap vectors for next iter tmpsoln = soln; soln = soln2; soln2 = tmpsoln; } // Print vector (for debugging) //mainLog.println(soln); // Finished bounded probabilistic reachability timer = System.currentTimeMillis() - timer; if (verbosity >= 1) { mainLog.print("Bounded probabilistic reachability (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")"); mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds."); } // Return results res = new ModelCheckerResult(); res.soln = soln; res.lastSoln = soln2; res.numIters = iters; res.timeTaken = timer / 1000.0; res.timePre = 0.0; return res; } /** * Compute expected reachability rewards. * @param stpg The STPG * @param rewards The rewards * @param target Target states * @param min1 Min or max rewards for player 1 (true=min, false=max) * @param min2 Min or max rewards for player 2 (true=min, false=max) */ public ModelCheckerResult computeReachRewards(STPG stpg, STPGRewards rewards, BitSet target, boolean min1, boolean min2) throws PrismException { return computeReachRewards(stpg, rewards, target, min1, min2, null, null); } /** * Compute expected reachability rewards. * i.e. compute the min/max reward accumulated to reach a state in {@code target}. * @param stpg The STPG * @param rewards The rewards * @param target Target states * @param min1 Min or max rewards for player 1 (true=min, false=max) * @param min2 Min or max rewards for player 2 (true=min, false=max) * @param init Optionally, an initial solution vector (may be overwritten) * @param known Optionally, a set of states for which the exact answer is known * Note: if 'known' is specified (i.e. is non-null, 'init' must also be given and is used for the exact values. */ public ModelCheckerResult computeReachRewards(STPG stpg, STPGRewards rewards, BitSet target, boolean min1, boolean min2, double init[], BitSet known) throws PrismException { ModelCheckerResult res = null; BitSet inf; int i, n, numTarget, numInf; long timer, timerProb1; // Start expected reachability timer = System.currentTimeMillis(); if (verbosity >= 1) mainLog.println("\nStarting expected reachability..."); // Check for deadlocks in non-target state (because breaks e.g. prob1) stpg.checkForDeadlocks(target); // Store num states n = stpg.getNumStates(); // Optimise by enlarging target set (if more info is available) if (init != null && known != null) { BitSet targetNew = new BitSet(n); for (i = 0; i < n; i++) { targetNew.set(i, target.get(i) || (known.get(i) && init[i] == 0.0)); } target = targetNew; } // Precomputation (not optional) timerProb1 = System.currentTimeMillis(); inf = prob1(stpg, null, target, !min1, !min2); inf.flip(0, n); timerProb1 = System.currentTimeMillis() - timerProb1; // Print results of precomputation numTarget = target.cardinality(); numInf = inf.cardinality(); if (verbosity >= 1) mainLog.println("target=" + numTarget + ", inf=" + numInf + ", rest=" + (n - (numTarget + numInf))); // Compute rewards switch (solnMethod) { case VALUE_ITERATION: res = computeReachRewardsValIter(stpg, rewards, target, inf, min1, min2, init, known); break; default: throw new PrismException("Unknown STPG solution method " + solnMethod); } // Finished expected reachability timer = System.currentTimeMillis() - timer; if (verbosity >= 1) mainLog.println("Expected reachability took " + timer / 1000.0 + " seconds."); // Update time taken res.timeTaken = timer / 1000.0; res.timePre = timerProb1 / 1000.0; return res; } /** * Compute expected reachability rewards using value iteration. * @param stpg The STPG * @param rewards The rewards * @param target Target states * @param inf States for which reward is infinite * @param min1 Min or max rewards for player 1 (true=min, false=max) * @param min2 Min or max rewards for player 2 (true=min, false=max) * @param init Optionally, an initial solution vector (will be overwritten) * @param known Optionally, a set of states for which the exact answer is known * Note: if 'known' is specified (i.e. is non-null, 'init' must also be given and is used for the exact values. */ protected ModelCheckerResult computeReachRewardsValIter(STPG stpg, STPGRewards rewards, BitSet target, BitSet inf, boolean min1, boolean min2, double init[], BitSet known) throws PrismException { ModelCheckerResult res; BitSet unknown; int i, n, iters; double soln[], soln2[], tmpsoln[]; boolean done; long timer; // Start value iteration timer = System.currentTimeMillis(); if (verbosity >= 1) mainLog.println("Starting value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")..."); // Store num states n = stpg.getNumStates(); // Create solution vector(s) soln = new double[n]; soln2 = (init == null) ? new double[n] : init; // Initialise solution vectors. Use (where available) the following in order of preference: // (1) exact answer, if already known; (2) 0.0/infinity if in target/inf; (3) passed in initial value; (4) 0.0 if (init != null) { if (known != null) { for (i = 0; i < n; i++) soln[i] = soln2[i] = known.get(i) ? init[i] : target.get(i) ? 0.0 : inf.get(i) ? Double.POSITIVE_INFINITY : init[i]; } else { for (i = 0; i < n; i++) soln[i] = soln2[i] = target.get(i) ? 0.0 : inf.get(i) ? Double.POSITIVE_INFINITY : init[i]; } } else { for (i = 0; i < n; i++) soln[i] = soln2[i] = target.get(i) ? 0.0 : inf.get(i) ? Double.POSITIVE_INFINITY : 0.0; } // Determine set of states actually need to compute values for unknown = new BitSet(); unknown.set(0, n); unknown.andNot(target); unknown.andNot(inf); if (known != null) unknown.andNot(known); // Start iterations iters = 0; done = false; while (!done && iters < maxIters) { //mainLog.println(soln); iters++; // Matrix-vector multiply and min/max ops stpg.mvMultRewMinMax(soln, rewards, min1, min2, soln2, unknown, false, null); // Check termination done = PrismUtils.doublesAreClose(soln, soln2, termCritParam, termCrit == TermCrit.ABSOLUTE); // Swap vectors for next iter tmpsoln = soln; soln = soln2; soln2 = tmpsoln; } // Finished value iteration timer = System.currentTimeMillis() - timer; if (verbosity >= 1) { mainLog.print("Value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")"); mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds."); } // Non-convergence is an error (usually) if (!done && errorOnNonConverge) { String msg = "Iterative method did not converge within " + iters + " iterations."; msg += "\nConsider using a different numerical method or increasing the maximum number of iterations"; throw new PrismException(msg); } // Return results res = new ModelCheckerResult(); res.soln = soln; res.numIters = iters; res.timeTaken = timer / 1000.0; return res; } /** * Simple test program. */ public static void main(String args[]) { STPGModelChecker mc; STPGAbstrSimple stpg; ModelCheckerResult res; BitSet target; Map<String, BitSet> labels; boolean min1 = true, min2 = true; try { mc = new STPGModelChecker(null); stpg = new STPGAbstrSimple(); stpg.buildFromPrismExplicit(args[0]); //System.out.println(stpg); labels = mc.loadLabelsFile(args[1]); //System.out.println(labels); target = labels.get(args[2]); if (target == null) throw new PrismException("Unknown label \"" + args[2] + "\""); for (int i = 3; i < args.length; i++) { if (args[i].equals("-minmin")) { min1 = true; min2 = true; } else if (args[i].equals("-maxmin")) { min1 = false; min2 = true; } else if (args[i].equals("-minmax")) { min1 = true; min2 = false; } else if (args[i].equals("-maxmax")) { min1 = false; min2 = false; } } //stpg.exportToDotFile("stpg.dot", target); //stpg.exportToPrismExplicit("stpg"); res = mc.computeReachProbs(stpg, target, min1, min2); System.out.println(res.soln[0]); } catch (PrismException e) { System.out.println(e); } } }
gpl-2.0
helloworld1/AnyMemo
app/src/main/java/org/liberty/android/fantastischmemo/utils/AMUiUtil.java
1574
/* Copyright (C) 2012 Haowen Ning 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.liberty.android.fantastischmemo.utils; import android.content.Context; import android.util.TypedValue; import org.liberty.android.fantastischmemo.modules.ForApplication; import javax.inject.Inject; /* * Util that is related to user interface. */ @ForApplication public class AMUiUtil { private Context mContext; @Inject public AMUiUtil(@ForApplication Context context) { mContext = context; } /* * Convert Pixel unit to DP unit. */ public int convertPxToDp(int px) { return (int)(px * mContext.getResources().getDisplayMetrics().density); } /* * Convert DP to Pixel */ public int convertDpToPx(int dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dp, mContext.getResources().getDisplayMetrics()); } }
gpl-2.0
shelan/jdk9-mirror
jaxws/src/java.xml.bind/share/classes/javax/xml/bind/ContextFinder.java
22680
/* * Copyright (c) 2003, 2015, 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 javax.xml.bind; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * This class is package private and therefore is not exposed as part of the * JAXB API. * * This code is designed to implement the JAXB 1.0 spec pluggability feature * * @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul> * @see JAXBContext */ class ContextFinder { /** * When JAXB is in J2SE, rt.jar has to have a JAXB implementation. * However, rt.jar cannot have META-INF/services/javax.xml.bind.JAXBContext * because if it has, it will take precedence over any file that applications have * in their jar files. * * <p> * When the user bundles his own JAXB implementation, we'd like to use it, and we * want the platform default to be used only when there's no other JAXB provider. * * <p> * For this reason, we have to hard-code the class name into the API. */ private static final String PLATFORM_DEFAULT_FACTORY_CLASS = "com.sun.xml.internal.bind.v2.ContextFactory"; private static final Logger logger; static { logger = Logger.getLogger("javax.xml.bind"); try { if (AccessController.doPrivileged(new GetPropertyAction("jaxb.debug")) != null) { // disconnect the logger from a bigger framework (if any) // and take the matters into our own hands logger.setUseParentHandlers(false); logger.setLevel(Level.ALL); ConsoleHandler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); logger.addHandler(handler); } else { // don't change the setting of this logger // to honor what other frameworks // have done on configurations. } } catch (Throwable t) { // just to be extra safe. in particular System.getProperty may throw // SecurityException. } } /** * If the {@link InvocationTargetException} wraps an exception that shouldn't be wrapped, * throw the wrapped exception. */ private static void handleInvocationTargetException(InvocationTargetException x) throws JAXBException { Throwable t = x.getTargetException(); if (t != null) { if (t instanceof JAXBException) // one of our exceptions, just re-throw throw (JAXBException) t; if (t instanceof RuntimeException) // avoid wrapping exceptions unnecessarily throw (RuntimeException) t; if (t instanceof Error) throw (Error) t; } } /** * Determine if two types (JAXBContext in this case) will generate a ClassCastException. * * For example, (targetType)originalType * * @param originalType * The Class object of the type being cast * @param targetType * The Class object of the type that is being cast to * @return JAXBException to be thrown. */ private static JAXBException handleClassCastException(Class originalType, Class targetType) { final URL targetTypeURL = which(targetType); return new JAXBException(Messages.format(Messages.ILLEGAL_CAST, // we don't care where the impl class is, we want to know where JAXBContext lives in the impl // class' ClassLoader getClassClassLoader(originalType).getResource("javax/xml/bind/JAXBContext.class"), targetTypeURL)); } /** * Create an instance of a class using the specified ClassLoader */ static JAXBContext newInstance(String contextPath, String className, ClassLoader classLoader, Map properties) throws JAXBException { try { Class spFactory = ServiceLoaderUtil.safeLoadClass(className, PLATFORM_DEFAULT_FACTORY_CLASS, classLoader); return newInstance(contextPath, spFactory, classLoader, properties); } catch (ClassNotFoundException x) { throw new JAXBException(Messages.format(Messages.PROVIDER_NOT_FOUND, className), x); } catch (RuntimeException x) { // avoid wrapping RuntimeException to JAXBException, // because it indicates a bug in this code. throw x; } catch (Exception x) { // can't catch JAXBException because the method is hidden behind // reflection. Root element collisions detected in the call to // createContext() are reported as JAXBExceptions - just re-throw it // some other type of exception - just wrap it throw new JAXBException(Messages.format(Messages.COULD_NOT_INSTANTIATE, className, x), x); } } static JAXBContext newInstance(String contextPath, Class spFactory, ClassLoader classLoader, Map properties) throws JAXBException { try { /* * javax.xml.bind.context.factory points to a class which has a * static method called 'createContext' that * returns a javax.xml.JAXBContext. */ Object context = null; // first check the method that takes Map as the third parameter. // this is added in 2.0. try { Method m = spFactory.getMethod("createContext", String.class, ClassLoader.class, Map.class); // any failure in invoking this method would be considered fatal context = m.invoke(null, contextPath, classLoader, properties); } catch (NoSuchMethodException e) { // it's not an error for the provider not to have this method. } if (context == null) { // try the old method that doesn't take properties. compatible with 1.0. // it is an error for an implementation not to have both forms of the createContext method. Method m = spFactory.getMethod("createContext", String.class, ClassLoader.class); // any failure in invoking this method would be considered fatal context = m.invoke(null, contextPath, classLoader); } if (!(context instanceof JAXBContext)) { // the cast would fail, so generate an exception with a nice message throw handleClassCastException(context.getClass(), JAXBContext.class); } return (JAXBContext) context; } catch (InvocationTargetException x) { handleInvocationTargetException(x); // for other exceptions, wrap the internal target exception // with a JAXBException Throwable e = x; if (x.getTargetException() != null) e = x.getTargetException(); throw new JAXBException(Messages.format(Messages.COULD_NOT_INSTANTIATE, spFactory, e), e); } catch (RuntimeException x) { // avoid wrapping RuntimeException to JAXBException, // because it indicates a bug in this code. throw x; } catch (Exception x) { // can't catch JAXBException because the method is hidden behind // reflection. Root element collisions detected in the call to // createContext() are reported as JAXBExceptions - just re-throw it // some other type of exception - just wrap it throw new JAXBException(Messages.format(Messages.COULD_NOT_INSTANTIATE, spFactory, x), x); } } /** * Create an instance of a class using the thread context ClassLoader */ static JAXBContext newInstance(Class[] classes, Map properties, String className) throws JAXBException { Class spi; try { spi = ServiceLoaderUtil.safeLoadClass(className, PLATFORM_DEFAULT_FACTORY_CLASS, getContextClassLoader()); } catch (ClassNotFoundException e) { throw new JAXBException(e); } if (logger.isLoggable(Level.FINE)) { // extra check to avoid costly which operation if not logged logger.log(Level.FINE, "loaded {0} from {1}", new Object[]{className, which(spi)}); } return newInstance(classes, properties, spi); } static JAXBContext newInstance(Class[] classes, Map properties, Class spFactory) throws JAXBException { try { Method m = spFactory.getMethod("createContext", Class[].class, Map.class); Object context = m.invoke(null, classes, properties); if (!(context instanceof JAXBContext)) { // the cast would fail, so generate an exception with a nice message throw handleClassCastException(context.getClass(), JAXBContext.class); } return (JAXBContext) context; } catch (NoSuchMethodException e) { throw new JAXBException(e); } catch (IllegalAccessException e) { throw new JAXBException(e); } catch (InvocationTargetException e) { handleInvocationTargetException(e); Throwable x = e; if (e.getTargetException() != null) x = e.getTargetException(); throw new JAXBException(x); } } static JAXBContext find(String factoryId, String contextPath, ClassLoader classLoader, Map properties) throws JAXBException { // TODO: do we want/need another layer of searching in $java.home/lib/jaxb.properties like JAXP? StringTokenizer packages = new StringTokenizer(contextPath, ":"); if (!packages.hasMoreTokens()) { // no context is specified throw new JAXBException(Messages.format(Messages.NO_PACKAGE_IN_CONTEXTPATH)); } // search for jaxb.properties in the class loader of each class first logger.fine("Searching jaxb.properties"); while (packages.hasMoreTokens()) { // com.acme.foo - > com/acme/foo/jaxb.properties String className = classNameFromPackageProperties(factoryId, classLoader, packages.nextToken(":").replace('.', '/')); if (className != null) return newInstance(contextPath, className, classLoader, properties); } String factoryName = classNameFromSystemProperties(); if (factoryName != null) return newInstance(contextPath, factoryName, classLoader, properties); Class ctxFactory = (Class) ServiceLoaderUtil.lookupUsingOSGiServiceLoader("javax.xml.bind.JAXBContext", logger); if (ctxFactory != null) { return newInstance(contextPath, ctxFactory, classLoader, properties); } // TODO: SPEC change required! This is supposed to be! // JAXBContext obj = firstByServiceLoader(JAXBContext.class, EXCEPTION_HANDLER); // if (obj != null) return obj; // TODO: Deprecated - SPEC change required! factoryName = firstByServiceLoaderDeprecated(JAXBContext.class, classLoader); if (factoryName != null) return newInstance(contextPath, factoryName, classLoader, properties); // else no provider found logger.fine("Trying to create the platform default provider"); return newInstance(contextPath, PLATFORM_DEFAULT_FACTORY_CLASS, classLoader, properties); } static JAXBContext find(Class[] classes, Map properties) throws JAXBException { // search for jaxb.properties in the class loader of each class first logger.fine("Searching jaxb.properties"); for (final Class c : classes) { // this classloader is used only to load jaxb.properties, so doing this should be safe. if (c.getPackage() == null) continue; // this is possible for primitives, arrays, and classes that are loaded by poorly implemented ClassLoaders // TODO: do we want to optimize away searching the same package? org.Foo, org.Bar, com.Baz // classes from the same package might come from different class loades, so it might be a bad idea // TODO: it's easier to look things up from the class // c.getResourceAsStream("jaxb.properties"); String className = classNameFromPackageProperties(JAXBContext.JAXB_CONTEXT_FACTORY, getClassClassLoader(c), c.getPackage().getName().replace('.', '/')); if (className != null) return newInstance(classes, properties, className); } String factoryName = classNameFromSystemProperties(); if (factoryName != null) return newInstance(classes, properties, factoryName); Class ctxFactoryClass = (Class) ServiceLoaderUtil.lookupUsingOSGiServiceLoader("javax.xml.bind.JAXBContext", logger); if (ctxFactoryClass != null) { return newInstance(classes, properties, ctxFactoryClass); } // TODO: to be removed - deprecated!!! Requires SPEC change!!! String className = firstByServiceLoaderDeprecated(JAXBContext.class, getContextClassLoader()); if (className != null) return newInstance(classes, properties, className); // // TODO: supposed to be: // obj = firstByServiceLoader(JAXBContext.class, EXCEPTION_HANDLER); // if (obj != null) return obj; // else no provider found logger.fine("Trying to create the platform default provider"); return newInstance(classes, properties, PLATFORM_DEFAULT_FACTORY_CLASS); } private static String classNameFromPackageProperties(String factoryId, ClassLoader classLoader, String packageName) throws JAXBException { String resourceName = packageName + "/jaxb.properties"; logger.log(Level.FINE, "Trying to locate {0}", resourceName); Properties props = loadJAXBProperties(classLoader, resourceName); if (props != null) { if (props.containsKey(factoryId)) { return props.getProperty(factoryId); } else { throw new JAXBException(Messages.format(Messages.MISSING_PROPERTY, packageName, factoryId)); } } return null; } private static String classNameFromSystemProperties() throws JAXBException { logger.log(Level.FINE, "Checking system property {0}", JAXBContext.JAXB_CONTEXT_FACTORY); // search for a system property second (javax.xml.bind.JAXBContext) String factoryClassName = AccessController.doPrivileged(new GetPropertyAction(JAXBContext.JAXB_CONTEXT_FACTORY)); if (factoryClassName != null) { logger.log(Level.FINE, " found {0}", factoryClassName); return factoryClassName; } else { // leave this here to assure compatibility logger.fine(" not found"); logger.log(Level.FINE, "Checking system property {0}", JAXBContext.class.getName()); factoryClassName = AccessController.doPrivileged(new GetPropertyAction(JAXBContext.class.getName())); if (factoryClassName != null) { logger.log(Level.FINE, " found {0}", factoryClassName); return factoryClassName; } else { logger.fine(" not found"); } } return null; } private static Properties loadJAXBProperties(ClassLoader classLoader, String propFileName) throws JAXBException { Properties props = null; try { URL url; if (classLoader == null) url = ClassLoader.getSystemResource(propFileName); else url = classLoader.getResource(propFileName); if (url != null) { logger.log(Level.FINE, "loading props from {0}", url); props = new Properties(); InputStream is = url.openStream(); props.load(is); is.close(); } } catch (IOException ioe) { logger.log(Level.FINE, "Unable to load " + propFileName, ioe); throw new JAXBException(ioe.toString(), ioe); } return props; } /** * Search the given ClassLoader for an instance of the specified class and * return a string representation of the URL that points to the resource. * * @param clazz * The class to search for * @param loader * The ClassLoader to search. If this parameter is null, then the * system class loader will be searched * @return * the URL for the class or null if it wasn't found */ static URL which(Class clazz, ClassLoader loader) { String classnameAsResource = clazz.getName().replace('.', '/') + ".class"; if (loader == null) { loader = getSystemClassLoader(); } return loader.getResource(classnameAsResource); } /** * Get the URL for the Class from it's ClassLoader. * * Convenience method for {@link #which(Class, ClassLoader)}. * * Equivalent to calling: which(clazz, clazz.getClassLoader()) * * @param clazz * The class to search for * @return * the URL for the class or null if it wasn't found */ static URL which(Class clazz) { return which(clazz, getClassClassLoader(clazz)); } @SuppressWarnings("unchecked") private static ClassLoader getContextClassLoader() { if (System.getSecurityManager() == null) { return Thread.currentThread().getContextClassLoader(); } else { return (ClassLoader) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { return Thread.currentThread().getContextClassLoader(); } }); } } @SuppressWarnings("unchecked") private static ClassLoader getClassClassLoader(final Class c) { if (System.getSecurityManager() == null) { return c.getClassLoader(); } else { return (ClassLoader) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { return c.getClassLoader(); } }); } } private static ClassLoader getSystemClassLoader() { if (System.getSecurityManager() == null) { return ClassLoader.getSystemClassLoader(); } else { return (ClassLoader) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { return ClassLoader.getSystemClassLoader(); } }); } } // TODO: to be removed - SPEC change required // ServiceLoaderUtil.firstByServiceLoaderDeprecated should be used instead. @Deprecated static String firstByServiceLoaderDeprecated(Class spiClass, ClassLoader classLoader) throws JAXBException { final String jaxbContextFQCN = spiClass.getName(); logger.fine("Searching META-INF/services"); // search META-INF services next BufferedReader r = null; final String resource = new StringBuilder().append("META-INF/services/").append(jaxbContextFQCN).toString(); try { final InputStream resourceStream = (classLoader == null) ? ClassLoader.getSystemResourceAsStream(resource) : classLoader.getResourceAsStream(resource); if (resourceStream != null) { r = new BufferedReader(new InputStreamReader(resourceStream, "UTF-8")); String factoryClassName = r.readLine(); if (factoryClassName != null) { factoryClassName = factoryClassName.trim(); } r.close(); logger.log(Level.FINE, "Configured factorty class:{0}", factoryClassName); return factoryClassName; } else { logger.log(Level.FINE, "Unable to load:{0}", resource); return null; } } catch (UnsupportedEncodingException e) { // should never happen throw new JAXBException(e); } catch (IOException e) { throw new JAXBException(e); } finally { try { if (r != null) { r.close(); } } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to close resource: " + resource, ex); } } } }
gpl-2.0
bkdonline/perfcenter
src/perfcenter/baseclass/Node.java
2909
/* * Copyright (C) 2011-12 by Varsha Apte - <varsha@cse.iitb.ac.in>, et al. * This file is distributed as part of PerfCenter * * 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 perfcenter.baseclass; import java.util.ArrayList; /** * This is used to make tree for a scenario * * @author akhila */ public class Node { public String name; /** probability of the node */ public Variable prob; /** packet size received from the parent(if thru network link) */ public Variable pktsize; /** set to true if an arc is defined as SYNC in input file */ public boolean issync; /** arrival rate to the node */ public double arrate; /** pointer to parent node */ public Node parent; /** server name the node/task belongs to */ public String servername = "none"; /** used when finding compound task */ public boolean isCT = false; /** set to true of node is of type root or branch(start of branch) */ public boolean isRoot = false; /** has the name of compound task this node is part of */ public String belongsToCT; /** a node can have list of children nodes */ public ArrayList<Node> children = new ArrayList<Node>(); public Node(String name1) { name = name1; } /** * * @param src name of the task * @param server name of the server on which task will happen * @param size packetsize * @param sync is this a synchronous task */ public Node(String src, String server, Variable size, boolean sync) { name = src; pktsize = size; issync = sync; if (server != null) { servername = server; } } public boolean isSync() { return issync; } // prints the node details public void print() { System.out.print(name + " prob " + prob.value + " sync:" + issync + " packet:" + pktsize.value + " arate:" + arrate + " servername:" + servername); if (parent != null) { System.out.println(" parent:" + parent.name); } else { System.out.println(" rootnode "); } } public Node getCopy() // added by niranjan { Node n = new Node(name, servername, pktsize, issync); n.arrate = this.arrate; n.belongsToCT = this.belongsToCT; n.isCT = this.isCT; n.isRoot = this.isRoot; n.parent = this.parent; n.prob = this.prob; for (Node child : this.children) { n.children.add(child); } return n; } }
gpl-2.0