answer
stringlengths
17
10.2M
package org.xbill.DNS; import java.io.*; import java.util.*; /** * A DNS Zone. This encapsulates all data related to a Zone, and provides * convenient lookup methods. * * @author Brian Wellington */ public class Zone extends NameSet { class ZoneIterator implements Iterator { private Iterator znames; private Name nextName; private Object [] current; int count; boolean wantLastSOA; ZoneIterator(boolean axfr) { znames = names(); wantLastSOA = axfr; Object [] sets = findExactSets(origin); current = new Object[sets.length]; for (int i = 0, j = 2; i < sets.length; i++) { int type = ((RRset) sets[i]).getType(); if (type == Type.SOA) current[0] = sets[i]; else if (type == Type.NS) current[1] = sets[i]; else current[j++] = sets[i]; } } public boolean hasNext() { return (current != null || wantLastSOA); } public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } if (current == null && wantLastSOA) { wantLastSOA = false; return (RRset) findExactSet(origin, Type.SOA); } Object set = current[count++]; if (count == current.length) { nextName = null; current = null; while (znames.hasNext()) { Name name = (Name) znames.next(); if (name.equals(origin)) continue; Object [] sets = findExactSets(name); if (sets.length == 0) continue; nextName = name; current = sets; count = 0; break; } } return set; } public void remove() { throw new UnsupportedOperationException(); } } /** A primary zone */ public static final int PRIMARY = 1; /** A secondary zone */ public static final int SECONDARY = 2; private int type; private Name origin; private int dclass = DClass.IN; private RRset NS; private SOARecord SOA; private boolean hasWild; private void validate() throws IOException { RRset rrset = (RRset) findExactSet(origin, Type.SOA); if (rrset == null || rrset.size() != 1) throw new IOException(origin + ": exactly 1 SOA must be specified"); Iterator it = rrset.rrs(); SOA = (SOARecord) it.next(); NS = (RRset) findExactSet(origin, Type.NS); if (NS == null) throw new IOException(origin + ": no NS set specified"); } private final void maybeAddRecord(Record record, Cache cache, Object source) throws IOException { int type = record.getType(); Name name = record.getName(); if (origin == null) { if (type == Type.SOA) { origin = name; setOrigin(origin); } else { throw new IOException("non-SOA record seen at " + name + " with no origin set"); } } if (type == Type.SOA && !name.equals(origin)) { throw new IOException("SOA owner " + name + " does not match zone origin " + origin); } if (name.subdomain(origin)) addRecord(record); else if (cache != null) cache.addRecord(record, Credibility.GLUE, source); } /** * Creates a Zone from the records in the specified master file. All * records that do not belong in the Zone are added to the specified Cache, * if the Cache is not null. * @see Cache * @see Master */ public Zone(String file, Cache cache, Name initialOrigin) throws IOException { super(false); Master m = new Master(file, initialOrigin); Record record; origin = initialOrigin; if (origin != null) setOrigin(origin); while ((record = m.nextRecord()) != null) maybeAddRecord(record, cache, file); validate(); } /** * Creates a Zone from an array of records. All records that do not belong * in the Zone are added to the specified Cache, if the Cache is not null. * @see Cache * @see Master */ public Zone(Record [] records, Cache cache, Name initialOrigin) throws IOException { super(false); origin = initialOrigin; if (origin != null) setOrigin(origin); for (int i = 0; i < records.length; i++) { maybeAddRecord(records[i], cache, records); } validate(); } /** * Creates a Zone from the records in the specified master file. All * records that do not belong in the Zone are added to the specified Cache, * if the Cache is not null. * @see Cache * @see Master */ public Zone(String file, Cache cache) throws IOException { this(file, cache, null); } public void fromXFR(Name zone, int dclass, String remote) throws IOException, ZoneTransferException { if (!zone.isAbsolute()) throw new RelativeNameException(zone); DClass.check(dclass); origin = zone; setOrigin(origin); this.dclass = dclass; type = SECONDARY; ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(zone, remote, null); List records = xfrin.run(); for (Iterator it = records.iterator(); it.hasNext(); ) { Record rec = (Record) it.next(); if (!rec.getName().subdomain(origin)) { if (Options.check("verbose")) System.err.println(rec.getName() + "is not in zone " + origin); continue; } addRecord(rec); } validate(); } /** * Creates a Zone by performing a zone transfer to the specified host. * @see Master */ public Zone(Name zone, int dclass, String remote) throws IOException, ZoneTransferException { super(false); fromXFR(zone, dclass, remote); } /** * Creates a Zone by performing a zone transfer to the specified host. * The cache is unused. * @see Master */ public Zone(Name zone, int dclass, String remote, Cache cache) throws IOException { super(false); DClass.check(dclass); try { fromXFR(zone, dclass, remote); } catch (ZoneTransferException e) { throw new IOException(e.getMessage()); } } /** Returns the Zone's origin */ public Name getOrigin() { return origin; } /** Returns the Zone origin's NS records */ public RRset getNS() { return NS; } /** Returns the Zone's SOA record */ public SOARecord getSOA() { return SOA; } /** Returns the Zone's class */ public int getDClass() { return dclass; } /** * Looks up Records in the Zone. This follows CNAMEs and wildcards. * @param name The name to look up * @param type The type to look up * @return A SetResponse object * @see SetResponse */ public SetResponse findRecords(Name name, int type) { SetResponse zr = null; Object o = lookup(name, type); if (o == null) { /* The name does not exist */ if (name.isWild() || !hasWild) return SetResponse.ofType(SetResponse.NXDOMAIN); int labels = name.labels() - origin.labels(); SetResponse sr; Name tname = name; do { sr = findRecords(tname.wild(1), type); if (!sr.isNXDOMAIN()) return sr; tname = new Name(tname, 1); } while (labels return SetResponse.ofType(SetResponse.NXDOMAIN); } else if (o == NXRRSET) { /* The name exists but the type does not. */ return SetResponse.ofType(SetResponse.NXRRSET); } Object [] objects; RRset rrset; if (o instanceof RRset) { objects = null; rrset = (RRset) o; } else { objects = (Object []) o; rrset = (RRset) objects[0]; } if (name.equals(rrset.getName())) { if (type != Type.CNAME && type != Type.ANY && rrset.getType() == Type.CNAME) zr = new SetResponse(SetResponse.CNAME, rrset); else if (rrset.getType() == Type.NS && !name.equals(origin)) zr = new SetResponse(SetResponse.DELEGATION, rrset); else { zr = new SetResponse(SetResponse.SUCCESSFUL); zr.addRRset(rrset); if (objects != null) { for (int i = 1; i < objects.length; i++) zr.addRRset((RRset)objects[i]); } } } else { if (rrset.getType() == Type.CNAME) zr = SetResponse.ofType(SetResponse.NXDOMAIN); else if (rrset.getType() == Type.DNAME) zr = new SetResponse(SetResponse.DNAME, rrset); else if (rrset.getType() == Type.NS) zr = new SetResponse(SetResponse.DELEGATION, rrset); } return zr; } /** * Looks up Records in the zone, finding exact matches only. * @param name The name to look up * @param type The type to look up * @return The matching RRset * @see RRset */ public RRset findExactMatch(Name name, int type) { return (RRset) findExactSet(name, type); } /** * Adds a record to the Zone * @param r The record to be added * @see Record */ public void addRecord(Record r) { Name name = r.getName(); int type = r.getRRsetType(); RRset rrset = (RRset) findExactSet (name, type); if (rrset == null) addSet(name, type, rrset = new RRset()); rrset.addRR(r); } /** * Adds a set associated with a name/type. The data contained in the * set is abstract. */ protected void addSet(Name name, int type, TypedObject set) { if (!hasWild && name.isWild()) hasWild = true; super.addSet(name, type, set); } /** * Removes a record from the Zone * @param r The record to be removed * @see Record */ public void removeRecord(Record r) { Name name = r.getName(); int type = r.getRRsetType(); RRset rrset = (RRset) findExactSet (name, type); if (rrset != null) { rrset.deleteRR(r); if (rrset.size() == 0) removeSet(name, type, rrset); } } /** * Returns an Iterator over the RRsets in the zone. */ public Iterator iterator() { return new ZoneIterator(false); } /** * Returns an Iterator over the RRsets in the zone that can be used to * construct an AXFR response. This is identical to {@link #iterator} except * that the SOA is returned at the end as well as the beginning. */ public Iterator AXFR() { return new ZoneIterator(true); } /** * Returns the contents of a Zone in master file format. */ public String toMasterFile() { Iterator znames = names(); StringBuffer sb = new StringBuffer(); while (znames.hasNext()) { Name name = (Name) znames.next(); Object [] sets = findExactSets(name); for (int i = 0; i < sets.length; i++) { RRset rrset = (RRset) sets[i]; Iterator it = rrset.rrs(); while (it.hasNext()) sb.append(it.next() + "\n"); it = rrset.sigs(); while (it.hasNext()) sb.append(it.next() + "\n"); } } return sb.toString(); } }
package org.eclipse.birt.report.model.api; import java.util.Iterator; import java.util.List; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.command.PropertyNameException; import org.eclipse.birt.report.model.api.core.IStructure; import org.eclipse.birt.report.model.api.elements.structures.StyleRule; import org.eclipse.birt.report.model.api.metadata.IElementPropertyDefn; import org.eclipse.birt.report.model.api.metadata.IPropertyType; import org.eclipse.birt.report.model.api.metadata.IStructureDefn; import org.eclipse.birt.report.model.api.metadata.PropertyValueException; import org.eclipse.birt.report.model.command.ComplexPropertyCommand; import org.eclipse.birt.report.model.core.DesignElement; import org.eclipse.birt.report.model.core.MemberRef; import org.eclipse.birt.report.model.core.Module; import org.eclipse.birt.report.model.core.Structure; import org.eclipse.birt.report.model.core.StructureContext; import org.eclipse.birt.report.model.metadata.ElementPropertyDefn; import org.eclipse.birt.report.model.metadata.PropertyDefn; import org.eclipse.birt.report.model.metadata.StructPropertyDefn; import org.eclipse.birt.report.model.util.ModelUtil; import org.eclipse.birt.report.model.util.StructureContextUtil; import com.ibm.icu.util.ULocale; /** * Handle to a structure within a list property. List properties contain objects * called structures. Structures have <em>members</em> that hold data values. * * @see MemberHandle */ public class StructureHandle extends ValueHandle { /** * Reference to the structure. */ protected StructureContext structContext; /** * Constructs a handle for a structure within a list property of a given * element. * * @param element * handle to the report element. * @param context * context of the structure */ public StructureHandle( DesignElementHandle element, StructureContext context ) { super( element ); structContext = context; checkValidation( ); } /** * Constructs a handle for a structure within a list property of a given * element. * * @param element * handle to the report element. * @param ref * reference to the structure * @deprecated */ public StructureHandle( DesignElementHandle element, MemberRef ref ) { super( element ); if ( ref == null ) throw new IllegalArgumentException( "The member reference can not be null when creating the structure handle." ); //$NON-NLS-1$ structContext = ref.getContext( ); checkValidation( ); } /** * Constructs a handle for a structure within a list property or a structure * member. * * @param valueHandle * handle to a list property or member * @param index * index of the structure within the list */ public StructureHandle( SimpleValueHandle valueHandle, int index ) { super( valueHandle.getElementHandle( ) ); StructureContext context = valueHandle.getContext( ); assert context.isListRef( ); assert context.getPropDefn( ).getTypeCode( ) == IPropertyType.STRUCT_TYPE; Object value = context.getValue( valueHandle.getModule( ) ); if ( value instanceof Structure ) { assert index == 0; this.structContext = ( (Structure) value ).getContext( ); } else if ( value instanceof List ) { List valueList = (List) value; assert index >= 0 && index < valueList.size( ); Object item = valueList.get( index ); assert item instanceof Structure; this.structContext = ( (Structure) item ).getContext( ); } else { assert false; } checkValidation( ); } private void checkValidation( ) { if ( structContext == null ) throw new IllegalArgumentException( "The context can not be null when creating a structure handle!" ); //$NON-NLS-1$ assert structContext.getStructure( ) != null; } // Implementation of abstract method defined in base class. public IElementPropertyDefn getPropertyDefn( ) { return structContext.getElementProp( ); } /** * Returns the structure. The application can cast this to the specific * structure type to query the structure directly. Note: do not modify the * structure directly; use the <code>MemberHandle</code> class for all * modifications. * * @return the structure */ public IStructure getStructure( ) { Structure struct = structContext.getStructure( ); // user may cache this structure handle, when the structure is removed, // we must return null; in another word, if the structure has no // context, return null if ( struct.getContext( ) == null ) return null; return struct; } /** * Gets the value of a member. * * @param memberName * name of the member to get * @return String value of the member, or <code>null</code> if the member is * not set or is not found. */ public Object getProperty( String memberName ) { MemberHandle handle = getMember( memberName ); if ( handle == null ) return null; return handle.getValue( ); } /** * Get the string value of a member. * * @param memberName * name of the member to get * @return String value of the member, or <code>null</code> if the member is * not set or is not found. */ protected String getStringProperty( String memberName ) { if ( !StructureContextUtil.isValidStructureHandle( this ) ) { throw new RuntimeException( "The structure is floating, and its handle is invalid!" ); //$NON-NLS-1$ } Structure struct = null; Module module = getModule( ); DesignElement target = structContext.getElement( ); DesignElement element = getElement( ); ElementPropertyDefn propDefn = structContext.getElementProp( ); if ( target == element || ( propDefn != null && element.getLocalProperty( module, propDefn ) == null ) ) { // the structContext cached in this handle is valid: the context // element is the same as this handle element, or this handle // element has no local value struct = (Structure) getStructure( ); } else { // the structContext cached in this handle is invalid for some // command change, therefore we must update and get the new context StructureContext targetContext = StructureContextUtil .getLocalStructureContext( module, element, structContext ); if ( targetContext != null ) struct = targetContext.getStructure( ); } if ( struct == null ) return null; PropertyDefn defn = (PropertyDefn) struct.getMemberDefn( memberName ); if ( defn == null ) return null; Object value = struct.getProperty( module, defn ); if ( value == null ) return null; return defn.getStringValue( module, value ); } /** * Get the integer value of a member. * * @param memberName * name of the member to get * @return integer value of the member, or <code>0</code> if the member is * not set or is not defined. */ protected int getIntProperty( String memberName ) { MemberHandle handle = getMember( memberName ); if ( handle == null ) return 0; return handle.getIntValue( ); } /** * Sets the value of the member. * * @param memberName * name of the member to set. * @param value * the value to set * @throws SemanticException * if the member name is not defined on the structure or the * value is not valid for the member. */ public void setProperty( String memberName, Object value ) throws SemanticException { MemberHandle memberHandle = getMember( memberName ); if ( memberHandle == null ) throw new PropertyNameException( getElement( ), getStructure( ), memberName ); memberHandle.setValue( value ); } /** * Set the value of a member without throwing exceptions. That is the set * operation should not failed. This method is designed to be called by the * sub-class where that it is certain that a set operation should never * failed. * <p> * Note that this method will internal swallow exceptions thrown when * performing the set operation. The exception will be deemed as internal * error. So calling this method when you are sure that exception is a * programming error. * * @param memberName * name of the member to set. * @param value * value to set. * */ protected final void setPropertySilently( String memberName, Object value ) { try { setProperty( memberName, value ); } catch ( SemanticException e ) { assert false; } } /** * Returns the definition of the structure. * * @return the structure definition */ public IStructureDefn getDefn( ) { return structContext.getStructDefn( ); } /** * Returns a handle to a structure member. * * @param memberName * the name of the member * @return a handle to the member or <code>null</code> if the member is not * defined on the structure. */ public MemberHandle getMember( String memberName ) { StructPropertyDefn memberDefn = (StructPropertyDefn) getDefn( ) .getMember( memberName ); if ( memberDefn == null ) return null; return new MemberHandle( this, memberDefn ); } /** * Returns an iterator over the members of this structure. The iterator is * of type <code>MemberIterator</code>. * * @return an iterator over the members of the structure. * @see MemberIterator */ public Iterator iterator( ) { return new MemberIterator( this ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.ValueHandle#getContext() */ public StructureContext getContext( ) { return structContext; } /** * Removes this structure from a list property or member. Once the structure * is dropped, the handle should not be used to do any setter operations. * * @throws PropertyValueException * if the structure is not contained in the list. */ public void drop( ) throws PropertyValueException { Structure struct = (Structure) getStructure( ); ComplexPropertyCommand cmd = new ComplexPropertyCommand( getModule( ), getElement( ) ); cmd.removeItem( struct.getContext( ), struct ); } /** * Returns externalized message. * * @param textIDProp * name of the property that defines the message key * @param textProp * name of the property that defines the default non-externalized * value if the key is not found in message file * @return externalized message if found, otherwise return the default * non-externalized value defined by property <code>textProp</code> */ public String getExternalizedValue( String textIDProp, String textProp ) { return ModelUtil .getExternalizedStructValue( getElement( ).getRoot( ), getStructure( ), textIDProp, textProp, getModule( ) .getLocale( ) ); } /** * Returns the externalized message. * * @param textIDProp * name of the property that defines the message key * @param textProp * name of the property that defines the default non-externalized * value if the key is not found in message file * @param locale * the user-defined locale * @return externalized message if found, otherwise return the default * non-externalized value defined by property <code>textProp</code> */ public String getExternalizedValue( String textIDProp, String textProp, ULocale locale ) { return ModelUtil.getExternalizedStructValue( getElement( ).getRoot( ), getStructure( ), textIDProp, textProp, locale ); } /** * Justifies whether this structure handle is generated in design time. * * @return <true> if the structure handle is generated in design time, * otherwise return <false>. */ public boolean isDesignTime( ) { return getStructure( ).isDesignTime( ); } /** * * @param isDesignTime * @throws SemanticException */ public void setDesignTime( boolean isDesignTime ) throws SemanticException { MemberHandle memberHandle = getMember( StyleRule.IS_DESIGN_TIME_MEMBER ); if ( memberHandle != null ) memberHandle.setValue( Boolean.valueOf( isDesignTime ) ); } /** * Sets the value of the member as an expression. * * @param memberName * name of the member to set. * @param value * the expression to set * @throws SemanticException * if the member name is not defined on the structure or the * value is not valid for the member. */ public void setExpressionProperty( String memberName, Expression value ) throws SemanticException { setProperty( memberName, value ); } /** * Gets the value of the member as an expression. * * @param memberName * name of the member to set. * @return the expression * @throws SemanticException * if the member name is not defined on the structure or the * value is not valid for the member. */ public ExpressionHandle getExpressionProperty( String memberName ) { PropertyDefn defn = (PropertyDefn) getDefn( ).getMember( memberName ); if ( defn == null ) return null; if ( defn.allowExpression( ) && !defn.isListType( ) ) return new ExpressionHandle( getElementHandle( ), StructureContextUtil.createStructureContext( this, memberName ) ); return null; } }
package net.anotheria.moskito.webui.shared.action; import net.anotheria.anoplass.api.APICallContext; import net.anotheria.anoplass.api.session.APISession; import net.anotheria.maf.action.AbortExecutionException; import net.anotheria.maf.action.Action; import net.anotheria.maf.action.ActionMapping; import net.anotheria.moskito.core.decorators.DecoratorRegistryFactory; import net.anotheria.moskito.core.decorators.IDecoratorRegistry; import net.anotheria.moskito.core.stats.TimeUnit; import net.anotheria.moskito.core.threshold.ThresholdStatus; import net.anotheria.moskito.webui.Features; import net.anotheria.moskito.webui.MoSKitoWebUIContext; import net.anotheria.moskito.webui.accumulators.api.AccumulatorAPI; import net.anotheria.moskito.webui.dashboards.api.DashboardAPI; import net.anotheria.moskito.webui.gauges.api.GaugeAPI; import net.anotheria.moskito.webui.journey.api.JourneyAPI; import net.anotheria.moskito.webui.producers.api.ProducerAPI; import net.anotheria.moskito.webui.shared.annotations.BetaAction; import net.anotheria.moskito.webui.shared.api.AdditionalFunctionalityAPI; import net.anotheria.moskito.webui.shared.bean.LabelValueBean; import net.anotheria.moskito.webui.shared.bean.NaviItem; import net.anotheria.moskito.webui.shared.bean.UnitBean; import net.anotheria.moskito.webui.threshold.api.ThresholdAPI; import net.anotheria.moskito.webui.tracers.api.TracerAPI; import net.anotheria.moskito.webui.util.APILookupUtility; import net.anotheria.moskito.webui.util.ConnectivityMode; import net.anotheria.moskito.webui.util.RemoteInstance; import net.anotheria.moskito.webui.util.WebUIConfig; import net.anotheria.moskito.webui.util.DeepLinkUtil; import net.anotheria.util.NumberUtils; import net.anotheria.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; /** * BaseAction providing some common functionality for all moskitouiactions. * @author another * */ public abstract class BaseMoskitoUIAction implements Action{ /** * Constant for the forward parameter. */ public static final String PARAM_FORWARD = "pForward"; /** * Default forward parameter if no forward has been specified. */ public static final String DEFAULT_FORWARD = "html"; /** * Bean name for currently selected interval. */ public static final String BEAN_INTERVAL = "moskito.CurrentInterval"; /** * Parameter name for the interval. */ public static final String PARAM_INTERVAL = "pInterval"; /** * Default interval name. */ public static final String DEFAULT_INTERVAL = "default"; /** * Bean name for currently selected unit. */ public static final String BEAN_UNIT = "moskito.CurrentUnit"; /** * Param for unit. */ public static final String PARAM_UNIT = "pUnit"; /** * Default unit. */ public static final String DEFAULT_UNIT = "millis"; /** * General id parameter, for example for accumulators or thresholds. */ public static final String PARAM_ID = "pId"; /** * Parameter producer id. */ public static final String PARAM_PRODUCER_ID = "pProducerId"; /** * Parameter for producer category. */ public static final String PARAM_CATEGORY = "pCategory"; /** * Parameter for producer subsystem. */ public static final String PARAM_SUBSYSTEM = "pSubsystem"; /** * Parameter for producer's decorator. */ public static final String PARAM_DECORATOR = "pDecorator"; /** * SortBy usually accompanied by an integer that defines the sort method. */ public static final String PARAM_SORT_BY = "pSortBy"; /** * Sort order, ASC or DESC. */ public static final String PARAM_SORT_ORDER = "pSortOrder"; /** * If set (to true) the zero request values will be removed from producer presentation. */ public static final String PARAM_FILTER_ZERO = "pFilterZero"; /** * Reload interval. */ public static final String PARAM_RELOAD_INTERVAL = "pReloadInterval"; /** * Currently set autoreload interval. Session attribute. */ public static final String BEAN_AUTORELOAD = "autoreloadInterval"; /** * Attribute name for indication if menu navigation is collapsed or not. */ public static final String ATTR_IS_NAV_MENU_COLLAPSED = "isNavMenuCollapsed"; /** * Default title string for the web page &lt;title$gt; element. */ public static final String DEFAULT_TITLE = "MoSKito Inspect"; /** * If set to off the configured filtering of producer names will be switched off. */ public static final String PARAM_FILTERING = "pFiltering"; /** * Value that switches filtering feature off. */ public static final String PARAM_VALUE_FILTER_OFF = "off"; /** * Cumulated caption value. */ public static final String CUMULATED_STAT_NAME_VALUE = "cumulated"; /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(BaseMoskitoUIAction.class); /** * Available units. */ static final UnitBean[] AVAILABLE_UNITS = { new UnitBean(TimeUnit.SECONDS), new UnitBean(TimeUnit.MILLISECONDS), new UnitBean(TimeUnit.MICROSECONDS), new UnitBean(TimeUnit.NANOSECONDS), }; /** * Default unit. */ public static final UnitBean DEFAULT_UNIT_BEAN = AVAILABLE_UNITS[1]; //millis /** * List of the available units. */ public static final List<UnitBean> AVAILABLE_UNITS_LIST = Arrays.asList(AVAILABLE_UNITS); /** * Stored sort type bean prefix name. */ public static final String BEAN_SORT_TYPE_PREFIX = "moskito.SortType"; /** * Prefix for producer sort type session storage. */ public static final String BEAN_SORT_TYPE_SINGLE_PRODUCER_PREFIX = BEAN_SORT_TYPE_PREFIX+".single"; /** * Instance of the decorator registry. */ private static IDecoratorRegistry decoratorRegistry; public static final char[] WHITESPACES = { ' ', '\r','\n','\t','\'','"','<','>' }; /** * ProducerId for moskito. */ private String myProducerId; static{ decoratorRegistry = DecoratorRegistryFactory.getDecoratorRegistry(); } /** * Creates a new action. */ protected BaseMoskitoUIAction(){ super(); } public String getSubsystem(){ return "moskitoUI"; } public String getProducerId(){ if (myProducerId==null) myProducerId = "moskito."+getClass().getName().substring(getClass().getName().lastIndexOf('.')+1); return myProducerId; } /** * Returns the specified forward. * @param req * @return */ protected String getForward(HttpServletRequest req){ String forward = req.getParameter(PARAM_FORWARD); if (forward==null) forward = DEFAULT_FORWARD; return forward; } /** * Returns the currently selected interval, either as parameter or from session. * @param req * @return */ protected String getCurrentInterval(HttpServletRequest req){ return getCurrentInterval(req, true); } /** * Returns the currently selected interval, either as parameter or from session. * @param req * @param saveToSession - if true the value from request will be stored to session. * @return */ protected String getCurrentInterval(HttpServletRequest req, boolean saveToSession){ String intervalParameter = req.getParameter(PARAM_INTERVAL); String interval = intervalParameter; if (interval==null){ interval = (String)req.getSession().getAttribute(BEAN_INTERVAL); if (interval == null) interval = DEFAULT_INTERVAL; } if (intervalParameter!=null && saveToSession) req.getSession().setAttribute(BEAN_INTERVAL, interval); return interval; } /** * Returns the currently selected unit either from request or session. * @param req * @return */ protected UnitBean getCurrentUnit(HttpServletRequest req){ return getCurrentUnit(req, true); } /** * Returns the currently selected unit either from request or session. * @param req * @param saveToSession - if true the request parameter will be saved into session. * @return */ protected UnitBean getCurrentUnit(HttpServletRequest req, boolean saveToSession){ String unitParameter = req.getParameter(PARAM_UNIT); if (unitParameter==null){ UnitBean ret = (UnitBean)req.getSession().getAttribute(BEAN_UNIT); if (ret==null){ ret = DEFAULT_UNIT_BEAN; //ensure a unit bean is always in the session. req.getSession().setAttribute(BEAN_UNIT, ret); } return ret; } int index = -1; for (int i = 0; i<AVAILABLE_UNITS_LIST.size(); i++){ if (AVAILABLE_UNITS_LIST.get(i).getUnitName().equalsIgnoreCase(unitParameter)){ index = i; break; } } UnitBean ret = index == -1 ? DEFAULT_UNIT_BEAN : AVAILABLE_UNITS[index]; if (saveToSession) req.getSession().setAttribute(BEAN_UNIT, ret); return ret; } protected void prepareBasics(HttpServletRequest req){ String currentIntervalName = getCurrentInterval(req); MoSKitoWebUIContext context = MoSKitoWebUIContext.getCallContextAndReset(); context.setCurrentIntervalName(currentIntervalName); context.setCurrentSession(req.getSession()); String paramFilteringOff = req.getParameter(PARAM_FILTERING); if (paramFilteringOff!=null && paramFilteringOff.equals(PARAM_VALUE_FILTER_OFF)) context.addAttribute(Features.PRODUCER_FILTERING.name(), Boolean.FALSE); //we need to set navi/subnavi item to none, in order to prevent exceptions in rendering of the menu. NaviItem currentNaviItem = getCurrentNaviItem(); if (currentNaviItem==null) currentNaviItem = NaviItem.NONE; req.setAttribute("currentNaviItem", currentNaviItem); NaviItem currentSubNaviItem = getCurrentSubNaviItem(); if (currentSubNaviItem==null) currentSubNaviItem = NaviItem.NONE; req.setAttribute("currentSubNaviItem", currentSubNaviItem); ////////////// prepare units req.setAttribute("units", AVAILABLE_UNITS_LIST); //ensure current unit is properly set. context.setCurrentTimeUnit(getCurrentUnit(req).getUnit()); //Link to current page req.setAttribute("linkToCurrentPage", DeepLinkUtil.makeDeepLink(getLinkToCurrentPage(req))); req.setAttribute("linkToCurrentPageAsXml", maskAsXML(getLinkToCurrentPage(req))); req.setAttribute("linkToCurrentPageAsCsv", maskAsCSV(getLinkToCurrentPage(req))); req.setAttribute("linkToCurrentPageAsJson", maskAsJSON(getLinkToCurrentPage(req))); // Link to remote monitoring connection req.setAttribute("remoteLink", DeepLinkUtil.getCurrentRemoteConnectionLink()); req.setAttribute("betaMode", WebUIConfig.getInstance().isBetaMode()); } /** * Acquire remote connection url from request parameter. * If current user is not connected to application * from url - moskito will be connected to this application. * This made up for possibility to share links on moskito-inspect pages. * * This method expects, that request will contain `remoteConnection` parameter * with value contains host and port separated by column. Example : `localhost:9401`. * If request have no such parameter - current connection will not be changed. * * @param req current request object */ private void fetchRemoteConnectionFromUrl(HttpServletRequest req){ String connection = req.getParameter("remoteConnection"); if(connection != null) try { connection = URLDecoder.decode(connection, "UTF-8"); } catch (UnsupportedEncodingException e) { return; } else return; String[] remoteHostAndPort; if( (remoteHostAndPort = connection.split(":")).length == 2 ){ String remoteHost = remoteHostAndPort[0]; int remotePort; try { remotePort = Integer.valueOf(remoteHostAndPort[1]); }catch (NumberFormatException e){ return; } try { if (!APILookupUtility.isLocal() && APILookupUtility.getCurrentRemoteInstance().equalsByKey(remoteHost + '-' + remotePort)) return; // Current remote connection already points to url from params }catch (IllegalStateException ignored){ // Means moskito has no remote connection while GET query specifies one. } RemoteInstance newRemoteInstance = new RemoteInstance(); newRemoteInstance.setHost(remoteHost); newRemoteInstance.setPort(remotePort); WebUIConfig.getInstance().addRemote(newRemoteInstance); APILookupUtility.setCurrentConnectivityMode(ConnectivityMode.REMOTE); APILookupUtility.setCurrentRemoteInstance(newRemoteInstance); } } /** * Checks is current action available only in beta mode * by {@link BetaAction} annotation. * * @return true - this action is beta * false - */ private boolean isBetaAction(){ return this.getClass().getAnnotation(BetaAction.class) != null; } @Override public void preProcess(ActionMapping mapping, HttpServletRequest req, HttpServletResponse res) throws Exception { if(!WebUIConfig.getInstance().isBetaMode() && isBetaAction()){ res.sendError(403, "This action available only in beta mode."); throw new AbortExecutionException(); } String currentIntervalName = getCurrentInterval(req); prepareBasics(req); fetchRemoteConnectionFromUrl(req); //configuration issues. req.setAttribute("config", WebUIConfig.getInstance()); //moved connectivity app, otherwise we don't have selector in case of an error. //set pagename req.setAttribute("pagename", getPageName()); req.setAttribute("connection", APILookupUtility.describeConnectivity()); //prepare selector. LinkedList<LabelValueBean> connectivityOptions = new LinkedList<LabelValueBean>(); connectivityOptions.add(new LabelValueBean("Local", "Local")); for (RemoteInstance ri : WebUIConfig.getInstance().getRemotes()){ connectivityOptions.add(new LabelValueBean(ri.toString(), ri.getSelectKey())); } req.setAttribute("connectivityOptions", connectivityOptions); req.setAttribute("selectedConnectivity", APILookupUtility.isLocal() ? "Local" : APILookupUtility.getCurrentRemoteInstance().getSelectKey()); ///////////// prepare intervals req.setAttribute("intervals", APILookupUtility.getAdditionalFunctionalityAPI().getIntervalInfos()); req.setAttribute("currentInterval", currentIntervalName); //prepare interval timestamp and age. Long currentIntervalUpdateTimestamp = getAdditionalFunctionalityAPI().getIntervalUpdateTimestamp(currentIntervalName); if (currentIntervalUpdateTimestamp==null){ req.setAttribute("currentIntervalUpdateTimestamp", "Never"); req.setAttribute("currentIntervalUpdateAge", "n.A."); }else{ req.setAttribute("currentIntervalUpdateTimestamp", NumberUtils.makeISO8601TimestampString(currentIntervalUpdateTimestamp)); req.setAttribute("currentIntervalUpdateAge", (System.currentTimeMillis()-currentIntervalUpdateTimestamp)/1000+" seconds"); } req.setAttribute("currentCategory", ""); req.setAttribute("currentSubsystem", ""); ThresholdStatus systemStatus = getThresholdAPI().getWorstStatus(); req.setAttribute("systemStatus", systemStatus); req.setAttribute("systemStatusColor", systemStatus.toString().toLowerCase()); //check for autoreload. String pReloadInterval = req.getParameter(PARAM_RELOAD_INTERVAL); if (pReloadInterval!=null && pReloadInterval.length()>0){ if (pReloadInterval.equalsIgnoreCase("OFF")){ req.getSession().removeAttribute(BEAN_AUTORELOAD); }else{ try{ Integer.parseInt(pReloadInterval); req.getSession().setAttribute(BEAN_AUTORELOAD, pReloadInterval); }catch(NumberFormatException e){ log.warn("Attempt to set illegal reload time "+pReloadInterval+" ignored: ", e); } } } checkNavigationMenuState(req); //set page title. String subTitle = getSubTitle(); String title = DEFAULT_TITLE; if (subTitle!=null && subTitle.length()>0){ title += " :: "+subTitle; } req.setAttribute("title", title); req.setAttribute("exportSupported", exportSupported()); req.setAttribute("logoUrl", WebUIConfig.getInstance().getCustomLogoUrl()); //check if a new threshold has been added. if(req.getParameter("newThreshold")!=null){ req.setAttribute("newThresholdAdded","true"); req.setAttribute("newThresholdName",req.getParameter("newThreshold")); } //check if a new accumulator has been added. if (req.getParameter("newAccumulator") != null) { req.setAttribute("newAccumulatorAdded", "true"); req.setAttribute("newAccumulatorName", req.getParameter("newAccumulator")); } } @Override public void postProcess(ActionMapping mapping, HttpServletRequest req, HttpServletResponse res) throws Exception { long timestamp = System.currentTimeMillis(); String timestampAsDate = NumberUtils.makeISO8601TimestampString(timestamp); req.setAttribute("timestamp", timestamp); req.setAttribute("timestampAsDate", timestampAsDate); } /** * Returns the link to the current page. * @param req * @return */ protected abstract String getLinkToCurrentPage(HttpServletRequest req); protected static IDecoratorRegistry getDecoratorRegistry(){ return decoratorRegistry; } private String maskAsXML(String link){ return maskAsExtension(link, ".xml"); } private String maskAsCSV(String link){ return maskAsExtension(link, ".csv"); } /** * Masks the link as json. * @param link * @return */ private String maskAsJSON(String link){ return maskAsExtension(link, ".json"); } private String maskAsExtension(String link, String extension){ if (link==null || link.length()==0) return link; int indexOfQ = link.indexOf('?'); if (indexOfQ==-1) return link + extension; return link.substring(0,indexOfQ)+extension+link.substring(indexOfQ); } /** * Returns the highlighted navigation item. * @return */ protected abstract NaviItem getCurrentNaviItem(); /** * Returns the highlighted sub navigation item, if subnavigation is active. * This method returns a string instead of naviitem, because we actually don't need * @return */ protected NaviItem getCurrentSubNaviItem(){ return NaviItem.NONE; } /** * Rebuilds query string from source. * @param source original source. * @param params parameters that should be included in the query string. * @return */ protected String rebuildQueryStringWithoutParameter(String source, String ... params){ if (source==null || source.length()==0) return ""; if (params == null || params.length==0) return source; HashSet<String> paramsSet = new HashSet<String>(params.length); paramsSet.addAll(Arrays.asList(params)); String[] tokens = StringUtils.tokenize(source, '&'); StringBuilder ret = new StringBuilder(); for (String t : tokens){ String[] values = StringUtils.tokenize(t, '='); if (paramsSet.contains(values[0])) continue; if (ret.length()>0) ret.append('&'); ret.append(values[0]).append('=').append(values.length >= 2 ? values[1] : ""); } return ret.toString(); } /** * Check, if navigation menu default state present in request. If there is no state, set default value. * * @param req * {@link HttpServletRequest} */ private void checkNavigationMenuState(final HttpServletRequest req) { if (req == null) return; if (req.getSession().getAttribute(ATTR_IS_NAV_MENU_COLLAPSED) != null) return; // here we can specify default collapse value req.getSession().setAttribute(ATTR_IS_NAV_MENU_COLLAPSED, false); } protected String getPageName(){ return "unnamed"; } protected ProducerAPI getProducerAPI(){ return APILookupUtility.getProducerAPI(); } protected ThresholdAPI getThresholdAPI(){ return APILookupUtility.getThresholdAPI(); } protected JourneyAPI getJourneyAPI(){ return APILookupUtility.getJourneyAPI(); } protected AccumulatorAPI getAccumulatorAPI(){ return APILookupUtility.getAccumulatorAPI(); } protected GaugeAPI getGaugeAPI() { return APILookupUtility.getGaugeAPI(); } protected AdditionalFunctionalityAPI getAdditionalFunctionalityAPI(){ return APILookupUtility.getAdditionalFunctionalityAPI(); } protected DashboardAPI getDashboardAPI(){ return APILookupUtility.getDashboardAPI(); } protected TracerAPI getTracerAPI(){ return APILookupUtility.getTracerAPI(); } protected String getSubTitle(){ return ""; } /** * Override and return true if your action supports csv/xml/json export. * @return */ protected boolean exportSupported(){ return false; } /** * Sets an info message that can be shown on next screen. The info message is readable exactly once. * @param message the info message. */ protected void setInfoMessage(String message) { APICallContext.getCallContext().getCurrentSession().setAttribute("infoMessage", APISession.POLICY_FLASH, message); } /** * Returns a previously set info message or null if no message has been set. * @return */ protected String getInfoMessage() { try { return (String) APICallContext.getCallContext().getCurrentSession().getAttribute("infoMessage"); }catch(Exception any){ return null; } } protected void addInfoMessage(String message){ String previousMessage = getInfoMessage(); if (previousMessage == null) previousMessage = ""; if (previousMessage.length()>0) previousMessage+= " "; setInfoMessage(previousMessage+message); } }
package org.navalplanner.business.orders.daos; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.navalplanner.business.common.daos.GenericDAOHibernate; import org.navalplanner.business.common.exceptions.InstanceNotFoundException; import org.navalplanner.business.orders.entities.OrderElement; import org.navalplanner.business.workreports.daos.IWorkReportLineDAO; import org.navalplanner.business.workreports.entities.WorkReportLine; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository @Scope(BeanDefinition.SCOPE_SINGLETON) public class OrderElementDAO extends GenericDAOHibernate<OrderElement, Long> implements IOrderElementDAO { @Autowired private IWorkReportLineDAO workReportLineDAO; public List<OrderElement> findByCode(String code) { Criteria c = getSession().createCriteria(OrderElement.class); c.add(Restrictions.eq("code", code)); return (List<OrderElement>) c.list(); } public OrderElement findUniqueByCode(String code) throws InstanceNotFoundException { List<OrderElement> list = findByCode(code); if (list.size() > 1) { throw new InstanceNotFoundException(code, OrderElement.class .getName()); } return list.get(0); } public List<OrderElement> findByCodeAndParent(OrderElement parent, String code) { Criteria c = getSession().createCriteria(OrderElement.class); c.add(Restrictions.eq("code", code)); if (parent != null) { c.add(Restrictions.eq("parent", parent)); } else { c.add(Restrictions.isNull("parent")); } return c.list(); } public OrderElement findUniqueByCodeAndParent(OrderElement parent, String code) throws InstanceNotFoundException { List<OrderElement> list = findByCodeAndParent(parent, code); if (list.isEmpty() || list.size() > 1) { throw new InstanceNotFoundException(code, OrderElement.class .getName()); } return list.get(0); } @Override public List<OrderElement> findParent(OrderElement orderElement) { Criteria c = getSession().createCriteria(OrderElement.class) .createCriteria("children").add( Restrictions.idEq(orderElement.getId())); return ((List<OrderElement>) c.list()); } public String getDistinguishedCode(OrderElement orderElement) throws InstanceNotFoundException { String code = orderElement.getCode(); while (orderElement.getParent() != null) { OrderElement parent = find(orderElement.getParent().getId()); code = parent.getCode() + "-" + code; orderElement = parent; } return code; } @Override @Transactional(readOnly = true) public int getAssignedHours(OrderElement orderElement) { int addAsignedHoursChildren = 0; if (!orderElement.getChildren().isEmpty()) { List<OrderElement> children = orderElement.getChildren(); Iterator<OrderElement> iterador = children.iterator(); while (iterador.hasNext()) { OrderElement w = iterador.next(); addAsignedHoursChildren = addAsignedHoursChildren + getAssignedHours(w); } } List<WorkReportLine> listWRL = this.workReportLineDAO .findByOrderElement(orderElement); return (getAssignedDirectHours(listWRL) + addAsignedHoursChildren); } private int getAssignedDirectHours(List<WorkReportLine> listWRL) { int asignedDirectHours = 0; Iterator<WorkReportLine> iterator = listWRL.iterator(); while (iterator.hasNext()) { asignedDirectHours = asignedDirectHours + iterator.next().getNumHours(); } return asignedDirectHours; } @Override @Transactional(readOnly = true) public BigDecimal getHoursAdvancePercentage(OrderElement orderElement) { BigDecimal assignedHours = new BigDecimal( getAssignedHours(orderElement)).setScale(2); BigDecimal estimatedHours = new BigDecimal(orderElement.getWorkHours()) .setScale(2); if (estimatedHours.compareTo(BigDecimal.ZERO) <= 0) { return BigDecimal.ZERO; } return assignedHours.divide(estimatedHours, RoundingMode.DOWN); } }
package org.navalplanner.business.planner.entities; import java.util.Date; import org.apache.commons.lang.Validate; import org.navalplanner.business.common.BaseEntity; import org.navalplanner.business.planner.limiting.entities.LimitingResourceQueueDependency; import org.navalplanner.business.util.deepcopy.Strategy; import org.navalplanner.business.util.deepcopy.OnCopy; public class Dependency extends BaseEntity { public enum Type { END_START { @Override public boolean modifiesDestinationStart() { return true; } @Override public boolean modifiesDestinationEnd() { return false; } }, START_START { @Override public boolean modifiesDestinationStart() { return true; } @Override public boolean modifiesDestinationEnd() { return false; } }, END_END { @Override public boolean modifiesDestinationStart() { return false; } @Override public boolean modifiesDestinationEnd() { return true; } }, START_END { @Override public boolean modifiesDestinationStart() { return false; } @Override public boolean modifiesDestinationEnd() { return true; } }; public abstract boolean modifiesDestinationStart(); public abstract boolean modifiesDestinationEnd(); } public static Dependency create(TaskElement origin, TaskElement destination, Type type) { Dependency dependency = new Dependency(origin, destination, type); dependency.setNewObject(true); origin.add(dependency); destination.add(dependency); return dependency; } private TaskElement origin; private TaskElement destination; @OnCopy(Strategy.IGNORE) private LimitingResourceQueueDependency queueDependency; private Type type; /** * Constructor for hibernate. Do not use! */ public Dependency() { } private Dependency(TaskElement origin, TaskElement destination, Type type) { Validate.notNull(origin); Validate.notNull(destination); Validate.notNull(type); Validate.isTrue(!origin.equals(destination), "a dependency must have a different origin than destination"); this.origin = origin; this.destination = destination; this.type = type; } public TaskElement getOrigin() { return origin; } public TaskElement getDestination() { return destination; } public Type getType() { return type; } public void setQueueDependency(LimitingResourceQueueDependency queueDependency) { this.queueDependency = queueDependency; } public LimitingResourceQueueDependency getQueueDependency() { return queueDependency; } public boolean isDependencyBetweenLimitedAllocatedTasks() { return getOrigin().hasLimitedResourceAllocation() && getDestination().hasLimitedResourceAllocation(); } public boolean hasLimitedQueueDependencyAssociated() { return queueDependency != null; } public Date getDateFromOrigin() { switch (type) { case END_START: case END_END: return origin.getEndDate(); case START_END: case START_START: return origin.getStartDate(); default: throw new RuntimeException("unexpected type"); } } }
package org.nakedobjects.reflector.java.reflect; import org.nakedobjects.object.NakedCollection; import org.nakedobjects.object.NakedObject; import org.nakedobjects.object.NakedObjectLoader; import org.nakedobjects.object.NakedObjects; import org.nakedobjects.object.control.Consent; import org.nakedobjects.object.control.DefaultHint; import org.nakedobjects.object.control.Hint; import org.nakedobjects.object.reflect.MemberIdentifier; import org.nakedobjects.object.reflect.OneToManyPeer; import org.nakedobjects.object.reflect.ReflectionException; import org.nakedobjects.reflector.java.control.SimpleFieldAbout; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Vector; import org.apache.log4j.Category; public class JavaOneToManyAssociation extends JavaField implements OneToManyPeer { private final static Category LOG = Category.getInstance(JavaOneToManyAssociation.class); private Method addMethod; private Method removeMethod; private Method clearMethod; public JavaOneToManyAssociation(MemberIdentifier name, Class type, Method get, Method add, Method remove, Method about, boolean isHidden) { super(name, type, get, about, isHidden, add == null && remove == null); this.addMethod = add; this.removeMethod = remove; } public void addAssociation(NakedObject inObject, NakedObject associate) { LOG.debug("local set association " + getIdentifier() + " in " + inObject + " with " + associate); try { addMethod.invoke(inObject.getObject(), new Object[] { associate.getObject() }); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("set method expects a " + getType().getFullName() + " object; not a " + associate.getClass().getName() + ", " + e.getMessage()); } catch (InvocationTargetException e) { invocationException("Exception executing " + addMethod, e); } catch (IllegalAccessException ignore) { LOG.error("illegal access of " + addMethod, ignore); throw new RuntimeException(ignore.getMessage()); } } public void initAssociation(NakedObject inObject, NakedObject associate) { LOG.debug("init association " + getIdentifier() + " in " + inObject + " with " + associate); try { Object obj = getMethod.invoke(inObject.getObject(), new Object[0]); if (obj instanceof Vector) { ((Vector) obj).addElement(associate.getObject()); } else { throw new ReflectionException(); } // addMethod.invoke(inObject.getObject(), new Object[] { associate.getObject() }); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("set method expects a " + getType().getFullName() + " object; not a " + associate.getClass().getName() + ", " + e.getMessage()); } catch (InvocationTargetException e) { invocationException("Exception executing " + addMethod, e); } catch (IllegalAccessException ignore) { LOG.error("illegal access of " + addMethod, ignore); throw new RuntimeException(ignore.getMessage()); } } private Hint getHint(NakedObject object, NakedObject element, boolean add) { Method aboutMethod = getAboutMethod(); if(aboutMethod == null){ return new DefaultHint(); } try { SimpleFieldAbout hint = new SimpleFieldAbout(NakedObjects.getCurrentSession(), object.getObject()); Object[] parameters; if (aboutMethod.getParameterTypes().length == 3) { parameters = new Object[] { hint, element == null ? null : element.getObject(), new Boolean(add) }; } else { // default about parameters = new Object[] { hint }; } aboutMethod.invoke(object.getObject(), parameters); if (hint.getDescription().equals("")) { hint.setDescription("Add " + element.getObject() + " to field " + getIdentifier()); } return hint; } catch (InvocationTargetException e) { invocationException("Exception executing " + aboutMethod, e); } catch (IllegalAccessException ignore) { LOG.error("illegal access of " + aboutMethod, ignore); } return null; } public NakedCollection getAssociations(NakedObject fromObject) { return (NakedCollection) get(fromObject); } public Object getExtension(Class cls) { return null; } public Class[] getExtensions() { return new Class[0]; } public String getName() { return null; } public void removeAllAssociations(NakedObject inObject) { try { if(clearMethod != null) { clearMethod.invoke(inObject, null); } } catch (InvocationTargetException e) { invocationException("Exception executing " + clearMethod, e); } catch (IllegalAccessException ignore) { LOG.error("illegal access of " + clearMethod, ignore); throw new RuntimeException(ignore.getMessage()); } } /** * Remove an associated object (the element) from the specified NakedObject in the association field * represented by this object. */ public void removeAssociation(NakedObject inObject, NakedObject associate) { LOG.debug("local clear association " + associate + " from field " + getIdentifier() + " in " + inObject); try { removeMethod.invoke(inObject.getObject(), new Object[] { associate.getObject() }); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " object: " + inObject.getObject() + ", parameter: " + associate.getObject()); } catch (InvocationTargetException e) { invocationException("Exception executing " + addMethod, e); } catch (IllegalAccessException ignore) { LOG.error("illegal access of " + addMethod, ignore); throw new RuntimeException(ignore.getMessage()); } } public String toString() { String methods = (getMethod == null ? "" : "GET") + (addMethod == null ? "" : " ADD") + (removeMethod == null ? "" : " REMOVE"); return "OneToManyAssociation [name=\"" + getIdentifier() + "\", method=" + getMethod + ",about=" + getAboutMethod() + ", methods=" + methods + ", type=" + getType() + " ]"; } private NakedCollection get(NakedObject fromObject) { try { Object collection = getMethod.invoke(fromObject.getObject(), new Object[0]); NakedCollection adapter; if (collection == null) { return null; } else { NakedObjectLoader objectLoader = NakedObjects.getObjectLoader(); adapter = objectLoader.getAdapterForElseCreateAdapterForCollection(fromObject, getIdentifier().getName(), getType(), collection); if (adapter == null) { throw new ReflectionException("no adapter created"); } else { return adapter; } } } catch (InvocationTargetException e) { invocationException("Exception executing " + getMethod, e); throw new ReflectionException(e); } catch (IllegalAccessException ignore) { LOG.error("illegal access of " + getMethod, ignore); throw new ReflectionException(ignore); } } public boolean isEmpty(NakedObject fromObject) { try { Object obj = getMethod.invoke(fromObject.getObject(), new Object[0]); if (obj == null) { return true; } else if (obj instanceof Vector) { return ((Vector) obj).isEmpty(); } else { throw new ReflectionException(); } } catch (InvocationTargetException e) { invocationException("Exception executing " + getMethod, e); throw new ReflectionException(e); } catch (IllegalAccessException ignore) { LOG.error("illegal access of " + getMethod, ignore); throw new ReflectionException(ignore); } } public void initOneToManyAssociation(NakedObject fromObject, NakedObject[] instances) { try { Object obj = getMethod.invoke(fromObject.getObject(), new Object[0]); if (obj instanceof Vector) { ((Vector) obj).removeAllElements(); for (int i = 0; i < instances.length; i++) { ((Vector) obj).addElement(instances[i].getObject()); } } else if (obj instanceof Object[]) { throw new ReflectionException("not set up to deal with arrays"); } else { throw new ReflectionException("Can't initialise " + obj); } } catch (InvocationTargetException e) { LOG.error("exception executing " + getMethod, e.getTargetException()); throw new ReflectionException(e); } catch (IllegalAccessException ignore) { LOG.error("illegal access of " + getMethod, ignore); throw new ReflectionException(ignore); } } public Consent isUsable(NakedObject target) { return getHint(target, null, true).canUse(); } public Consent isRemoveValid(NakedObject container, NakedObject element) { Hint about = getHint(container, element, false); Consent edit = about.canUse(); return edit; } public Consent isAddValid(NakedObject container, NakedObject element) { Hint about = getHint(container, element, true); Consent edit = about.canUse(); return edit; } public Consent isVisible(NakedObject target) { return getHint(target, null, true).canAccess(); } public boolean isAccessible() { return true; } }
package org.nuxeo.ecm.webapp.action; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.ejb.Remove; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.RequestParameter; import org.jboss.seam.annotations.Transactional; import org.jboss.seam.annotations.WebRemote; import org.nuxeo.ecm.core.api.Blob; import org.nuxeo.ecm.core.api.model.PropertyException; import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeEntry; import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry; import org.nuxeo.ecm.platform.transform.api.TransformServiceDelegate; import org.nuxeo.ecm.platform.transform.interfaces.TransformDocument; import org.nuxeo.ecm.platform.transform.interfaces.TransformServiceCommon; import org.nuxeo.ecm.platform.ui.web.api.NavigationContext; import org.nuxeo.runtime.api.Framework; /** * @author <a href="mailto:florent.bonnet@nuxeo.com">Florent BONNET</a> */ @Name("conversionActions") @Transactional public class ConversionActionBean implements ConversionAction { private static final Log log = LogFactory.getLog(ConversionActionBean.class); @In(create = true) NavigationContext navigationContext; @RequestParameter private String fileFieldFullName; @RequestParameter private String filename; @Remove public void destroy() { log.debug("Removing Seam action listener..."); } public String display() { return "view_file"; } private String getMimetypeFromDocument(String propertyName) throws PropertyException { Blob blob = (Blob) navigationContext.getCurrentDocument().getPropertyValue( propertyName); return blob.getMimeType(); } public boolean isExportableToPDF(Blob blob) { boolean isSupported = false; try { if (blob != null) { String mimetype = blob.getMimeType(); TransformServiceCommon nxt = TransformServiceDelegate.getRemoteTransformService(); isSupported = nxt.isMimetypeSupportedByPlugin("any2pdf", mimetype); } } catch (Exception e) { log.error("error asking the any2pdf plugin whether pdf conversion " + " is supported: " + e.getMessage()); } return isSupported; } @WebRemote public boolean isFileExportableToPDF(String fieldName) { boolean isSupported = false; try { String mimetype = getMimetypeFromDocument(fieldName); TransformServiceCommon nxt = TransformServiceDelegate.getRemoteTransformService(); isSupported = nxt.isMimetypeSupportedByPlugin("any2pdf", mimetype); } catch (Exception e) { log.error("error asking the any2pdf plugin whether " + fieldName + " is supported: " + e.getMessage()); } return isSupported; } @WebRemote public String generatePdfFile() { try { if (fileFieldFullName == null) { return null; } Blob blob = (Blob) navigationContext.getCurrentDocument().getPropertyValue( fileFieldFullName); TransformServiceCommon nxt = Framework.getService(TransformServiceCommon.class); List<TransformDocument> resultingDocs = nxt.transform("any2pdf", null, blob); String name; if (filename == null || filename.equals("")) { name = "file"; } else { name = filename; } // add pdf extension int pos = name.lastIndexOf("."); if (pos <= 0) { name += ".pdf"; } else { String sub = name.substring(pos + 1); name = name.replace(sub, "pdf"); } if (resultingDocs.size() == 0) { log.error("Transform service didn't return any resulting documents which is not normal."); return "pdf_generation_error"; } // converting the result into byte[] to be able to put it in the // response InputStream inputStream = resultingDocs.get(0).getBlob().getStream(); int length = inputStream.available(); byte[] array = new byte[length]; int offset = 0; int n; do { n = inputStream.read(array, offset, length - offset); } while (n != -1); String headerContent = "attachment; filename=\"" + name + "\";"; writeResponse("Content-Disposition", headerContent, "application/pdf", array); return null; } catch (Exception e) { log.error("PDF generation error for file " + filename, e); } return "pdf_generation_error"; } /** * @deprecated use LiveEditBootstrapHelper.isCurrentDocumentLiveEditable() * instead */ @Deprecated @WebRemote public boolean isFileOnlineEditable(String fieldName) { try { boolean isOnlineEditable; String mimetype = getMimetypeFromDocument(fieldName); MimetypeRegistry mimeTypeService = Framework.getService(MimetypeRegistry.class); MimetypeEntry mimetypeEntry = mimeTypeService.getMimetypeEntryByMimeType(mimetype); if (mimetypeEntry == null) { isOnlineEditable = false; } else { isOnlineEditable = mimetypeEntry.isOnlineEditable(); } return isOnlineEditable; } catch (Exception e) { log.error("error getting the mimetype entry for " + fieldName + ": " + e.getMessage()); return false; } } /** * Simply sends what to be downloaded or shown at screen via * HttpServletResponse. * * @param header * @param headerContent * @param contentType * @param value * @throws IOException */ private void writeResponse(String header, String headerContent, String contentType, byte[] value) throws IOException { FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setHeader(header, headerContent); response.setContentType(contentType); response.getOutputStream().write(value); context.responseComplete(); } public void initialize() { log.info("initializing FileViewAction"); } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // Modifications: // 2007 Apr 06: Separate out testSimple into individual tests and // pass the virtual host in the config to keep cookie // warnings from happening. Verify that nothing is // logged at a level at WARN or higher. - dj@opennms.org // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.netmgt.poller.monitors; import static org.junit.Assert.assertTrue; import java.net.InetAddress; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.opennms.netmgt.dao.db.OpenNMSConfigurationExecutionListener; import org.opennms.netmgt.mock.JUnitMockHttpServer; import org.opennms.netmgt.mock.JUnitMockHttpServerExecutionListener; import org.opennms.netmgt.mock.MockMonitoredService; import org.opennms.netmgt.model.PollStatus; import org.opennms.netmgt.poller.MonitoredService; import org.opennms.test.mock.MockLogAppender; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author <a href="mailto:david@opennms.org">David Hustace</a> * @author <a href="mailto:brozow@opennms.org">Matt Brozowski</a> * */ @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({ OpenNMSConfigurationExecutionListener.class, JUnitMockHttpServerExecutionListener.class, }) @ContextConfiguration(locations={}) @JUnitMockHttpServer(port=10342) public class PageSequenceMonitorTest { PageSequenceMonitor m_monitor; Map<String, String> m_params; @Before public void setUp() throws Exception { MockLogAppender.setupLogging(); m_monitor = new PageSequenceMonitor(); m_monitor.initialize(Collections.EMPTY_MAP); m_params = new HashMap<String, String>(); m_params.put("timeout", "8000"); m_params.put("retries", "1"); } protected MonitoredService getHttpService(String hostname) throws Exception { return getHttpService(hostname, InetAddress.getByName(hostname).getHostAddress()); } protected MonitoredService getHttpService(String hostname, String ip) throws Exception { MonitoredService svc = new MockMonitoredService(1, hostname, ip, "HTTP"); m_monitor.initialize(svc); return svc; } @After public void tearDown() throws Exception { MockLogAppender.assertNoWarningsOrGreater(); } @Test public void testSimple() throws Exception { setPageSequenceParam("localhost"); PollStatus googleStatus = m_monitor.poll(getHttpService("localhost"), m_params); assertTrue("Expected available but was "+googleStatus+": reason = "+googleStatus.getReason(), googleStatus.isAvailable()); } @Test public void testSimpleBogus() throws Exception { setPageSequenceParam(null); PollStatus notLikely = m_monitor.poll(getHttpService("bogus", "1.1.1.1"), m_params); assertTrue("should not be available", notLikely.isUnavailable()); } private void setPageSequenceParam(String virtualHost) { String virtualHostParam; if (virtualHost == null) { virtualHostParam = ""; } else { virtualHostParam = "virtual-host=\"" + virtualHost + "\""; } m_params.put("page-sequence", "" + "<?xml version=\"1.0\"?>" + "<page-sequence>\n" + " <page path=\"/index.html\" port=\"10342\" user-agent=\"Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)\" successMatch=\"It was written by monkeys.\" " + virtualHostParam + "/>\n" + "</page-sequence>\n"); } @Test public void testHttps() throws Exception { m_params.put("page-sequence", "" + "<?xml version=\"1.0\"?>" + "<page-sequence>\n" + " <page scheme=\"https\" path=\"/ws/eBayISAPI.dll?RegisterEnterInfo\" port=\"443\" user-agent=\"Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)\" successMatch=\"Hi! Ready to register with eBay?\" virtual-host=\"support.opennms.com\"/>\n" + "</page-sequence>\n"); PollStatus googleStatus = m_monitor.poll(getHttpService("scgi.ebay.com"), m_params); assertTrue("Expected available but was "+googleStatus+": reason = "+googleStatus.getReason(), googleStatus.isAvailable()); } @Test public void testLogin() throws Exception { m_params.put("page-sequence", "" + "<?xml version=\"1.0\"?>" + "<page-sequence>\n" + " <page path=\"/opennms\" port=\"80\" successMatch=\"Password\" />\n" + " <page path=\"/opennms/j_acegi_security_check\" port=\"80\" method=\"POST\" failureMatch=\"(?s)Your log-in attempt failed.*Reason: ([^&lt;]*)\" failureMessage=\"Login in Failed: ${1}\" successMatch=\"Log out\">\n" + " <parameter key=\"j_username\" value=\"demo\"/>\n" + " <parameter key=\"j_password\" value=\"demo\"/>\n" + " </page>\n" + " <page path=\"/opennms/event/index.jsp\" port=\"80\" successMatch=\"Event Queries\" />\n" + " <page path=\"/opennms/j_acegi_logout\" port=\"80\" successMatch=\"logged off\" />\n" + "</page-sequence>\n"); PollStatus status = m_monitor.poll(getHttpService("demo.opennms.org"), m_params); assertTrue("Expected available but was "+status+": reason = "+status.getReason(), status.isAvailable()); } @Test public void testVirtualHost() throws Exception { m_params.put("page-sequence", "" + "<?xml version=\"1.0\"?>" + "<page-sequence>\n" + " <page path=\"/\" port=\"80\" successMatch=\"Zero Bull\" virtual-host=\"www.opennms.com\"/>\n" + "</page-sequence>\n"); PollStatus status = m_monitor.poll(getHttpService("www.opennms.com"), m_params); assertTrue("Expected available but was "+status+": reason = "+status.getReason(), status.isAvailable()); } }
package org.csstudio.display.builder.model.persist; import java.io.InputStream; import java.util.Iterator; import java.util.Optional; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** XML Utility. * @author Kay Kasemir */ @SuppressWarnings("nls") public class XMLUtil { /** Text encoding used for the XML */ public static final String ENCODING = "UTF-8"; /** Open XML document, locate root element * @param stream XML stream * @param expected_root Desired name of root element * @return That root element * @throws Exception on error, including document with wrong root */ public static Element openXMLDocument(final InputStream stream, final String expected_root) throws Exception { // Parse XML final Document doc = PositionalXMLReader.readXML(stream); doc.getDocumentElement().normalize(); // Check root element final Element root_node = doc.getDocumentElement(); if (! expected_root.equals(root_node.getNodeName())) throw new Exception("Wrong document type. Expected <" + expected_root + "> but found <" + root_node.getNodeName() + ">"); return root_node; } /** (Try to) obtain original line number in XML file for a node. * * @param node Node in document * @return Line number. Empty if not known. */ public static Optional<Integer> getLineNumber(final Node node) { final Object info = node.getUserData(PositionalXMLReader.LINE_NUMBER); if (info instanceof Integer) return Optional.of((Integer)info); return Optional.empty(); } /** Get line number info for XML-related error messages. * * @param node Node in document * @return Line number as string or "unknown" */ public static String getLineInfo(final Node node) { final Optional<Integer> number = getLineNumber(node); if (number.isPresent()) return Integer.toString(number.get()); return "unknown"; } /** Iterator over all Elements (not just Nodes) of a parent */ private static class ElementIterator implements Iterator<Element> { private Element next_node; ElementIterator(final Node parent) { next_node = findElement(parent.getFirstChild()); } @Override public boolean hasNext() { return next_node != null; } @Override public Element next() { final Element current = next_node; next_node = findElement(current.getNextSibling()); return current; } } /** Iterator over all Elements (not just Nodes) of a parent * that have specific name. */ private static class NamedElementIterator implements Iterator<Element> { private Element next_node; NamedElementIterator(final Node parent, final String name) { next_node = findElementByName(parent.getFirstChild(), name); } @Override public boolean hasNext() { return next_node != null; } @Override public Element next() { final Element current = next_node; next_node = findElementByName(current.getNextSibling(), current.getNodeName()); return current; } } /** Obtain all child elements. * @param parent Parent node * @return {@link Iterable} for child elements */ public static Iterable<Element> getChildElements(final Node parent) { return () -> new ElementIterator(parent); } /** Obtain all child elements with given name. * @param parent Parent node * @param name Name of child elements * @return {@link Iterable} for matching child elements */ public static Iterable<Element> getChildElements(final Node parent, final String name) { return () -> new NamedElementIterator(parent, name); } /** Look for child node of given name. * * @param parent Node where to start. * @param name Name of the node to look for. * @return Returns Element or <code>null</code>. */ public static final Element getChildElement(final Node parent, final String name) { return findElementByName(parent.getFirstChild(), name); } /** Look for Element node. * * <p>Checks the node and its siblings. * Does not descent down the 'child' links. * * @param node Node where to start. * @return Returns node, next Element sibling or <code>null</code>. */ public static final Element findElement(Node node) { while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) return (Element) node; node = node.getNextSibling(); } return null; } /** Look for Element node of given name. * * <p>Checks the node itself and its siblings for an {@link Element}. * Does not descent down the 'child' links. * * @param node Node where to start. * @param name Name of the node to look for. * @return Returns node, the next matching sibling, or <code>null</code>. */ private static final Element findElementByName(Node node, final String name) { while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(name)) return (Element) node; node = node.getNextSibling(); } return null; } /** Get string value of an element. * @param element Element * @return String of the node. Empty string if nothing found. */ public static String getString(final Element element) { final Node text = element.getFirstChild(); if (text == null) // <empty /> node return ""; if ((text.getNodeType() == Node.TEXT_NODE || text.getNodeType() == Node.CDATA_SECTION_NODE)) return text.getNodeValue(); return ""; } /** Given a parent element, locate string value of a child node. * @param parent Parent element * @param name Name of child element * @return Value of child element, or empty result */ public static Optional<String> getChildString(final Element parent, final String name) { final Element child = getChildElement(parent, name); if (child != null) return Optional.of(getString(child)); else return Optional.empty(); } /** @param text Text that should contain true or false * @param default_value Value to use when text is empty * @return Boolean value of text */ public static boolean parseBoolean(final String text, final boolean default_value) { if (text == null || text.isEmpty()) return default_value; return Boolean.parseBoolean(text); } /** Transform xml element and children into a string * * @param nd Node root of elements to transform * @return String representation of xml */ public static String elementToString(Node nd, boolean add_newlines) { //short type = n.getNodeType(); if (Node.CDATA_SECTION_NODE == nd.getNodeType()) { return "<![CDATA[" + nd.getNodeValue() + "]]&gt;"; } // return if simple element type final String name = nd.getNodeName(); if (name.startsWith(" if (name.equals("#text")) return nd.getNodeValue(); return ""; } // output name String ret = "<" + name; // output attributes NamedNodeMap attrs = nd.getAttributes(); if (attrs != null) { for (int idx = 0; idx < attrs.getLength(); idx++) { Node attr = attrs.item(idx); ret += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\""; } } final String text = nd.getTextContent(); final NodeList child_ndls = nd.getChildNodes(); String all_child_str = ""; for (int idx = 0; idx < child_ndls.getLength(); idx++) { final String child_str = elementToString(child_ndls.item(idx), add_newlines); if ((child_str != null) && (child_str.length() > 0)) { all_child_str += child_str; } } if (all_child_str.length() > 0) { // output children ret += ">" + (add_newlines ? "\n" : " "); ret += all_child_str; ret += "</" + name + ">"; } else if ((text != null) && (text.length() > 0)) { // output text ret += text; ret += "</" + name + ">"; } else { // output nothing ret += "/>" + (add_newlines ? "\n" : " "); } return ret; } public static String elementsToString(NodeList nls, boolean add_newlines) { String ret = ""; for (int i = 0; i < nls.getLength(); i++) { final String nextstr = elementToString(nls.item(i), add_newlines).trim(); if (nextstr.length() > 0) { if (ret.length() > 0) ret += (add_newlines)? "\n" : " "; ret += nextstr; } } return ret; } }
package org.strategoxt.imp.runtime.stratego; import static org.eclipse.core.resources.IResourceChangeEvent.POST_CHANGE; import static org.eclipse.core.resources.IResourceChangeEvent.PRE_CLOSE; import static org.eclipse.core.resources.IResourceChangeEvent.PRE_DELETE; import static org.eclipse.core.resources.IResourceDelta.ADDED; import static org.eclipse.core.resources.IResourceDelta.CHANGED; import static org.eclipse.core.resources.IResourceDelta.CONTENT; import static org.eclipse.core.resources.IResourceDelta.MOVED_FROM; import static org.eclipse.core.resources.IResourceDelta.MOVED_TO; import static org.eclipse.core.resources.IResourceDelta.NO_CHANGE; import static org.eclipse.core.resources.IResourceDelta.REMOVED; import static org.eclipse.core.resources.IResourceDelta.REPLACED; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.imp.language.LanguageRegistry; import org.spoofax.interpreter.library.index.notification.FilePartition; import org.spoofax.interpreter.library.index.notification.NotificationCenter; import org.strategoxt.imp.runtime.Environment; /** * Sends Eclipse resource change notifications to the Spoofax {@link NotificationCenter}. * * @author Lennart Kats <lennart add lclnet.nl> */ public class FileNotificationServer implements IResourceChangeListener { private boolean projectClosing = false; private FileNotificationServer() { // Use the statics } public static void init() { // (note: don't set eventMask parameter; Eclipse will ignore some events) ResourcesPlugin.getWorkspace().addResourceChangeListener(new FileNotificationServer()); NotificationCenter.putObserver(null, null, new QueueAnalysisService()); } public void resourceChanged(IResourceChangeEvent event) { switch(event.getType()) { case PRE_CLOSE: case PRE_DELETE: projectClosing = true; break; case POST_CHANGE: { if(!projectClosing) postResourceChanged(event.getDelta()); projectClosing = false; break; } } } private void postResourceChanged(IResourceDelta delta) { try { final List<FilePartition> changedFiles = new ArrayList<FilePartition>(); delta.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { if((delta.getFlags() & IResourceDelta.OPEN) == IResourceDelta.OPEN) { return false; } IResource resource = delta.getResource(); if(isSignificantChange(delta) && !isIgnoredChange(resource) && resource.getLocation() != null && LanguageRegistry.findLanguage(resource.getLocation(), null) != null) { changedFiles.add(new FilePartition(resource.getLocationURI(), null)); } return true; } }); if(changedFiles.size() > 0) NotificationCenter.notifyFileChanges(changedFiles.toArray(new FilePartition[0]), false); } catch(CoreException e) { Environment.logException("Exception when processing fileystem events", e); } } public static boolean isSignificantChange(IResourceDelta delta) { switch(delta.getKind()) { case ADDED: case REMOVED: return true; case CHANGED: final int flags = delta.getFlags(); return (flags & CONTENT) == CONTENT || (flags & MOVED_TO) == MOVED_TO || (flags & MOVED_FROM) == MOVED_FROM || (flags & REPLACED) == REPLACED; case NO_CHANGE: return false; default: assert false : "Unknown state"; return false; } } private static boolean isIgnoredChange(IResource resource) { IPath path = resource.getProjectRelativePath(); if(path.segmentCount() > 1) { String base = path.segment(0); if(".cache".equals(base) || ".shadowdir".equals(base) || "include".equals(base) || "bin".equals(base) || ".spxcache".equals(base) || "__MACOS_X".equals(base)) return true; } return false; } }
package com.sitdh.master.eaa.main; import com.sitdh.master.eaa.subsystem.Y9NewYorkRadioStation; public class ZController { public static void testCase1() { System.out.println("~~~~~~~~~~~~~~~~ Case 1 ~~~~~~~~~~~~~~~~"); A1Motorbike a1 = new A1Motorbike(); B1Helicopter b1 = new B1Helicopter(); System.out.println(String.format("Motorbike wheel size:\t%,.2f", a1.getWheelSize())); System.out.println(String.format("Motorbike length:\t%,.2f", a1.getLength())); System.out.println(String.format("Motorbike blueprint:\t%s", a1.getBlueprint())); System.out.println(" System.out.println(String.format("Helicopter length:\t%,.2f", b1.getPaddleLength())); System.out.println(String.format("Helicopter weight:\t%,.2f", b1.getWeight())); System.out.println(String.format("Helicopter blueprint:\t%s", b1.getBlueprint())); } public static void testCase2() { System.out.println("~~~~~~~~~~~~~~~~ Case 2 ~~~~~~~~~~~~~~~~"); A2PointOfSell pos = new A2PointOfSell(); System.out.println(String.format("Cash available in machine: $%,.2f", pos.getCashDeposit())); System.out.println(String.format("Number of sell transaction available: %d", pos.getTransaction().length)); System.out.println(" System.out.println(String.format("Staff name: %s", pos.getStaff().getName())); System.out.println(String.format("Staff working hour: %s", pos.getStaff().getWorkingHour())); System.out.println(String.format("Staff salary (bucks): $%,.2f", pos.getStaff().getSalary())); } public static void testCase3() { System.out.println("~~~~~~~~~~~~~~~~ Case 3 ~~~~~~~~~~~~~~~~"); B3Coffee espresso = new B3Coffee(); espresso.setName("Espresso"); espresso.setSize("Tall"); espresso.setPrice(3f); B3Coffee latte = new B3Coffee(); latte.setName("Latte"); latte.setSize("Grande"); latte.setPrice(5.5f); A3CoffeeMenu coffeeMenu = new A3CoffeeMenu(); coffeeMenu.addCoffee(espresso); coffeeMenu.addCoffee(latte); B3Coffee coffee = null; while(!coffeeMenu.getCoffeeList().isEmpty()) { coffee = coffeeMenu.getCoffeeList().firstElement(); System.out.println(String.format("Name: %s", coffee.getName())); System.out.println(String.format("Size: %s", coffee.getSize())); System.out.println(String.format("Price: $%,.2f", coffee.getPrice())); coffeeMenu.getCoffeeList().remove(coffee); System.out.println(" } } public static void testCase4() { System.out.println("~~~~~~~~~~~~~~~~ Case 4 ~~~~~~~~~~~~~~~~"); A4Dish largeDish = new A4Dish(); B4Food salad = new B4Food(); largeDish.setFood(salad); salad.setPlaceInDish(largeDish); System.out.println(String.format("Dish size:\t%s", largeDish.getDishSize())); System.out.println(String.format("Color:\t\t%s", largeDish.getColor())); System.out.println(String.format("Food in dish:\t%s", largeDish.food.getName())); System.out.println(" System.out.println(String.format("Food name:\t%s", salad.getName())); System.out.println(String.format("Food price:\t$%,.2f", salad.getPrice())); System.out.println(String.format("Food description:%s", salad.getDescription())); System.out.println(String.format("Place in dish:\t%s", salad.placeInDish.getDishSize())); } public static void testCase5() { System.out.println("~~~~~~~~~~~~~~~~ Case 5 ~~~~~~~~~~~~~~~~"); A5Department department = new A5Department(); department.setName("Computer Engineering"); department.setDepartmentDescription("The computer engineering faculty members enjoy a close relationship with the applied mathematics and statistics, computer science, electrical engineering, and computational biology faculty members. Faculty members carry out joint research projects, supervise students, and teach courses outside their own departments. "); B5Professor schlag = new B5Professor(); schlag.setName("Martine"); schlag.setLastname("Schlag"); schlag.setRoom("Engineering 2, Room 219"); schlag.setOfficehour("Winter 16: W 12:30-1:30pm, F 11-12pm, Spring 16: to be determined"); B5Professor obraczka = new B5Professor(); obraczka.setName("Katia"); obraczka.setLastname("Obraczka"); obraczka.setRoom("Engineering 2, Room 323"); obraczka.setOfficehour("Wednesdays 9-10:30am"); department.addProfessor(schlag); department.addProfessor(obraczka); System.out.println(String.format("Department name:\t\t%s", department.getName())); System.out.println(String.format("Department description:\t%s", department.getDepartmentDescription())); System.out.println(" for(B5Professor professor : department.getProfessors()) { System.out.println(String.format("Name:\t\t%s %s", professor.getName(), professor.getLastname())); System.out.println(String.format("Room:\t\t%s", professor.getRoom())); System.out.println(String.format("Office hour:\t%s", professor.getOfficehour())); } } public static void testCase6() { System.out.println("~~~~~~~~~~~~~~~~ Case 6 ~~~~~~~~~~~~~~~~"); B6CoordinatePoint focusA = new B6CoordinatePoint(3, 5); B6CoordinatePoint focusB = new B6CoordinatePoint(20, 5); A6Ellipse ellipse = new A6Ellipse(16, focusA, focusB); System.out.println(String.format("Focus A: (%d, %d)", ellipse.getFocusPointA().getX(), ellipse.getFocusPointA().getY())); System.out.println(String.format("Focus B: (%d, %d)", ellipse.getFocusPointB().getX(), ellipse.getFocusPointB().getY())); System.out.println(String.format("Major axis lenth: %,.2f", ellipse.getMajorAxis())); System.out.println(String.format("Minor axis lenth: %,.2f", ellipse.getMinorAxis())); System.out.println("Draw: " + ellipse.rendorEllipse()); } public static void testCase7() { System.out.println("~~~~~~~~~~~~~~~~ Case 7 ~~~~~~~~~~~~~~~~"); A7Customer customer = new A7Customer(); B7Waiter waiter = new B7Waiter(); customer.callForWaiter(waiter); customer.makeAnOrder("Coconut Milk Soup with Chicken"); } public static void testCase8() { System.out.println("~~~~~~~~~~~~~~~~ Case 8 ~~~~~~~~~~~~~~~~"); A8Driver taxiDriver = new A8Driver(); I8Car taxi = new B8TaxiCar(); taxiDriver.getinTheCar(taxi); taxiDriver.drive(); } public static void testCase9() { System.out.println("~~~~~~~~~~~~~~~~ Case 9 ~~~~~~~~~~~~~~~~"); X9BangkokRadioStation bkkRadioStation = new X9BangkokRadioStation(); Y9NewYorkRadioStation nyRadioStation = new Y9NewYorkRadioStation(); nyRadioStation.startLiveStreamingFromAnoterStation(bkkRadioStation); for(String song : nyRadioStation.getStreaming()) { System.out.println("ny> Streamed " + song); } System.out.println(String.format("ny> Stream location %s", nyRadioStation.getCurrentStreamingLocation())); nyRadioStation.rerouteStreamingServer(); } public static void main(String[] args) { // TODO Auto-generated method stub /** * #1 * * A and B has no relationship. */ ZController.testCase1(); System.out.println(); ZController.testCase2(); System.out.println(); ZController.testCase3(); System.out.println(); ZController.testCase4(); System.out.println(); ZController.testCase5(); System.out.println(); ZController.testCase6(); System.out.println(); ZController.testCase7(); System.out.println(); ZController.testCase8(); System.out.println(); ZController.testCase9(); } }
package ru.matevosyan; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class ConsoleChat { private Scanner scanner = new Scanner(System.in); private List<String> string = new ArrayList<>(); private File file; private File outPutFile; private String LN = System.getProperty("line.separator"); public ConsoleChat(final File fileName, final File outFileName) { this.file = fileName; this.outPutFile = outFileName; } public void readUserData() { String exit = "EXIT"; String sameStuff = "CONTINUE"; String stop = "STOP"; String readUser; do { readUser = scanner.nextLine(); if (!(readUser.equals(exit)) && !(readUser.equals(stop))) { if (readUser.equals(sameStuff)) { readUser = scanner.nextLine(); } readFile(readUser); } if (readUser.equals(stop)) { boolean exitFromWhile = false; while (!(readUser.equals(sameStuff))) { writeFile(this.outPutFile, readUser); if (!(readUser.equals(exit))) { readUser = scanner.nextLine(); writeFile(this.outPutFile, readUser); if (readUser.equals(exit)) { readUser = sameStuff; exitFromWhile = true; writeFile(this.outPutFile, readUser); } } } if (exitFromWhile) { readUser = exit; } } } while (!readUser.equals(exit)); writeFile(this.outPutFile, readUser); } public void readFile(String readUser) { try (BufferedReader fin = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { while (fin.ready()) { this.string.add(fin.readLine()); } String answer = this.string.get((int) (Math.random() * this.string.size())); System.out.printf(answer); System.out.println(); writeFile(this.outPutFile, readUser, answer); } catch (IOException ioe) { ioe.getMessage(); } } public void writeFile(File file, String ... readAndAnswerUser) { try (FileWriter fileWriter = new FileWriter(file, true); PrintWriter pWriter = new PrintWriter(new BufferedWriter(fileWriter), true)) { ArrayList<String> writeString = new ArrayList<>(); Collections.addAll(writeString, readAndAnswerUser); int size = writeString.size(); String string; if (size == 2) { string = String.format("User: %s%sBot: %s%s%s", writeString.get(0), LN, writeString.get(1), LN, LN); } else { string = String.format("User: %s%s", writeString.get(0), LN); } pWriter.write(string); } catch (IOException e) { e.printStackTrace(); } } // public static void main(String[] args) { // String pathSource = "C:\\Users\\Admin\\Desktop\\sourceFile.txt"; // String outPutPathSource = "C:\\Users\\Admin\\Desktop\\outPutPathSourceFile.txt"; // File sourceFile = new File(pathSource); // File outPutPathSourceFile = new File(outPutPathSource); // String pathSource = "sourceFile.txt"; // String outPutPathSource = "outPutPathSourceFile.txt"; // ConsoleChat consoleChat = new ConsoleChat(pathSource, outPutPathSource); // consoleChat.readUserData(); }
package com.intellij.structuralsearch; import com.intellij.codeInsight.template.TemplateContextType; import com.intellij.codeInsight.template.XmlContextType; import com.intellij.dupLocator.iterators.NodeIterator; import com.intellij.dupLocator.util.NodeFilter; import com.intellij.ide.highlighter.HtmlFileType; import com.intellij.ide.highlighter.XmlFileType; import com.intellij.lang.Language; import com.intellij.lang.html.HTMLLanguage; import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.xml.*; import com.intellij.structuralsearch.impl.matcher.*; import com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilingVisitor; import com.intellij.structuralsearch.impl.matcher.compiler.XmlCompilingVisitor; import com.intellij.structuralsearch.plugin.replace.ReplaceOptions; import com.intellij.structuralsearch.plugin.replace.ReplacementInfo; import com.intellij.structuralsearch.plugin.replace.impl.Replacer; import com.intellij.structuralsearch.plugin.replace.impl.ReplacerUtil; import com.intellij.structuralsearch.plugin.ui.Configuration; import com.intellij.util.IncorrectOperationException; import com.intellij.util.LocalTimeCounter; import com.intellij.xml.psi.XmlPsiBundle; import com.intellij.xml.util.HtmlUtil; import com.intellij.xml.util.XmlUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.intellij.structuralsearch.PredefinedConfigurationUtil.createLegacyConfiguration; /** * @author Eugene.Kudelevsky */ public class XmlStructuralSearchProfile extends StructuralSearchProfile { @Override public void compile(PsiElement @NotNull [] elements, @NotNull GlobalCompilingVisitor globalVisitor) { new XmlCompilingVisitor(globalVisitor).compile(elements); } @Override @NotNull public PsiElementVisitor createMatchingVisitor(@NotNull GlobalMatchingVisitor globalVisitor) { return new XmlMatchingVisitor(globalVisitor); } @Override public boolean isIdentifier(@Nullable PsiElement element) { return element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_NAME; } @NotNull @Override public String getTypedVarString(@NotNull PsiElement element) { return element instanceof XmlText ? element.getText().trim() : super.getTypedVarString(element); } @NotNull @Override public NodeFilter getLexicalNodesFilter() { return element -> XmlMatchUtil.isWhiteSpace(element) || element instanceof PsiErrorElement; } @Override @NotNull public CompiledPattern createCompiledPattern() { return new XmlCompiledPattern(); } @Override public boolean isMyLanguage(@NotNull Language language) { return language instanceof XMLLanguage; } @Override public PsiElement @NotNull [] createPatternTree(@NonNls @NotNull String text, @NotNull PatternTreeContext context, @NotNull LanguageFileType fileType, @NotNull Language language, String contextId, @NotNull Project project, boolean physical) { text = context == PatternTreeContext.File ? text : "<QQQ>" + text + "</QQQ>"; @NonNls final String fileName = "dummy." + fileType.getDefaultExtension(); final PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), physical, true); final XmlDocument document = HtmlUtil.getRealXmlDocument(((XmlFile)fileFromText).getDocument()); if (context == PatternTreeContext.File) { return new PsiElement[] {document}; } assert document != null; final XmlTag rootTag = document.getRootTag(); assert rootTag != null; final XmlTagChild[] children = rootTag.getValue().getChildren(); return (children.length == 1 && children[0] instanceof XmlText) ? children[0].getChildren() : children; } @Override public @NotNull PsiElement extendMatchedByDownUp(@NotNull PsiElement node) { if (XmlUtil.isXmlToken(node, XmlTokenType.XML_DATA_CHARACTERS)) { final PsiElement parent = node.getParent(); if (parent.getTextRange().equals(node.getTextRange())) { return parent; } } return super.extendMatchedByDownUp(node); } @NotNull @Override public Class<? extends TemplateContextType> getTemplateContextTypeClass() { return XmlContextType.class; } @NotNull @Override public LanguageFileType detectFileType(@NotNull PsiElement context) { final PsiFile file = context instanceof PsiFile ? (PsiFile)context : context.getContainingFile(); final Language contextLanguage = context instanceof PsiFile ? null : context.getLanguage(); if (file.getLanguage() == HTMLLanguage.INSTANCE || (file.getFileType().getName().equals("JSP") && contextLanguage == HTMLLanguage.INSTANCE)) { return HtmlFileType.INSTANCE; } return XmlFileType.INSTANCE; } @Override public void checkSearchPattern(@NotNull CompiledPattern pattern) { final ValidatingVisitor visitor = new ValidatingVisitor(); final NodeIterator nodes = pattern.getNodes(); while (nodes.hasNext()) { nodes.current().accept(visitor); nodes.advance(); } nodes.reset(); } static class ValidatingVisitor extends PsiRecursiveElementWalkingVisitor { @Override public void visitErrorElement(@NotNull PsiErrorElement element) { super.visitErrorElement(element); final String errorDescription = element.getErrorDescription(); final PsiElement parent = element.getParent(); if (parent instanceof XmlAttribute && XmlPsiBundle.message("xml.parsing.expected.attribute.eq.sign").equals(errorDescription)) { return; } else if (parent instanceof XmlTag && XmlPsiBundle.message("xml.parsing.named.element.is.not.closed", ((XmlTag)parent).getName()).equals(errorDescription)) { return; } throw new MalformedPatternException(errorDescription); } } @Override public void checkReplacementPattern(@NotNull Project project, @NotNull ReplaceOptions options) { } @Override public StructuralReplaceHandler getReplaceHandler(@NotNull Project project, @NotNull ReplaceOptions replaceOptions) { return new XmlReplaceHandler(project, replaceOptions); } private static class XmlReplaceHandler extends StructuralReplaceHandler { @NotNull private final Project myProject; @NotNull private final ReplaceOptions myReplaceOptions; XmlReplaceHandler(@NotNull Project project, @NotNull ReplaceOptions replaceOptions) { myProject = project; myReplaceOptions = replaceOptions; } @Override public void replace(@NotNull ReplacementInfo info, @NotNull ReplaceOptions options) { final PsiElement elementToReplace = StructuralSearchUtil.getPresentableElement(info.getMatch(0)); assert elementToReplace != null; final String replacementToMake = info.getReplacement(); final PsiElement elementParent = elementToReplace.getParent(); final boolean listContext = elementParent instanceof XmlTag; if (listContext) { doReplaceInContext(info, elementToReplace, replacementToMake, elementParent); } else { final PsiElement[] replacements = MatcherImplUtil.createTreeFromText(replacementToMake, PatternTreeContext.Block, myReplaceOptions.getMatchOptions().getFileType(), myProject); if (replacements.length > 0) { final PsiElement replacement = ReplacerUtil.copySpacesAndCommentsBefore(elementToReplace, replacements, replacementToMake, elementParent); // preserve comments Replacer.handleComments(elementToReplace, replacement, info); elementToReplace.replace(replacement); } else { elementToReplace.delete(); } } } private void doReplaceInContext(ReplacementInfo info, PsiElement elementToReplace, String replacementToMake, PsiElement elementParent) { PsiElement[] replacements = MatcherImplUtil.createTreeFromText(replacementToMake, PatternTreeContext.Block, myReplaceOptions.getMatchOptions().getFileType(), myProject); if (replacements.length > 0 && !(replacements[0] instanceof XmlAttribute) && !(replacements[0] instanceof XmlTagChild)) { replacements = new PsiElement[] { replacements[0].getParent() }; } if (replacements.length > 1) { elementParent.addRangeBefore(replacements[0], replacements[replacements.length - 1], elementToReplace); } else if (replacements.length == 1) { Replacer.handleComments(elementToReplace, replacements[0], info); try { elementParent.addBefore(replacements[0], elementToReplace); } catch (IncorrectOperationException e) { elementToReplace.replace(replacements[0]); } } final int matchSize = info.getMatchesCount(); for (int i = 0; i < matchSize; ++i) { final PsiElement match = info.getMatch(i); if (match == null) continue; final PsiElement element = StructuralSearchUtil.getPresentableElement(match); final PsiElement prevSibling = element.getPrevSibling(); element.getParent().deleteChildRange(XmlMatchUtil.isWhiteSpace(prevSibling) ? prevSibling : element, element); } } } @Override public Configuration @NotNull [] getPredefinedTemplates() { return XmlPredefinedConfigurations.createPredefinedTemplates(); } private static final class XmlPredefinedConfigurations { static Configuration[] createPredefinedTemplates() { return new Configuration[]{ createLegacyConfiguration(SSRBundle.message("predefined.template.xml.tag"), "Xml tag", "<'a/>", getHtmlXml(), XmlFileType.INSTANCE), createLegacyConfiguration(SSRBundle.message("predefined.template.xml.attribute"), "Xml attribute", "<'_tag 'attribute=\"'_value\"/>", getHtmlXml(), XmlFileType.INSTANCE), createLegacyConfiguration(SSRBundle.message("predefined.template.html.attribute"), "Html attribute", "<'_tag 'attribute />", getHtmlXml(), HtmlFileType.INSTANCE), createLegacyConfiguration(SSRBundle.message("predefined.template.xml.attribute.value"), "Xml attribute value", "<'_tag '_attribute=\"'value\"/>", getHtmlXml(), XmlFileType.INSTANCE), createLegacyConfiguration(SSRBundle.message("predefined.template.html.attribute.value"), "Html attribute value", "<'_tag '_attribute='value />", getHtmlXml(), HtmlFileType.INSTANCE), createLegacyConfiguration(SSRBundle.message("predefined.template.xml.html.tag.value"), "Xml/html tag value", "<table>'_content*</table>", getHtmlXml(), HtmlFileType.INSTANCE), createLegacyConfiguration(SSRBundle.message("predefined.template.ul.or.ol"), "<ul> or <ol>", "<'_tag:[regex( ul|ol )] />", getHtmlXml(), HtmlFileType.INSTANCE), createLegacyConfiguration(SSRBundle.message("predefined.template.li.not.contained.in.ul.or.ol"), "<li> not contained in <ul> or <ol>", "[!within( <ul> or <ol> )]<li />", getHtmlXml(), HtmlFileType.INSTANCE), createLegacyConfiguration(SSRBundle.message("predefined.configuration.xml.attribute.referencing.java.class"), "xml attribute referencing java class", "<'_tag 'attribute=\"'_value:[ref( classes, interfaces & enums )]\"/>", SSRBundle.message("xml_html.category"), XmlFileType.INSTANCE), }; } private static String getHtmlXml() { return SSRBundle.message("xml_html.category"); } } }
package org.elasticsearch.xpack.monitoring.exporter.local; import org.apache.lucene.util.SetOnce; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.action.admin.indices.get.GetIndexResponse; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.ingest.GetPipelineResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.cluster.metadata.AliasMetaData; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.metrics.max.Max; import org.elasticsearch.test.TestCluster; import org.elasticsearch.xpack.XPackClient; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.monitoring.MonitoredSystem; import org.elasticsearch.xpack.monitoring.MonitoringSettings; import org.elasticsearch.xpack.monitoring.action.MonitoringBulkDoc; import org.elasticsearch.xpack.monitoring.action.MonitoringBulkRequestBuilder; import org.elasticsearch.xpack.monitoring.action.MonitoringIndex; import org.elasticsearch.xpack.monitoring.exporter.ClusterAlertsUtil; import org.elasticsearch.xpack.monitoring.exporter.Exporter; import org.elasticsearch.xpack.monitoring.exporter.MonitoringTemplateUtils; import org.elasticsearch.xpack.monitoring.test.MonitoringIntegTestCase; import org.elasticsearch.xpack.watcher.client.WatcherClient; import org.elasticsearch.xpack.watcher.transport.actions.get.GetWatchRequest; import org.elasticsearch.xpack.watcher.transport.actions.get.GetWatchResponse; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.junit.After; import org.junit.AfterClass; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.elasticsearch.search.aggregations.AggregationBuilders.max; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.xpack.monitoring.MonitoredSystem.BEATS; import static org.elasticsearch.xpack.monitoring.MonitoredSystem.KIBANA; import static org.elasticsearch.xpack.monitoring.MonitoredSystem.LOGSTASH; import static org.elasticsearch.xpack.monitoring.exporter.MonitoringTemplateUtils.DATA_INDEX; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; public class LocalExporterTests extends MonitoringIntegTestCase { private SetOnce<String> indexTimeFormat = new SetOnce<>(); private static Boolean ENABLE_WATCHER; @AfterClass public static void cleanUpStatic() { ENABLE_WATCHER = null; } @Override protected boolean enableWatcher() { if (ENABLE_WATCHER == null) { ENABLE_WATCHER = randomBoolean(); } return ENABLE_WATCHER; } @Override protected TestCluster buildTestCluster(Scope scope, long seed) throws IOException { String customTimeFormat = null; if (randomBoolean()) { customTimeFormat = randomFrom("YY", "YYYY", "YYYY.MM", "YYYY-MM", "MM.YYYY", "MM"); } indexTimeFormat.set(customTimeFormat); return super.buildTestCluster(scope, seed); } @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal)) .put("xpack.monitoring.exporters._local.type", LocalExporter.TYPE) .put("xpack.monitoring.exporters._local.enabled", false) .put(MonitoringSettings.INTERVAL.getKey(), "-1") .put(NetworkModule.HTTP_ENABLED.getKey(), false) .put(XPackSettings.WATCHER_ENABLED.getKey(), enableWatcher()) .build(); } @After public void stopMonitoring() throws Exception { // Now disabling the monitoring service, so that no more collection are started assertAcked(client().admin().cluster().prepareUpdateSettings() .setTransientSettings(Settings.builder().putNull(MonitoringSettings.INTERVAL.getKey()))); // Exporters are still enabled, allowing on-going collections to be exported without errors. // This assertion loop waits for in flight exports to terminate. It checks that the latest // node_stats document collected for each node is at least 10 seconds old, corresponding to // 2 or 3 elapsed collection intervals. final int elapsedInSeconds = 10; assertBusy(() -> { refresh(".monitoring-es-2-*"); SearchResponse response = client().prepareSearch(".monitoring-es-2-*").setTypes("node_stats").setSize(0) .addAggregation(terms("agg_nodes_ids").field("node_stats.node_id") .subAggregation(max("agg_last_time_collected").field("timestamp"))) .get(); Terms aggregation = response.getAggregations().get("agg_nodes_ids"); for (String nodeName : internalCluster().getNodeNames()) { String nodeId = internalCluster().clusterService(nodeName).localNode().getId(); Terms.Bucket bucket = aggregation.getBucketByKey(nodeId); assertTrue("No bucket found for node id [" + nodeId + "]", bucket != null); assertTrue(bucket.getDocCount() >= 1L); Max subAggregation = bucket.getAggregations().get("agg_last_time_collected"); DateTime lastCollection = new DateTime(Math.round(subAggregation.getValue()), DateTimeZone.UTC); assertTrue(lastCollection.plusSeconds(elapsedInSeconds).isBefore(DateTime.now(DateTimeZone.UTC))); } }, 30L, TimeUnit.SECONDS); // We can now disable the exporters and reset the settings. assertAcked(client().admin().cluster().prepareUpdateSettings() .setTransientSettings(Settings.builder() .putNull("xpack.monitoring.exporters._local.enabled") .putNull("xpack.monitoring.exporters._local.index.name.time_format"))); } public void testExport() throws Exception { if (randomBoolean()) { // indexing some random documents IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[5]; for (int i = 0; i < indexRequestBuilders.length; i++) { indexRequestBuilders[i] = client().prepareIndex("test", "type", Integer.toString(i)) .setSource("title", "This is a random document"); } indexRandom(true, indexRequestBuilders); } if (randomBoolean()) { // create some marvel indices to check if aliases are correctly created final int oldies = randomIntBetween(1, 5); for (int i = 0; i < oldies; i++) { assertAcked(client().admin().indices().prepareCreate(".marvel-es-1-2014.12." + i) .setSettings("number_of_shards", 1, "number_of_replicas", 0).get()); } } Settings.Builder exporterSettings = Settings.builder() .put("xpack.monitoring.exporters._local.enabled", true); String timeFormat = indexTimeFormat.get(); if (timeFormat != null) { exporterSettings.put("xpack.monitoring.exporters._local.index.name.time_format", timeFormat); } // local exporter is now enabled assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(exporterSettings)); if (randomBoolean()) { // export some documents now, before starting the monitoring service final int nbDocs = randomIntBetween(1, 20); List<MonitoringBulkDoc> monitoringDocs = new ArrayList<>(nbDocs); for (int i = 0; i < nbDocs; i++) { monitoringDocs.add(createMonitoringBulkDoc(String.valueOf(i))); } assertBusy(() -> { MonitoringBulkRequestBuilder bulk = monitoringClient().prepareMonitoringBulk(); monitoringDocs.forEach(bulk::add); assertEquals(RestStatus.OK, bulk.get().status()); refresh(); SearchResponse response = client().prepareSearch(".monitoring-*").get(); assertEquals(nbDocs, response.getHits().getTotalHits()); }); checkMonitoringTemplates(); checkMonitoringPipeline(); checkMonitoringAliases(); checkMonitoringMappings(); checkMonitoringDocs(); } // monitoring service is started exporterSettings = Settings.builder() .put(MonitoringSettings.INTERVAL.getKey(), 3L, TimeUnit.SECONDS); assertAcked(client().admin().cluster().prepareUpdateSettings() .setTransientSettings(exporterSettings)); final int numNodes = internalCluster().getNodeNames().length; assertBusy(() -> { assertThat(client().admin().indices().prepareExists(".monitoring-*").get().isExists(), is(true)); ensureYellow(".monitoring-*"); assertThat(client().prepareSearch(".monitoring-es-2-*").setTypes("cluster_state") .get().getHits().getTotalHits(), greaterThan(0L)); assertEquals(0L, client().prepareSearch(".monitoring-es-2-*").setTypes("node") .get().getHits().getTotalHits() % numNodes); assertThat(client().prepareSearch(".monitoring-es-2-*").setTypes("cluster_stats") .get().getHits().getTotalHits(), greaterThan(0L)); assertThat(client().prepareSearch(".monitoring-es-2-*").setTypes("index_recovery") .get().getHits().getTotalHits(), greaterThan(0L)); assertThat(client().prepareSearch(".monitoring-es-2-*").setTypes("index_stats") .get().getHits().getTotalHits(), greaterThan(0L)); assertThat(client().prepareSearch(".monitoring-es-2-*").setTypes("indices_stats") .get().getHits().getTotalHits(), greaterThan(0L)); assertThat(client().prepareSearch(".monitoring-es-2-*").setTypes("shards") .get().getHits().getTotalHits(), greaterThan(0L)); assertThat(client().prepareSearch(".monitoring-data-2").setTypes("cluster_info") .get().getHits().getTotalHits(), greaterThan(0L)); SearchResponse response = client().prepareSearch(".monitoring-es-2-*") .setTypes("node_stats") .setSize(0) .addAggregation(terms("agg_nodes_ids").field("node_stats.node_id")) .get(); Terms aggregation = response.getAggregations().get("agg_nodes_ids"); assertEquals("Aggregation on node_id must return a bucket per node involved in test", numNodes, aggregation.getBuckets().size()); for (String nodeName : internalCluster().getNodeNames()) { String nodeId = internalCluster().clusterService(nodeName).localNode().getId(); Terms.Bucket bucket = aggregation.getBucketByKey(nodeId); assertTrue("No bucket found for node id [" + nodeId + "]", bucket != null); assertTrue(bucket.getDocCount() >= 1L); } }, 30L, TimeUnit.SECONDS); checkMonitoringTemplates(); checkMonitoringPipeline(); checkMonitoringAliases(); checkMonitoringMappings(); checkMonitoringWatches(); checkMonitoringDocs(); } private void checkMonitoringTemplates() { final Set<String> templates = new HashSet<>(); templates.add(".monitoring-data-2"); templates.add(".monitoring-alerts-2"); for (MonitoredSystem system : MonitoredSystem.values()) { templates.add(String.join("-", ".monitoring", system.getSystem(), "2")); } GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates(".monitoring-*").get(); Set<String> actualTemplates = response.getIndexTemplates().stream() .map(IndexTemplateMetaData::getName).collect(Collectors.toSet()); assertEquals(templates, actualTemplates); } private void checkMonitoringPipeline() { GetPipelineResponse response = client().admin().cluster().prepareGetPipeline(Exporter.EXPORT_PIPELINE_NAME).get(); assertTrue("monitoring ingest pipeline not found", response.isFound()); } /** * Checks that the local exporter correctly added aliases to indices created with previous * Marvel versions. */ private void checkMonitoringAliases() { GetIndexResponse response = client().admin().indices().prepareGetIndex().setIndices(".marvel-es-1-*").get(); for (String index : response.getIndices()) { List<AliasMetaData> aliases = response.getAliases().get(index); assertEquals("marvel index should have at least 1 alias: " + index, 1, aliases.size()); String indexDate = index.substring(".marvel-es-1-".length()); String expectedAlias = ".monitoring-es-2-" + indexDate + "-alias"; assertEquals(expectedAlias, aliases.get(0).getAlias()); } } /** * Checks that the local exporter correctly updated the mappings of an existing data index. */ private void checkMonitoringMappings() { IndicesExistsResponse exists = client().admin().indices().prepareExists(DATA_INDEX).get(); if (exists.isExists()) { GetMappingsResponse response = client().admin().indices().prepareGetMappings(DATA_INDEX).get(); for (String mapping : MonitoringTemplateUtils.NEW_DATA_TYPES) { assertTrue("mapping [" + mapping + "] should exist in data index", response.getMappings().get(DATA_INDEX).containsKey(mapping)); } } } /** * Checks that the local exporter correctly creates Watches. */ private void checkMonitoringWatches() throws ExecutionException, InterruptedException { if (enableWatcher()) { final XPackClient xpackClient = new XPackClient(client()); final WatcherClient watcher = xpackClient.watcher(); for (final String watchId : ClusterAlertsUtil.WATCH_IDS) { final String uniqueWatchId = ClusterAlertsUtil.createUniqueWatchId(clusterService(), watchId); final GetWatchResponse response = watcher.getWatch(new GetWatchRequest(uniqueWatchId)).get(); assertTrue("watch [" + watchId + "] should exist", response.isFound()); } } } /** * Checks that the monitoring documents all have the cluster_uuid, timestamp and source_node * fields and belongs to the right data or timestamped index. */ private void checkMonitoringDocs() { ClusterStateResponse response = client().admin().cluster().prepareState().get(); String customTimeFormat = response.getState().getMetaData().transientSettings() .get("xpack.monitoring.exporters._local.index.name.time_format"); assertEquals(indexTimeFormat.get(), customTimeFormat); if (customTimeFormat == null) { customTimeFormat = "YYYY.MM.dd"; } DateTimeFormatter dateParser = ISODateTimeFormat.dateTime().withZoneUTC(); DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(customTimeFormat).withZoneUTC(); SearchResponse searchResponse = client().prepareSearch(".monitoring-*").setSize(100).get(); assertThat(searchResponse.getHits().getTotalHits(), greaterThan(0L)); for (SearchHit hit : searchResponse.getHits().getHits()) { Map<String, Object> source = hit.getSourceAsMap(); assertTrue(source != null && source.isEmpty() == false); String clusterUUID = (String) source.get("cluster_uuid"); assertTrue("document is missing cluster_uuid field", Strings.hasText(clusterUUID)); String timestamp = (String) source.get("timestamp"); assertTrue("document is missing timestamp field", Strings.hasText(timestamp)); String type = hit.getType(); assertTrue(Strings.hasText(type)); @SuppressWarnings("unchecked") Map<String, Object> docSource = (Map<String, Object>) source.get("doc"); boolean isData; MonitoredSystem expectedSystem; if (docSource == null) { // This is a document indexed by the Monitoring service expectedSystem = MonitoredSystem.ES; isData = "cluster_info".equals(type); } else { // This is a document indexed through the Monitoring Bulk API expectedSystem = MonitoredSystem.fromSystem((String) docSource.get("expected_system")); isData = (Boolean) docSource.getOrDefault("is_data", false); } Set<String> expectedIndex = new HashSet<>(); if (isData) { expectedIndex.add(".monitoring-data-2"); } else { String dateTime = dateFormatter.print(dateParser.parseDateTime(timestamp)); expectedIndex.add(".monitoring-" + expectedSystem.getSystem() + "-2-" + dateTime); if ("node".equals(type)) { expectedIndex.add(".monitoring-data-2"); } } assertTrue("Expected " + expectedIndex + " but got " + hit.getIndex(), expectedIndex.contains(hit.getIndex())); @SuppressWarnings("unchecked") Map<String, Object> sourceNode = (Map<String, Object>) source.get("source_node"); if ("shards".equals(type) == false) { assertNotNull("document is missing source_node field", sourceNode); } } } private static MonitoringBulkDoc createMonitoringBulkDoc(String id) throws IOException { String monitoringId = randomFrom(BEATS, KIBANA, LOGSTASH).getSystem(); String monitoringVersion = MonitoringTemplateUtils.TEMPLATE_VERSION; MonitoringIndex index = randomFrom(MonitoringIndex.values()); XContentType xContentType = randomFrom(XContentType.values()); BytesReference source; try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { builder.startObject(); { builder.field("expected_system", monitoringId); if (index == MonitoringIndex.DATA) { builder.field("is_data", true); } final int nbFields = randomIntBetween(1, 3); for (int i = 0; i < nbFields; i++) { builder.field("field_" + i, i); } } builder.endObject(); source = builder.bytes(); } return new MonitoringBulkDoc(monitoringId, monitoringVersion, index, "doc", id, source, xContentType); } }
package edu.umd.cs.findbugs.cloud.appEngine; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.UnknownHostException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; import com.google.protobuf.GeneratedMessage; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.IGuiCallback; import edu.umd.cs.findbugs.Version; import edu.umd.cs.findbugs.cloud.Cloud.SigninState; import edu.umd.cs.findbugs.cloud.MutableCloudTask; import edu.umd.cs.findbugs.cloud.SignInCancelledException; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.Evaluation; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.FindIssues; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.FindIssuesResponse; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.GetRecentEvaluations; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.Issue; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.LogIn; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.RecentEvaluations; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.SetBugLink; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.UpdateIssueTimestamps; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.UpdateIssueTimestamps.IssueGroup; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.UploadEvaluation; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.UploadIssues; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.UploadIssues.Builder; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.WebCloudProtoUtil; import edu.umd.cs.findbugs.cloud.username.WebCloudNameLookup; import edu.umd.cs.findbugs.util.Util; public class WebCloudNetworkClient { private static final Logger LOGGER = Logger.getLogger(WebCloudNetworkClient.class.getPackage().getName()); /** For debugging */ private static final boolean FORCE_UPLOAD_ALL_ISSUES = false; private static final int GLOBAL_HTTP_SOCKET_TIMEOUT = 5000; private static final int BUG_UPLOAD_PARTITION_SIZE = 5; /** For updating firstSeen timestamps */ private static final int BUG_UPDATE_PARTITION_SIZE = 10; /** * This needs to stay low to prevent overloading the App Engine clusters * with long-running requests. */ private static final int HASH_CHECK_PARTITION_SIZE = 20; private WebCloudClient cloudClient; private WebCloudNameLookup lookerupper; private ConcurrentMap<String, Issue> issuesByHash = new ConcurrentHashMap<String, Issue>(); private String host; private Long sessionId; private String username; private volatile long earliestSeenServerTime = System.currentTimeMillis(); private volatile long maxRecentEvaluationMillis = 0; private CopyOnWriteArrayList<String> timestampsToUpdate = new CopyOnWriteArrayList<String>(); public void setCloudClient(WebCloudClient webCloudClient) { this.cloudClient = webCloudClient; } /** returns whether soft initialization worked and the user is now signed in */ public boolean initialize() throws IOException { lookerupper = createNameLookup(); lookerupper.softSignin(); this.sessionId = lookerupper.getSessionId(); this.username = lookerupper.getUsername(); this.host = lookerupper.getHost(); return this.sessionId != null; } public void signIn(boolean force) throws IOException { if (!force && sessionId != null) throw new IllegalStateException("already signed in"); if (!lookerupper.signIn(cloudClient.getPlugin(), cloudClient.getBugCollection())) { getGuiCallback().setErrorMessage("Signing into " + cloudClient.getCloudName() + " failed!"); return; } this.sessionId = lookerupper.getSessionId(); this.username = lookerupper.getUsername(); this.host = lookerupper.getHost(); if (getUsername() == null || host == null) { throw new IllegalStateException("No App Engine Cloud username or hostname found! Check etc/findbugs.xml"); } // now that we know our own username, we need to update all the bugs in // the UI to show what "our" // designation & comments are. // this might be really slow with a lot of issues. seems fine so far. for (BugInstance instance : cloudClient.getBugCollection().getCollection()) { Issue issue = issuesByHash.get(instance.getInstanceHash()); if (issue != null && issue.getEvaluationsCount() > 0) { cloudClient.updateBugInstanceAndNotify(instance); } } } public void setBugLinkOnCloud(final BugInstance b, final String type, final String bugLink) throws IOException, SignInCancelledException { cloudClient.signInIfNecessary("To store the bug URL on the " + cloudClient.getCloudName() + ", you must sign in."); RetryableConnection<Object> conn = new RetryableConnection<Object>("/set-bug-link", true) { @Override public void write(OutputStream out) throws IOException { SetBugLink.newBuilder().setSessionId(sessionId).setHash(WebCloudProtoUtil.encodeHash(b.getInstanceHash())).setBugLinkType(type) .setUrl(bugLink).build().writeTo(out); } @Override public Object finish(int responseCode, String responseMessage, InputStream response) { if (responseCode != 200) { throw new IllegalStateException("server returned error code " + responseCode + " " + responseMessage); } return null; } }; conn.go(); } public void setBugLinkOnCloudAndStoreIssueDetails(BugInstance b, String viewUrl, String linkType) throws IOException, SignInCancelledException { setBugLinkOnCloud(b, linkType, viewUrl); String hash = b.getInstanceHash(); storeIssueDetails(hash, Issue.newBuilder(getIssueByHash(hash)) .setBugLink(viewUrl) .setBugLinkTypeStr(linkType) .build()); } public void logIntoCloudForce() throws IOException { RetryableConnection<Object> conn = new RetryableConnection<Object>("/log-in", true) { @Override public void write(OutputStream out) throws IOException { LogIn logIn = LogIn.newBuilder().setSessionId(sessionId) .setAnalysisTimestamp(cloudClient.getBugCollection().getAnalysisTimestamp()).build(); logIn.writeTo(out); } @Override public Object finish(int responseCode, String responseMessage, InputStream response) { if (responseCode != 200) { throw new IllegalStateException("Could not log into cloud with ID " + sessionId + " - error " + responseCode + " " + responseMessage); } return null; } }; conn.go(); } public void generateHashCheckRunnables(final MutableCloudTask task, final List<String> hashes, List<Callable<Object>> tasks, final ConcurrentMap<String, BugInstance> bugsByHash) { final int numBugs = hashes.size(); final AtomicInteger numberOfBugsCheckedSoFar = new AtomicInteger(); for (int i = 0; i < numBugs; i += HASH_CHECK_PARTITION_SIZE) { final List<String> partition = hashes.subList(i, Math.min(i + HASH_CHECK_PARTITION_SIZE, numBugs)); tasks.add(new Callable<Object>() { public Object call() throws Exception { checkHashesPartition(partition, bugsByHash); numberOfBugsCheckedSoFar.addAndGet(partition.size()); int sofar = numberOfBugsCheckedSoFar.get(); task.update("Checked " + sofar + " of " + numBugs, (sofar * 100.0 / numBugs)); return null; } }); } } public CopyOnWriteArrayList<String> getTimestampsToUpdate() { return timestampsToUpdate; } public MutableCloudTask generateUpdateTimestampRunnables(List<Callable<Void>> callables) throws SignInCancelledException { List<String> timestamps = new ArrayList<String>(timestampsToUpdate); final int bugCount = timestamps.size(); if (bugCount == 0) return null; final List<BugInstance> bugs = new ArrayList<BugInstance>(); long biggestDiffMs = 0; boolean someZeroOnCloud = false; long earliestFirstSeen = Long.MAX_VALUE; for (String hash : timestamps) { BugInstance bug = cloudClient.getBugByHash(hash); if (bug != null) { bugs.add(bug); long firstSeenFromCloud = getFirstSeenFromCloud(bug); long localFirstSeen = cloudClient.getLocalFirstSeen(bug); long diffMs = firstSeenFromCloud - localFirstSeen; if (diffMs > biggestDiffMs) { biggestDiffMs = diffMs; earliestFirstSeen = Math.min(earliestFirstSeen, localFirstSeen); } else if (firstSeenFromCloud == 0 && localFirstSeen != 0) someZeroOnCloud = true; } } if (!someZeroOnCloud && biggestDiffMs < 1000 * 60) // less than 1 minute off return null; // if some bugs have a zero timestamp, let's not bother telling the user // anything specific String durationStr; if (someZeroOnCloud) durationStr = ""; else durationStr = " up to " + toDuration(biggestDiffMs); Calendar now = Calendar.getInstance(); TimeZone timeZone = now.getTimeZone(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); String timeStr = df.format(now.getTime()); boolean daylight = timeZone.inDaylightTime(now.getTime()); String zoneStr = timeZone.getDisplayName(daylight, TimeZone.LONG) + " (" + timeZone.getDisplayName(daylight, TimeZone.SHORT) + ")"; Calendar earliest = Calendar.getInstance(timeZone); earliest.setTimeInMillis(earliestFirstSeen); String earliestStr = df.format(earliest.getTime()); int result = getGuiCallback().showConfirmDialog( "Your first-seen dates for " + bugCount + " bugs are " + durationStr + " earlier than those on the " + cloudClient.getCloudName() + ".\n" + "The earliest first-seen from the local analysis is " + earliestStr + "\n" + "Would you like to back date the first-seen dates on the Cloud?\n" + "\n" + "Current time: " + timeStr + " " + zoneStr + "\n" + "(If you're not sure the time and time zone are correct, click Cancel.)", cloudClient.getCloudName(), "Update", "Cancel"); if (result != 0) return null; cloudClient.signInIfNecessary(null); // since the protocol groups bugs by timestamp, let's optimize network // bandwidth by sorting first. probably // doesn't matter. Collections.sort(bugs, new Comparator<BugInstance>() { public int compare(BugInstance o1, BugInstance o2) { long v1 = o1.getFirstVersion(); long v2 = o2.getFirstVersion(); if (v1 < v2) return -1; if (v1 > v2) return 1; return 0; } }); final MutableCloudTask task = cloudClient.createTask("Updating " + cloudClient.getCloudName()); final AtomicInteger soFar = new AtomicInteger(0); for (int i = 0; i < bugCount; i += BUG_UPDATE_PARTITION_SIZE) { final List<BugInstance> partition = bugs.subList(i, Math.min(bugCount, i + BUG_UPLOAD_PARTITION_SIZE)); callables.add(new Callable<Void>() { public Void call() throws Exception { updateTimestampsNow(partition); int updated = soFar.addAndGet(partition.size()); task.update("Updated " + updated + " of " + bugCount + " timestamps", updated * 100.0 / bugCount); return null; } }); } return task; } public MutableCloudTask generateUploadRunnables(final List<BugInstance> newBugs, List<Callable<Void>> callables) throws SignInCancelledException { final int bugCount = newBugs.size(); if (bugCount == 0) return null; if (cloudClient.getCloudTokenProperty() == null && cloudClient.getSigninState().askToSignIn()) cloudClient.signInIfNecessary("Some bugs were not found on the " + cloudClient.getCloudName() + ".\n" + "Your signin status is " + cloudClient.getSigninState() +"\n" + "Would you like to sign in and upload them to the Cloud?"); final MutableCloudTask task = cloudClient.createTask("Uploading to the " + cloudClient.getCloudName()); final AtomicInteger bugsUploaded = new AtomicInteger(0); for (int i = 0; i < bugCount; i += BUG_UPLOAD_PARTITION_SIZE) { final List<BugInstance> partition = newBugs.subList(i, Math.min(bugCount, i + BUG_UPLOAD_PARTITION_SIZE)); callables.add(new Callable<Void>() { public Void call() throws Exception { uploadNewBugsPartition(partition); bugsUploaded.addAndGet(partition.size()); int uploaded = bugsUploaded.get(); task.update("Uploaded " + uploaded + " of " + bugCount + " issues", uploaded * 100.0 / bugCount); return null; } }); } return task; } public long getFirstSeenFromCloud(BugInstance b) { String instanceHash = b.getInstanceHash(); Issue issue = issuesByHash.get(instanceHash); if (issue == null) return Long.MAX_VALUE; if (WebCloudClient.DEBUG_FIRST_SEEN) System.out.println("First seen is " + issue.getFirstSeen() + " for " + b.getMessage()); if (issue.getFirstSeen() == 0) return Long.MAX_VALUE; return issue.getFirstSeen(); } public void storeIssueDetails(String hash, Issue issue) { for (Evaluation eval : issue.getEvaluationsList()) { if (eval.getWhen() > maxRecentEvaluationMillis) { maxRecentEvaluationMillis = eval.getWhen(); } } issuesByHash.put(hash, issue); } public RecentEvaluations getRecentEvaluationsFromServer() throws IOException { RetryableConnection<RecentEvaluations> conn = new RetryableConnection<RecentEvaluations>("/get-recent-evaluations", true) { @Override public void write(OutputStream out) throws IOException { GetRecentEvaluations.Builder msgb = GetRecentEvaluations.newBuilder(); if (sessionId != null) { msgb.setSessionId(sessionId); } // I'm not sure if we really need mostRecentEvaluationMillis // anymore, as earliestSeenServerTime should always be later msgb.setTimestamp(Math.max(earliestSeenServerTime, maxRecentEvaluationMillis)); msgb.build().writeTo(out); } @Override public RecentEvaluations finish(int responseCode, String responseMessage, InputStream response) throws IOException { if (responseCode != 200) { throw new ServerReturnedErrorCodeException(responseCode, responseMessage); } RecentEvaluations evals = RecentEvaluations.parseFrom(response); updateMostRecentEvaluationField(evals); if (!(evals.hasAskAgain() && evals.getAskAgain())) // only update the server last seen time if we're done checking for evals earliestSeenServerTime = evals.getCurrentServerTime(); return evals; } }; return conn.go(); } public Evaluation getMostRecentEvaluationBySelf(BugInstance b) { Issue issue = issuesByHash.get(b.getInstanceHash()); if (issue == null) return null; Evaluation mostRecent = null; long when = Long.MIN_VALUE; String myUsername = getUsername(); for (Evaluation e : issue.getEvaluationsList()) { if (e.getWho().equals(myUsername) && e.getWhen() > when) { mostRecent = e; when = e.getWhen(); } } return mostRecent; } public String getUsername() { return username; } public String getHost() { return host; } @SuppressWarnings({ "deprecation" }) public void storeUserAnnotation(BugInstance bugInstance) throws SignInCancelledException, IOException { // store this stuff first because signIn might clobber it. this is // kludgy but works. BugDesignation designation = bugInstance.getNonnullUserDesignation(); long timestamp = designation.getTimestamp(); String designationKey = designation.getDesignationKey(); String comment = designation.getAnnotationText(); cloudClient.signInIfNecessary("To store your reviews on the " + cloudClient.getCloudName() + ", you must sign in first."); Evaluation.Builder evalBuilder = Evaluation.newBuilder().setWhen(timestamp).setDesignation(designationKey); if (comment != null) { evalBuilder.setComment(comment); } String hash = bugInstance.getInstanceHash(); Evaluation eval = evalBuilder.build(); UploadEvaluation uploadMsg = UploadEvaluation.newBuilder().setSessionId(sessionId).setHash(WebCloudProtoUtil.encodeHash(hash)) .setEvaluation(eval).build(); openPostUrl("/upload-evaluation", uploadMsg); // store so it shows up in cloud report, etc Issue issue = issuesByHash.get(hash); if (issue == null) // I think this only happens in tests -keith return; Evaluation evalToStore = username == null ? eval : Evaluation.newBuilder(eval).setWho(username).build(); Issue.Builder issueToStore = Issue.newBuilder(issue); issuesByHash.put(hash, issueToStore.addEvaluations(evalToStore).build()); cloudClient.updateBugInstanceAndNotify(bugInstance); } public @CheckForNull Issue getIssueByHash(String hash) { return issuesByHash.get(hash); } public void signOut(boolean background) { if (sessionId != null) { final long oldSessionId = sessionId; sessionId = null; Runnable logoutRequest = new Runnable() { public void run() { try { openPostUrl("/log-out/" + oldSessionId, null); } catch (Exception e) { LOGGER.log(Level.INFO, "Could not sign out", e); } } }; if (background) cloudClient.getBackgroundExecutor().execute(logoutRequest); else logoutRequest.run(); WebCloudNameLookup.clearSavedSessionInformation(); } } public boolean ready() { return host != null; } public Long getSessionId() { return sessionId; } protected WebCloudNameLookup createNameLookup() { WebCloudNameLookup nameLookup = new WebCloudNameLookup(); nameLookup.loadProperties(cloudClient.getPlugin()); return nameLookup; } private void updateMostRecentEvaluationField(RecentEvaluations evaluations) { for (Issue issue : evaluations.getIssuesList()) for (Evaluation evaluation : issue.getEvaluationsList()) if (evaluation.getWhen() > maxRecentEvaluationMillis) maxRecentEvaluationMillis = evaluation.getWhen(); } private void checkHashesPartition(List<String> hashes, Map<String, BugInstance> bugsByHash) throws IOException { FindIssuesResponse response = submitHashes(hashes); if (response.hasCurrentServerTime() && (response.getCurrentServerTime() < earliestSeenServerTime)) earliestSeenServerTime = response.getCurrentServerTime(); int count = Math.min(hashes.size(), response.getFoundIssuesCount()); if (hashes.size() != response.getFoundIssuesCount()) { LOGGER.severe(String.format("Requested %d issues, got %d responses", hashes.size(), response.getFoundIssuesCount())); } for (int j = 0; j < count; j++) { String hash = hashes.get(j); Issue issue = response.getFoundIssues(j); if (isEmpty(issue)) // the issue was not found! continue; storeIssueDetails(hash, issue); BugInstance bugInstance; if (FORCE_UPLOAD_ALL_ISSUES) bugInstance = bugsByHash.get(hash); else bugInstance = bugsByHash.remove(hash); if (bugInstance == null) { LOGGER.warning("Server sent back issue that we don't know about: " + hash + " - " + issue); continue; } long firstSeen = cloudClient.getLocalFirstSeen(bugInstance); long cloudFirstSeen = issue.getFirstSeen(); if (WebCloudClient.DEBUG_FIRST_SEEN) System.out.printf("%s %s%n", new Date(firstSeen), new Date(cloudFirstSeen)); if (firstSeen > 0 && firstSeen < cloudFirstSeen) timestampsToUpdate.add(hash); cloudClient.updateBugInstanceAndNotify(bugInstance); } } private boolean isEmpty(Issue issue) { return !issue.hasFirstSeen() && !issue.hasLastSeen() && issue.getEvaluationsCount() == 0; } private String toDuration(long ms) { long weeks = ms / (1000 * 60 * 60 * 24 * 7); if (weeks > 0) return plural(weeks, "week"); long days = ms / (1000 * 60 * 60 * 24); if (days > 0) return plural(days, "day"); long hours = ms / (1000 * 60 * 60); if (hours > 0) return plural(hours, "hour"); long minutes = ms / (1000 * 60); if (minutes > 0) return plural(minutes, "minute"); return "less than a minute"; } private String plural(long value, String noun) { return value + " " + (value == 1 ? noun : noun + "s"); } private void updateTimestampsNow(final Collection<BugInstance> bugs) throws IOException { final UpdateIssueTimestamps.Builder builder = UpdateIssueTimestamps.newBuilder().setSessionId(sessionId); for (Map.Entry<Long, Set<BugInstance>> entry : groupBugsByTimestamp(bugs).entrySet()) { UpdateIssueTimestamps.IssueGroup.Builder groupBuilder = IssueGroup.newBuilder().setTimestamp(entry.getKey()); for (BugInstance bugInstance : entry.getValue()) { groupBuilder.addIssueHashes(WebCloudProtoUtil.encodeHash(bugInstance.getInstanceHash())); } builder.addIssueGroups(groupBuilder.build()); } LOGGER.finer("Updating timestamps for " + bugs.size() + " bugs in " + builder.getIssueGroupsCount() + " groups"); RetryableConnection<Void> conn = new RetryableConnection<Void>("/update-issue-timestamps", true) { @Override public void write(OutputStream out) throws IOException { builder.build().writeTo(out); } @Override public Void finish(int responseCode, String responseMessage, InputStream response) throws IOException { if (responseCode != 200) throw new IllegalStateException("server returned error code " + responseCode + " " + responseMessage); return null; } }; conn.go(); } private Map<Long, Set<BugInstance>> groupBugsByTimestamp(Collection<BugInstance> bugs) { Map<Long, Set<BugInstance>> map = new HashMap<Long, Set<BugInstance>>(); for (BugInstance bug : bugs) { long firstSeen = cloudClient.getFirstSeen(bug); Set<BugInstance> bugsForTimestamp = map.get(firstSeen); if (bugsForTimestamp == null) { bugsForTimestamp = new HashSet<BugInstance>(); map.put(firstSeen, bugsForTimestamp); } bugsForTimestamp.add(bug); } return map; } private IGuiCallback getGuiCallback() { return cloudClient.getGuiCallback(); } private FindIssuesResponse submitHashes(final List<String> bugsByHash) throws IOException { LOGGER.finer("Checking " + bugsByHash.size() + " bugs against App Engine Cloud"); FindIssues.Builder msgb = FindIssues.newBuilder(); if (sessionId != null) { msgb.setSessionId(sessionId); } msgb.setVersionInfo(ProtoClasses.VersionInfo.newBuilder() .setAppName(Version.getApplicationName()) .setAppVersion(Version.getApplicationVersion()) .setFindbugsVersion(Version.getReleaseWithDateIfDev())); final FindIssues hashList = msgb.addAllMyIssueHashes(WebCloudProtoUtil.encodeHashes(bugsByHash)).build(); RetryableConnection<FindIssuesResponse> conn = new RetryableConnection<FindIssuesResponse>("/find-issues", true) { @Override public void write(OutputStream out) throws IOException { long start = System.currentTimeMillis(); hashList.writeTo(out); long elapsed = System.currentTimeMillis() - start; LOGGER.finer("Submitted hashes (" + hashList.getSerializedSize() / 1024 + " KB) in " + elapsed + "ms (" + (elapsed / bugsByHash.size()) + "ms per hash)"); } @Override public FindIssuesResponse finish(int responseCode, String responseMessage, InputStream response) throws IOException { long start = System.currentTimeMillis(); if (responseCode != 200) { LOGGER.info("Error " + responseCode + " : " + responseMessage); throw new IOException("Response code " + responseCode + " : " + responseMessage); } FindIssuesResponse firesponse = FindIssuesResponse.parseFrom(response); int foundIssues = firesponse.getFoundIssuesCount(); long elapsed = System.currentTimeMillis() - start; LOGGER.fine("Received " + foundIssues + " bugs from server in " + elapsed + "ms (" + (elapsed / (foundIssues + 1)) + "ms per bug)"); return firesponse; } }; return conn.go(); } private void uploadNewBugsPartition(final Collection<BugInstance> bugsToSend) throws IOException { LOGGER.finer("Uploading " + bugsToSend.size() + " bugs to App Engine Cloud"); UploadIssues uploadIssues = buildUploadIssuesCommandInUIThread(bugsToSend); if (uploadIssues == null) return; openPostUrl("/upload-issues", uploadIssues); // if it worked, store the issues locally final List<String> hashes = new ArrayList<String>(); for (final Issue issue : uploadIssues.getNewIssuesList()) { final String hash = WebCloudProtoUtil.decodeHash(issue.getHash()); storeIssueDetails(hash, issue); hashes.add(hash); } // let the GUI know that things changed cloudClient.getBugUpdateExecutor().execute(new Runnable() { public void run() { for (String hash : hashes) { BugInstance bugInstance = cloudClient.getBugByHash(hash); if (bugInstance != null) { cloudClient.updatedIssue(bugInstance); } } } }); } private UploadIssues buildUploadIssuesCommandInUIThread(final Collection<BugInstance> bugsToSend) { ExecutorService updateExecutor = cloudClient.getBugUpdateExecutor(); Future<UploadIssues> future = updateExecutor.submit(new Callable<UploadIssues>() { public UploadIssues call() throws Exception { Builder uploadIssuesCmd = UploadIssues.newBuilder(); if (cloudClient.getCloudTokenProperty() != null) { uploadIssuesCmd.setToken(cloudClient.getCloudTokenProperty()); LOGGER.info("Using Cloud Token: " + cloudClient.getCloudTokenProperty()); } if (sessionId != null) uploadIssuesCmd.setSessionId(sessionId); for (BugInstance bug : bugsToSend) { uploadIssuesCmd.addNewIssues(Issue.newBuilder() .setHash(WebCloudProtoUtil.encodeHash(bug.getInstanceHash())) .setBugPattern(bug.getType()).setPriority(bug.getPriority()) .setPrimaryClass(bug.getPrimaryClass().getClassName()) .setFirstSeen(cloudClient.getFirstSeen(bug)) .build()); } return uploadIssuesCmd.build(); } }); try { return future.get(); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "", e); return null; } catch (ExecutionException e) { LOGGER.log(Level.SEVERE, "", e); return null; } } /** * package-private for testing */ HttpURLConnection openConnection(String url) throws IOException { URL u = new URL(host + url); return (HttpURLConnection) u.openConnection(); } private void openPostUrl(String url, final GeneratedMessage uploadMsg) throws IOException { RetryableConnection<Void> rc = new RetryableConnection<Void>(url, true) { @Override public void write(OutputStream out) throws IOException { if (uploadMsg != null) { uploadMsg.writeTo(out); } else { out.write(0); // why write a null byte?? } } @Override public Void finish(int responseCode, String responseMessage, InputStream response) throws IOException { if (responseCode != 200) throw new IllegalStateException("server returned error code when opening " + url + ": " + responseCode + " " + responseMessage); return null; } }; rc.go(); } protected abstract class RetryableConnection<RV> { protected final String url; private final boolean post; public RetryableConnection(String url, boolean post) { this.post = post; this.url = url; } /** NOTE: this may be called more than once if the connection fails the first time! */ public abstract void write(OutputStream out) throws IOException; public abstract RV finish(int responseCode, String responseMessage, InputStream response) throws IOException; public RV go() throws IOException { RV result = null; HttpURLConnection conn = null; boolean finished = false; IOException firstException = null; IOException lastException = null; for (int i = 0; i < 3 && !finished; i++) { if (i > 0 && lastException != null) LOGGER.warning("Retrying connection to " + url + " due to " + lastException.getClass().getSimpleName() + ": " + lastException.getMessage()); try { conn = openConnection(url); // increase the timeout by 5 seconds each iteration int timeout = GLOBAL_HTTP_SOCKET_TIMEOUT; if (lastException instanceof SocketTimeoutException) // increase timeout by 5 seconds each iteration timeout *= i; conn.setConnectTimeout(timeout); if (post) { conn.setDoOutput(true); conn.setRequestMethod("POST"); } conn.connect(); OutputStream out = conn.getOutputStream(); write(out); out.close(); result = finish(conn.getResponseCode(), conn.getResponseMessage(), conn.getInputStream()); finished = true; } catch (UnknownHostException ex2) { UnknownHostException ex = new UnknownHostException(ex2.getMessage()); if (firstException == null) firstException = ex; lastException = ex; finished = true; } catch (IOException ex) { if (firstException == null) firstException = ex; lastException = ex; } finally { if (conn != null) { int responseCode; try { responseCode = conn.getResponseCode(); if (responseCode != 500 && responseCode != -1) // only retry on 500 or no-response finished = true; } catch (IOException e) { // skip this check } try { conn.disconnect(); } catch (Exception e) { // ignore } } } } if (result != null) return result; if (firstException != null) throw firstException; return null; } } }
package org.batfish.datamodel; import static com.google.common.base.MoreObjects.firstNonNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.batfish.common.BatfishException; public abstract class AbstractRouteBuilder< S extends AbstractRouteBuilder<S, T>, T extends AbstractRoute> { private int _admin; private long _metric; private Prefix _network; private Ip _nextHopIp = Route.UNSET_ROUTE_NEXT_HOP_IP; private boolean _nonForwarding; private boolean _nonRouting; private int _tag = Route.UNSET_ROUTE_TAG; @Nonnull public abstract T build(); public final int getAdmin() { return _admin; } public final S setAdmin(int admin) { _admin = admin; return getThis(); } // To handle the class casting exception while returning S in chaining methods @Nonnull protected abstract S getThis(); public final long getMetric() { return _metric; } public final S setMetric(long metric) { _metric = metric; return getThis(); } public final Prefix getNetwork() { return _network; } public final S setNetwork(Prefix network) { if (network == null) { throw new BatfishException("Cannot construct AbstractRoute with null network"); } _network = network; return getThis(); } public final Ip getNextHopIp() { return _nextHopIp; } public final S setNextHopIp(@Nullable Ip nextHopIp) { _nextHopIp = firstNonNull(nextHopIp, Route.UNSET_ROUTE_NEXT_HOP_IP); return getThis(); } public final boolean getNonForwarding() { return _nonForwarding; } public final S setNonForwarding(boolean nonForwarding) { _nonForwarding = nonForwarding; return getThis(); } public final boolean getNonRouting() { return _nonRouting; } public final S setNonRouting(boolean nonRouting) { _nonRouting = nonRouting; return getThis(); } public int getTag() { return _tag; } public final S setTag(@Nullable Integer tag) { _tag = firstNonNull(tag, Route.UNSET_ROUTE_TAG); return getThis(); } }
package pl.grzeslowski.jsupla.protocol.structs.sd; import pl.grzeslowski.jsupla.protocol.calltypes.ServerDeviceCallType; import java.util.Arrays; import static pl.grzeslowski.jsupla.protocol.ProtoPreconditions.checkArrayLength; import static pl.grzeslowski.jsupla.protocol.consts.JavaConsts.BYTE_SIZE; import static pl.grzeslowski.jsupla.protocol.consts.JavaConsts.INT_SIZE; import static pl.grzeslowski.jsupla.protocol.consts.ProtoConsts.SUPLA_CHANNELVALUE_SIZE; public final class TSD_SuplaChannelNewValue implements ServerDevice { public final int senderId; /** * unsigned */ public final byte channelNumber; /** * unsigned */ public final int durationMs; public final byte[] value; public TSD_SuplaChannelNewValue(int senderId, byte channelNumber, int durationMs, byte[] value) { this.senderId = senderId; this.channelNumber = channelNumber; this.durationMs = durationMs; this.value = checkArrayLength(value, SUPLA_CHANNELVALUE_SIZE); } @Override public ServerDeviceCallType callType() { throw new UnsupportedOperationException(); } @Override public int size() { return BYTE_SIZE + INT_SIZE * 2 + SUPLA_CHANNELVALUE_SIZE; } @Override public String toString() { return "TSD_SuplaChannelNewValue{" + "senderId=" + senderId + ", channelNumber=" + channelNumber + ", durationMs=" + durationMs + ", value=" + Arrays.toString(value) + '}'; } }
package io.advantageous.qbit.vertx.http.server; import io.advantageous.qbit.http.request.HttpResponseCreator; import io.advantageous.qbit.http.request.HttpResponseDecorator; import io.advantageous.qbit.http.HttpStatus; import io.advantageous.qbit.http.request.HttpResponse; import io.advantageous.qbit.http.request.HttpResponseReceiver; import io.advantageous.qbit.util.MultiMap; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpServerResponse; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; public class VertxHttpResponseReceiver implements HttpResponseReceiver<Object> { private final HttpServerResponse response; private final CopyOnWriteArrayList<HttpResponseDecorator> decorators; private final HttpResponseCreator httpResponseCreator; private final String requestPath; private final MultiMap<String, String> requestHeaders; private final MultiMap<String, String> requestParams; public VertxHttpResponseReceiver(final String requestPath, final MultiMap<String, String> headers, final MultiMap<String, String> params, final HttpServerResponse response, final CopyOnWriteArrayList<HttpResponseDecorator> decorators, final HttpResponseCreator httpResponseCreator) { this.response = response; this.decorators = decorators; this.httpResponseCreator = httpResponseCreator; this.requestPath = requestPath; this.requestHeaders = headers; this.requestParams = params; } @Override public void response(int code, String contentType, Object body) { response(code, contentType, body, MultiMap.empty()); } @Override public void response(final int code, final String contentType, final Object body, final MultiMap<String, String> responseHeaders) { final HttpResponse<?> decoratedResponse = decorators.size() > 0 ? httpResponseCreator.createResponse( decorators, requestPath, code, contentType, body, responseHeaders, this.requestHeaders, this.requestParams) : null; /** Response was not decorated. */ if (decoratedResponse == null) { doResponse(code, contentType, body, responseHeaders); } else { /** Response was decorated. */ doResponse(decoratedResponse.code(), decoratedResponse.contentType(), decoratedResponse.body(), decoratedResponse.headers()); } } private void doResponse(final int code, final String contentType, final Object body, final MultiMap<String, String> headers) { if (headers!= null && !headers.isEmpty()) { for (Map.Entry<String, Collection<String>> entry : headers) { this.response.putHeader(entry.getKey(), entry.getValue()); } } if (contentType!=null) { this.response.putHeader("Content-Type", contentType); } this.response.setStatusCode(code); final String message = HttpStatus.message(code); if (message!=null) { this.response.setStatusMessage(message); } final Buffer buffer = createBuffer(body, this.response); this.response.end(buffer); } private static Buffer createBuffer(Object body, HttpServerResponse response) { Buffer buffer = null; if (body instanceof byte[]) { byte[] bBody = ((byte[]) body); response.putHeader("Content-Length", String.valueOf(bBody.length)); buffer = Buffer.buffer(bBody); } else if (body instanceof String) { String sBody = ((String) body); byte[] bBody = sBody.getBytes(StandardCharsets.UTF_8); response.putHeader("Content-Length", String.valueOf(bBody.length)); buffer = Buffer.buffer(bBody); } return buffer; } }
import java.io.* ; import java.util.zip.* ; import javax.servlet.* ; import javax.servlet.http.* ; import org.apache.oro.text.perl.* ; public class Version extends HttpServlet { private final static String CVS_REV = "$Revision$" ; private final static String CVS_DATE = "$Date$" ; private final static String CVS_NAME = "$Name$" ; private final static String CVS_TAG = CVS_NAME.substring(CVS_NAME.indexOf(' ')+1,CVS_NAME.lastIndexOf(' ')) ; private final static int BUFFERLENGTH = 32768 ; private class DirectoryFilter implements FileFilter { public boolean accept(File file) { return file.isDirectory() ; } } private class NotDirectoryFilter implements FileFilter { public boolean accept(File file) { return !file.isDirectory() ; } } public void init (ServletConfig config) throws ServletException { super.init(config) ; } public void doGet (HttpServletRequest req, HttpServletResponse res) throws java.io.IOException { res.setContentType("text/plain") ; ServletOutputStream out = res.getOutputStream() ; // Print out the tag this file was checked out with. out.println(CVS_TAG.length() > 0 ? CVS_TAG : "Unknown" ) ; checksumDirectory(new File(this.getServletContext().getRealPath("/")), "", out) ; } public void checksumDirectory(File parent_dir, String sub_dir, ServletOutputStream out) throws java.io.IOException { Perl5Util perl = new Perl5Util() ; File dir = new File(parent_dir,sub_dir) ; File[] files = dir.listFiles(new NotDirectoryFilter()) ; // Loop through the files and get a checksum for each. for (int i = 0; i < files.length; ++i) { out.print(files[i].getPath().substring(parent_dir.getPath().length()+1)+' ') ; Checksum checksum = new CRC32() ; int class_length = (int)files[i].length() ; char[] buffer = new char[BUFFERLENGTH] ; Reader in = new InputStreamReader(new CheckedInputStream(new FileInputStream(files[i]), checksum), "8859_1") ; StringBuffer file_buffer = new StringBuffer() ; // Read the classfile, and have the inputstream compute the checksum as we go. for (int read; -1 != (read = in.read(buffer,0,BUFFERLENGTH));) { file_buffer.append(buffer, 0, read) ; } ; // Find and print the revision. if (perl.match("/\\$"+"Revision: (\\d(?:\\.\\d)+) "+"\\$/",file_buffer.toString())) { String revision = perl.group(1) ; out.print(revision+' ') ; } else { out.print("Unknown ") ; } // Find and print the date. if (perl.match("/\\$"+"Date: (\\S+)\\s+(\\S+) "+"\\$/",file_buffer.toString())) { String date = perl.group(1) ; String time = perl.group(2) ; out.print(date+' '+time+' ') ; } else { out.print("Unknown ") ; } // Print the checksum. out.println(checksum.getValue()) ; } File[] subdirs = dir.listFiles(new DirectoryFilter()) ; for (int i = 0; i < subdirs.length; ++i) { checksumDirectory(parent_dir, subdirs[i].getPath().substring(parent_dir.getPath().length()), out) ; } } }
package org.opens.tanaguru.rules.accessiweb22; import org.opens.tanaguru.entity.audit.ProcessRemark; import org.opens.tanaguru.entity.audit.ProcessResult; import org.opens.tanaguru.entity.audit.TestSolution; import org.opens.tanaguru.rules.accessiweb22.test.Aw22RuleImplementationTestCase; import org.opens.tanaguru.rules.keystore.RemarkMessageStore; /** * Unit test class for the implementation of the rule 6.3.4 of the referential Accessiweb 2.2. * * @author jkowalczyk */ public class Aw22Rule06034Test extends Aw22RuleImplementationTestCase { /** * Default constructor */ public Aw22Rule06034Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.opens.tanaguru.rules.accessiweb22.Aw22Rule06034"); } @Override protected void setUpWebResourceMap() { getWebResourceMap().put("AW22.Test.06.03.04-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-01.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-02.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-03.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-04.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-05.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-06.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-07.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-08", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-08.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-09", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-09.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-10", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-10.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-11", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-11.html")); getWebResourceMap().put("AW22.Test.06.03.04-2Failed-12", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-2Failed-12.html")); getWebResourceMap().put("AW22.Test.06.03.04-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-3NMI-01.html")); getWebResourceMap().put("AW22.Test.06.03.04-3NMI-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-3NMI-02.html")); getWebResourceMap().put("AW22.Test.06.03.04-3NMI-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-3NMI-03.html")); getWebResourceMap().put("AW22.Test.06.03.04-3NMI-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-3NMI-04.html")); getWebResourceMap().put("AW22.Test.06.03.04-3NMI-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-3NMI-05.html")); getWebResourceMap().put("AW22.Test.06.03.04-3NMI-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-3NMI-06.html")); getWebResourceMap().put("AW22.Test.06.03.04-4NA-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-4NA-01.html")); getWebResourceMap().put("AW22.Test.06.03.04-4NA-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-4NA-02.html")); getWebResourceMap().put("AW22.Test.06.03.04-4NA-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-4NA-03.html")); getWebResourceMap().put("AW22.Test.06.03.04-4NA-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-4NA-04.html")); getWebResourceMap().put("AW22.Test.06.03.04-4NA-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06034/AW22.Test.06.03.04-4NA-05.html")); // 06.03.01 testcases getWebResourceMap().put("AW22.Test.06.03.01-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-2Failed-01.html")); getWebResourceMap().put("AW22.Test.06.03.01-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-2Failed-02.html")); getWebResourceMap().put("AW22.Test.06.03.01-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-2Failed-03.html")); getWebResourceMap().put("AW22.Test.06.03.01-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-2Failed-04.html")); getWebResourceMap().put("AW22.Test.06.03.01-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-2Failed-05.html")); getWebResourceMap().put("AW22.Test.06.03.01-2Failed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-2Failed-06.html")); getWebResourceMap().put("AW22.Test.06.03.01-2Failed-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-2Failed-07.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-01.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-02.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-03.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-04.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-05.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-06.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-07.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-08", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-08.html")); getWebResourceMap().put("AW22.Test.06.03.01-3NMI-09", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06031/AW22.Test.06.03.01-3NMI-09.html")); //06.03.02 testcases getWebResourceMap().put("AW22.Test.06.03.02-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-01.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-02.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-03.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-04.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-05.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-06.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-07.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-08", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-08.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-09", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-09.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-10", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-10.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-11", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-11.html")); getWebResourceMap().put("AW22.Test.06.03.02-2Failed-12", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-2Failed-12.html")); getWebResourceMap().put("AW22.Test.06.03.02-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-3NMI-01.html")); getWebResourceMap().put("AW22.Test.06.03.02-3NMI-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-3NMI-02.html")); getWebResourceMap().put("AW22.Test.06.03.02-3NMI-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-3NMI-03.html")); getWebResourceMap().put("AW22.Test.06.03.02-3NMI-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-3NMI-04.html")); getWebResourceMap().put("AW22.Test.06.03.02-3NMI-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-3NMI-05.html")); getWebResourceMap().put("AW22.Test.06.03.02-3NMI-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06032/AW22.Test.06.03.02-3NMI-06.html")); //06.03.03 testcases getWebResourceMap().put("AW22.Test.06.03.03-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-2Failed-01.html")); getWebResourceMap().put("AW22.Test.06.03.03-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-2Failed-02.html")); getWebResourceMap().put("AW22.Test.06.03.03-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-2Failed-03.html")); getWebResourceMap().put("AW22.Test.06.03.03-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-2Failed-04.html")); getWebResourceMap().put("AW22.Test.06.03.03-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-2Failed-05.html")); getWebResourceMap().put("AW22.Test.06.03.03-2Failed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-2Failed-06.html")); getWebResourceMap().put("AW22.Test.06.03.03-2Failed-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-2Failed-07.html")); getWebResourceMap().put("AW22.Test.06.03.03-2Failed-08", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-2Failed-08.html")); getWebResourceMap().put("AW22.Test.06.03.03-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-3NMI-01.html")); getWebResourceMap().put("AW22.Test.06.03.03-3NMI-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-3NMI-02.html")); getWebResourceMap().put("AW22.Test.06.03.03-3NMI-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-3NMI-03.html")); getWebResourceMap().put("AW22.Test.06.03.03-3NMI-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-3NMI-04.html")); getWebResourceMap().put("AW22.Test.06.03.03-3NMI-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-3NMI-05.html")); getWebResourceMap().put("AW22.Test.06.03.03-3NMI-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-3NMI-06.html")); getWebResourceMap().put("AW22.Test.06.03.03-3NMI-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06033/AW22.Test.06.03.03-3NMI-07.html")); //06.06.01 testcases -> empty links getWebResourceMap().put("AW22.Test.06.06.01-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-01.html")); getWebResourceMap().put("AW22.Test.06.06.01-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-02.html")); getWebResourceMap().put("AW22.Test.06.06.01-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-03.html")); getWebResourceMap().put("AW22.Test.06.06.01-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-04.html")); getWebResourceMap().put("AW22.Test.06.06.01-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-05.html")); getWebResourceMap().put("AW22.Test.06.06.01-4NA-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW22/Aw22Rule06061/AW22.Test.06.06.01-4NA-01.html")); } @Override protected void setProcess() { ProcessResult processResult = processPageTest("AW22.Test.06.03.04-2Failed-01"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-02"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-03"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-04"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-05"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(3, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[2]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[2]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-06"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(2, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-07"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(2, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-08"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(2, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-09"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-10"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-11"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-2Failed-12"); assertEquals(TestSolution.FAILED,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.FAILED, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-3NMI-01"); assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue()); assertEquals(2, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-3NMI-02"); assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue()); assertEquals(2, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-3NMI-03"); assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-3NMI-04"); assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue()); assertEquals(2, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-3NMI-05"); assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-3NMI-06"); assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue()); assertEquals(1, processResult.getRemarkSet().size()); assertEquals(RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, ((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue()); processResult = processPageTest("AW22.Test.06.03.04-4NA-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.04-4NA-02"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.04-4NA-03"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.04-4NA-04"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.04-4NA-05"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); // 06.03.01 testcases : All is Not Applicable processResult = processPageTest("AW22.Test.06.03.01-2Failed-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-2Failed-02"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-2Failed-03"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-2Failed-04"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-2Failed-05"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-2Failed-06"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-2Failed-07"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-02"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-03"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-04"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-05"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-06"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-07"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-08"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.01-3NMI-09"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); // 06.03.02 testcases : All is Not Applicable processResult = processPageTest("AW22.Test.06.03.02-2Failed-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-02"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-03"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-04"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-05"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-06"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-07"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-08"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-09"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-10"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-11"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-2Failed-12"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-3NMI-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-3NMI-02"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-3NMI-03"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-3NMI-04"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-3NMI-05"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.02-3NMI-06"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); // 06.03.03 testcases : All is Not Applicable processResult = processPageTest("AW22.Test.06.03.03-2Failed-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-2Failed-02"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-2Failed-03"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-2Failed-04"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-2Failed-05"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-2Failed-06"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-2Failed-07"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-2Failed-08"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-3NMI-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-3NMI-02"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-3NMI-03"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-3NMI-04"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-3NMI-05"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-3NMI-06"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.03.03-3NMI-07"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); // 06.06.01 testcases : All is Not Applicable processResult = processPageTest("AW22.Test.06.06.01-2Failed-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.06.01-2Failed-02"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.06.01-2Failed-03"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.06.01-2Failed-04"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.06.01-2Failed-05"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); processResult = processPageTest("AW22.Test.06.06.01-4NA-01"); assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue()); assertNull(processResult.getRemarkSet()); } @Override protected void setConsolidate() { assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-01").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-02").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-03").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-04").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-05").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-06").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-07").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-08").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-09").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-10").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-11").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.06.03.04-2Failed-12").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.06.03.04-3NMI-01").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.06.03.04-3NMI-02").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.06.03.04-3NMI-03").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.06.03.04-3NMI-04").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.06.03.04-3NMI-05").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.06.03.04-3NMI-06").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.04-4NA-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.04-4NA-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.04-4NA-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.04-4NA-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.04-4NA-05").getValue()); // 06.03.01 testcases : All is Not Applicable assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-2Failed-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-2Failed-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-2Failed-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-2Failed-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-2Failed-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-2Failed-06").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-2Failed-07").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-06").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-07").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-08").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.01-3NMI-09").getValue()); // 06.03.02 testcases : All is Not Applicable assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-06").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-07").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-08").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-09").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-10").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-11").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-2Failed-12").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-3NMI-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-3NMI-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-3NMI-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-3NMI-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-3NMI-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.02-3NMI-06").getValue()); // 06.03.03 testcases : All is Not Applicable assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-06").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-07").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-2Failed-08").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-3NMI-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-3NMI-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-3NMI-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-3NMI-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-3NMI-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-3NMI-06").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.03.03-3NMI-07").getValue()); // 06.06.01 testcases : All is Not Applicable assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.06.01-2Failed-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.06.01-2Failed-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.06.01-2Failed-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.06.01-2Failed-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.06.01-2Failed-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("AW22.Test.06.06.01-4NA-01").getValue()); } }
package net.runelite.client.plugins.idlenotifier; import com.google.common.eventbus.Subscribe; import com.google.inject.Provides; import java.time.Duration; import java.time.Instant; import javax.inject.Inject; import net.runelite.api.Actor; import static net.runelite.api.AnimationID.*; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.Player; import net.runelite.api.Skill; import net.runelite.api.Varbits; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.GameTick; import net.runelite.client.Notifier; import net.runelite.client.config.ConfigManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; @PluginDescriptor( name = "Idle Notifier", description = "Send a notification when going idle, or when HP/Prayer reaches a threshold", tags = {"health", "hitpoints", "notifications", "prayer"} ) public class IdleNotifierPlugin extends Plugin { private static final int LOGOUT_WARNING_AFTER_TICKS = 14000; // 4 minutes and 40 seconds private static final Duration SIX_HOUR_LOGOUT_WARNING_AFTER_DURATION = Duration.ofMinutes(340); @Inject private Notifier notifier; @Inject private Client client; @Inject private IdleNotifierConfig config; private Actor lastOpponent; private Instant lastAnimating; private int lastAnimation = AnimationID.IDLE; private Instant lastInteracting; private boolean notifyHitpoints = true; private boolean notifyPrayer = true; private boolean notifyIdleLogout = true; private boolean notify6HourLogout = true; private Instant sixHourWarningTime; private boolean ready; @Provides IdleNotifierConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(IdleNotifierConfig.class); } @Subscribe public void onAnimationChanged(AnimationChanged event) { if (client.getGameState() != GameState.LOGGED_IN) { return; } Player localPlayer = client.getLocalPlayer(); if (localPlayer != event.getActor()) { return; } int animation = localPlayer.getAnimation(); switch (animation) { /* Woodcutting */ case WOODCUTTING_BRONZE: case WOODCUTTING_IRON: case WOODCUTTING_STEEL: case WOODCUTTING_BLACK: case WOODCUTTING_MITHRIL: case WOODCUTTING_ADAMANT: case WOODCUTTING_RUNE: case WOODCUTTING_DRAGON: case WOODCUTTING_INFERNAL: case WOODCUTTING_3A_AXE: /* Cooking(Fire, Range) */ case COOKING_FIRE: case COOKING_RANGE: case COOKING_WINE: /* Crafting(Gem Cutting, Glassblowing, Spinning, Battlestaves) */ case GEM_CUTTING_OPAL: case GEM_CUTTING_JADE: case GEM_CUTTING_REDTOPAZ: case GEM_CUTTING_SAPPHIRE: case GEM_CUTTING_EMERALD: case GEM_CUTTING_RUBY: case GEM_CUTTING_DIAMOND: case CRAFTING_GLASSBLOWING: case CRAFTING_SPINNING: case CRAFTING_BATTLESTAVES: case CRAFTING_LEATHER: /* Fletching(Cutting, Stringing) */ case FLETCHING_BOW_CUTTING: case FLETCHING_STRING_NORMAL_SHORTBOW: case FLETCHING_STRING_OAK_SHORTBOW: case FLETCHING_STRING_WILLOW_SHORTBOW: case FLETCHING_STRING_MAPLE_SHORTBOW: case FLETCHING_STRING_YEW_SHORTBOW: case FLETCHING_STRING_MAGIC_SHORTBOW: case FLETCHING_STRING_NORMAL_LONGBOW: case FLETCHING_STRING_OAK_LONGBOW: case FLETCHING_STRING_WILLOW_LONGBOW: case FLETCHING_STRING_MAPLE_LONGBOW: case FLETCHING_STRING_YEW_LONGBOW: case FLETCHING_STRING_MAGIC_LONGBOW: /* Smithing(Anvil, Furnace, Cannonballs */ case SMITHING_ANVIL: case SMITHING_SMELTING: case SMITHING_CANNONBALL: /* Fishing */ case FISHING_NET: case FISHING_BIG_NET: case FISHING_HARPOON: case FISHING_BARBTAIL_HARPOON: case FISHING_DRAGON_HARPOON: case FISHING_CAGE: case FISHING_POLE_CAST: case FISHING_INFERNAL_HARPOON: case FISHING_OILY_ROD: case FISHING_KARAMBWAN: case FISHING_CRUSHING_INFERNAL_EELS: case FISHING_BAREHAND: /* Mining(Normal) */ case MINING_BRONZE_PICKAXE: case MINING_IRON_PICKAXE: case MINING_STEEL_PICKAXE: case MINING_BLACK_PICKAXE: case MINING_MITHRIL_PICKAXE: case MINING_ADAMANT_PICKAXE: case MINING_RUNE_PICKAXE: case MINING_DRAGON_PICKAXE: case MINING_DRAGON_PICKAXE_ORN: case MINING_INFERNAL_PICKAXE: case MINING_3A_PICKAXE: /* Mining(Motherlode) */ case MINING_MOTHERLODE_BRONZE: case MINING_MOTHERLODE_IRON: case MINING_MOTHERLODE_STEEL: case MINING_MOTHERLODE_BLACK: case MINING_MOTHERLODE_MITHRIL: case MINING_MOTHERLODE_ADAMANT: case MINING_MOTHERLODE_RUNE: case MINING_MOTHERLODE_DRAGON: case MINING_MOTHERLODE_DRAGON_ORN: case MINING_MOTHERLODE_INFERNAL: case MINING_MOTHERLODE_3A: /* Herblore */ case HERBLORE_POTIONMAKING: case HERBLORE_MAKE_TAR: /* Magic */ case MAGIC_CHARGING_ORBS: case MAGIC_LUNAR_STRING_JEWELRY: case MAGIC_LUNAR_BAKE_PIE: case MAGIC_MAKE_TABLET: /* Prayer */ case USING_GILDED_ALTAR: resetTimers(); lastAnimation = animation; break; case IDLE: break; default: // On unknown animation simply assume the animation is invalid and dont throw notification lastAnimation = IDLE; } } @Subscribe public void onGameStateChanged(GameStateChanged gameStateChanged) { lastInteracting = null; GameState state = gameStateChanged.getGameState(); switch (state) { case LOGIN_SCREEN: resetTimers(); break; case LOGGING_IN: case HOPPING: case CONNECTION_LOST: ready = true; break; case LOGGED_IN: if (ready) { sixHourWarningTime = Instant.now().plus(SIX_HOUR_LOGOUT_WARNING_AFTER_DURATION); ready = false; resetTimers(); } break; } } @Subscribe public void onGameTick(GameTick event) { final Player local = client.getLocalPlayer(); final Duration waitDuration = Duration.ofMillis(config.getIdleNotificationDelay()); if (client.getGameState() != GameState.LOGGED_IN || local == null || client.getMouseIdleTicks() < 10) { resetTimers(); return; } if (checkIdleLogout()) { notifier.notify("[" + local.getName() + "] is about to log out from idling too long!"); } if (check6hrLogout()) { notifier.notify("[" + local.getName() + "] is about to log out from being online for 6 hours!"); } if (config.animationIdle() && checkAnimationIdle(waitDuration, local)) { notifier.notify("[" + local.getName() + "] is now idle!"); } if (config.combatIdle() && checkOutOfCombat(waitDuration, local)) { notifier.notify("[" + local.getName() + "] is now out of combat!"); } if (checkLowHitpoints()) { notifier.notify("[" + local.getName() + "] has low hitpoints!"); } if (checkLowPrayer()) { notifier.notify("[" + local.getName() + "] has low prayer!"); } } private boolean checkLowHitpoints() { if (config.getHitpointsThreshold() == 0) { return false; } if (client.getRealSkillLevel(Skill.HITPOINTS) > config.getHitpointsThreshold()) { if (client.getBoostedSkillLevel(Skill.HITPOINTS) + client.getVar(Varbits.NMZ_ABSORPTION) <= config.getHitpointsThreshold()) { if (!notifyHitpoints) { notifyHitpoints = true; return true; } } else { notifyHitpoints = false; } } return false; } private boolean checkLowPrayer() { if (config.getPrayerThreshold() == 0) { return false; } if (client.getRealSkillLevel(Skill.PRAYER) > config.getPrayerThreshold()) { if (client.getBoostedSkillLevel(Skill.PRAYER) <= config.getPrayerThreshold()) { if (!notifyPrayer) { notifyPrayer = true; return true; } } else { notifyPrayer = false; } } return false; } private boolean checkOutOfCombat(Duration waitDuration, Player local) { Actor opponent = local.getInteracting(); boolean isPlayer = opponent instanceof Player; if (opponent != null && !isPlayer && opponent.getCombatLevel() > 0) { resetTimers(); lastOpponent = opponent; } else if (opponent == null) { lastOpponent = null; } if (lastOpponent != null && opponent == lastOpponent) { lastInteracting = Instant.now(); } if (lastInteracting != null && Instant.now().compareTo(lastInteracting.plus(waitDuration)) >= 0) { lastInteracting = null; return true; } return false; } private boolean checkIdleLogout() { if (client.getMouseIdleTicks() > LOGOUT_WARNING_AFTER_TICKS && client.getKeyboardIdleTicks() > LOGOUT_WARNING_AFTER_TICKS) { if (notifyIdleLogout) { notifyIdleLogout = false; return true; } } else { notifyIdleLogout = true; } return false; } private boolean check6hrLogout() { if (sixHourWarningTime == null) { return false; } if (Instant.now().compareTo(sixHourWarningTime) >= 0) { if (notify6HourLogout) { notify6HourLogout = false; return true; } } else { notify6HourLogout = true; } return false; } private boolean checkAnimationIdle(Duration waitDuration, Player local) { if (lastAnimation == IDLE) { return false; } final int animation = local.getAnimation(); if (animation == IDLE) { if (lastAnimating != null && Instant.now().compareTo(lastAnimating.plus(waitDuration)) >= 0) { lastAnimation = IDLE; lastAnimating = null; return true; } } else { lastAnimating = Instant.now(); } return false; } private void resetTimers() { final Player local = client.getLocalPlayer(); // Reset animation idle timer lastAnimating = null; if (client.getGameState() == GameState.LOGIN_SCREEN || local == null || local.getAnimation() != lastAnimation) { lastAnimation = IDLE; } // Reset combat idle timer lastOpponent = null; lastInteracting = null; } }
package src.io.controller; import java.util.Scanner; import javax.print.attribute.standard.RequestingUserName; import src.HardCodedStrings; import src.RunGame; import src.enumHandler; /** * Processes /commands given in the chatbox * * @author mbregg * */ class CommandMiniController { private KeyRemapper remap_ = null; private Controller cont_ = null; public CommandMiniController(KeyRemapper remap, Controller cont) { remap_ = remap; cont_ = cont; } private static final String man = "man"; private static final String pwd = "pwd"; private static final String help = "help"; private static final String controls = "controls"; private static final String loadControls = "load-controls"; private static final String saveControls = "save-controls"; private static final String save = "save"; private static final String load = "load"; private static final String rebind = "rebind"; private static final String bindings = "bindings"; private static final String setIP = "set-ip"; private static final String setControl = "set-control"; private static final String setTCP = "set-tcp"; private static final String commandKey = "/"; public String processCommand(String foo) { //Firstly ensure we are dealing with a command. Scanner sc = new Scanner(foo); String command = ""; try { command = sc.next(); if (!command.startsWith(commandKey)) { System.err.println("This isn't a command!"); return "Error in the CommandMini"; } command = command.substring(1);//Strip the command key away now, we already checked that it exists. }finally{sc.close();} //invalid command send apparently, so nothing to read.... if (command.equals(rebind)) { return this.processRebind(foo); } if (command.equals(saveControls)) { return this.processSaveControls(foo); } if (command.equals(loadControls)) { return this.processLoadControls(foo); } if (command.equals(save)) { return this.processSave(foo); } if (command.equals(load)) { return this.processLoad(foo); } if (command.equals(controls)) { return this.processCommands(); } if (command.equals(help)) { return this.processHelp(); } if (command.equals(pwd)) { return System.getProperty("user.dir"); } if (command.equals("cat")) { return "meow"; } if (command.equals("tiger")) { return "ROAR!"; } if (command.equals(man)) { return this.processManCommand(foo); } if (command.equals(bindings)) { return this.remap_.getBindingList(); } if (command.equals(setIP)) { int error_code = RunGame.internet.makeConnectionUsingIP_Address(foo.split(" ")[foo.split(" ").length - 1]); if (error_code == 0) { return "Successfully connected to ip address: " + foo; } else { int error_code_2 = RunGame.internet.makeConnectionUsingIP_Address("localhost"); if (error_code_2 == 0) { return "Connection failed. Reconnecting to localhost."; } else { RunGame.setUseInternet(false); return "Something is seriously wrong with the program. Cannot connect to the internet."; } } } if (command.equals(setControl)) { return this.setControl(foo); } if (command.equals(setTCP)) { if (command.toLowerCase().contains("n")) { RunGame.setUseTCP(false); return "TCP turned off because you said no"; } else { RunGame.setUseTCP(true); return "TCP turned on because you didn't say no."; } } return "No valid command given!"; } private String setControl(String foo) { Scanner sc = new Scanner(foo); String in = ""; try { sc.next(); //Get rid of the command /man in = sc.next(); cont_.setControlling(in); } catch (Exception e) { sc.close(); return HardCodedStrings.setControl_error; } sc.close(); return HardCodedStrings.setControlSuccess; } private String processManCommand(String foo) { Scanner sc = new Scanner(foo); String in = ""; try { sc.next(); //Get rid of the command /man in = sc.next(); } catch (Exception e) { sc.close(); return HardCodedStrings.command_error; } try { if (in.equals(rebind)) { return HardCodedStrings.rebindHelp; } if (in.equals(save)) { return HardCodedStrings.saveHelp; } if (in.equals(load)) { return HardCodedStrings.loadHelp; } if (in.equals(saveControls)) { return HardCodedStrings.saveControlsHelp; } if (in.equals(loadControls)) { return HardCodedStrings.loadControlsHelp; } if (in.equals(controls)) { return HardCodedStrings.controlsHelp; } if (in.equals(help)) { return HardCodedStrings.helpHelp; } if (in.equals(pwd)) { return HardCodedStrings.pwdHelp; } if (in.equals(man)) { return HardCodedStrings.manHelp; } if (in.equals(bindings)) { return HardCodedStrings.bindingsHelp; } if (in.equals(setIP)) { return HardCodedStrings.setIPHelp; } if (in.equals(setControl)) { return HardCodedStrings.setControlHelp; } if (in.equals("fontsize")) { return HardCodedStrings.fontsizeHelp; } } finally { sc.close(); } return HardCodedStrings.command_error; } private String processLoad(String foo) { Scanner sc = new Scanner(foo); try { sc.next(); if (sc.hasNext()) { foo = sc.next(); } else { return HardCodedStrings.loadHelp; } } finally { sc.close(); } cont_.saveGame(foo); return "Loaded " + foo; } private String processLoadControls(String foo) { // TODO Auto-generated method stub return "Not implemented yet"; } private String processSaveControls(String foo) { // TODO Auto-generated method stub return "Not implemneted yet"; } private String processCommands() { return enumHandler.getAllCommands(); //The output box seems a bit bugged here.... //Scrolling horizontally horrifically garbles the text. This should be avoided. } private String processHelp() { return HardCodedStrings.help; } private String processRebind(String foo) { String error = HardCodedStrings.command_error + System.lineSeparator() + HardCodedStrings.rebindHelp; Scanner sc = new Scanner(foo); String command; char c = '\0'; try { sc.next(); command = sc.next(); String temp = sc.next(); if (temp.length() != 1) { sc.close(); return error; } c = temp.charAt(0); remap_.bind(c, enumHandler.stringCommandToKeyCommand(command)); } catch (Exception e) { sc.close(); return error; } sc.close(); return "Success, Rebound : " + command + " To " + String.valueOf(c); } private String processSave(String foo) { Scanner sc = new Scanner(foo); try { sc.next(); if (sc.hasNext()) { foo = sc.next(); } else { foo = ""; } } finally { sc.close(); } cont_.saveGame(foo); if (foo != "") { return "Saved to " + foo; } return "Saved to default"; } }
package net.runelite.client.plugins.skillcalculator; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import net.runelite.api.Client; import net.runelite.api.Experience; import net.runelite.client.game.ItemManager; import net.runelite.client.game.SpriteManager; import net.runelite.client.plugins.skillcalculator.beans.SkillData; import net.runelite.client.plugins.skillcalculator.beans.SkillDataBonus; import net.runelite.client.plugins.skillcalculator.beans.SkillDataEntry; import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.DynamicGridLayout; import net.runelite.client.ui.FontManager; class SkillCalculator extends JPanel { private static final int MAX_XP = 200_000_000; private static final DecimalFormat XP_FORMAT = new DecimalFormat(" static SpriteManager spriteManager; static ItemManager itemManager; private Client client; private SkillData skillData; private List<UIActionSlot> uiActionSlots = new ArrayList<>(); private UICalculatorInputArea uiInput; private CacheSkillData cacheSkillData = new CacheSkillData(); private UICombinedActionSlot combinedActionSlot = new UICombinedActionSlot(); private ArrayList<UIActionSlot> combinedActionSlots = new ArrayList<>(); private int currentLevel = 1; private int currentXP = Experience.getXpForLevel(currentLevel); private int targetLevel = currentLevel + 1; private int targetXP = Experience.getXpForLevel(targetLevel); private float xpFactor = 1.0f; SkillCalculator(Client client, UICalculatorInputArea uiInput) { this.client = client; this.uiInput = uiInput; setLayout(new DynamicGridLayout(0, 1, 0, 5)); // Register listeners on the input fields and then move on to the next related text field uiInput.uiFieldCurrentLevel.addActionListener(e -> { onFieldCurrentLevelUpdated(); uiInput.uiFieldTargetLevel.requestFocusInWindow(); }); uiInput.uiFieldCurrentXP.addActionListener(e -> { onFieldCurrentXPUpdated(); uiInput.uiFieldTargetXP.requestFocusInWindow(); }); uiInput.uiFieldTargetLevel.addActionListener(e -> onFieldTargetLevelUpdated()); uiInput.uiFieldTargetXP.addActionListener(e -> onFieldTargetXPUpdated()); } void openCalculator(CalculatorType calculatorType) { // Load the skill data. skillData = cacheSkillData.getSkillData(calculatorType.getDataFile()); // Reset the XP factor, removing bonuses. xpFactor = 1.0f; // Update internal skill/XP values. currentXP = client.getSkillExperience(calculatorType.getSkill()); currentLevel = Experience.getLevelForXp(currentXP); targetLevel = enforceSkillBounds(currentLevel + 1); targetXP = Experience.getXpForLevel(targetLevel); // Remove all components (action slots) from this panel. removeAll(); // Add in checkboxes for available skill bonuses. renderBonusOptions(); // Add the combined action slot. add(combinedActionSlot); // Create action slots for the skill actions. renderActionSlots(); // Update the input fields. updateInputFields(); } private void updateCombinedAction() { int size = combinedActionSlots.size(); if (size > 1) { combinedActionSlot.setTitle(size + " actions selected"); } else if (size == 1) { combinedActionSlot.setTitle("1 action selected"); } else { combinedActionSlot.setTitle("No action selected"); combinedActionSlot.setText("Shift-click to select multiple"); return; } int actionCount = 0; int neededXP = targetXP - currentXP; double xp = 0; for (UIActionSlot slot : combinedActionSlots) xp += slot.value; if (neededXP > 0) actionCount = (int) Math.ceil(neededXP / xp); combinedActionSlot.setText(formatXPActionString(xp, actionCount, "exp - ")); } private void clearCombinedSlots() { for (UIActionSlot slot : combinedActionSlots) slot.setSelected(false); combinedActionSlots.clear(); } private void renderBonusOptions() { if (skillData.getBonuses() != null) { for (SkillDataBonus bonus : skillData.getBonuses()) { JPanel uiOption = new JPanel(new BorderLayout()); JLabel uiLabel = new JLabel(bonus.getName()); JCheckBox uiCheckbox = new JCheckBox(); uiLabel.setForeground(Color.WHITE); uiLabel.setFont(FontManager.getRunescapeSmallFont()); uiOption.setBorder(BorderFactory.createEmptyBorder(3, 7, 3, 0)); uiOption.setBackground(ColorScheme.DARKER_GRAY_COLOR); // Adjust XP bonus depending on check-state of the boxes. uiCheckbox.addActionListener(e -> adjustXPBonus(uiCheckbox.isSelected(), bonus.getValue())); uiCheckbox.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); uiOption.add(uiLabel, BorderLayout.WEST); uiOption.add(uiCheckbox, BorderLayout.EAST); add(uiOption); add(Box.createRigidArea(new Dimension(0, 5))); } } } private void renderActionSlots() { // Wipe the list of references to the slot components. uiActionSlots.clear(); // Create new components for the action slots. for (SkillDataEntry action : skillData.getActions()) { UIActionSlot slot = new UIActionSlot(action); uiActionSlots.add(slot); // Keep our own reference. add(slot); // Add component to the panel. slot.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (!e.isShiftDown()) clearCombinedSlots(); if (slot.isSelected) combinedActionSlots.remove(slot); else combinedActionSlots.add(slot); slot.setSelected(!slot.isSelected); updateCombinedAction(); } }); } // Refresh the rendering of this panel. revalidate(); repaint(); } private void calculate() { for (UIActionSlot slot : uiActionSlots) { int actionCount = 0; int neededXP = targetXP - currentXP; double xp = (slot.action.isIgnoreBonus()) ? slot.action.getXp() : slot.action.getXp() * xpFactor; if (neededXP > 0) actionCount = (int) Math.ceil(neededXP / xp); slot.setText("Lvl. " + slot.action.getLevel() + " (" + formatXPActionString(xp, actionCount, "exp) - ")); slot.setAvailable(currentLevel >= slot.action.getLevel()); slot.value = xp; } } private String formatXPActionString(double xp, int actionCount, String expExpression) { return XP_FORMAT.format(xp) + expExpression + NumberFormat.getIntegerInstance().format(actionCount) + (actionCount > 1 ? " actions" : " action"); } private void updateInputFields() { if (targetXP < currentXP) { targetLevel = enforceSkillBounds(currentLevel + 1); targetXP = Experience.getXpForLevel(targetLevel); } uiInput.setCurrentLevelInput(currentLevel); uiInput.setCurrentXPInput(currentXP); uiInput.setTargetLevelInput(targetLevel); uiInput.setTargetXPInput(targetXP); calculate(); } private void adjustXPBonus(boolean addBonus, float value) { xpFactor += addBonus ? value : -value; calculate(); } private void onFieldCurrentLevelUpdated() { currentLevel = enforceSkillBounds(uiInput.getCurrentLevelInput()); currentXP = Experience.getXpForLevel(currentLevel); updateInputFields(); } private void onFieldCurrentXPUpdated() { currentXP = enforceXPBounds(uiInput.getCurrentXPInput()); currentLevel = Experience.getLevelForXp(currentXP); updateInputFields(); } private void onFieldTargetLevelUpdated() { targetLevel = enforceSkillBounds(uiInput.getTargetLevelInput()); targetXP = Experience.getXpForLevel(targetLevel); updateInputFields(); } private void onFieldTargetXPUpdated() { targetXP = enforceXPBounds(uiInput.getTargetXPInput()); targetLevel = Experience.getLevelForXp(targetXP); updateInputFields(); } private static int enforceSkillBounds(int input) { return Math.min(Experience.MAX_VIRT_LEVEL, Math.max(1, input)); } private static int enforceXPBounds(int input) { return Math.min(MAX_XP, Math.max(0, input)); } }
package supahnickie.caffeineTester; import static org.junit.Assert.*; import org.junit.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import supahnickie.caffeine.*; import supahnickie.testClasses.*; public class CaffeineTest { @Test public void executeUpdate() throws Exception { Caffeine.executeUpdate("insert into downloads (id, org_id, file_file_name) values (15, 1, 'download1'), (16, 1, 'download2')"); CaffeineObject.setQueryClass(Download.class); List<CaffeineObject> downloads = Caffeine.executeQuery("select * from downloads where id in (15, 16)"); Download download15 = (Download) downloads.get(0); Download download16 = (Download) downloads.get(1); assertArrayEquals("returned downloads should match expected ids", new int[] {15, 16}, new int[] {download15.id, download16.id}); assertArrayEquals("returned downloads should match expected file names", new String[] {"download1", "download2"}, new String[] {download15.file_file_name, download16.file_file_name}); assertArrayEquals("returned downloads should match expected org_ids", new int[] {1, 1}, new int[] {download15.org_id, download16.org_id}); } @Test public void executeUpdateWithListArgs() throws Exception { Download download = (Download) CaffeineObject.find(Download.class, 1); assertEquals("file_file_name should match seed before transformation", "FileTest num 1", download.file_file_name); assertEquals("org_id should match seed before transformation", 2, download.org_id); List<Object> args = new ArrayList<Object>(); args.add("RenamedFile"); args.add(3); args.add(1); Caffeine.executeUpdate("update downloads set (file_file_name, org_id) = (?, ?) where id = ?", args); download = (Download) CaffeineObject.find(Download.class, 1); assertEquals("file_file_name should be changed to reflect the update", "RenamedFile", download.file_file_name); assertEquals("org_id should should be changed to reflect the update", 3, download.org_id); } @Test public void executeQuery() throws Exception { CaffeineObject.setQueryClass(Download.class); List<CaffeineObject> downloads = Caffeine.executeQuery("select * from downloads"); assertEquals("size of return array should match seeds", 4, downloads.size()); Download download1 = (Download) downloads.get(0); Download download2 = (Download) downloads.get(1); assertEquals("download1 file name should match seed", "FileTest num 1", download1.file_file_name); assertEquals("download1 org_id should match seed", 2, download1.org_id); assertEquals("download2 file name should match seed", "FileTest num 2", download2.file_file_name); assertEquals("download2 org_id should match seed", 1, download2.org_id); } @Test public void executeQueryWithListArgs() throws Exception { List<Object> args = new ArrayList<Object>(); args.add("FileTest num 2"); args.add(2); CaffeineObject.setQueryClass(Download.class); List<CaffeineObject> downloads = Caffeine.executeQuery("select * from downloads where file_file_name = ? or org_id = ? order by id asc", args); assertEquals("size of return array should match expected return", 3, downloads.size()); Download download1 = (Download) downloads.get(0); Download download2 = (Download) downloads.get(1); assertEquals("download1 file name should match seed", "FileTest num 1", download1.file_file_name); assertEquals("download1 org_id should match seed", 2, download1.org_id); assertEquals("download2 file name should match seed", "FileTest num 2", download2.file_file_name); assertEquals("download2 org_id should match seed", 1, download2.org_id); } @Test public void executeQueryWithListArgsAndOptions() throws Exception { List<Object> args = new ArrayList<Object>(); args.add("FileTest num 3"); args.add(6); Map<String, Object> options = new HashMap<String, Object>(); options.put("limit", 1); options.put("orderBy", "id asc"); CaffeineObject.setQueryClass(Download.class); List<CaffeineObject> downloads = Caffeine.executeQuery("select * from downloads where file_file_name = ? or org_id = ?", args, options); assertEquals("size of return array should match expected return", 1, downloads.size()); Download download1 = (Download) downloads.get(0); assertEquals("download1 file name should match seed", "FileTest num 3", download1.file_file_name); assertEquals("download1 org_id should match seed", 2, download1.org_id); } @Test public void executeARlikeQuery() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("file_file_name", "FileTest num 4"); args.put("org_id", 3); CaffeineObject.setQueryClass(Download.class); List<CaffeineObject> downloads = Caffeine.executeQuery(args); assertEquals("size of return array should match expected return", 1, downloads.size()); Download download1 = (Download) downloads.get(0); assertEquals("download1 file name should match seed", "FileTest num 4", download1.file_file_name); assertEquals("download1 org_id should match seed", 3, download1.org_id); } @Test public void executeARlikeQueryWithOptions() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("file_file_name", "FileTest num 3"); args.put("org_id", 2); Map<String, Object> options = new HashMap<String, Object>(); options.put("limit", 1); options.put("orderBy", "id asc"); CaffeineObject.setQueryClass(Download.class); List<CaffeineObject> downloads = Caffeine.executeQuery(args, options); assertEquals("size of return array should match expected return", 1, downloads.size()); Download download1 = (Download) downloads.get(0); assertEquals("download1 file name should match seed", "FileTest num 3", download1.file_file_name); assertEquals("download1 org_id should match seed", 2, download1.org_id); } @Test public void queryWhereNoConditionsMatch() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("file_file_name", "FileTest num 6"); args.put("org_id", 2); Map<String, Object> options = new HashMap<String, Object>(); options.put("limit", 1); options.put("orderBy", "id asc"); CaffeineObject.setQueryClass(Download.class); List<CaffeineObject> downloads = Caffeine.executeQuery(args, options); assertEquals("size of return array should match expected return", 0, downloads.size()); } // AR-like methods tests @Test public void find() throws Exception { User user = (User) CaffeineObject.find(User.class, 2); assertEquals("ids should match", 2, user.id); assertEquals("first name should match", "Nick", user.first_name); assertEquals("last name should match", "Case", user.last_name); assertNotEquals("ids should not match others", 1, user.id); assertNotEquals("first name should not match others", "Grawr", user.first_name); assertNotEquals("last name should not match others", "McPhee", user.last_name); } @Test public void findWithNonexistentUser() throws Exception { User user = (User) CaffeineObject.find(User.class, 8); assertEquals("returned object id should be 0", 0, user.id); assertEquals("returned object first_name should be null", null, user.first_name); assertEquals("returned object last_name should be null", null, user.last_name); } @Test public void create() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("id", 4); args.put("first_name", "Superman"); args.put("last_name", "is not as cool as a flawed hero"); User newUser = (User) CaffeineObject.create(User.class, args); assertEquals("id should match what was put in the args", 4, newUser.id); assertEquals("first name should match what was put in the args", "Superman", newUser.first_name); assertEquals("last name should match what was put in the args", "is not as cool as a flawed hero", newUser.last_name); User dbUser = (User) CaffeineObject.find(User.class, 4); assertEquals("id should match what was put in the args", 4, dbUser.id); assertEquals("first name should match what was put in the args", "Superman", dbUser.first_name); assertEquals("last name should match what was put in the args", "is not as cool as a flawed hero", dbUser.last_name); } @Test public void createFromInstance() throws Exception { User newUser = new User(); newUser.id = 4; newUser.first_name = "Superman"; newUser.last_name = "is not as cool as a flawed hero"; newUser.create(); assertEquals("id should match what was put in the args", 4, newUser.id); assertEquals("first name should match what was put in the args", "Superman", newUser.first_name); assertEquals("last name should match what was put in the args", "is not as cool as a flawed hero", newUser.last_name); User dbUser = (User) CaffeineObject.find(User.class, 4); assertEquals("id should match what was put in the args", 4, dbUser.id); assertEquals("first name should match what was put in the args", "Superman", dbUser.first_name); assertEquals("last name should match what was put in the args", "is not as cool as a flawed hero", dbUser.last_name); } @Test public void update() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("first_name", "Superman"); args.put("last_name", "is not as cool as a flawed hero"); User user = (User) CaffeineObject.find(User.class, 2); user.update(args); assertEquals("id should not have been updated", 2, user.id); assertEquals("first name should match what was put in the args", "Superman", user.first_name); assertEquals("last name should match what was put in the args", "is not as cool as a flawed hero", user.last_name); User dbUser = (User) CaffeineObject.find(User.class, 2); assertEquals("id should not have been updated", 2, dbUser.id); assertEquals("first name should match what was put in the args", "Superman", dbUser.first_name); assertEquals("last name should match what was put in the args", "is not as cool as a flawed hero", dbUser.last_name); } @Test public void updateNonExistentUser() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("first_name", "Superman"); args.put("last_name", "is not as cool as a flawed hero"); User user = (User) CaffeineObject.find(User.class, 7); user.update(args); assertArrayEquals("no user should have been updated or created", new Object[] {0, null, null}, new Object[] {user.id, user.first_name, user.last_name}); User dbUser = (User) CaffeineObject.find(User.class, 7); assertArrayEquals("no user should have been updated or created", new Object[] {0, null, null}, new Object[] {dbUser.id, dbUser.first_name, dbUser.last_name}); CaffeineObject.setQueryClass(User.class); List<CaffeineObject> users = Caffeine.executeQuery("select * from users"); assertEquals("size of return should match expected", 3, users.size()); User user1 = (User) users.get(0); User user2 = (User) users.get(1); User user3 = (User) users.get(2); assertArrayEquals("deleted object should not be in return", new int[] {1, 2, 3}, new int[] {user1.id, user2.id, user3.id}); assertArrayEquals("deleted object attrs should not be in return objects", new String[] {"Grawr", "Nick", "Test"}, new String[] {user1.first_name, user2.first_name, user3.first_name}); } @Test public void delete() throws Exception { User user = (User) CaffeineObject.find(User.class, 3); boolean result = user.delete(); assertEquals("return should be whether or not object was deleted", true, result); CaffeineObject.setQueryClass(User.class); List<CaffeineObject> users = Caffeine.executeQuery("select * from users"); assertEquals("size of return should match expected", 2, users.size()); User user1 = (User) users.get(0); User user2 = (User) users.get(1); assertArrayEquals("deleted object should not be in return", new int[] {1, 2}, new int[] {user1.id, user2.id}); assertArrayEquals("deleted object attrs should not be in return objects", new String[] {"Grawr", "Nick"}, new String[] {user1.first_name, user2.first_name}); } @Test public void deleteNonExistentUser() throws Exception { User user = (User) CaffeineObject.find(User.class, 8); boolean result = user.delete(); assertEquals("return true if sql ran without error", true, result); CaffeineObject.setQueryClass(User.class); List<CaffeineObject> users = Caffeine.executeQuery("select * from users"); assertEquals("size of return should match expected", 3, users.size()); User user1 = (User) users.get(0); User user2 = (User) users.get(1); User user3 = (User) users.get(2); assertArrayEquals("no objects should have been deleted", new int[] {1, 2, 3}, new int[] {user1.id, user2.id, user3.id}); assertArrayEquals("no object attrs should have been deleted", new String[] {"Grawr", "Nick", "Test"}, new String[] {user1.first_name, user2.first_name, user3.first_name}); } @Test public void join() throws Exception { CaffeineObject.setQueryClass(Download.class); List<CaffeineObject> downloads = CaffeineObject.chainable().join("downloads.user_id", "users.id").where("users.id = ?", 3).execute(); assertEquals("size of return list should match expected", 1, downloads.size()); Download download = (Download) downloads.get(0); assertEquals("id should match expected", 2, download.id); assertEquals("file name should match expected", "FileTest num 2", download.file_file_name); assertEquals("user_id should match expected", 3, download.user_id); } @Test public void joinWithChainable() throws Exception { List<CaffeineObject> downloads = CaffeineObject.chainable(Download.class).join("downloads.user_id", "users.id").where("users.id = ?", 3).execute(); assertEquals("size of return list should match expected", 1, downloads.size()); Download download = (Download) downloads.get(0); assertEquals("id should match expected", 2, download.id); assertEquals("file name should match expected", "FileTest num 2", download.file_file_name); assertEquals("user_id should match expected", 3, download.user_id); } @Test public void joinWithSpecificType() throws Exception { List<CaffeineObject> downloads = CaffeineObject.chainable(Download.class).join("inner", "downloads.user_id", "users.id").where("users.id = ?", 3).execute(); assertEquals("size of return list should match expected", downloads.size(), 1); Download download = (Download) downloads.get(0); assertEquals("id should match expected", 2, download.id); assertEquals("file name should match expected", "FileTest num 2", download.file_file_name); assertEquals("user_id should match expected", 3, download.user_id); } @Test public void where() throws Exception { CaffeineObject.setQueryClass(User.class); List<CaffeineObject> users = CaffeineObject.chainable().where("id in (2, 3)").execute(); assertEquals("size of return list should match expected", 2, users.size()); User user1 = (User) users.get(0); User user2 = (User) users.get(1); assertEquals("id should match expected", 2, user1.id); assertEquals("first name should match expected", "Nick", user1.first_name); assertEquals("last name should match expected", "Case", user1.last_name); assertEquals("id should match expected", 3, user2.id); assertEquals("first name should match expected", "Test", user2.first_name); assertEquals("last name should match expected", "User", user2.last_name); } @Test public void whereWithVariables() throws Exception { List<CaffeineObject> users = CaffeineObject.chainable(User.class).where("id = ?", 2).execute(); assertEquals("size of return list should match expected", 1, users.size()); User user1 = (User) users.get(0); assertEquals("id should match expected", 2, user1.id); assertEquals("first name should match expected", "Nick", user1.first_name); assertEquals("last name should match expected", "Case", user1.last_name); } @Test public void whereWithListArgs() throws Exception { List<Object> args = new ArrayList<Object>(); args.add(2); args.add(3); List<CaffeineObject> users = CaffeineObject.chainable().where("id in (?, ?)", args).execute(); assertEquals("size of return list should match expected", 2, users.size()); User user1 = (User) users.get(0); User user2 = (User) users.get(1); assertEquals("id should match expected", 2, user1.id); assertEquals("first name should match expected", "Nick", user1.first_name); assertEquals("last name should match expected", "Case", user1.last_name); assertEquals("id should match expected", 3, user2.id); assertEquals("first name should match expected", "Test", user2.first_name); assertEquals("last name should match expected", "User", user2.last_name); } @Test public void or() throws Exception { List<CaffeineObject> users = CaffeineObject.chainable(User.class).where("id in (2, 3)").or("first_name = 'Grawr'").execute(); assertEquals("size of return list should match expected", 3, users.size()); User user1 = (User) users.get(0); User user2 = (User) users.get(1); User user3 = (User) users.get(2); assertEquals("id should matched expected", 1, user1.id); assertEquals("first name should match expected", "Grawr", user1.first_name); assertEquals("last name should match expected", "McPhee", user1.last_name); assertEquals("id should match expected", 2, user2.id); assertEquals("first name should match expected", "Nick", user2.first_name); assertEquals("last name should match expected", "Case", user2.last_name); assertEquals("id should match expected", 3, user3.id); assertEquals("first name should match expected", "Test", user3.first_name); assertEquals("last name should match expected", "User", user3.last_name); } @Test public void orWithVariables() throws Exception { List<CaffeineObject> users = CaffeineObject.chainable(User.class).where("id = ?", 2).or("id = ?", 3).execute(); assertEquals("size of return list should match expected", 2, users.size()); User user1 = (User) users.get(0); User user2 = (User) users.get(1); assertEquals("id should match expected", 2, user1.id); assertEquals("first name should match expected", "Nick", user1.first_name); assertEquals("last name should match expected", "Case", user1.last_name); assertEquals("id should match expected", 3, user2.id); assertEquals("first name should match expected", "Test", user2.first_name); assertEquals("last name should match expected", "User", user2.last_name); } @Test public void orWithListArgs() throws Exception { List<Object> args = new ArrayList<Object>(); args.add(2); args.add(3); List<CaffeineObject> users = CaffeineObject.chainable(User.class).where("id = 2").or("id in (?, ?)", args).execute(); assertEquals("size of return list should match expected", 2, users.size()); User user1 = (User) users.get(0); User user2 = (User) users.get(1); assertEquals("id should match expected", 2, user1.id); assertEquals("first name should match expected", "Nick", user1.first_name); assertEquals("last name should match expected", "Case", user1.last_name); assertEquals("id should match expected", 3, user2.id); assertEquals("first name should match expected", "Test", user2.first_name); assertEquals("last name should match expected", "User", user2.last_name); } @Test public void getAssociatedHasMany() throws Exception { User user = (User) CaffeineObject.find(User.class, 2); List<CaffeineObject> downloads = user.getAssociated(Download.class); assertEquals("size of return should match expected", 2, downloads.size()); Download download1 = (Download) downloads.get(0); Download download2 = (Download) downloads.get(1); assertArrayEquals("ids of associated downloads should match expected", new int[] {1, 4}, new int[] {download1.id, download2.id}); } @Test public void getAssociatedHasManyWithForeignKey() throws Exception { User user = (User) CaffeineObject.find(User.class, 2); List<CaffeineObject> downloads = user.getAssociated(Download.class, "org_id"); assertEquals("size of return should match expected", 2, downloads.size()); Download download1 = (Download) downloads.get(0); Download download2 = (Download) downloads.get(1); assertArrayEquals("ids of associated downloads should match expected", new int[] {1, 3}, new int[] {download1.id, download2.id}); } @Test public void getAssociatedBelongsTo() throws Exception { Download download = (Download) CaffeineObject.find(Download.class, 3); List<CaffeineObject> users = download.getAssociated(User.class); assertEquals("return list should only contain the possessing object", 1, users.size()); User user = (User) users.get(0); assertEquals("id should match expected possessing user", 1, user.id); } @Test public void getAssociatedBelongsToWithForeignKey() throws Exception { Download download = (Download) CaffeineObject.find(Download.class, 3); List<CaffeineObject> users = download.getAssociated(User.class, "org_id"); assertEquals("return list should only contain the possessing object", 1, users.size()); User user = (User) users.get(0); assertEquals("id should match expected possessing user", 2, user.id); } // Test helper methods @Before public void setUp() throws Exception { // The database must already exist, but should be blank otherwise. Caffeine.setConfiguration(System.getenv("CAFFEINE_DB_DRIVER"), System.getenv("CAFFEINE_DB_TEST_URL"), System.getenv("CAFFEINE_DB_USERNAME"), System.getenv("CAFFEINE_DB_PASSWORD")); insertTables(); insertUsers(); insertDownloads(); } @After public void tearDown() throws Exception { Caffeine.executeUpdate("drop table if exists users"); Caffeine.executeUpdate("drop table if exists downloads"); } public void insertTables() throws Exception { Caffeine.executeUpdate("drop table if exists users"); Caffeine.executeUpdate("drop table if exists downloads"); Caffeine.executeUpdate("create table if not exists users (" + "id integer not null, " + "first_name varchar(255), " + "last_name varchar(255), " + "encrypted_password varchar(255), " + "sign_in_count integer, " + "role varchar(255))" ); Caffeine.executeUpdate("create table if not exists downloads (" + "id integer not null, " + "file_file_name varchar(255), " + "org_id integer, " + "user_id integer)" ); } private void insertUsers() throws Exception { Caffeine.executeUpdate("insert into users (id, first_name, last_name, encrypted_password, sign_in_count, role) values " + "(1, 'Grawr', 'McPhee', 'qwerqwer', 13, 'admin')," + "(2, 'Nick', 'Case', 'asdfasdf', 0, 'super')," + "(3, 'Test', 'User', 'zxcvzxcv', 3, 'moderator')" ); } private void insertDownloads() throws Exception { Caffeine.executeUpdate("insert into downloads (id, file_file_name, org_id, user_id) values " + "(1, 'FileTest num 1', 2, 2)," + "(2, 'FileTest num 2', 1, 3)," + "(3, 'FileTest num 3', 2, 1)," + "(4, 'FileTest num 4', 3, 2)" ); } }
package rx.android.concurrency; import android.os.Handler; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import rx.Scheduler; import rx.Subscription; import rx.operators.SafeObservableSubscription; import rx.util.functions.Func2; import java.util.concurrent.TimeUnit; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Schedules actions to run on an Android Handler thread. */ public class HandlerThreadScheduler extends Scheduler { private final Handler handler; /** * Constructs a {@link HandlerThreadScheduler} using the given {@link Handler} * @param handler {@link Handler} to use when scheduling actions */ public HandlerThreadScheduler(Handler handler) { this.handler = handler; } /** * Calls {@link HandlerThreadScheduler#schedule(Object, rx.util.functions.Func2, long, java.util.concurrent.TimeUnit)} * with a delay of zero milliseconds. * * See {@link #schedule(Object, rx.util.functions.Func2, long, java.util.concurrent.TimeUnit)} */ @Override public <T> Subscription schedule(final T state, final Func2<Scheduler, T, Subscription> action) { return schedule(state, action, 0L, TimeUnit.MILLISECONDS); } /** * Calls {@link Handler#postDelayed(Runnable, long)} with a runnable that executes the given action. * @param state * State to pass into the action. * @param action * Action to schedule. * @param delayTime * Time the action is to be delayed before executing. * @param unit * Time unit of the delay time. * @return A Subscription from which one can unsubscribe from. */ @Override public <T> Subscription schedule(final T state, final Func2<Scheduler, T, Subscription> action, long delayTime, TimeUnit unit) { final SafeObservableSubscription subscription = new SafeObservableSubscription(); final Scheduler _scheduler = this; handler.postDelayed(new Runnable() { @Override public void run() { subscription.wrap(action.call(_scheduler, state)); } }, unit.toMillis(delayTime)); return subscription; } @RunWith(RobolectricTestRunner.class) @Config(manifest=Config.NONE) public static final class UnitTest { @Test public void shouldScheduleImmediateActionOnHandlerThread() { final Handler handler = mock(Handler.class); final Object state = new Object(); final Func2<Scheduler, Object, Subscription> action = mock(Func2.class); Scheduler scheduler = new HandlerThreadScheduler(handler); scheduler.schedule(state, action); // verify that we post to the given Handler ArgumentCaptor<Runnable> runnable = ArgumentCaptor.forClass(Runnable.class); verify(handler).postDelayed(runnable.capture(), eq(0L)); // verify that the given handler delegates to our action runnable.getValue().run(); verify(action).call(scheduler, state); } @Test public void shouldScheduleDelayedActionOnHandlerThread() { final Handler handler = mock(Handler.class); final Object state = new Object(); final Func2<Scheduler, Object, Subscription> action = mock(Func2.class); Scheduler scheduler = new HandlerThreadScheduler(handler); scheduler.schedule(state, action, 1L, TimeUnit.SECONDS); // verify that we post to the given Handler ArgumentCaptor<Runnable> runnable = ArgumentCaptor.forClass(Runnable.class); verify(handler).postDelayed(runnable.capture(), eq(1000L)); // verify that the given handler delegates to our action runnable.getValue().run(); verify(action).call(scheduler, state); } } }
package test.beast.evolution.datatype; import beast.evolution.datatype.Codon; import beast.evolution.datatype.DataType; import beast.evolution.datatype.Nucleotide; import org.junit.Before; import org.junit.Test; import test.beast.evolution.CodonTestData; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static junit.framework.Assert.assertEquals; /** * @author Walter Xie */ public class CodonTest { protected Codon codon; @Before public void setUp() { codon = CodonTestData.codonUNIVERSAL; } @Test public void testCodeMap(){ int stateCount = codon.getStateCount(); System.out.println("stateCount = " + stateCount); assertEquals("Codon stateCount : ", 64, stateCount); int codeLength = codon.getCodeLength(); System.out.println("codeLength = " + codeLength); assertEquals("Codon codeLength : ", 3, codeLength); String codeMap = codon.getCodeMap(); System.out.println("codeMap = " + codeMap); assertEquals("Codon codeMap : ", CodonTestData.getTriplets(), codeMap); } // @Test // public void testGetStatesForCode() { // for (int i = 0; i < codon.getStateCountAmbiguous(); i++) { // int[] stateSet = codon.getStatesForCode(i); // System.out.println("mapCodeToStateSet " + i + " = " + Arrays.toString(stateSet)); // assertEquals("Codon mapCodeToStateSet : ", 0, codon.getStatesForCode(0)[0]); // assertEquals("Codon mapCodeToStateSet : ", 10, codon.getStatesForCode(10)[0]); // assertEquals("Codon mapCodeToStateSet : ", 49, codon.getStatesForCode(48)[0]); // assertEquals("Codon mapCodeToStateSet : ", 51, codon.getStatesForCode(49)[0]); // assertEquals("Codon mapCodeToStateSet : ", 57, codon.getStatesForCode(54)[0]); // assertEquals("Codon mapCodeToStateSet : ", 63, codon.getStatesForCode(60)[0]); // // stop codon // assertEquals("Codon mapCodeToStateSet : ", 48, codon.getStatesForCode(61)[0]); // assertEquals("Codon mapCodeToStateSet : ", 50, codon.getStatesForCode(62)[0]); // assertEquals("Codon mapCodeToStateSet : ", 56, codon.getStatesForCode(63)[0]); @SafeVarargs private final <T> List<T> toList(T... a) { return new ArrayList<>(Arrays.asList(a)); } @Test public void testStringToEncoding() { String data = CodonTestData.getTriplets(); List<Integer> states = codon.stringToEncoding(data); System.out.println("StringToEncoding : " + data); System.out.println("StringToEncoding : " + states); data = "AAATTT"; states = codon.stringToEncoding(data); assertEquals("StringToEncoding : ", toList(0, 63), states); // stop codon data = "TAATAGTGA"; states = codon.stringToEncoding(data); assertEquals("StringToEncoding : ", toList(48, 50, 56), states); // ambiguous data = "AA-A states = codon.stringToEncoding(data); assertEquals("StringToEncoding : ", toList(64, 112, 124), states); } @Test public void testEncodingToString() { String data = codon.encodingToString(toList(0, 63)); assertEquals("StringToEncoding : ", "AAATTT", data); data = codon.encodingToString(toList(48, 50, 56)); assertEquals("StringToEncoding : ", "TAATAGTGA", data); data = codon.encodingToString(toList(64, 112, 124)); assertEquals("StringToEncoding : ", "AA-A } @Test public void testNucleotideState() { Nucleotide nuc = new Nucleotide(); int gapState = nuc.getCodeMap().indexOf(DataType.GAP_CHAR); assertEquals("Nucleotide '-' state : ", Codon.NUC_GAP_STATE, gapState); int missState = nuc.getCodeMap().indexOf(DataType.MISSING_CHAR); assertEquals("Nucleotide '?' state : ", Codon.NUC_MISSING_STATE, missState); } @Test public void testGetTriplet() { int[] states = CodonTestData.getTestStates(); for (int i = 0; i < states.length; i++) { int state = states[i]; String triplet = codon.getTriplet(state); System.out.println(state + " " + triplet); assertEquals("Triplet : ", Codon.CODON_TRIPLETS[state], triplet); } } @Test(expected = RuntimeException.class) public void testGetTripletException1() { String triplet = codon.getTriplet(-1); } @Test(expected = RuntimeException.class) public void testGetTripletException2() { String triplet = codon.getTriplet(125); } @Test public void testStateToAminoAcid() { int[] states = new int[]{0, 8, 63}; String aa = codon.stateToAminoAcid(states); System.out.println("StateToAminoAcid : 0, 8, 63 => " + aa); assertEquals("StateToAminoAcid : ", "KRF", aa); states = new int[]{48, 50, 56}; aa = codon.stateToAminoAcid(states); System.out.println("StateToAminoAcid : 48, 50, 56 => " + aa); assertEquals("StateToAminoAcid : ", "***", aa); states = new int[]{64, 124}; aa = codon.stateToAminoAcid(states); System.out.println("StateToAminoAcid : 64, 124 => " + aa); assertEquals("StateToAminoAcid : ", " } }
package com.github.nsnjson; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; import org.junit.*; import static com.github.nsnjson.format.Format.*; public class DriverTest extends AbstractFormatTest { @Test public void testNull() { shouldBeConsistencyWhenGivenNull(getNull(), getNullPresentation()); } @Test public void testNumberInt() { NumericNode value = getNumberInt(); shouldBeConsistencyWhenGivenNumberIsInt(value, getNumberIntPresentation(value)); } @Test public void testNumberLong() { NumericNode value = getNumberLong(); shouldBeConsistencyWhenGivenNumberIsLong(value, getNumberLongPresentation(value)); } @Test public void testNumberDouble() { NumericNode value = getNumberDouble(); shouldBeConsistencyWhenGivenNumberIsDouble(value, getNumberDoublePresentation(value)); } @Test public void shouldBeConsistencyWhenGivenStringIsEmpty() { TextNode value = getEmptyString(); assertConsistency(value, getStringPresentation(value)); } @Test public void shouldBeConsistencyWhenGivenString() { TextNode value = getString(); assertConsistency(value, getStringPresentation(value)); } @Test public void shouldBeConsistencyWhenGivenBooleanIsTrue() { BooleanNode value = getBooleanTrue(); assertConsistency(value, getBooleanPresentation(value)); } @Test public void shouldBeConsistencyWhenGivenBooleanIsFalse() { BooleanNode value = getBooleanFalse(); assertConsistency(value, getBooleanPresentation(value)); } @Test public void shouldBeConsistencyWhenGivenArrayIsEmpty() { assertConsistency(getEmptyArray(), getEmptyArrayPresentation()); } @Test public void shouldBeConsistencyWhenGivenArray() { ObjectMapper objectMapper = new ObjectMapper(); JsonNode numberInt = getNumberInt(); JsonNode numberLong = getNumberLong(); JsonNode numberDouble = getNumberDouble(); JsonNode string = getString(); JsonNode booleanTrue = getBooleanTrue(); JsonNode booleanFalse = getBooleanFalse(); ArrayNode array = objectMapper.createArrayNode(); array.add(getNull()); array.add(numberInt); array.add(numberLong); array.add(numberDouble); array.add(string); array.add(booleanTrue); array.add(booleanFalse); ObjectNode presentationOfNull = objectMapper.createObjectNode(); presentationOfNull.put(FIELD_TYPE, TYPE_MARKER_NULL); ObjectNode presentationOfNumberInt = objectMapper.createObjectNode(); presentationOfNumberInt.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberInt.put(FIELD_VALUE, numberInt.asInt()); ObjectNode presentationOfNumberLong = objectMapper.createObjectNode(); presentationOfNumberLong.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberLong.put(FIELD_VALUE, numberLong.asLong()); ObjectNode presentationOfNumberDouble = objectMapper.createObjectNode(); presentationOfNumberDouble.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberDouble.put(FIELD_VALUE, numberDouble.asDouble()); ObjectNode presentationOfString = objectMapper.createObjectNode(); presentationOfString.put(FIELD_TYPE, TYPE_MARKER_STRING); presentationOfString.put(FIELD_VALUE, string.asText()); ObjectNode presentationOfBooleanTrue = objectMapper.createObjectNode(); presentationOfBooleanTrue.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanTrue.put(FIELD_VALUE, BOOLEAN_TRUE); ObjectNode presentationOfBooleanFalse = objectMapper.createObjectNode(); presentationOfBooleanFalse.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanFalse.put(FIELD_VALUE, BOOLEAN_FALSE); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); presentationOfArrayItems.add(presentationOfNull); presentationOfArrayItems.add(presentationOfNumberInt); presentationOfArrayItems.add(presentationOfNumberLong); presentationOfArrayItems.add(presentationOfNumberDouble); presentationOfArrayItems.add(presentationOfString); presentationOfArrayItems.add(presentationOfBooleanTrue); presentationOfArrayItems.add(presentationOfBooleanFalse); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_ARRAY); presentation.set(FIELD_VALUE, presentationOfArrayItems); assertConsistency(array, presentation); } @Test public void shouldBeConsistencyWhenGivenObjectIsEmpty() { assertConsistency(getEmptyObject(), getEmptyObjectPresentation()); } @Test public void shouldBeConsistencyWhenGivenObject() { ObjectMapper objectMapper = new ObjectMapper(); String nullField = "null_field"; String numberIntField = "int_field"; String numberLongField = "long_field"; String numberDoubleField = "double_field"; String stringField = "string_field"; String booleanTrueField = "true_field"; String booleanFalseField = "false_field"; JsonNode numberInt = getNumberInt(); JsonNode numberLong = getNumberLong(); JsonNode numberDouble = getNumberDouble(); JsonNode string = getString(); JsonNode booleanTrue = getBooleanTrue(); JsonNode booleanFalse = getBooleanFalse(); ObjectNode object = objectMapper.createObjectNode(); object.set(nullField, getNull()); object.set(numberIntField, numberInt); object.set(numberLongField, numberLong); object.set(numberDoubleField, numberDouble); object.set(stringField, string); object.set(booleanTrueField, booleanTrue); object.set(booleanFalseField, booleanFalse); ObjectNode presentationOfNullField = objectMapper.createObjectNode(); presentationOfNullField.put(FIELD_NAME, nullField); presentationOfNullField.put(FIELD_TYPE, TYPE_MARKER_NULL); ObjectNode presentationOfNumberIntField = objectMapper.createObjectNode(); presentationOfNumberIntField.put(FIELD_NAME, numberIntField); presentationOfNumberIntField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberIntField.put(FIELD_VALUE, numberInt.asInt()); ObjectNode presentationOfNumberLongField = objectMapper.createObjectNode(); presentationOfNumberLongField.put(FIELD_NAME, numberLongField); presentationOfNumberLongField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberLongField.put(FIELD_VALUE, numberLong.asLong()); ObjectNode presentationOfNumberDoubleField = objectMapper.createObjectNode(); presentationOfNumberDoubleField.put(FIELD_NAME, numberDoubleField); presentationOfNumberDoubleField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberDoubleField.put(FIELD_VALUE, numberDouble.asDouble()); ObjectNode presentationOfStringField = objectMapper.createObjectNode(); presentationOfStringField.put(FIELD_NAME, stringField); presentationOfStringField.put(FIELD_TYPE, TYPE_MARKER_STRING); presentationOfStringField.put(FIELD_VALUE, string.asText()); ObjectNode presentationOfBooleanTrueField = objectMapper.createObjectNode(); presentationOfBooleanTrueField.put(FIELD_NAME, booleanTrueField); presentationOfBooleanTrueField.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanTrueField.put(FIELD_VALUE, BOOLEAN_TRUE); ObjectNode presentationOfBooleanFalseField = objectMapper.createObjectNode(); presentationOfBooleanFalseField.put(FIELD_NAME, booleanFalseField); presentationOfBooleanFalseField.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanFalseField.put(FIELD_VALUE, BOOLEAN_FALSE); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); presentationOfArrayItems.add(presentationOfNullField); presentationOfArrayItems.add(presentationOfNumberIntField); presentationOfArrayItems.add(presentationOfNumberLongField); presentationOfArrayItems.add(presentationOfNumberDoubleField); presentationOfArrayItems.add(presentationOfStringField); presentationOfArrayItems.add(presentationOfBooleanTrueField); presentationOfArrayItems.add(presentationOfBooleanFalseField); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_OBJECT); presentation.set(FIELD_VALUE, presentationOfArrayItems); assertConsistency(object, presentation); } private void shouldBeConsistencyWhenGivenNull(NullNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenNumberIsInt(NumericNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenNumber(value, presentation); } private void shouldBeConsistencyWhenGivenNumberIsLong(NumericNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenNumber(value, presentation); } private void shouldBeConsistencyWhenGivenNumberIsDouble(NumericNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenNumber(value, presentation); } private void shouldBeConsistencyWhenGivenNumber(NumericNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private static void assertConsistency(JsonNode value, ObjectNode presentation) { Assert.assertEquals(value, Driver.decode(Driver.encode(value))); Assert.assertEquals(presentation, Driver.encode(Driver.decode(presentation))); } }
package org.realityforge.replicant.server.ee.rest; import java.io.Serializable; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Set; import javax.annotation.Nonnull; import javax.json.Json; import javax.json.stream.JsonGenerator; import javax.json.stream.JsonGeneratorFactory; import javax.validation.constraints.NotNull; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import org.realityforge.replicant.server.ChannelDescriptor; import org.realityforge.replicant.server.ee.JsonUtil; import org.realityforge.replicant.server.transport.ChannelMetaData; import org.realityforge.replicant.server.transport.Packet; import org.realityforge.replicant.server.transport.PacketQueue; import org.realityforge.replicant.server.transport.ReplicantSession; import org.realityforge.replicant.server.transport.ReplicantSessionManager; import org.realityforge.replicant.server.transport.SubscriptionEntry; import org.realityforge.replicant.shared.transport.ReplicantContext; import org.realityforge.rest.field_filter.FieldFilter; import org.realityforge.ssf.SessionInfo; /** * The session management rest resource. * * It is expected that this endpoint has already had security applied. * * Extend this class and provider a SessionManager as required. ie. * * <pre> * \@Path( ReplicantContext.SESSION_URL_FRAGMENT ) * \@Produces( MediaType.APPLICATION_JSON ) * \@ApplicationScoped * public class CalendarSessionRestService * extends AbstractSessionRestService * { * \@Inject * private MySessionManager _sessionManager; * * \@Override * protected ReplicantSessionManager getSessionManager() * { * return _sessionManager; * } * * \@Override * \@PostConstruct * public void postConstruct() * { * super.postConstruct(); * } * } * </pre> */ public abstract class AbstractSessionRestService { private DatatypeFactory _datatypeFactory; private JsonGeneratorFactory _factory; protected abstract ReplicantSessionManager getSessionManager(); public void postConstruct() { final HashMap<String, Object> config = new HashMap<>(); config.put( JsonGenerator.PRETTY_PRINTING, true ); _factory = Json.createGeneratorFactory( config ); try { _datatypeFactory = DatatypeFactory.newInstance(); } catch ( final DatatypeConfigurationException dtce ) { throw new IllegalStateException( "Unable to initialize DatatypeFactory", dtce ); } } @POST @Produces( MediaType.TEXT_PLAIN ) public Response createSession() { return doCreateSession(); } @Path( "{sessionID}" ) @DELETE public Response deleteSession( @PathParam( "sessionID" ) @NotNull final String sessionID ) { return doDeleteSession( sessionID ); } @GET public Response listSessions( @QueryParam( "fields" ) @DefaultValue( "url" ) @NotNull final FieldFilter filter, @Context @Nonnull final UriInfo uri ) { return doListSessions( filter, uri ); } @Path( "{sessionID}" ) @GET public Response getSession( @PathParam( "sessionID" ) @NotNull final String sessionID, @QueryParam( "fields" ) @DefaultValue( "" ) @Nonnull final FieldFilter filter, @Context @Nonnull final UriInfo uri ) { return doGetSession( sessionID, filter, uri ); } @Nonnull protected Response doCreateSession() { final Response.ResponseBuilder builder = Response.ok(); CacheUtil.configureNoCacheHeaders( builder ); return builder.entity( getSessionManager().createSession().getSessionID() ).build(); } @Nonnull protected Response doDeleteSession( @Nonnull final String sessionID ) { final StringWriter writer = new StringWriter(); final JsonGenerator g = factory().createGenerator( writer ); g.writeStartObject(); g.write( "code", Response.Status.OK.getStatusCode() ); g.write( "description", "Session removed." ); g.writeEnd(); g.close(); final Response.ResponseBuilder builder = Response.ok(); CacheUtil.configureNoCacheHeaders( builder ); getSessionManager().invalidateSession( sessionID ); return builder.entity( writer.toString() ).build(); } @Nonnull protected Response doListSessions( @Nonnull final FieldFilter filter, @Nonnull final UriInfo uri ) { final Response.ResponseBuilder builder = Response.ok(); CacheUtil.configureNoCacheHeaders( builder ); final StringWriter writer = new StringWriter(); final JsonGenerator g = factory().createGenerator( writer ); final Set<String> sessionIDs = getSessionManager().getSessionIDs(); g.writeStartArray(); for ( final String sessionID : sessionIDs ) { final ReplicantSession session = getSessionManager().getSession( sessionID ); if ( null != session ) { emitSession( session, g, filter, uri ); } } g.writeEnd(); g.close(); return builder.entity( writer.toString() ).build(); } @Nonnull protected Response doGetSession( @Nonnull final String sessionID, @Nonnull final FieldFilter filter, @Nonnull final UriInfo uri ) { final StringWriter writer = new StringWriter(); final JsonGenerator g = factory().createGenerator( writer ); final ReplicantSession session = getSessionManager().getSession( sessionID ); final Response.ResponseBuilder builder; if ( null == session ) { builder = Response.status( Response.Status.NOT_FOUND ); CacheUtil.configureNoCacheHeaders( builder ); g.writeStartObject(); g.write( "code", Response.Status.NOT_FOUND.getStatusCode() ); g.write( "description", "No such session." ); g.writeEnd(); } else { builder = Response.ok(); emitSession( session, g, filter, uri ); } CacheUtil.configureNoCacheHeaders( builder ); g.close(); return builder.entity( writer.toString() ).build(); } private void emitSession( @Nonnull final ReplicantSession session, @Nonnull final JsonGenerator g, @Nonnull final FieldFilter filter, @Nonnull final UriInfo uri ) { g.writeStartObject(); if ( filter.allow( "id" ) ) { g.write( "id", session.getSessionID() ); } if ( filter.allow( "url" ) ) { g.write( "url", getSessionURL( session, uri ) ); } if ( filter.allow( "createdAt" ) ) { g.write( "createdAt", asDateTimeString( session.getCreatedAt() ) ); } if ( filter.allow( "lastAccessedAt" ) ) { g.write( "lastAccessedAt", asDateTimeString( session.getLastAccessedAt() ) ); } if ( filter.allow( "attributes" ) ) { final FieldFilter subFilter = filter.subFilter( "attributes" ); g.writeStartObject( "attributes" ); for ( final String attributeKey : session.getAttributeKeys() ) { if ( subFilter.allow( attributeKey ) ) { final Serializable attribute = session.getAttribute( attributeKey ); if ( null == attribute ) { g.writeNull( attributeKey ); } else { g.write( attributeKey, String.valueOf( attribute ) ); } } } g.writeEnd(); } if ( filter.allow( "net" ) ) { final FieldFilter subFilter = filter.subFilter( "net" ); g.writeStartObject( "net" ); final PacketQueue queue = session.getQueue(); if ( subFilter.allow( "queueSize" ) ) { g.write( "queueSize", queue.size() ); } if ( subFilter.allow( "lastSequenceAcked" ) ) { g.write( "lastSequenceAcked", queue.getLastSequenceAcked() ); } if ( subFilter.allow( "nextPacketSequence" ) ) { final Packet nextPacket = queue.nextPacketToProcess(); if ( null != nextPacket ) { g.write( "nextPacketSequence", nextPacket.getSequence() ); } else { g.writeNull( "nextPacketSequence" ); } } g.writeEnd(); } if ( filter.allow( "status" ) ) { final FieldFilter subFilter = filter.subFilter( "status" ); g.writeStartObject( "status" ); emitSubscriptions( g, session.getSubscriptions().values(), subFilter ); g.writeEnd(); } g.writeEnd(); } @Nonnull private String getSessionURL( @Nonnull final SessionInfo session, @Nonnull final UriInfo uri ) { return uri.getBaseUri() + ReplicantContext.SESSION_URL_FRAGMENT.substring( 1 ) + "/" + session.getSessionID(); } @Nonnull private String asDateTimeString( final long timeInMillis ) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeInMillis( timeInMillis ); return _datatypeFactory.newXMLGregorianCalendar( calendar ).toXMLFormat(); } private void emitSubscriptions( @Nonnull final JsonGenerator g, @Nonnull final Collection<SubscriptionEntry> subscriptionEntries, @Nonnull final FieldFilter filter ) { if ( filter.allow( "subscriptions" ) ) { g.writeStartArray( "subscriptions" ); final FieldFilter subFilter = filter.subFilter( "subscriptions" ); final ArrayList<SubscriptionEntry> subscriptions = new ArrayList<>( subscriptionEntries ); Collections.sort( subscriptions ); for ( final SubscriptionEntry subscription : subscriptions ) { emitSubscriptionEntry( g, subscription, subFilter ); } g.writeEnd(); } } private void emitChannelID( @Nonnull final JsonGenerator g, @Nonnull final FieldFilter filter, final int channelID ) { if ( filter.allow( "channelID" ) ) { g.write( "channelID", channelID ); } } private void emitSubChannelID( @Nonnull final JsonGenerator g, @Nonnull final FieldFilter filter, final Serializable subChannelID ) { if ( null != subChannelID && filter.allow( "instanceID" ) ) { if ( subChannelID instanceof Integer ) { g.write( "instanceID", (Integer) subChannelID ); } else { g.write( "instanceID", String.valueOf( subChannelID ) ); } } } private void emitChannelDescriptors( @Nonnull final JsonGenerator g, @Nonnull final Set<ChannelDescriptor> descriptors, @Nonnull final FieldFilter filter ) { for ( final ChannelDescriptor descriptor : descriptors ) { g.writeStartObject(); emitChannelDescriptor( g, filter, descriptor ); g.writeEnd(); } } private void emitSubscriptionEntry( @Nonnull final JsonGenerator g, @Nonnull final SubscriptionEntry entry, @Nonnull final FieldFilter filter ) { if ( filter.allow( "subscription" ) ) { final FieldFilter subFilter = filter.subFilter( "subscription" ); g.writeStartObject(); final ChannelMetaData channelMetaData = getSessionManager().getChannelMetaData( entry.getDescriptor() ); if ( subFilter.allow( "name" ) ) { g.write( "name", channelMetaData.getName() ); } emitChannelDescriptor( g, subFilter, entry.getDescriptor() ); if ( subFilter.allow( "explicitlySubscribed" ) ) { g.write( "explicitlySubscribed", entry.isExplicitlySubscribed() ); } if ( channelMetaData.getFilterType() != ChannelMetaData.FilterType.NONE && subFilter.allow( "filter" ) ) { final Object f = entry.getFilter(); if ( null == f ) { g.writeNull( "filter" ); } else { g.write( "filter", JsonUtil.toJsonObject( f ) ); } } emitChannelDescriptors( g, "inwardSubscriptions", entry.getInwardSubscriptions(), subFilter ); emitChannelDescriptors( g, "outwardSubscriptions", entry.getOutwardSubscriptions(), subFilter ); g.writeEnd(); } } private void emitChannelDescriptor( @Nonnull final JsonGenerator g, @Nonnull final FieldFilter filter, @Nonnull final ChannelDescriptor descriptor ) { emitChannelID( g, filter, descriptor.getChannelID() ); emitSubChannelID( g, filter, descriptor.getSubChannelID() ); } private void emitChannelDescriptors( @Nonnull final JsonGenerator g, @Nonnull final String key, @Nonnull final Set<ChannelDescriptor> descriptors, @Nonnull final FieldFilter filter ) { if ( !descriptors.isEmpty() && filter.allow( key ) ) { final FieldFilter subFilter = filter.subFilter( key ); g.writeStartArray( key ); emitChannelDescriptors( g, descriptors, subFilter ); g.writeEnd(); } } protected JsonGeneratorFactory factory() { return _factory; } }
package core.time.parse; import org.junit.Test; import java.time.LocalDate; import java.time.Month; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import static org.junit.Assert.assertEquals; public class ParseDateTest { @Test public void parseDate() { LocalDate expected = LocalDate.of(2015, Month.OCTOBER, 30); assertEquals(LocalDate.parse("2015-10-30"), expected); } @Test public void parseDateWithISOFormatter() { LocalDate expected = LocalDate.of(2015, Month.OCTOBER, 30); DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE; assertEquals(LocalDate.parse("2015-10-30", isoFormatter), expected); } @Test public void parseDateWithCustomFormatter() { LocalDate expected = LocalDate.of(2015, Month.OCTOBER, 30); DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-dd-MM"); assertEquals(LocalDate.parse("2015-30-10", customFormatter), expected); } @Test(expected = DateTimeParseException.class) public void parseWrongFormatDate() { LocalDate.parse("2015-00-00"); } }
package mho.qbar.objects; import mho.wheels.misc.Readers; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.util.List; import java.util.Optional; import java.util.SortedSet; import java.util.TreeSet; import static mho.qbar.objects.Interval.*; import static mho.wheels.ordering.Ordering.*; import static org.junit.Assert.*; public class IntervalTest { @Test public void testConstants() { aeq(ZERO, "[0, 0]"); aeq(ONE, "[1, 1]"); aeq(ALL, "(-Infinity, Infinity)"); } @Test public void testGetLower() { aeq(ZERO.getLower().get(), "0"); aeq(ONE.getLower().get(), "1"); aeq(read("[-2, 5/3]").get().getLower().get(), "-2"); assertFalse(ALL.getLower().isPresent()); } @Test public void testGetUpper() { aeq(ZERO.getUpper().get(), "0"); aeq(ONE.getUpper().get(), "1"); aeq(read("[-2, 5/3]").get().getUpper().get(), "5/3"); assertFalse(ALL.getUpper().isPresent()); } @Test public void testOf_Rational_Rational() { aeq(of(Rational.read("1/3").get(), Rational.read("1/2").get()), "[1/3, 1/2]"); aeq(of(Rational.read("-5").get(), Rational.ZERO), "[-5, 0]"); aeq(of(Rational.read("2").get(), Rational.read("2").get()), "[2, 2]"); try { of(Rational.read("3").get(), Rational.read("2").get()); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testLessThanOrEqualTo() { aeq(lessThanOrEqualTo(Rational.read("1/3").get()), "(-Infinity, 1/3]"); aeq(lessThanOrEqualTo(Rational.ZERO), "(-Infinity, 0]"); } @Test public void testGreaterThanOrEqualTo() { aeq(greaterThanOrEqualTo(Rational.read("1/3").get()), "[1/3, Infinity)"); aeq(greaterThanOrEqualTo(Rational.ZERO), "[0, Infinity)"); } @Test public void testOf_Rational() { aeq(of(Rational.ZERO), "[0, 0]"); aeq(of(Rational.read("5/4").get()), "[5/4, 5/4]"); aeq(of(Rational.read("-2").get()), "[-2, -2]"); } @Test public void testIsFinitelyBounded() { assertTrue(ZERO.isFinitelyBounded()); assertTrue(ONE.isFinitelyBounded()); assertFalse(ALL.isFinitelyBounded()); assertTrue(read("[-2, 5/3]").get().isFinitelyBounded()); assertTrue(read("[4, 4]").get().isFinitelyBounded()); assertFalse(read("(-Infinity, 3/2]").get().isFinitelyBounded()); assertFalse(read("[-6, Infinity)").get().isFinitelyBounded()); } @Test public void testContains_Rational() { assertTrue(ZERO.contains(Rational.ZERO)); assertFalse(ZERO.contains(Rational.ONE)); assertTrue(ONE.contains(Rational.ONE)); assertFalse(ONE.contains(Rational.ZERO)); assertTrue(ALL.contains(Rational.ZERO)); assertTrue(ALL.contains(Rational.ONE)); assertTrue(ALL.contains(Rational.read("-4/3").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("-2").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("-1").get())); assertTrue(read("[-2, 5/3]").get().contains(Rational.ZERO)); assertTrue(read("[-2, 5/3]").get().contains(Rational.ONE)); assertTrue(read("[-2, 5/3]").get().contains(Rational.read("5/3").get())); assertFalse(read("[-2, 5/3]").get().contains(Rational.read("-3").get())); assertFalse(read("[-2, 5/3]").get().contains(Rational.read("2").get())); assertTrue(read("[4, 4]").get().contains(Rational.read("4").get())); assertFalse(read("[4, 4]").get().contains(Rational.read("3").get())); assertFalse(read("[4, 4]").get().contains(Rational.read("5").get())); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.ZERO)); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.ONE)); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.read("-10").get())); assertTrue(read("(-Infinity, 3/2]").get().contains(Rational.read("3/2").get())); assertFalse(read("(-Infinity, 3/2]").get().contains(Rational.read("2").get())); assertTrue(read("[-6, Infinity)").get().contains(Rational.ZERO)); assertTrue(read("[-6, Infinity)").get().contains(Rational.ONE)); assertTrue(read("[-6, Infinity)").get().contains(Rational.read("-4").get())); assertTrue(read("[-6, Infinity)").get().contains(Rational.read("5").get())); assertFalse(read("[-6, Infinity)").get().contains(Rational.read("-8").get())); } @Test public void testContains_Interval() { assertTrue(ZERO.contains(ZERO)); assertTrue(ONE.contains(ONE)); assertTrue(ALL.contains(ALL)); assertTrue(ALL.contains(ZERO)); assertTrue(ALL.contains(ONE)); assertFalse(ZERO.contains(ONE)); assertFalse(ZERO.contains(ALL)); assertFalse(ONE.contains(ZERO)); assertFalse(ONE.contains(ALL)); assertTrue(read("[1, 4]").get().contains(read("[2, 3]").get())); assertTrue(read("[1, 4]").get().contains(read("[1, 4]").get())); assertFalse(read("[1, 4]").get().contains(read("[0, 2]").get())); assertTrue(read("(-Infinity, 1/2]").get().contains(read("(-Infinity, 0]").get())); assertTrue(read("(-Infinity, 1/2]").get().contains(read("[0, 0]").get())); assertFalse(read("(-Infinity, 1/2]").get().contains(read("(-Infinity, 1]").get())); assertTrue(read("[1/2, Infinity)").get().contains(read("[1, Infinity)").get())); assertTrue(read("[1/2, Infinity)").get().contains(read("[1, 1]").get())); assertFalse(read("[1/2, Infinity)").get().contains(read("[0, Infinity)").get())); assertFalse(read("[1/2, Infinity)").get().contains(read("(-Infinity, 1/2]").get())); } @Test public void testDiameter() { aeq(ZERO.diameter().get(), "0"); aeq(ONE.diameter().get(), "0"); assertFalse(ALL.diameter().isPresent()); aeq(read("[-2, 5/3]").get().diameter().get(), "11/3"); aeq(read("[4, 4]").get().diameter().get(), "0"); assertFalse(read("(-Infinity, 3/2]").get().diameter().isPresent()); assertFalse(read("[-6, Infinity)").get().diameter().isPresent()); } @Test public void testConvexHull_Interval() { aeq(ZERO.convexHull(ZERO), "[0, 0]"); aeq(ZERO.convexHull(ONE), "[0, 1]"); aeq(ZERO.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ZERO.convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ZERO.convexHull(read("[4, 4]").get()), "[0, 4]"); aeq(ZERO.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ZERO.convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ONE.convexHull(ZERO), "[0, 1]"); aeq(ONE.convexHull(ONE), "[1, 1]"); aeq(ONE.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ONE.convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(ONE.convexHull(read("[4, 4]").get()), "[1, 4]"); aeq(ONE.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(ONE.convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(ALL.convexHull(ZERO), "(-Infinity, Infinity)"); aeq(ALL.convexHull(ONE), "(-Infinity, Infinity)"); aeq(ALL.convexHull(ALL), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[-2, 5/3]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[4, 4]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(ALL.convexHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().convexHull(ZERO), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(ONE), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get().convexHull(read("[-2, 5/3]").get()), "[-2, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(read("[4, 4]").get()), "[-2, 4]"); aeq(read("[-2, 5/3]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 5/3]"); aeq(read("[-2, 5/3]").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(read("[4, 4]").get().convexHull(ZERO), "[0, 4]"); aeq(read("[4, 4]").get().convexHull(ONE), "[1, 4]"); aeq(read("[4, 4]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[4, 4]").get().convexHull(read("[-2, 5/3]").get()), "[-2, 4]"); aeq(read("[4, 4]").get().convexHull(read("[4, 4]").get()), "[4, 4]"); aeq(read("[4, 4]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 4]"); aeq(read("[4, 4]").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); aeq(read("(-Infinity, 3/2]").get().convexHull(ZERO), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(ONE), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[-2, 5/3]").get()), "(-Infinity, 5/3]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[4, 4]").get()), "(-Infinity, 4]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, 3/2]"); aeq(read("(-Infinity, 3/2]").get().convexHull(read("[-6, Infinity)").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ZERO), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ONE), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(ALL), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[-2, 5/3]").get()), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[4, 4]").get()), "[-6, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("(-Infinity, 3/2]").get()), "(-Infinity, Infinity)"); aeq(read("[-6, Infinity)").get().convexHull(read("[-6, Infinity)").get()), "[-6, Infinity)"); } @Test public void testConvexHull_List_Interval() { aeq(convexHull(readIntervalList("[[0, 0]]").get()), "[0, 0]"); aeq(convexHull(readIntervalList("[[-1, 2]]").get()), "[-1, 2]"); aeq(convexHull(readIntervalList("[[-1, Infinity)]").get()), "[-1, Infinity)"); aeq(convexHull(readIntervalList("[(-Infinity, 4]]").get()), "(-Infinity, 4]"); aeq(convexHull(readIntervalList("[(-Infinity, Infinity)]").get()), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[0, 0], [1, 1]]").get()), "[0, 1]"); aeq(convexHull(readIntervalList("[[1, 2], [3, 4]]").get()), "[1, 4]"); aeq(convexHull(readIntervalList("[[1, 3], [2, 4]]").get()), "[1, 4]"); aeq(convexHull(readIntervalList("[(-Infinity, Infinity), [3, 4]]").get()), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[-1, Infinity), (-Infinity, 4]]").get()), "(-Infinity, Infinity)"); aeq(convexHull(readIntervalList("[[1, 2], [3, 4], [5, 6]]").get()), "[1, 6]"); aeq(convexHull(readIntervalList("[[1, 2], [2, 2], [3, Infinity)]").get()), "[1, Infinity)"); try { convexHull(readIntervalList("[]").get()); fail(); } catch (IllegalStateException ignored) {} try { convexHull(readIntervalListWithNulls("[[1, 2], null]").get()); fail(); } catch (NullPointerException ignored) {} } @Test public void testIntersection() { aeq(ZERO.intersection(ZERO).get(), "[0, 0]"); aeq(ONE.intersection(ONE).get(), "[1, 1]"); aeq(ALL.intersection(ALL).get(), "(-Infinity, Infinity)"); aeq(ALL.intersection(ZERO).get(), "[0, 0]"); aeq(ALL.intersection(ONE).get(), "[1, 1]"); assertFalse(ZERO.intersection(ONE).isPresent()); aeq(read("[1, 3]").get().intersection(read("[2, 4]").get()).get(), "[2, 3]"); aeq(read("[1, 2]").get().intersection(read("[2, 4]").get()).get(), "[2, 2]"); assertFalse(read("[1, 2]").get().intersection(read("[3, 4]").get()).isPresent()); aeq(ALL.intersection(read("[1, 2]").get()).get(), "[1, 2]"); aeq(read("(-Infinity, 2]").get().intersection(read("[1, 3]").get()).get(), "[1, 2]"); aeq(read("(-Infinity, 2]").get().intersection(read("(-Infinity, 3]").get()).get(), "(-Infinity, 2]"); aeq(read("[2, Infinity)").get().intersection(read("[1, 3]").get()).get(), "[2, 3]"); aeq(read("[2, Infinity)").get().intersection(read("[3, Infinity)").get()).get(), "[3, Infinity)"); aeq(read("[2, Infinity)").get().intersection(read("(-Infinity, 3]").get()).get(), "[2, 3]"); assertFalse(read("[2, Infinity)").get().intersection(read("(-Infinity, 1]").get()).isPresent()); } @Test public void testDisjoint() { assertFalse(ZERO.disjoint(ZERO)); assertFalse(ONE.disjoint(ONE)); assertFalse(ALL.disjoint(ALL)); assertFalse(ALL.disjoint(ZERO)); assertFalse(ALL.disjoint(ONE)); assertTrue(ZERO.disjoint(ONE)); assertFalse(read("[1, 3]").get().disjoint(read("[2, 4]").get())); assertTrue(read("[1, 2]").get().disjoint(read("[3, 4]").get())); assertFalse(read("(-Infinity, 2]").get().disjoint(read("[1, 3]").get())); assertTrue(read("(-Infinity, 2]").get().disjoint(read("[3, 4]").get())); assertFalse(read("[2, Infinity)").get().disjoint(read("[1, 3]").get())); assertTrue(read("[2, Infinity)").get().disjoint(read("[0, 1]").get())); assertTrue(read("[2, Infinity)").get().disjoint(read("(-Infinity, 1]").get())); assertFalse(read("[2, Infinity)").get().disjoint(read("(-Infinity, 3]").get())); } @Test public void testMakeDisjoint() { aeq(makeDisjoint(readIntervalList("[]").get()), "[]"); aeq(makeDisjoint(readIntervalList("[[0, 0]]").get()), "[[0, 0]]"); aeq(makeDisjoint(readIntervalList("[[1, 1]]").get()), "[[1, 1]]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, Infinity)]").get()), "[(-Infinity, Infinity)]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3]]").get()), "[(-Infinity, 3]]"); aeq(makeDisjoint(readIntervalList("[[2, Infinity)]").get()), "[[2, Infinity)]"); aeq(makeDisjoint(readIntervalList("[[2, 3]]").get()), "[[2, 3]]"); aeq( makeDisjoint(readIntervalList("[(-Infinity, 3], [4, 5], [6, 7]]").get()), "[(-Infinity, 3], [4, 5], [6, 7]]" ); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3], [3, 5], [5, 7]]").get()), "[(-Infinity, 7]]"); aeq(makeDisjoint(readIntervalList("[(-Infinity, 3], [2, 5], [6, 7]]").get()), "[(-Infinity, 5], [6, 7]]"); aeq( makeDisjoint(readIntervalList("[[1, 2], [4, 6], [10, Infinity), [3, 7], [5, 9]]").get()), "[[1, 2], [3, 9], [10, Infinity)]" ); try { makeDisjoint(readIntervalListWithNulls("[[1, 3], null, [5, Infinity)]").get()); fail(); } catch (NullPointerException ignored) {} } @Test public void testMidpoint() { aeq(ZERO.midpoint(), "0"); aeq(ONE.midpoint(), "1"); aeq(read("[4, 4]").get().midpoint(), "4"); aeq(read("[1, 2]").get().midpoint(), "3/2"); aeq(read("[-2, 5/3]").get().midpoint(), "-1/6"); try { ALL.midpoint(); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().midpoint(); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().midpoint(); fail(); } catch (ArithmeticException ignored) {} } @Test public void testSplit() { aeq(ZERO.split(Rational.ZERO), "([0, 0], [0, 0])"); aeq(ONE.split(Rational.ONE), "([1, 1], [1, 1])"); aeq(ALL.split(Rational.ONE), "((-Infinity, 1], [1, Infinity))"); aeq(read("[4, 4]").get().split(Rational.read("4").get()), "([4, 4], [4, 4])"); aeq(read("[0, 1]").get().split(Rational.read("1/3").get()), "([0, 1/3], [1/3, 1])"); aeq(read("[0, 1]").get().split(Rational.ZERO), "([0, 0], [0, 1])"); aeq(read("[0, 1]").get().split(Rational.ONE), "([0, 1], [1, 1])"); aeq(read("[-2, 5/3]").get().split(Rational.read("1").get()), "([-2, 1], [1, 5/3])"); aeq(read("(-Infinity, 1]").get().split(Rational.read("-3").get()), "((-Infinity, -3], [-3, 1])"); aeq(read("[5/3, Infinity)").get().split(Rational.read("10").get()), "([5/3, 10], [10, Infinity))"); try { ZERO.split(Rational.ONE); fail(); } catch (ArithmeticException ignored) {} try { read("[-2, 5/3]").get().split(Rational.read("-4").get()); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().split(Rational.read("4").get()); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().split(Rational.read("-4").get()); fail(); } catch (ArithmeticException ignored) {} } @Test public void testBisect() { aeq(ZERO.bisect(), "([0, 0], [0, 0])"); aeq(ONE.bisect(), "([1, 1], [1, 1])"); aeq(read("[4, 4]").get().bisect(), "([4, 4], [4, 4])"); aeq(read("[1, 2]").get().bisect(), "([1, 3/2], [3/2, 2])"); aeq(read("[-2, 5/3]").get().bisect(), "([-2, -1/6], [-1/6, 5/3])"); try { ALL.bisect(); fail(); } catch (ArithmeticException ignored) {} try { read("(-Infinity, 1]").get().bisect(); fail(); } catch (ArithmeticException ignored) {} try { read("[1, Infinity)").get().bisect(); fail(); } catch (ArithmeticException ignored) {} } @Test public void testEquals() { //noinspection EqualsWithItself assertTrue(ZERO.equals(ZERO)); //noinspection EqualsWithItself assertTrue(ONE.equals(ONE)); //noinspection EqualsWithItself assertTrue(ALL.equals(ALL)); assertTrue(read("[-2, 5/3]").equals(read("[-2, 5/3]"))); assertTrue(read("[4, 4]").equals(read("[4, 4]"))); assertTrue(read("(-Infinity, 3/2]").equals(read("(-Infinity, 3/2]"))); assertTrue(read("[-6, Infinity)").equals(read("[-6, Infinity)"))); assertFalse(ZERO.equals(ONE)); assertFalse(ZERO.equals(ALL)); assertFalse(ZERO.equals(read("[-2, 5/3]").get())); assertFalse(ZERO.equals(read("[4, 4]").get())); assertFalse(ZERO.equals(read("(-Infinity, 3/2]").get())); assertFalse(ZERO.equals(read("[-6, Infinity)").get())); assertFalse(ONE.equals(ZERO)); assertFalse(ONE.equals(ALL)); assertFalse(ONE.equals(read("[-2, 5/3]").get())); assertFalse(ONE.equals(read("[4, 4]").get())); assertFalse(ONE.equals(read("(-Infinity, 3/2]").get())); assertFalse(ONE.equals(read("[-6, Infinity)").get())); assertFalse(ALL.equals(ZERO)); assertFalse(ALL.equals(ONE)); assertFalse(ALL.equals(read("[-2, 5/3]").get())); assertFalse(ALL.equals(read("[4, 4]").get())); assertFalse(ALL.equals(read("(-Infinity, 3/2]").get())); assertFalse(ALL.equals(read("[-6, Infinity)").get())); assertFalse(read("[-2, 5/3]").get().equals(ZERO)); assertFalse(read("[-2, 5/3]").get().equals(ONE)); assertFalse(read("[-2, 5/3]").get().equals(ALL)); assertFalse(read("[-2, 5/3]").get().equals(read("[4, 4]").get())); assertFalse(read("[-2, 5/3]").get().equals(read("(-Infinity, 3/2]").get())); assertFalse(read("[-2, 5/3]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("[4, 4]").get().equals(ZERO)); assertFalse(read("[4, 4]").get().equals(ONE)); assertFalse(read("[4, 4]").get().equals(ALL)); assertFalse(read("[4, 4]").get().equals(read("[-2, 5/3]").get())); assertFalse(read("[4, 4]").get().equals(read("(-Infinity, 3/2]").get())); assertFalse(read("[4, 4]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(ZERO)); assertFalse(read("(-Infinity, 3/2]").get().equals(ONE)); assertFalse(read("(-Infinity, 3/2]").get().equals(ALL)); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[-2, 5/3]").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[4, 4]").get())); assertFalse(read("(-Infinity, 3/2]").get().equals(read("[-6, Infinity)").get())); assertFalse(read("[-6, Infinity)").get().equals(ZERO)); assertFalse(read("[-6, Infinity)").get().equals(ONE)); assertFalse(read("[-6, Infinity)").get().equals(ALL)); assertFalse(read("[-6, Infinity)").get().equals(read("[-2, 5/3]").get())); assertFalse(read("[-6, Infinity)").get().equals(read("[4, 4]").get())); assertFalse(read("[-6, Infinity)").get().equals(read("(-Infinity, 3/2]").get())); //noinspection ObjectEqualsNull assertFalse(ZERO.equals(null)); //noinspection ObjectEqualsNull assertFalse(ONE.equals(null)); //noinspection ObjectEqualsNull assertFalse(ALL.equals(null)); assertTrue(read("[-2, 5/3]").isPresent()); assertTrue(read("[4, 4]").isPresent()); assertTrue(read("(-Infinity, 3/2]").isPresent()); assertTrue(read("[-6, Infinity)").isPresent()); } @Test public void testHashCode() { aeq(ZERO.hashCode(), 32); aeq(ONE.hashCode(), 1024); aeq(ALL.hashCode(), 0); aeq(read("[-2, 5/3]").hashCode(), -1733); aeq(read("[4, 4]").hashCode(), 4000); aeq(read("(-Infinity, 3/2]").hashCode(), 95); aeq(read("[-6, Infinity)").hashCode(), -5735); } @Test public void testCompareTo() { assertTrue(eq(ZERO, ZERO)); assertTrue(eq(ONE, ONE)); assertTrue(eq(ALL, ALL)); assertTrue(eq(read("[-2, 5/3]").get(), read("[-2, 5/3]").get())); assertTrue(eq(read("[4, 4]").get(), read("[4, 4]").get())); assertTrue(eq(read("(-Infinity, 3/2]").get(), read("(-Infinity, 3/2]").get())); assertTrue(eq(read("[-6, Infinity)").get(), read("[-6, Infinity)").get())); assertTrue(lt(ZERO, ONE)); assertTrue(gt(ZERO, ALL)); assertTrue(gt(ZERO, read("[-2, 5/3]").get())); assertTrue(lt(ZERO, read("[4, 4]").get())); assertTrue(gt(ZERO, read("(-Infinity, 3/2]").get())); assertTrue(gt(ZERO, read("[-6, Infinity)").get())); assertTrue(gt(ONE, ZERO)); assertTrue(gt(ONE, ALL)); assertTrue(gt(ONE, read("[-2, 5/3]").get())); assertTrue(lt(ONE, read("[4, 4]").get())); assertTrue(gt(ONE, read("(-Infinity, 3/2]").get())); assertTrue(gt(ONE, read("[-6, Infinity)").get())); assertTrue(lt(ALL, ZERO)); assertTrue(lt(ALL, ONE)); assertTrue(lt(ALL, read("[-2, 5/3]").get())); assertTrue(lt(ALL, read("[4, 4]").get())); assertTrue(gt(ALL, read("(-Infinity, 3/2]").get())); assertTrue(lt(ALL, read("[-6, Infinity)").get())); assertTrue(lt(read("[-2, 5/3]").get(), ZERO)); assertTrue(lt(read("[-2, 5/3]").get(), ONE)); assertTrue(gt(read("[-2, 5/3]").get(), ALL)); assertTrue(lt(read("[-2, 5/3]").get(), read("[4, 4]").get())); assertTrue(gt(read("[-2, 5/3]").get(), read("(-Infinity, 3/2]").get())); assertTrue(gt(read("[-2, 5/3]").get(), read("[-6, Infinity)").get())); assertTrue(gt(read("[4, 4]").get(), ZERO)); assertTrue(gt(read("[4, 4]").get(), ONE)); assertTrue(gt(read("[4, 4]").get(), ALL)); assertTrue(gt(read("[4, 4]").get(), read("[-2, 5/3]").get())); assertTrue(gt(read("[4, 4]").get(), read("(-Infinity, 3/2]").get())); assertTrue(gt(read("[4, 4]").get(), read("[-6, Infinity)").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), ZERO)); assertTrue(lt(read("(-Infinity, 3/2]").get(), ONE)); assertTrue(lt(read("(-Infinity, 3/2]").get(), ALL)); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[-2, 5/3]").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[4, 4]").get())); assertTrue(lt(read("(-Infinity, 3/2]").get(), read("[-6, Infinity)").get())); assertTrue(lt(read("[-6, Infinity)").get(), ZERO)); assertTrue(lt(read("[-6, Infinity)").get(), ONE)); assertTrue(gt(read("[-6, Infinity)").get(), ALL)); assertTrue(lt(read("[-6, Infinity)").get(), read("[-2, 5/3]").get())); assertTrue(lt(read("[-6, Infinity)").get(), read("[4, 4]").get())); assertTrue(gt(read("[-6, Infinity)").get(), read("(-Infinity, 3/2]").get())); } @Test public void testRead() { aeq(read("[0, 0]").get(), ZERO); aeq(read("[1, 1]").get(), ONE); aeq(read("(-Infinity, Infinity)").get(), ALL); aeq(read("[-2, 5/3]").get(), "[-2, 5/3]"); aeq(read("[4, 4]").get(), "[4, 4]"); aeq(read("(-Infinity, 3/2]").get(), "(-Infinity, 3/2]"); aeq(read("[-6, Infinity)").get(), "[-6, Infinity)"); assertFalse(read("").isPresent()); assertFalse(read("[").isPresent()); assertFalse(read("[]").isPresent()); assertFalse(read("[,]").isPresent()); assertFalse(read("[1, 1").isPresent()); assertFalse(read("[12]").isPresent()); assertFalse(read("[1 1]").isPresent()); assertFalse(read("[1, 1]").isPresent()); assertFalse(read("[ 1, 1]").isPresent()); assertFalse(read("[1, 1 ]").isPresent()); assertFalse(read("[1, 1] ").isPresent()); assertFalse(read("[-Infinity, Infinity]").isPresent()); assertFalse(read("(-Infinity, 4)").isPresent()); assertFalse(read("[4, Infinity]").isPresent()); assertFalse(read("(Infinity, -Infinity)").isPresent()); assertFalse(read("[2, 3-]").isPresent()); assertFalse(read("[2.0, 4]").isPresent()); assertFalse(read("[2,4]").isPresent()); assertFalse(read("[5, 4]").isPresent()); assertFalse(read("[5, 4/0]").isPresent()); } @Test public void testFindIn() { aeq(findIn("abcd[-5, 2/3]xyz").get(), "([-5, 2/3], 4)"); aeq(findIn("vdfvdf(-Infinity, 3]cds").get(), "((-Infinity, 3], 6)"); aeq(findIn("gvrgw49((-Infinity, Infinity)Infinity)").get(), "((-Infinity, Infinity), 8)"); assertFalse(findIn("").isPresent()); assertFalse(findIn("hello").isPresent()); assertFalse(findIn("vdfsvfbf").isPresent()); assertFalse(findIn("vdfvds[-Infinity, 2]vsd").isPresent()); assertFalse(findIn("vdfvds(Infinity, 2]vsd").isPresent()); assertFalse(findIn("abcd[5, 4]xyz").isPresent()); assertFalse(findIn("abcd[5, 4/0]xyz").isPresent()); } @Test public void testToString() { aeq(ZERO, "[0, 0]"); aeq(ONE, "[1, 1]"); aeq(ALL, "(-Infinity, Infinity)"); aeq(read("[-2, 5/3]").get(), "[-2, 5/3]"); aeq(read("[4, 4]").get(), "[4, 4]"); aeq(read("(-Infinity, 3/2]").get(), "(-Infinity, 3/2]"); aeq(read("[-6, Infinity)").get(), "[-6, Infinity)"); } private static void aeq(Object a, Object b) { assertEquals(a.toString(), b.toString()); } private static @NotNull Optional<List<Interval>> readIntervalList(@NotNull String s) { return Readers.readList(Interval::findIn, s); } private static @NotNull Optional<List<Interval>> readIntervalListWithNulls(@NotNull String s) { return Readers.readList(t -> Readers.findInWithNulls(Interval::findIn, t), s); } }
package net.imagej.ops; import net.imglib2.FinalInterval; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImg; import net.imglib2.img.array.ArrayImgs; import net.imglib2.img.basictypeaccess.array.FloatArray; import net.imglib2.type.numeric.integer.ByteType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.util.Intervals; import org.junit.After; import org.junit.Before; import org.scijava.Context; import org.scijava.plugin.Parameter; /** * Base class for {@link Op} unit testing. * <p> * <i>All</i> {@link Op} unit tests need to have an {@link OpService} instance. * Following the DRY principle, we should implement it only once. Here. * </p> * * @author Johannes Schindelin * @author Curtis Rueden */ public abstract class AbstractOpTest { @Parameter protected Context context; @Parameter protected OpService ops; @Parameter protected OpMatchingService matcher; /** Subclasses can override to create a context with different services. */ protected Context createContext() { return new Context(OpService.class, OpMatchingService.class); } /** Sets up a SciJava context with {@link OpService}. */ @Before public void setUp() { createContext().inject(this); } /** * Disposes of the {@link OpService} that was initialized in {@link #setUp()}. */ @After public synchronized void cleanUp() { if (context != null) { context.dispose(); context = null; ops = null; matcher = null; } } private int seed; private int pseudoRandom() { return seed = 3170425 * seed + 132102; } public Img<ByteType> generateByteTestImg(final boolean fill, final long... dims) { final byte[] array = new byte[(int) Intervals.numElements(new FinalInterval(dims))]; if (fill) { seed = 17; for (int i = 0; i < array.length; i++) { array[i] = (byte) pseudoRandom(); } } return ArrayImgs.bytes(array, dims); } public Img<UnsignedByteType> generateUnsignedByteTestImg(final boolean fill, final long... dims) { final byte[] array = new byte[(int) Intervals.numElements(new FinalInterval(dims))]; if (fill) { seed = 17; for (int i = 0; i < array.length; i++) { array[i] = (byte) pseudoRandom(); } } return ArrayImgs.unsignedBytes(array, dims); } public ArrayImg<FloatType, FloatArray> generateFloatArrayTestImg( final boolean fill, final long... dims) { final float[] array = new float[(int) Intervals.numElements(new FinalInterval(dims))]; if (fill) { seed = 17; for (int i = 0; i < array.length; i++) { array[i] = (float) pseudoRandom() / (float) Integer.MAX_VALUE; } } return ArrayImgs.floats(array, dims); } }
package org.g_node.srv; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.vocabulary.RDFS; import org.apache.commons.io.FileUtils; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the {@link RDFService} class. Output and Error streams are redirected * from the console to a different PrintStream and reset after tests are finished * to avoid mixing tool error messages with actual test error messages. * * @author Michael Sonntag (sonntag@bio.lmu.de) */ public class RDFServiceTest { private final String tmpRoot = System.getProperty("java.io.tmpdir"); private final String testFolderName = "tdfservicetest"; private final String testFileName = "test.txt"; private final Path testFileFolder = Paths.get(tmpRoot, testFolderName); private ByteArrayOutputStream outStream = new ByteArrayOutputStream(); private PrintStream stdout; /** * Redirect Out stream and create a test folder and the main * test file in the java temp directory. * @throws Exception */ @Before public void setUp() throws Exception { this.stdout = System.out; this.outStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(this.outStream)); Logger rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.INFO); rootLogger.addAppender( new ConsoleAppender( new PatternLayout("[%-5p] %m%n") ) ); final File currTestFile = this.testFileFolder.resolve(this.testFileName).toFile(); FileUtils.write(currTestFile, "This is a normal test file"); } /** * Reset Out stream to the console and remove all created * folders and files after the tests are done. * @throws Exception */ @After public void tearDown() throws Exception { System.setOut(this.stdout); if (Files.exists(this.testFileFolder)) { FileUtils.deleteDirectory(this.testFileFolder.toFile()); } } /** * Check, that a Jena RDF model is written to file. * @throws Exception */ @Test public void testWriteModelToFile() throws Exception { final Model model = ModelFactory.createDefaultModel(); final Resource modelEntry = model.createResource(); final String outFileName = "testrdf.ttl"; final String outFilePath = this.testFileFolder.resolve(outFileName).toString(); final String outFileFormat = "TTL"; final String testString = String.join( "", "[INFO ] Writing data to RDF file, ", outFilePath, " using format '", outFileFormat, "'" ); RDFService.writeModelToFile("", model, outFileFormat); assertThat(this.outStream.toString()).startsWith("[ERROR] Could not open output file"); RDFService.writeModelToFile(outFilePath, model, outFileFormat); assertThat(this.outStream.toString()).contains(testString); } /** * Test that an empty and a non empty RDF file can be opened. * @throws Exception */ @Test public void testOpenModelFromFile() throws Exception { final File currEmptyTestFile = this.testFileFolder.resolve("testEmpty.ttl").toFile(); FileUtils.write(currEmptyTestFile, ""); Model emptyModel = RDFService.openModelFromFile(currEmptyTestFile.toString()); assertThat(emptyModel.isEmpty()).isTrue(); final String miniTTL = "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\n_:a foaf:name\t\"TestName\""; final File currTestFile = this.testFileFolder.resolve("test.ttl").toFile(); FileUtils.write(currTestFile, miniTTL); Model m = RDFService.openModelFromFile(currTestFile.toString()); assertThat(m.isEmpty()).isFalse(); } }
package pig.testing.runner; import java.util.ArrayList; import java.util.Properties; import org.codehaus.jackson.annotate.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class PigTestDef { private String id; private String file; private Properties args = new Properties(); private ArrayList<TestClass> tests = new ArrayList<TestClass>(); private ArrayList<String[]> hiveCli = new ArrayList<String[]>(); static class TestClass { Properties args; String name; public Properties getArgs() { return args; } public void setArgs(Properties args) { this.args = args; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public ArrayList<String[]> getHiveCli() { return hiveCli; } public void setHiveCli(ArrayList<String[]> hiveCli) { this.hiveCli = hiveCli; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public Properties getArgs() { return args; } public void setArgs(Properties args) { this.args = args; } public ArrayList<TestClass> getTests() { return tests; } public void setTests(ArrayList<TestClass> tests) { this.tests = tests; } }
package gov.nih.nci.evs.reportwriter.test.lexevs; import java.util.*; import gov.nih.nci.evs.reportwriter.test.utils.*; import gov.nih.nci.evs.reportwriter.utils.*; import org.LexGrid.commonTypes.*; import org.LexGrid.concepts.*; import org.apache.log4j.*; public class CDISCTest { private static Logger _logger = Logger.getLogger(CDISCTest.class); public static void main(String[] args) { try { args = SetupEnv.getInstance().parse(args); CDISCTest test = new CDISCTest(); test.test(); } catch (Exception e) { e.printStackTrace(); } } public void test() throws Exception { String codingScheme = "NCI Thesaurus"; String version = "09.12d"; String code = "C17998"; String associatedCode = "C66731"; String value = getCdiscPreferredTerm(codingScheme, version, code, associatedCode); _logger.debug("Value: " + value); } private String getCdiscPreferredTerm(String codingScheme, String version, String code, String associatedCode) throws Exception { Concept concept = DataUtils.getConceptByCode(codingScheme, version, null, code); if (concept == null) throw new Exception("Can not retrieve concept from code " + code + "."); Concept associatedConcept = DataUtils.getConceptByCode(codingScheme, version, null, associatedCode); if (associatedConcept == null) throw new Exception( "Can not retrieve associated concept from code " + associatedConcept + "."); String name = concept.getEntityDescription().getContent(); String associatedName = associatedConcept.getEntityDescription().getContent(); _logger.debug("* concept: " + name + "(" + code + ")"); _logger.debug("* associatedConcept: " + associatedName + "(" + associatedCode + ")"); return getCdiscPreferredTerm(concept, associatedConcept); } private String getCdiscPreferredTerm(Concept concept, Concept associated_concept) throws Exception { String nciABTerm = null; Vector<SynonymInfo> v = getSynonyms(associated_concept); ListUtils.debug(_logger, "getSynonyms(associatedConcept)", v); int n = v.size(); for (int i = 0; i < n; ++i) { SynonymInfo info = v.get(i); if (info.source.equalsIgnoreCase("NCI") && info.type.equalsIgnoreCase("AB")) { nciABTerm = info.name; } } if (nciABTerm == null) return ""; v = getSynonyms(concept); ListUtils.debug(_logger, "getSynonyms(concept)", v); n = v.size(); for (int i = 0; i < n; ++i) { SynonymInfo info = v.get(i); if (info.sourceCode.equals(nciABTerm)) return info.name; } for (int i = 0; i < n; ++i) { SynonymInfo info = v.get(i); if (info.source.equalsIgnoreCase("CDISC") && info.source.equalsIgnoreCase("SY")) return info.name; } for (int i = 0; i < n; ++i) { SynonymInfo info = v.get(i); if (info.source.equalsIgnoreCase("CDISC") && info.source.equalsIgnoreCase("PT")) return info.name; } return ""; } public class SynonymInfo { public String name = ""; public String type = ""; public String source = ""; public String sourceCode = ""; public String toString() { return "name=" + name + ", type=" + type + ", source=" + source + ", sourceCode=" + sourceCode; } } public Vector<SynonymInfo> getSynonyms(Concept concept) { Vector<SynonymInfo> v = new Vector<SynonymInfo>(); if (concept == null) return v; Presentation[] properties = concept.getPresentation(); for (int i = 0; i < properties.length; i++) { Presentation p = properties[i]; SynonymInfo info = new SynonymInfo(); info.name = p.getValue().getContent(); int n = p.getPropertyQualifierCount(); for (int j = 0; j < n; j++) { PropertyQualifier q = p.getPropertyQualifier(j); String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareTo("source-code") == 0) { info.sourceCode = qualifier_value; break; } } info.type = p.getRepresentationalForm(); Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; info.source = src.getContent(); } v.add(info); } SortUtils.quickSort(v); return v; } }
// copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // persons to whom the Software is furnished to do so, subject to the // notice shall be included in all copies or substantial portions of the // Software. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. package phasereditor.scene.ui.editor; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DragDetectEvent; import org.eclipse.swt.events.DragDetectListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Transform; import org.eclipse.swt.widgets.Composite; import org.eclipse.wb.swt.SWTResourceManager; import org.json.JSONObject; import phasereditor.assetpack.core.BitmapFontAssetModel; import phasereditor.assetpack.core.IAssetFrameModel; import phasereditor.assetpack.core.ImageAssetModel; import phasereditor.scene.core.BitmapTextComponent; import phasereditor.scene.core.BitmapTextModel; import phasereditor.scene.core.EditorComponent; import phasereditor.scene.core.ImageModel; import phasereditor.scene.core.NameComputer; import phasereditor.scene.core.ObjectModel; import phasereditor.scene.core.ParentComponent; import phasereditor.scene.core.SceneModel; import phasereditor.scene.core.SpriteModel; import phasereditor.scene.core.TextualComponent; import phasereditor.scene.core.TextureComponent; import phasereditor.scene.core.TransformComponent; import phasereditor.scene.ui.editor.interactive.InteractiveTool; import phasereditor.scene.ui.editor.undo.WorldSnapshotOperation; import phasereditor.ui.ColorUtil; import phasereditor.ui.ZoomCanvas; /** * @author arian * */ public class SceneCanvas extends ZoomCanvas implements MouseListener, MouseMoveListener, DragDetectListener { private static final String SCENE_COPY_STAMP = "--scene--copy--stamp public static final int X_LABELS_HEIGHT = 18; public static final int Y_LABEL_WIDTH = 18; private SceneEditor _editor; private SceneObjectRenderer _renderer; private float _renderModelSnapX; private float _renderModelSnapY; List<Object> _selection; private SceneModel _sceneModel; private DragObjectsEvents _dragObjectsEvents; private SelectionEvents _selectionEvents; private List<InteractiveTool> _interactiveTools; public SceneCanvas(Composite parent, int style) { super(parent, style); _selection = new ArrayList<>(); addPaintListener(this); _dragObjectsEvents = new DragObjectsEvents(this); _selectionEvents = new SelectionEvents(this); addDragDetectListener(this); addMouseListener(this); addMouseMoveListener(this); init_DND(); setZoomWhenShiftPressed(false); _interactiveTools = new ArrayList<>(); } public List<InteractiveTool> getInteractiveTools() { return _interactiveTools; } public void setInteractiveTools(InteractiveTool... tools) { _interactiveTools = Arrays.asList(tools); getEditor().updatePropertyPagesContentWithSelection(); redraw(); } public boolean hasInteractiveTool(Class<?> cls) { for (var tool : _interactiveTools) { if (cls.isInstance(tool)) { return true; } } return false; } private void init_DND() { { int options = DND.DROP_MOVE | DND.DROP_DEFAULT; DropTarget target = new DropTarget(this, options); Transfer[] types = { LocalSelectionTransfer.getTransfer() }; target.setTransfer(types); target.addDropListener(new DropTargetAdapter() { @Override public void drop(DropTargetEvent event) { var loc = toDisplay(0, 0); var x = event.x - loc.x; var y = event.y - loc.y; if (event.data instanceof Object[]) { selectionDropped(x, y, (Object[]) event.data); } if (event.data instanceof IStructuredSelection) { selectionDropped(x, y, ((IStructuredSelection) event.data).toArray()); } } }); } } public float[] viewToModel(int x, int y) { var calc = calc(); var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH; var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT; return new float[] { modelX, modelY }; } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void selectionDropped(int x, int y, Object[] data) { var nameComputer = new NameComputer(_sceneModel.getRootObject()); var beforeSnapshot = WorldSnapshotOperation.takeSnapshot(_editor); var calc = calc(); var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH; var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT; var newModels = new ArrayList<ObjectModel>(); for (var obj : data) { if (obj instanceof ImageAssetModel) { obj = ((ImageAssetModel) obj).getFrame(); } if (obj instanceof IAssetFrameModel) { var frame = (IAssetFrameModel) obj; var sprite = new ImageModel(); var name = nameComputer.newName(frame.getKey()); EditorComponent.set_editorName(sprite, name); TransformComponent.set_x(sprite, modelX); TransformComponent.set_y(sprite, modelY); TextureComponent.set_frame(sprite, (IAssetFrameModel) obj); newModels.add(sprite); } else if (obj instanceof BitmapFontAssetModel) { var asset = (BitmapFontAssetModel) obj; var textModel = new BitmapTextModel(); var name = nameComputer.newName(asset.getKey()); EditorComponent.set_editorName(textModel, name); TransformComponent.set_x(textModel, modelX); TransformComponent.set_y(textModel, modelY); BitmapTextComponent.set_font(textModel, asset); TextualComponent.set_text(textModel, "BitmapText"); textModel.updateSizeFromBitmapFont(); newModels.add(textModel); } } for (var model : newModels) { ParentComponent.addChild(_sceneModel.getRootObject(), model); } var afterSnapshot = WorldSnapshotOperation.takeSnapshot(_editor); _editor.executeOperation(new WorldSnapshotOperation(beforeSnapshot, afterSnapshot, "Drop assets")); setSelection_from_internal((List) newModels); redraw(); _editor.refreshOutline(); _editor.setDirty(true); _editor.getEditorSite().getPage().activate(_editor); } public void init(SceneEditor editor) { _editor = editor; _sceneModel = editor.getSceneModel(); _renderer = new SceneObjectRenderer(this); } public SceneEditor getEditor() { return _editor; } public SceneObjectRenderer getSceneRenderer() { return _renderer; } @Override public void dispose() { super.dispose(); _renderer.dispose(); } @Override protected void customPaintControl(PaintEvent e) { renderBackground(e); var calc = calc(); renderGrid(e, calc); var tx = new Transform(getDisplay()); tx.translate(Y_LABEL_WIDTH, X_LABELS_HEIGHT); _renderer.renderScene(e.gc, tx, _editor.getSceneModel()); renderBorders(e.gc, calc); renderSelection(e.gc); renderInteractiveElements(e.gc); renderLabels(e, calc); } private void renderInteractiveElements(GC gc) { for (var elem : _interactiveTools) { if (!elem.getModels().isEmpty()) { elem.render(gc); } } } private void renderBorders(GC gc, ZoomCalculator calc) { var view = calc.modelToView(_sceneModel.getBorderX(), _sceneModel.getBorderY(), _sceneModel.getBorderWidth(), _sceneModel.getBorderHeight()); view.x += Y_LABEL_WIDTH; view.y += X_LABELS_HEIGHT; gc.setAlpha(150); gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK)); gc.drawRectangle(view.x + 1, view.y + 1, view.width, view.height); gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); gc.drawRectangle(view); gc.setAlpha(255); } private void renderSelection(GC gc) { var selectionColor = SWTResourceManager.getColor(ColorUtil.GREENYELLOW.rgb); for (var obj : _selection) { if (obj instanceof ObjectModel) { var model = (ObjectModel) obj; var bounds = _renderer.getObjectBounds(model); if (obj instanceof ParentComponent) { if (!ParentComponent.get_children(model).isEmpty()) { var childrenBounds = _renderer.getObjectChildrenBounds(model); if (childrenBounds != null) { var merge = SceneObjectRenderer.joinBounds(bounds, childrenBounds); gc.setForeground(selectionColor); gc.drawPolygon(new int[] { (int) merge[0], (int) merge[1], (int) merge[2], (int) merge[3], (int) merge[4], (int) merge[5], (int) merge[6], (int) merge[7] }); } } } if (bounds != null) { gc.setLineWidth(3); gc.setAlpha(150); gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK)); gc.drawPolygon(new int[] { (int) bounds[0], (int) bounds[1], (int) bounds[2], (int) bounds[3], (int) bounds[4], (int) bounds[5], (int) bounds[6], (int) bounds[7] }); gc.setAlpha(255); gc.setLineWidth(1); gc.setForeground(selectionColor); gc.drawPolygon(new int[] { (int) bounds[0], (int) bounds[1], (int) bounds[2], (int) bounds[3], (int) bounds[4], (int) bounds[5], (int) bounds[6], (int) bounds[7] }); var name = EditorComponent.get_editorName(model); var x = bounds[0]; var y = bounds[1]; gc.setAlpha(150); gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK)); gc.drawText(name, (int) x - 1, (int) y - 21, true); gc.setAlpha(255); gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); gc.drawText(name, (int) x, (int) y - 20, true); } } } } private void renderBackground(PaintEvent e) { var gc = e.gc; gc.setBackground(getBackgroundColor()); gc.setForeground(getGridColor()); gc.fillRectangle(0, 0, e.width, e.height); } private Color getGridColor() { return SWTResourceManager.getColor(_sceneModel.getForegroundColor()); } private Color getBackgroundColor() { return SWTResourceManager.getColor(_sceneModel.getBackgroundColor()); } private void renderGrid(PaintEvent e, ZoomCalculator calc) { var gc = e.gc; gc.setForeground(getGridColor()); // paint labels var initialModelSnapX = 5f; var initialModelSnapY = 5f; if (_sceneModel.isSnapEnabled()) { initialModelSnapX = _sceneModel.getSnapWidth(); initialModelSnapY = _sceneModel.getSnapHeight(); } var modelSnapX = 10f; var modelSnapY = 10f; var viewSnapX = 0f; var viewSnapY = 0f; int i = 1; while (viewSnapX < 30) { modelSnapX = initialModelSnapX * i; viewSnapX = calc.modelToViewWidth(modelSnapX); i++; } i = 1; while (viewSnapY < 30) { modelSnapY = initialModelSnapY * i; viewSnapY = calc.modelToViewHeight(modelSnapY); i++; } _renderModelSnapX = modelSnapX; _renderModelSnapY = modelSnapY; var modelNextSnapX = modelSnapX * 4; var modelNextNextSnapX = modelSnapX * 8; var modelNextSnapY = modelSnapY * 4; var modelNextNextSnapY = modelSnapY * 8; var modelStartX = calc.viewToModelX(0); var modelStartY = calc.viewToModelY(0); var modelRight = calc.viewToModelX(e.width); var modelBottom = calc.viewToModelY(e.height); modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX; modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY; i = 0; while (true) { var modelX = modelStartX + i * modelSnapX; if (modelX > modelRight) { break; } if (modelX % modelNextNextSnapX == 0) { gc.setAlpha(255); // gc.setLineWidth(2); } else if (modelX % modelNextSnapX == 0) { gc.setAlpha(150); } else { gc.setAlpha(100); } var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH; gc.drawLine((int) viewX, X_LABELS_HEIGHT, (int) viewX, e.height); // gc.setLineWidth(1); i++; } gc.setAlpha(255); i = 0; while (true) { var modelY = modelStartY + i * modelSnapY; if (modelY > modelBottom) { break; } var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT; if (modelY % modelNextNextSnapY == 0) { // gc.setLineWidth(2); gc.setAlpha(255); } else if (modelY % modelNextSnapY == 0) { gc.setAlpha(150); } else { gc.setAlpha(100); } gc.drawLine(X_LABELS_HEIGHT, (int) viewY, e.width, (int) viewY); // gc.setLineWidth(1); i++; } gc.setAlpha(255); } private void renderLabels(PaintEvent e, ZoomCalculator calc) { var gc = e.gc; gc.setForeground(getGridColor()); gc.setBackground(getBackgroundColor()); gc.setAlpha(220); gc.fillRectangle(0, 0, e.width, X_LABELS_HEIGHT); gc.fillRectangle(0, 0, Y_LABEL_WIDTH, e.height); gc.setAlpha(255); // paint labels var modelSnapX = _renderModelSnapX; var modelSnapY = _renderModelSnapY; var modelStartX = calc.viewToModelX(0); var modelStartY = calc.viewToModelY(0); var modelRight = calc.viewToModelX(e.width); var modelBottom = calc.viewToModelY(e.height); int i; i = 2; while (true) { float viewSnapX = calc.modelToViewWidth(modelSnapX); if (viewSnapX > 80) { break; } modelSnapX = _renderModelSnapX * i; i++; } i = 2; while (true) { float viewSnapY = calc.modelToViewWidth(modelSnapY); if (viewSnapY > 80) { break; } modelSnapY = _renderModelSnapY * i; i++; } modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX; modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY; i = 0; while (true) { var modelX = modelStartX + i * modelSnapX; if (modelX > modelRight) { break; } var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH; if (viewX >= Y_LABEL_WIDTH && viewX <= e.width - Y_LABEL_WIDTH) { String label = Integer.toString((int) modelX); gc.drawString(label, (int) viewX + 5, 0, true); gc.drawLine((int) viewX, 0, (int) viewX, X_LABELS_HEIGHT); } i++; } gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, e.width, X_LABELS_HEIGHT); i = 0; while (true) { var modelY = modelStartY + i * modelSnapY; if (modelY > modelBottom) { break; } var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT; if (viewY >= X_LABELS_HEIGHT && viewY <= e.height - X_LABELS_HEIGHT) { String label = Integer.toString((int) modelY); var labelExtent = gc.stringExtent(label); var tx = new Transform(getDisplay()); tx.translate(0, viewY + 5 + labelExtent.x); tx.rotate(-90); gc.setTransform(tx); gc.drawString(label, 0, 0, true); gc.setTransform(null); tx.dispose(); gc.drawLine(0, (int) viewY, Y_LABEL_WIDTH, (int) viewY); } i++; } gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, Y_LABEL_WIDTH, e.height); gc.setAlpha(255); } @Override protected Point getImageSize() { return new Point(1, 1); } ObjectModel pickObject(int x, int y) { return pickObject(_sceneModel.getRootObject(), x, y); } private ObjectModel pickObject(ObjectModel model, int x, int y) { if (model instanceof ParentComponent) { if (EditorComponent.get_editorClosed(model) /* || groupModel.isPrefabInstance() */) { var polygon = _renderer.getObjectChildrenBounds(model); if (hitsPolygon(x, y, polygon)) { if (hitsImage(x, y, model)) { return model; } } } else { var children = ParentComponent.get_children(model); for (int i = children.size() - 1; i >= 0; i var model2 = children.get(i); var pick = pickObject(model2, x, y); if (pick != null) { return pick; } } } } var polygon = _renderer.getObjectBounds(model); if (hitsPolygon(x, y, polygon)) { if (hitsImage(x, y, model)) { return model; } } return null; } private boolean hitsImage(int x, int y, ObjectModel model) { var renderer = getSceneRenderer(); var img = renderer.getModelImageFromCache(model); var xy = renderer.sceneToLocal(model, x, y); var imgX = (int) xy[0]; var imgY = (int) xy[1]; if (img == null) { if (model instanceof ImageModel || model instanceof SpriteModel) { var frame = TextureComponent.get_frame(model); if (frame == null) { return false; } img = loadImage(frame.getImageFile()); if (img == null) { return false; } var frameData = frame.getFrameData(); imgX = imgX + frameData.src.x - frameData.dst.x; imgY = imgY + frameData.src.y - frameData.dst.y; } } if (img == null) { return false; } if (img.getBounds().contains(imgX, imgY)) { var data = img.getImageData(); var pixel = data.getAlpha(imgX, imgY); return pixel != 0; } return false; } void setSelection_from_internal(List<Object> list) { var sel = new StructuredSelection(list); _selection = list; _editor.getEditorSite().getSelectionProvider().setSelection(sel); if (_editor.getOutline() != null) { _editor.getOutline().setSelection_from_external(sel); } } private static boolean hitsPolygon(int x, int y, float[] polygon) { if (polygon == null) { return false; } int npoints = polygon.length / 2; if (npoints <= 2) { return false; } var xpoints = new int[npoints]; var ypoints = new int[npoints]; for (int i = 0; i < npoints; i++) { xpoints[i] = (int) polygon[i * 2]; ypoints[i] = (int) polygon[i * 2 + 1]; } int hits = 0; int lastx = xpoints[npoints - 1]; int lasty = ypoints[npoints - 1]; int curx, cury; // Walk the edges of the polygon for (int i = 0; i < npoints; lastx = curx, lasty = cury, i++) { curx = xpoints[i]; cury = ypoints[i]; if (cury == lasty) { continue; } int leftx; if (curx < lastx) { if (x >= lastx) { continue; } leftx = curx; } else { if (x >= curx) { continue; } leftx = lastx; } double test1, test2; if (cury < lasty) { if (y < cury || y >= lasty) { continue; } if (x < leftx) { hits++; continue; } test1 = x - curx; test2 = y - cury; } else { if (y < lasty || y >= cury) { continue; } if (x < leftx) { hits++; continue; } test1 = x - lastx; test2 = y - lasty; } if (test1 < (test2 / (lasty - cury) * (lastx - curx))) { hits++; } } return ((hits & 1) != 0); } public void setSelection_from_external(IStructuredSelection selection) { _selection = new ArrayList<>(List.of(selection.toArray())); redraw(); } public void reveal(ObjectModel model) { var objBounds = _renderer.getObjectBounds(model); if (objBounds == null) { return; } var x1 = objBounds[0]; var y1 = objBounds[1]; var x2 = objBounds[4]; var y2 = objBounds[5]; var w = x2 - x1; var h = y2 - y1; var canvasBounds = getBounds(); setOffsetX((int) (getOffsetX() - x1 + Y_LABEL_WIDTH + canvasBounds.width / 2 - w / 2)); setOffsetY((int) (getOffsetY() - y1 + X_LABELS_HEIGHT + canvasBounds.height / 2 - h / 2)); redraw(); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void selectAll() { var list = new ArrayList<ObjectModel>(); var root = getEditor().getSceneModel().getRootObject(); root.visitChildren(model -> list.add(model)); setSelection_from_internal((List) list); redraw(); } public void delete() { var beforeData = WorldSnapshotOperation.takeSnapshot(_editor); for (var obj : _selection) { var model = (ObjectModel) obj; ParentComponent.removeFromParent(model); } redraw(); _editor.setDirty(true); _editor.setSelection(StructuredSelection.EMPTY); var afterData = WorldSnapshotOperation.takeSnapshot(_editor); _editor.executeOperation(new WorldSnapshotOperation(beforeData, afterData, "Delete objects")); } public void copy() { var sel = new StructuredSelection( filterChidlren(_selection.stream().map(o -> (ObjectModel) o).collect(toList())) .stream().map(model -> { var data = new JSONObject(); data.put(SCENE_COPY_STAMP, true); model.write(data); // convert the local position to a global position if (model instanceof TransformComponent) { var parent = ParentComponent.get_parent(model); var globalPoint = new float[] { 0, 0 }; if (parent != null) { globalPoint = _renderer.localToScene(parent, TransformComponent.get_x(model), TransformComponent.get_y(model)); } data.put(TransformComponent.x_name, globalPoint[0]); data.put(TransformComponent.y_name, globalPoint[1]); } return data; }).toArray()); LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer(); transfer.setSelection(sel); Clipboard cb = new Clipboard(getDisplay()); cb.setContents(new Object[] { sel.toArray() }, new Transfer[] { transfer }); cb.dispose(); } public void cut() { copy(); delete(); } public void paste() { var root = getEditor().getSceneModel().getRootObject(); paste(root, true); } public void paste(ObjectModel parent, boolean placeAtCursorPosition) { var beforeData = WorldSnapshotOperation.takeSnapshot(_editor); LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer(); Clipboard cb = new Clipboard(getDisplay()); Object content = cb.getContents(transfer); cb.dispose(); if (content == null) { return; } var editor = getEditor(); var project = editor.getEditorInput().getFile().getProject(); var copyElements = ((IStructuredSelection) content).toArray(); List<ObjectModel> pasteModels = new ArrayList<>(); // create the copies for (var obj : copyElements) { if (obj instanceof JSONObject) { var data = (JSONObject) obj; if (data.has(SCENE_COPY_STAMP)) { String type = data.getString("-type"); var newModel = SceneModel.createModel(type); newModel.read(data, project); pasteModels.add(newModel); } } } // remove the children pasteModels = filterChidlren(pasteModels); var cursorPoint = toControl(getDisplay().getCursorLocation()); var localCursorPoint = _renderer.sceneToLocal(parent, cursorPoint.x, cursorPoint.y); // set new id and editorName var nameComputer = new NameComputer(_sceneModel.getRootObject()); float[] offsetPoint; { var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE; for (var model : pasteModels) { if (model instanceof TransformComponent) { var x = TransformComponent.get_x(model); var y = TransformComponent.get_y(model); minX = Math.min(minX, x); minY = Math.min(minY, y); } } offsetPoint = new float[] { minX - localCursorPoint[0], minY - localCursorPoint[1] }; } for (var model : pasteModels) { model.visit(model2 -> { model2.setId(UUID.randomUUID().toString()); var name = EditorComponent.get_editorName(model2); name = nameComputer.newName(name); EditorComponent.set_editorName(model2, name); }); if (model instanceof TransformComponent) { // TODO: honor the snapping settings var x = TransformComponent.get_x(model); var y = TransformComponent.get_y(model); if (placeAtCursorPosition) { // if (offsetPoint == null) { // offsetPoint = new float[] { x - localCursorPoint[0], y - localCursorPoint[1] TransformComponent.set_x(model, x - offsetPoint[0]); TransformComponent.set_y(model, y - offsetPoint[1]); } else { var point = _renderer.sceneToLocal(parent, x, y); TransformComponent.set_x(model, point[0]); TransformComponent.set_y(model, point[1]); } } } // add to the root object for (var model : pasteModels) { ParentComponent.addChild(parent, model); } editor.setSelection(new StructuredSelection(pasteModels)); editor.setDirty(true); var afterData = WorldSnapshotOperation.takeSnapshot(_editor); _editor.executeOperation(new WorldSnapshotOperation(beforeData, afterData, "Paste objects.")); } public static List<ObjectModel> filterChidlren(List<ObjectModel> models) { var result = new ArrayList<>(models); for (var i = 0; i < models.size(); i++) { for (var j = 0; j < models.size(); j++) { if (i != j) { var a = models.get(i); var b = models.get(j); if (ParentComponent.isDescendentOf(a, b)) { result.remove(a); } } } } return result; } @Override public void mouseDoubleClick(MouseEvent e) { } @Override public void mouseDown(MouseEvent e) { if (e.button != 1) { return; } for (var elem : _interactiveTools) { elem.mouseDown(e); } } @Override public void mouseUp(MouseEvent e) { if (e.button != 1) { return; } boolean contains = false; for (var elem : _interactiveTools) { if (elem.contains(e.x, e.y)) { contains = true; break; } } if (contains) { for (var elem : _interactiveTools) { elem.mouseUp(e); } } if (_dragDetected) { _dragDetected = false; if (_dragObjectsEvents.isDragging()) { _dragObjectsEvents.done(); } return; } if (!contains) { _selectionEvents.updateSelection(e); } } @Override public void mouseMove(MouseEvent e) { boolean contains = false; for (var elem : _interactiveTools) { if (elem.contains(e.x, e.y)) { contains = true; } } if (contains) { for (var elem : _interactiveTools) { elem.mouseMove(e); } } else { if (_dragObjectsEvents.isDragging()) { _dragObjectsEvents.update(e); } } if (!_interactiveTools.isEmpty()) { redraw(); } } private boolean _dragDetected; @Override public void dragDetected(DragDetectEvent e) { _dragDetected = true; var obj = pickObject(e.x, e.y); if (_selection.contains(obj)) { _dragObjectsEvents.start(e); } } public boolean isInteractiveDragging() { for (var elem : _interactiveTools) { if (elem.isDragging()) { return true; } } return false; } public List<Object> getSelection() { return _selection; } }
// copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // persons to whom the Software is furnished to do so, subject to the // notice shall be included in all copies or substantial portions of the // Software. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. package phasereditor.scene.ui.editor; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DragDetectEvent; import org.eclipse.swt.events.DragDetectListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Transform; import org.eclipse.swt.widgets.Composite; import org.eclipse.wb.swt.SWTResourceManager; import org.json.JSONObject; import phasereditor.assetpack.core.BitmapFontAssetModel; import phasereditor.assetpack.core.IAssetFrameModel; import phasereditor.assetpack.core.ImageAssetModel; import phasereditor.scene.core.BitmapTextComponent; import phasereditor.scene.core.BitmapTextModel; import phasereditor.scene.core.EditorComponent; import phasereditor.scene.core.ImageModel; import phasereditor.scene.core.NameComputer; import phasereditor.scene.core.ObjectModel; import phasereditor.scene.core.ParentComponent; import phasereditor.scene.core.SceneModel; import phasereditor.scene.core.TextualComponent; import phasereditor.scene.core.TextureComponent; import phasereditor.scene.core.TransformComponent; import phasereditor.scene.ui.editor.undo.WorldSnapshotOperation; import phasereditor.ui.ZoomCanvas; /** * @author arian * */ public class SceneCanvas extends ZoomCanvas implements MouseListener, MouseMoveListener, DragDetectListener { private static final String SCENE_COPY_STAMP = "--scene--copy--stamp public static final int X_LABELS_HEIGHT = 18; public static final int Y_LABEL_WIDTH = 18; private SceneEditor _editor; private SceneObjectRenderer _renderer; private float _renderModelSnapX; private float _renderModelSnapY; List<Object> _selection; private SceneModel _sceneModel; private DragObjectsEvents _dragObjectsEvents; private SelectionEvents _selectionEvents; public SceneCanvas(Composite parent, int style) { super(parent, style); _selection = new ArrayList<>(); addPaintListener(this); _dragObjectsEvents = new DragObjectsEvents(this); _selectionEvents = new SelectionEvents(this); addDragDetectListener(this); addMouseListener(this); addMouseMoveListener(this); init_DND(); } private void init_DND() { { int options = DND.DROP_MOVE | DND.DROP_DEFAULT; DropTarget target = new DropTarget(this, options); Transfer[] types = { LocalSelectionTransfer.getTransfer() }; target.setTransfer(types); target.addDropListener(new DropTargetAdapter() { @Override public void drop(DropTargetEvent event) { var loc = toDisplay(0, 0); var x = event.x - loc.x; var y = event.y - loc.y; if (event.data instanceof Object[]) { selectionDropped(x, y, (Object[]) event.data); } if (event.data instanceof IStructuredSelection) { selectionDropped(x, y, ((IStructuredSelection) event.data).toArray()); } } }); } } public float[] viewToModel(int x, int y) { var calc = calc(); var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH; var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT; return new float[] { modelX, modelY }; } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void selectionDropped(int x, int y, Object[] data) { var nameComputer = new NameComputer(_sceneModel.getRootObject()); var beforeSnapshot = WorldSnapshotOperation.takeSnapshot(_editor); var calc = calc(); var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH; var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT; var newModels = new ArrayList<ObjectModel>(); for (var obj : data) { if (obj instanceof ImageAssetModel) { obj = ((ImageAssetModel) obj).getFrame(); } if (obj instanceof IAssetFrameModel) { var frame = (IAssetFrameModel) obj; var sprite = new ImageModel(); var name = nameComputer.newName(frame.getKey()); EditorComponent.set_editorName(sprite, name); TransformComponent.set_x(sprite, modelX); TransformComponent.set_y(sprite, modelY); TextureComponent.set_frame(sprite, (IAssetFrameModel) obj); newModels.add(sprite); } else if (obj instanceof BitmapFontAssetModel) { var asset = (BitmapFontAssetModel) obj; var textModel = new BitmapTextModel(); var name = nameComputer.newName(asset.getKey()); EditorComponent.set_editorName(textModel, name); TransformComponent.set_x(textModel, modelX); TransformComponent.set_y(textModel, modelY); BitmapTextComponent.set_font(textModel, asset); TextualComponent.set_text(textModel, "BitmapText"); textModel.updateSizeFromBitmapFont(); newModels.add(textModel); } } for (var model : newModels) { ParentComponent.addChild(_sceneModel.getRootObject(), model); } var afterSnapshot = WorldSnapshotOperation.takeSnapshot(_editor); _editor.executeOperation(new WorldSnapshotOperation(beforeSnapshot, afterSnapshot, "Drop assets")); setSelection_from_internal((List) newModels); redraw(); _editor.refreshOutline(); _editor.setDirty(true); _editor.getEditorSite().getPage().activate(_editor); } public void init(SceneEditor editor) { _editor = editor; _sceneModel = editor.getSceneModel(); _renderer = new SceneObjectRenderer(this); } public SceneEditor getEditor() { return _editor; } public SceneObjectRenderer getSceneRenderer() { return _renderer; } @Override public void dispose() { super.dispose(); _renderer.dispose(); } @Override protected void customPaintControl(PaintEvent e) { renderBackground(e); var calc = calc(); renderGrid(e, calc); var tx = new Transform(getDisplay()); tx.translate(Y_LABEL_WIDTH, X_LABELS_HEIGHT); _renderer.renderScene(e.gc, tx, _editor.getSceneModel()); renderBorders(e.gc, calc); renderSelection(e.gc); renderLabels(e, calc); } private void renderBorders(GC gc, ZoomCalculator calc) { var view = calc.modelToView(_sceneModel.getBorderX(), _sceneModel.getBorderY(), _sceneModel.getBorderWidth(), _sceneModel.getBorderHeight()); view.x += Y_LABEL_WIDTH; view.y += X_LABELS_HEIGHT; gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK)); gc.drawRectangle(view.x + 1, view.y + 1, view.width, view.height); gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); gc.drawRectangle(view); } private void renderSelection(GC gc) { for (var obj : _selection) { if (obj instanceof ObjectModel) { var model = (ObjectModel) obj; var bounds = _renderer.getObjectBounds(model); if (obj instanceof ParentComponent) { if (!ParentComponent.get_children(model).isEmpty()) { var childrenBounds = _renderer.getObjectChildrenBounds(model); if (childrenBounds != null) { var merge = SceneObjectRenderer.joinBounds(bounds, childrenBounds); gc.setAlpha(150); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_GREEN)); gc.drawPolygon(new int[] { (int) merge[0], (int) merge[1], (int) merge[2], (int) merge[3], (int) merge[4], (int) merge[5], (int) merge[6], (int) merge[7] }); gc.setAlpha(255); } } } if (bounds != null) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLUE)); gc.drawPolygon(new int[] { (int) bounds[0], (int) bounds[1], (int) bounds[2], (int) bounds[3], (int) bounds[4], (int) bounds[5], (int) bounds[6], (int) bounds[7] }); } } } } private void renderBackground(PaintEvent e) { var gc = e.gc; gc.setBackground(getBackgroundColor()); gc.setForeground(getGridColor()); gc.fillRectangle(0, 0, e.width, e.height); } private Color getGridColor() { return SWTResourceManager.getColor(_sceneModel.getForegroundColor()); } private Color getBackgroundColor() { return SWTResourceManager.getColor(_sceneModel.getBackgroundColor()); } private void renderGrid(PaintEvent e, ZoomCalculator calc) { var gc = e.gc; gc.setForeground(getGridColor()); // paint labels var initialModelSnapX = 5f; var initialModelSnapY = 5f; if (_sceneModel.isSnapEnabled()) { initialModelSnapX = _sceneModel.getSnapWidth(); initialModelSnapY = _sceneModel.getSnapHeight(); } var modelSnapX = 10f; var modelSnapY = 10f; var viewSnapX = 0f; var viewSnapY = 0f; int i = 1; while (viewSnapX < 30) { modelSnapX = (float) Math.pow(initialModelSnapX, i); viewSnapX = calc.modelToViewWidth(modelSnapX); i++; } i = 1; while (viewSnapY < 30) { modelSnapY = (float) Math.pow(initialModelSnapY, i); viewSnapY = calc.modelToViewHeight(modelSnapY); i++; } _renderModelSnapX = modelSnapX; _renderModelSnapY = modelSnapY; var modelNextSnapX = modelSnapX * 4; var modelNextNextSnapX = modelSnapX * 8; var modelNextSnapY = modelSnapY * 4; var modelNextNextSnapY = modelSnapY * 8; var modelStartX = calc.viewToModelX(0); var modelStartY = calc.viewToModelY(0); var modelRight = calc.viewToModelX(e.width); var modelBottom = calc.viewToModelY(e.height); modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX; modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY; i = 0; while (true) { var modelX = modelStartX + i * modelSnapX; if (modelX > modelRight) { break; } if (modelX % modelNextNextSnapX == 0) { gc.setAlpha(255); // gc.setLineWidth(2); } else if (modelX % modelNextSnapX == 0) { gc.setAlpha(150); } else { gc.setAlpha(100); } var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH; gc.drawLine((int) viewX, X_LABELS_HEIGHT, (int) viewX, e.height); // gc.setLineWidth(1); i++; } gc.setAlpha(255); i = 0; while (true) { var modelY = modelStartY + i * modelSnapY; if (modelY > modelBottom) { break; } var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT; if (modelY % modelNextNextSnapY == 0) { // gc.setLineWidth(2); gc.setAlpha(255); } else if (modelY % modelNextSnapY == 0) { gc.setAlpha(150); } else { gc.setAlpha(100); } gc.drawLine(X_LABELS_HEIGHT, (int) viewY, e.width, (int) viewY); // gc.setLineWidth(1); i++; } gc.setAlpha(255); } private void renderLabels(PaintEvent e, ZoomCalculator calc) { var gc = e.gc; gc.setForeground(getGridColor()); gc.setBackground(getBackgroundColor()); gc.setAlpha(220); gc.fillRectangle(0, 0, e.width, X_LABELS_HEIGHT); gc.fillRectangle(0, 0, Y_LABEL_WIDTH, e.height); gc.setAlpha(255); // paint labels var modelSnapX = _renderModelSnapX; var modelSnapY = 10f; var modelStartX = calc.viewToModelX(0); var modelStartY = calc.viewToModelY(0); var modelRight = calc.viewToModelX(e.width); var modelBottom = calc.viewToModelY(e.height); int i; i = 2; while (true) { float viewSnapX = calc.modelToViewWidth(modelSnapX); if (viewSnapX > 80) { break; } modelSnapX = _renderModelSnapX * i; i++; } i = 2; while (true) { float viewSnapY = calc.modelToViewWidth(modelSnapY); if (viewSnapY > 80) { break; } modelSnapY = _renderModelSnapY * i; i++; } modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX; modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY; i = 0; while (true) { var modelX = modelStartX + i * modelSnapX; if (modelX > modelRight) { break; } var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH; if (viewX >= Y_LABEL_WIDTH && viewX <= e.width - Y_LABEL_WIDTH) { String label = Integer.toString((int) modelX); gc.drawString(label, (int) viewX + 5, 0, true); gc.drawLine((int) viewX, 0, (int) viewX, X_LABELS_HEIGHT); } i++; } gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, e.width, X_LABELS_HEIGHT); i = 0; while (true) { var modelY = modelStartY + i * modelSnapY; if (modelY > modelBottom) { break; } var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT; if (viewY >= X_LABELS_HEIGHT && viewY <= e.height - X_LABELS_HEIGHT) { String label = Integer.toString((int) modelY); var labelExtent = gc.stringExtent(label); var tx = new Transform(getDisplay()); tx.translate(0, viewY + 5 + labelExtent.x); tx.rotate(-90); gc.setTransform(tx); gc.drawString(label, 0, 0, true); gc.setTransform(null); tx.dispose(); gc.drawLine(0, (int) viewY, Y_LABEL_WIDTH, (int) viewY); } i++; } gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, Y_LABEL_WIDTH, e.height); gc.setAlpha(255); } @Override protected Point getImageSize() { return new Point(1, 1); } ObjectModel pickObject(int x, int y) { return pickObject(_sceneModel.getRootObject(), x, y); } private ObjectModel pickObject(ObjectModel model, int x, int y) { if (model instanceof ParentComponent) { if (EditorComponent.get_editorClosed(model) /* || groupModel.isPrefabInstance() */) { var polygon = _renderer.getObjectChildrenBounds(model); if (hitsPolygon(x, y, polygon)) { return model; } } else { var children = ParentComponent.get_children(model); for (int i = children.size() - 1; i >= 0; i var model2 = children.get(i); var pick = pickObject(model2, x, y); if (pick != null) { return pick; } } } } var polygon = _renderer.getObjectBounds(model); if (hitsPolygon(x, y, polygon)) { return model; } return null; } void setSelection_from_internal(List<Object> list) { var sel = new StructuredSelection(list); _selection = list; _editor.getEditorSite().getSelectionProvider().setSelection(sel); if (_editor.getOutline() != null) { _editor.getOutline().setSelection_from_external(sel); } } private static boolean hitsPolygon(int x, int y, float[] polygon) { if (polygon == null) { return false; } int npoints = polygon.length / 2; if (npoints <= 2) { return false; } var xpoints = new int[npoints]; var ypoints = new int[npoints]; for (int i = 0; i < npoints; i++) { xpoints[i] = (int) polygon[i * 2]; ypoints[i] = (int) polygon[i * 2 + 1]; } int hits = 0; int lastx = xpoints[npoints - 1]; int lasty = ypoints[npoints - 1]; int curx, cury; // Walk the edges of the polygon for (int i = 0; i < npoints; lastx = curx, lasty = cury, i++) { curx = xpoints[i]; cury = ypoints[i]; if (cury == lasty) { continue; } int leftx; if (curx < lastx) { if (x >= lastx) { continue; } leftx = curx; } else { if (x >= curx) { continue; } leftx = lastx; } double test1, test2; if (cury < lasty) { if (y < cury || y >= lasty) { continue; } if (x < leftx) { hits++; continue; } test1 = x - curx; test2 = y - cury; } else { if (y < lasty || y >= cury) { continue; } if (x < leftx) { hits++; continue; } test1 = x - lastx; test2 = y - lasty; } if (test1 < (test2 / (lasty - cury) * (lastx - curx))) { hits++; } } return ((hits & 1) != 0); } public void setSelection_from_external(IStructuredSelection selection) { _selection = new ArrayList<>(List.of(selection.toArray())); redraw(); } public void reveal(ObjectModel model) { var objBounds = _renderer.getObjectBounds(model); if (objBounds == null) { return; } var x1 = objBounds[0]; var y1 = objBounds[1]; var x2 = objBounds[4]; var y2 = objBounds[5]; var w = x2 - x1; var h = y2 - y1; var canvasBounds = getBounds(); setOffsetX((int) (getOffsetX() - x1 + Y_LABEL_WIDTH + canvasBounds.width / 2 - w / 2)); setOffsetY((int) (getOffsetY() - y1 + X_LABELS_HEIGHT + canvasBounds.height / 2 - h / 2)); redraw(); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void selectAll() { var list = new ArrayList<ObjectModel>(); var root = getEditor().getSceneModel().getRootObject(); root.visitChildren(model -> list.add(model)); setSelection_from_internal((List) list); redraw(); } public void delete() { var beforeData = WorldSnapshotOperation.takeSnapshot(_editor); for (var obj : _selection) { var model = (ObjectModel) obj; ParentComponent.removeFromParent(model); } redraw(); _editor.setDirty(true); _editor.setSelection(StructuredSelection.EMPTY); var afterData = WorldSnapshotOperation.takeSnapshot(_editor); _editor.executeOperation(new WorldSnapshotOperation(beforeData, afterData, "Delete objects")); } public void copy() { var sel = new StructuredSelection( filterChidlren(_selection.stream().map(o -> (ObjectModel) o).collect(toList())) .stream().map(model -> { var data = new JSONObject(); data.put(SCENE_COPY_STAMP, true); model.write(data); // convert the local position to a global position if (model instanceof TransformComponent) { var parent = ParentComponent.get_parent(model); var globalPoint = new float[] { 0, 0 }; if (parent != null) { globalPoint = _renderer.localToScene(parent, TransformComponent.get_x(model), TransformComponent.get_y(model)); } data.put(TransformComponent.x_name, globalPoint[0]); data.put(TransformComponent.y_name, globalPoint[1]); } return data; }).toArray()); LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer(); transfer.setSelection(sel); Clipboard cb = new Clipboard(getDisplay()); cb.setContents(new Object[] { sel.toArray() }, new Transfer[] { transfer }); cb.dispose(); } public void cut() { copy(); delete(); } public void paste() { var root = getEditor().getSceneModel().getRootObject(); paste(root, true); } public void paste(ObjectModel parent, boolean placeAtCursorPosition) { var beforeData = WorldSnapshotOperation.takeSnapshot(_editor); LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer(); Clipboard cb = new Clipboard(getDisplay()); Object content = cb.getContents(transfer); cb.dispose(); if (content == null) { return; } var editor = getEditor(); var project = editor.getEditorInput().getFile().getProject(); var copyElements = ((IStructuredSelection) content).toArray(); List<ObjectModel> pasteModels = new ArrayList<>(); // create the copies for (var obj : copyElements) { if (obj instanceof JSONObject) { var data = (JSONObject) obj; if (data.has(SCENE_COPY_STAMP)) { String type = data.getString("-type"); var newModel = SceneModel.createModel(type); newModel.read(data, project); pasteModels.add(newModel); } } } // remove the children pasteModels = filterChidlren(pasteModels); var cursorPoint = toControl(getDisplay().getCursorLocation()); var localCursorPoint = _renderer.sceneToLocal(parent, cursorPoint.x, cursorPoint.y); // set new id and editorName var nameComputer = new NameComputer(_sceneModel.getRootObject()); float[] offsetPoint; { var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE; for (var model : pasteModels) { if (model instanceof TransformComponent) { var x = TransformComponent.get_x(model); var y = TransformComponent.get_y(model); minX = Math.min(minX, x); minY = Math.min(minY, y); } } offsetPoint = new float[] { minX - localCursorPoint[0], minY - localCursorPoint[1] }; } for (var model : pasteModels) { model.visit(model2 -> { model2.setId(UUID.randomUUID().toString()); var name = EditorComponent.get_editorName(model2); name = nameComputer.newName(name); EditorComponent.set_editorName(model2, name); }); if (model instanceof TransformComponent) { // TODO: honor the snapping settings var x = TransformComponent.get_x(model); var y = TransformComponent.get_y(model); if (placeAtCursorPosition) { // if (offsetPoint == null) { // offsetPoint = new float[] { x - localCursorPoint[0], y - localCursorPoint[1] TransformComponent.set_x(model, x - offsetPoint[0]); TransformComponent.set_y(model, y - offsetPoint[1]); } else { var point = _renderer.sceneToLocal(parent, x, y); TransformComponent.set_x(model, point[0]); TransformComponent.set_y(model, point[1]); } } } // add to the root object for (var model : pasteModels) { ParentComponent.addChild(parent, model); } editor.setSelection(new StructuredSelection(pasteModels)); editor.setDirty(true); var afterData = WorldSnapshotOperation.takeSnapshot(_editor); _editor.executeOperation(new WorldSnapshotOperation(beforeData, afterData, "Paste objects.")); } public static List<ObjectModel> filterChidlren(List<ObjectModel> models) { var result = new ArrayList<>(models); for (var i = 0; i < models.size(); i++) { for (var j = 0; j < models.size(); j++) { if (i != j) { var a = models.get(i); var b = models.get(j); if (ParentComponent.isDescendentOf(a, b)) { result.remove(a); } } } } return result; } @Override public void mouseDoubleClick(MouseEvent e) { } @Override public void mouseDown(MouseEvent e) { } @Override public void mouseUp(MouseEvent e) { if (_dragDetected) { _dragDetected = false; if (_dragObjectsEvents.isDragging()) { _dragObjectsEvents.done(); } return; } _selectionEvents.updateSelection(e); } @Override public void mouseMove(MouseEvent e) { if (_dragObjectsEvents.isDragging()) { _dragObjectsEvents.update(e); } } private boolean _dragDetected; @Override public void dragDetected(DragDetectEvent e) { _dragDetected = true; var obj = pickObject(e.x, e.y); if (_selection.contains(obj)) { _dragObjectsEvents.start(e); } } }
package com.spotxchange.sdk.mopubintegration; import com.mopub.mobileads.CustomEventRewardedVideo; import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.mopub.common.DataKeys; import com.mopub.common.LifecycleListener; import com.mopub.common.BaseLifecycleListener; import com.mopub.common.MediationSettings; import com.mopub.common.MoPubReward; import com.mopub.mobileads.MoPubErrorCode; import com.mopub.mobileads.MoPubRewardedVideoManager; import java.util.*; import com.spotxchange.sdk.android.SpotxAdListener; import com.spotxchange.sdk.android.SpotxAdSettings; import com.spotxchange.sdk.android.SpotxAdView; public class SpotxRewardedVideo extends CustomEventRewardedVideo { /* * Constants inded for internal MoPub use. Do not modify. */ public static final String SPOTX_AD_NETWORK_CONSTANT = "spotx"; private static SpotxAdView _spotxAdView; private static SpotxRewardedVideoListener _spotxListener; private static boolean _initialized; private static boolean _isAdAvailable; private String _adUnitId; private static LifecycleListener _lifecycleListener = new BaseLifecycleListener(){ @Override public void onBackPressed(@NonNull final Activity activity){ _spotxAdView.setVisibility(View.INVISIBLE); _isAdAvailable = false; } @Override public void onDestroy(@NonNull final Activity activity){ _spotxAdView.setVisibility(View.INVISIBLE); _spotxAdView.unsetAdListener(); _spotxAdView = null; } }; public SpotxRewardedVideo(){ _initialized = _spotxAdView != null; _spotxListener = _spotxListener == null ? new SpotxRewardedVideoListener() : _spotxListener; _isAdAvailable = false; _adUnitId = null; } @Nullable @Override protected CustomEventRewardedVideoListener getVideoListenerForSdk() { return _spotxListener; } /** * Provides a {@link LifecycleListener} if the custom event's ad network wishes to be notified of * activity lifecycle events in the application. * * @return a LifecycleListener. May be null. */ @Nullable // @VisibleForTesting protected LifecycleListener getLifecycleListener(){ return _lifecycleListener; } /** * Called by the {@link MoPubRewardedVideoManager} after loading the custom event. * This should return the "ad unit id", "zone id" or similar identifier for the network. * May be empty if the network does not have anything more specific than an application ID. * * @return the id string for this ad unit with the ad network. */ @NonNull protected String getAdNetworkId(){ return SPOTX_AD_NETWORK_CONSTANT; }; /** * Called to when the custom event is no longer used. Implementers should cancel any * pending requests. The initialized SDK may be reused by another CustomEvent instance * and should not be shut down or cleaned up. */ protected void onInvalidate(){ _isAdAvailable = false; _spotxAdView.unsetAdListener(); _spotxAdView = null; } /** * Sets up the 3rd party ads SDK if it needs configuration. Extenders should use this * to do any static initialization the first time this method is run by any class instance. * From then on, the SDK should be reused without initialization. * * @return true if the SDK performed initialization, false if the SDK was already initialized. */ @NonNull protected boolean checkAndInitializeSdk(Activity launcherActivity, @NonNull Map<String, Object> localExtras, @NonNull Map<String, String> serverExtras) throws Exception{ synchronized (SpotxRewardedVideo.class){ if(!_initialized){ SpotxAdSettings adSettings = Common.constructAdSettings(localExtras, serverExtras, false); _spotxAdView = new SpotxAdView(launcherActivity, adSettings); _spotxAdView.setAdListener(_spotxListener); launcherActivity.addContentView(_spotxAdView, new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); _initialized = true; return true; } return false; } } /** * Runs the ad-loading logic for the 3rd party SDK. localExtras & serverExtras should together * contain all the data needed to load an ad. * * Implementers should also use this method (or checkAndInitializeSdk) * to register a listener for their SDK, wrap it in a * {@link com.mopub.mobileads.CustomEventRewardedVideo.CustomEventRewardedVideoListener} * * This method should not call any {@link MoPubRewardedVideoManager} event methods directly * (onAdLoadSuccess, etc). Instead the SDK delegate/listener should call these methods. * * @param activity the "main activity" of the app. Useful for initializing sdks. * @param localExtras * @param serverExtras */ @NonNull protected void loadWithSdkInitialized(Activity activity, Map<String, Object> localExtras, Map<String, String> serverExtras) throws Exception{ this._adUnitId = (String)localExtras.get(DataKeys.AD_UNIT_ID_KEY); SpotxMediationSettings ms = MoPubRewardedVideoManager.getInstanceMediationSettings(SpotxMediationSettings.class, this._adUnitId); String channel_id = (ms != null && ms.channel_id != null) ? ms.channel_id : ""; if(!channel_id.isEmpty()){ localExtras.put(Common.CHANNEL_ID_KEY, channel_id); } SpotxAdSettings adSettings = Common.constructAdSettings(localExtras, serverExtras, false); _spotxAdView.setAdSettings(adSettings); _spotxAdView.setVisibility(View.INVISIBLE); _spotxAdView.init(); } /** * Implementers should query the 3rd party SDK for whether there is a video available for the * 3rd party SDK & ID represented by the custom event. * * @return true iff a video is available to play. */ @Override protected boolean hasVideoAvailable(){ return _isAdAvailable; } /** * Implementers should now play the rewarded video for this custom event. */ protected void showVideo(){ _spotxAdView.setVisibility(View.VISIBLE); } private class SpotxRewardedVideoListener implements CustomEventRewardedVideoListener, SpotxAdListener { @Override public void adLoaded() { MoPubRewardedVideoManager.onRewardedVideoLoadSuccess(SpotxRewardedVideo.class, SPOTX_AD_NETWORK_CONSTANT); _isAdAvailable = true; } @Override public void adStarted() { MoPubRewardedVideoManager.onRewardedVideoStarted(SpotxRewardedVideo.class, SPOTX_AD_NETWORK_CONSTANT); } @Override public void adCompleted() { _spotxAdView.setVisibility(View.INVISIBLE); MoPubRewardedVideoManager.onRewardedVideoCompleted(SpotxRewardedVideo.class, SPOTX_AD_NETWORK_CONSTANT, MoPubReward.success(MoPubReward.NO_REWARD_LABEL, MoPubReward.NO_REWARD_AMOUNT)); _isAdAvailable = false; } @Override public void adError() { MoPubRewardedVideoManager.onRewardedVideoLoadFailure( SpotxRewardedVideo.class, SPOTX_AD_NETWORK_CONSTANT, MoPubErrorCode.UNSPECIFIED); _isAdAvailable = false; } @Override public void adExpired() { MoPubRewardedVideoManager.onRewardedVideoLoadFailure(SpotxRewardedVideo.class, SPOTX_AD_NETWORK_CONSTANT, MoPubErrorCode.UNSPECIFIED); _isAdAvailable = false; } @Override public void adClicked() { MoPubRewardedVideoManager.onRewardedVideoClicked(SpotxRewardedVideo.class, SPOTX_AD_NETWORK_CONSTANT); } } public static class SpotxMediationSettings implements MediationSettings { @Nullable private final String channel_id; public static class Builder { @Nullable private String channel_id; public Builder withChannelId(@NonNull final String channel_id) { this.channel_id = channel_id; return this; } public SpotxMediationSettings build() { return new SpotxMediationSettings(this); } } private SpotxMediationSettings(@NonNull final Builder builder) { this.channel_id = builder.channel_id; } } }
package com.vitco.layout.frames; import com.vitco.layout.frames.custom.CDockableFrame; import com.vitco.manager.action.ActionManager; import com.vitco.manager.lang.LangSelectorInterface; import com.vitco.manager.pref.PreferencesInterface; import org.springframework.beans.factory.annotation.Autowired; import javax.swing.*; import java.awt.*; /** * Prototype of class that links frame to content. */ public abstract class FrameLinkagePrototype { // var & setter protected PreferencesInterface preferences; @Autowired(required=true) public final void setPreferences(PreferencesInterface preferences) { this.preferences = preferences; } // var & setter protected LangSelectorInterface langSelector; @Autowired(required=true) public final void setLangSelector(LangSelectorInterface langSelector) { this.langSelector = langSelector; } // var & setter protected ActionManager actionManager; @Autowired(required=true) public final void setActionManager(ActionManager actionManager) { this.actionManager = actionManager; } // show frame public final void setVisible(boolean b) { if (frame.getDockingManager() != null) { if (b) { frame.getDockingManager().showFrame(frame.getName()); } else { frame.getDockingManager().hideFrame(frame.getName()); } } } // hide / show frame public void toggleVisible() { if (frame.getDockingManager() != null) { setVisible(!frame.getDockingManager().getFrame(frame.getName()).isVisible()); } } // returns true iff frame is visible public boolean isAutohideShowing() { return frame.getDockingManager() != null && frame.getDockingManager().getFrame(frame.getName()).isAutohideShowing(); } // returns true iff frame is visible public boolean isAutohide() { return frame.getDockingManager() != null && frame.getDockingManager().getFrame(frame.getName()).isAutohide(); } // returns true iff frame is visible public boolean isVisible() { return frame.getDockingManager() != null && frame.getDockingManager().getFrame(frame.getName()).isVisible(); } protected void setTitle(final String append) { // invoke when ready // "This method should be used when an application thread needs to update the GUI" SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String title = langSelector.getString(frame.getName() + "_caption"); if (append != null) { title += " - " + append; } frame.setTitle(title); frame.setTabTitle(title); frame.setSideTitle(title); } }); } // updates the title when the frame is ready protected void updateTitle() { setTitle(null); } // holds the reference of the actual frame container protected CDockableFrame frame; // constructs the frame (with content) public abstract CDockableFrame buildFrame(String key, Frame mainFrame); }
package test.operation; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import vash.Output; import vash.operation.Absolute; import vash.operation.Add; import vash.operation.ColorNode; import vash.operation.Const; import vash.operation.Divide; import vash.operation.Exponentiate; import vash.operation.Flower; import vash.operation.Invert; import vash.operation.LinearGradient; import vash.operation.Modulus; import vash.operation.Multiply; import vash.operation.OperationNode; import vash.operation.PolarTheta; import vash.operation.RGB_Space; import vash.operation.RadialGradient; import vash.operation.Sinc; import vash.operation.Sine; import vash.operation.Spiral; import vash.operation.Squircle; public class TestOperationIntegration { private vash.Options opt; private vash.ImageParameters ip; @Before public void setUp() throws Exception { this.opt = new vash.Options(); this.opt.setWidth(128); this.opt.setHeight(128); this.ip = new vash.ImageParameters(this.opt.getWidth(), this.opt.getHeight()); } @After public void tearDown() throws Exception { } private void runTest(String test, OperationNode a) { this.runTest(test, a, a.clone(), a.clone()); } public static double compare(byte[] actual, int w, int h, String goal_in, String diff_out) { // read the expected result BufferedImage img = null; File fp = new File(goal_in); try { img = ImageIO.read(fp); } catch (IOException e) { throw new IllegalArgumentException("Unknown test"); } Assert.assertEquals(img.getWidth(), w); Assert.assertEquals(img.getHeight(), h); // track total error in the image int error = 0; // compute the image difference in case we need it later byte[] diff = new byte[w * h * 3]; // compare each pixel for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { int expect_clr = img.getRGB(x, y); int expect_b = (expect_clr >> 0) & 0xFF; int expect_g = (expect_clr >> 8) & 0xFF; int expect_r = (expect_clr >> 16) & 0xFF; int expect_a = (expect_clr >> 24) & 0xFF; Assert.assertEquals(expect_a, 255); int actual_b = actual[(y * w + x) * 3 + 0] & 0xFF; int actual_g = actual[(y * w + x) * 3 + 1] & 0xFF; int actual_r = actual[(y * w + x) * 3 + 2] & 0xFF; diff[(y * w + x) * 3 + 0] = (byte)Math.abs(expect_b - actual_b); diff[(y * w + x) * 3 + 1] = (byte)Math.abs(expect_g - actual_g); diff[(y * w + x) * 3 + 2] = (byte)Math.abs(expect_r - actual_r); error += Math.abs(expect_r - actual_r); error += Math.abs(expect_g - actual_g); error += Math.abs(expect_b - actual_b); } } // write out the diff before asserting, so we have it even if we fail if(diff_out != null) { BufferedImage bdiff = Output.dataToImage(diff, w, h); Output.writeImageFile(diff_out, "png", bdiff); } for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { /* System.out.format("%dx%d: R: %x = %x, G: %x = %x, B: %x = %x%n", x, y, expect_r, actual_r, expect_g, actual_g, expect_b, actual_b); */ Assert.assertTrue(diff[(y * w + x) * 3 + 0] < 1); Assert.assertTrue(diff[(y * w + x) * 3 + 1] < 1); Assert.assertTrue(diff[(y * w + x) * 3 + 2] < 1); } } Assert.assertTrue(error < (w * h) / 2); return error; } private void runTest(String test, OperationNode r, OperationNode g, OperationNode b) { ColorNode tree = new RGB_Space(r, g, b); byte[] actual = tree.compute(this.ip, true); int w = this.opt.getWidth(); int h = this.opt.getHeight(); // write the image to show what we got so we can compare on failures BufferedImage bactual = Output.dataToImage(actual, w, h); Output.writeImageFile("./test/result/" + test + ".png", "png", bactual); compare(actual, w, h, "./test/goal/" + test + ".png", "test/diff/" + test + ".png"); // Total error should be limited //System.out.format("%s-TotalError: %d, per-pix: %f%n", test, error, (double)error / (opt.getWidth() * opt.getHeight())); } private OperationNode c1P() { return new Const(1); } private OperationNode c1N() { return new Const(-1); } private OperationNode c0() { return new Const(0); } // const/plane layout tests @Test public void testConstRed() { this.runTest("1101", c1P(), c1N(), c1N()); } @Test public void testConstGreen() { this.runTest("1102", c1N(), c1P(), c1N()); } @Test public void testConstBlue() { this.runTest("1103", c1N(), c1N(), c1P()); } @Test public void testConstMagenta(){ this.runTest("1104", c1P(), c1N(), c1P()); } // linear gradient / plane orientation tests @Test public void testLinGradDiagLeftFill() { this.runTest("2101", new LinearGradient(0, 0, 1, 1)); } @Test public void testLinGradDiagRightFill() { this.runTest("2102", new LinearGradient(-1, -1, 0, 0)); } @Test public void testLinGradDiagNorthSouth(){ this.runTest("2103", new LinearGradient(0, -1, 0, 1)); } @Test public void testLinGradDiagSouthNorth(){ this.runTest("2104", new LinearGradient(0, 1, 0, -1)); } // polar theta @Test public void testPolarTheta0() { this.runTest("2201", new PolarTheta(0, 0, 0)); } @Test public void testPolarTheta05N() { this.runTest("2202", new PolarTheta(0, 0, -0.5)); } @Test public void testPolarTheta05P() { this.runTest("2203", new PolarTheta(0, 0, 0.5)); } @Test public void testPolarTheta1P() { this.runTest("2204", new PolarTheta(0, 0, 1)); } @Test public void testPolarTheta1N() { this.runTest("2205", new PolarTheta(0, 0, -1)); } @Test public void testPolarTheta75at1N(){ this.runTest("2206", new PolarTheta(-1, -1, 0.75)); } // radial gradients @Test public void testRadGradCenterFull() { this.runTest("2300", new RadialGradient(0, 0, 0.8, 0.8, 0)); } @Test public void testRadGradCenterEdge() { this.runTest("2301", new RadialGradient(0, 0, 0.707, 0.707, 0)); } @Test public void testRadGradUpperLeft() { this.runTest("2302", new RadialGradient(-1, -1, 0.8, 0.8, 0)); } @Test public void testRadGradUpperRight() { this.runTest("2303", new RadialGradient(1, -1, 0.8, 0.8, 0)); } @Test public void testRadGradBottomRight() { this.runTest("2304", new RadialGradient(1, 1, 0.8, 0.8, 0)); } @Test public void testRadGradBottomLeft() { this.runTest("2305", new RadialGradient(-1, 1, 0.8, 0.8, 0)); } @Test public void testRadGrad45() { this.runTest("2306", new RadialGradient(0, 0, 0.5, 0.8, 45)); } @Test public void testRadGrad315() { this.runTest("2307", new RadialGradient(0, 0, 0.5, 0.8, 315)); } // flower @Test public void testFlower5() {this.runTest("2400", new Flower(0, 0, 0, 1, 0.5, 5));} @Test public void testFlowerAngle() {this.runTest("2401", new Flower(0, 0, 45, 1, 0.5, 5));} @Test public void testFlowerSmallR(){this.runTest("2402", new Flower(0, 0, 0, 1, 0, 12));} @Test public void testFlowerLargeR(){this.runTest("2403", new Flower(0, 0, 0, 1, 1, 12));} @Test public void testFlowerCorner(){this.runTest("2404", new Flower(-1, -1, 45, 2.4, 0.1, 4));} private OperationNode XCoord() { return new LinearGradient(-1, 0, 1, 0); } private OperationNode YCoord() { return new LinearGradient(0, 1, 0, -1); } // xcoord @Test public void testXCoord() {this.runTest("2500", XCoord());} @Test public void testYCoord() {this.runTest("2600", YCoord());} // Unary Op @Test public void testAbs() {this.runTest("3000", new Absolute(XCoord()));} @Test public void testInv() {this.runTest("3100", new Invert(XCoord()));} // Binary Op @Test public void testAdd() {this.runTest("3200", new Add(XCoord(), YCoord()));} @Test public void testDiv() {this.runTest("3300", new Divide(XCoord(), YCoord()));} @Test public void testExp() {this.runTest("3400", new Exponentiate(XCoord(), YCoord()));} @Test public void testMod() {this.runTest("3500", new Modulus(XCoord(), YCoord()));} @Test public void testMul() {this.runTest("3600", new Multiply(XCoord(), YCoord()));} // sin @Test public void testSin1x0() {this.runTest("4000", new Sine(1, 0, XCoord()));} @Test public void testSin0x0() {this.runTest("4001", new Sine(0, 0, XCoord()));} @Test public void testSinN1x0() {this.runTest("4002", new Sine(-1, 0, XCoord()));} @Test public void testSinPIx0() {this.runTest("4003", new Sine(3.14, 0, XCoord()));} @Test public void testSinPIxPI2() {this.runTest("4004", new Sine(3.14, 1.57, XCoord()));} // sinc @Test public void testSinc1x0() {this.runTest("4100", new Sinc(1, 0, XCoord()));} @Test public void testSinc0x0() {this.runTest("4101", new Sinc(0, 0, XCoord()));} @Test public void testSincN1x0() {this.runTest("4102", new Sinc(-1, 0, XCoord()));} //@Test public void testSinc10PIx0() {this.runTest("4103", new Sinc(31.4, 0, XCoord()));} //@Test public void testSinc10PIxPI2(){this.runTest("4104", new Sinc(31.4, 15.7, XCoord()));} // squircle @Test public void testSquircleCirle() {this.runTest("4200", new Squircle(0, 0, 1, 2, c0(), c0()));} @Test public void testSquircleStripe() {this.runTest("4201", new Squircle(0, 0, 1, 4, XCoord(), XCoord()));} @Test public void testSquircleOffset() {this.runTest("4202", new Squircle(1, -1, 2, 2, c0(), c0()));} @Test public void testSquircleCorner() {this.runTest("4203", new Squircle(0, 0, 1.414, 2, c0(), c0()));} @Test public void testSquircleSquare() {this.runTest("4204", new Squircle(0, 0, 1, 4, c0(), c0()));} // spiral @Test public void testSpiralBase() {this.runTest("4300", new Spiral(0, 0, 1, 1, c1P()));} @Test public void testSpiralInvert() {this.runTest("4301", new Spiral(0, 0, 1, -1, c1P()));} @Test public void testSpiralCircles() {this.runTest("4302", new Spiral(0, 0, 0, -1, c1P()));} @Test public void testSpiralOffset() {this.runTest("4303", new Spiral(1, -1, 1, 1, c1P()));} @Test public void testSpiralDistortX() {this.runTest("4304", new Spiral(0, 0, 1, 1, XCoord()));} @Test public void testSpiralDistortY() {this.runTest("4305", new Spiral(0, 0, 1, 1, YCoord()));} @Test public void testSpiralRationalN2(){this.runTest("4306", new Spiral(0, 0, 2.5, 1, c1P()));} @Test public void testSpiralRationalN3(){this.runTest("4307", new Spiral(0, 0, 3.5, 1, c1P()));} @Test public void testSpiralRationalN4(){this.runTest("4308", new Spiral(0, 0, 4.5, 1, c1P()));} @Test public void testSpiralRationalN5(){this.runTest("4309", new Spiral(0, 0, 5.5, 1, c1P()));} }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tonegod.gui.controls.extras; import com.jme3.input.event.MouseButtonEvent; import com.jme3.math.Vector2f; import com.jme3.math.Vector4f; import tonegod.gui.core.Element; import tonegod.gui.core.ElementManager; import tonegod.gui.core.Screen; import tonegod.gui.core.SubScreen; import tonegod.gui.core.utils.UIDUtil; import tonegod.gui.effects.Effect; import tonegod.gui.listeners.MouseButtonListener; /** * * @author t0neg0d */ public abstract class DragElement extends Element implements MouseButtonListener { private Vector2f originalPosition; private boolean useSpringBack = false; private boolean useSpringBackEffect = false; private boolean lockToDropElementCenter = false; private boolean useLockToDropElementEffect = false; private boolean isEnabled = true; private Element parentDroppable = null; private Effect slideTo; public DragElement(ElementManager screen, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { this(screen, UIDUtil.getUID(), position, dimensions, resizeBorders, defaultImg); } public DragElement(ElementManager screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { super(screen, UID, position, dimensions, resizeBorders, defaultImg); this.originalPosition = getPosition().clone(); originalPosition.setY(screen.getHeight()-originalPosition.getY()-getHeight()); this.setIsMovable(true); this.setIsDragDropDragElement(true); this.setScaleNS(false); this.setScaleEW(false); // this.setFontSize(screen.getStyle("Button").getFloat("fontSize")); // this.setFontColor(screen.getStyle("Button").getColorRGBA("fontColor")); // this.setTextVAlign(BitmapFont.VAlign.valueOf(screen.getStyle("Button").getString("textVAlign"))); // this.setTextAlign(BitmapFont.Align.valueOf(screen.getStyle("Button").getString("textAlign"))); // this.setTextWrap(LineWrapMode.valueOf(screen.getStyle("Button").getString("textWrap"))); } /** * Returns the DragElement's original position * @return Vector2f originalPosition */ public Vector2f getOriginalPosition() { return this.originalPosition; } /** * Enables/disables the DragElement * @param isEnabled boolean */ public void setIsEnabled(boolean isEnabled) { this.isEnabled = isEnabled; if (isEnabled) this.setIsMovable(true); else this.setIsMovable(false); } /** * Returns if the DragElement is current enabled/disabled * @return boolean isEnabled */ public boolean getIsEnabled() { return this.isEnabled; } /** * Set whether or not the DragElement should center itself within the drop element * @param lockToDropElementCenter boolean */ public void setUseLockToDropElementCenter(boolean lockToDropElementCenter) { this.lockToDropElementCenter = lockToDropElementCenter; } /** * Returns if the DragElement should center itself within the drop element * @return boolean */ public boolean getUseLockToDropElementCenter() { return this.lockToDropElementCenter; } /** * Enables/disables the use of the SlideTo Effect when centering within the drop element. * @param useLockToDropElementEffect boolean */ public void setUseLockToDropElementEffect(boolean useLockToDropElementEffect) { this.useLockToDropElementEffect = useLockToDropElementEffect; } /** * Returns if the SlideTo Effect is enabled/disabled when centering within a drop element * @return */ public boolean getUseLockToDropElementEffect() { return this.useLockToDropElementEffect; } /** * Enables/disables springback to original position when dropped outside of a valid drop element * @param useSpringBack boolean */ public void setUseSpringBack(boolean useSpringBack) { this.useSpringBack = useSpringBack; } /** * Returns if springback is enabled for springback to original position when dropped outside of a valid drop element * @return boolean */ public boolean getUseSpringBack() { return this.useSpringBack; } /** * Enables/disables the use of SlideTo Effect when springback is enabled * @param useSpringBackEffect boolean */ public void setUseSpringBackEffect(boolean useSpringBackEffect) { this.useSpringBackEffect = useSpringBackEffect; } /** * Returns if SpringBack Effects are enabled/disabled * @return boolean */ public boolean getUseSpringBackEffect() { return this.useSpringBackEffect; } public Element getParentDroppable() { return this.parentDroppable; } public void bindToDroppable(Element el) { float x = el.getAbsoluteX()+(el.getWidth()/2); float y = el.getAbsoluteY()+(el.getHeight()/2); MouseButtonEvent evt = new MouseButtonEvent(0, false, (int)x, (int)y); if (screen instanceof Screen) { ((Screen)screen).forceEventElement(this); ((Screen)screen).onMouseButtonEvent(evt); } } @Override public void onMouseLeftPressed(MouseButtonEvent evt) { onDragStart(evt); } @Override public void onMouseLeftReleased(MouseButtonEvent evt) { Element dropEl = screen.getDropElement(); int index = -1; boolean success = onDragEnd(evt, dropEl); if (parentDroppable != null && parentDroppable != dropEl) { parentDroppable.removeChild(this); } if (success) { parentDroppable = dropEl; System.out.println(getParentDroppable()); Vector2f pos = new Vector2f(getAbsoluteX(),getAbsoluteY()); Element parent = getElementParent(); if (parent != dropEl) { if (parent != null) { parent.removeChild(this); } else { screen.removeElement(this); } float nextY = (pos.y-dropEl.getAbsoluteY()); nextY = -nextY; setPosition(pos.x-dropEl.getAbsoluteX(), nextY); dropEl.addChild(this); this.setZOrder(screen.getZOrderStepMinor()); } if (lockToDropElementCenter) { Vector2f destination = new Vector2f( (dropEl.getWidth()/2)-(getWidth()/2), (dropEl.getHeight()/2)-(getHeight()/2) ); if (useLockToDropElementEffect) { slideTo = new Effect(Effect.EffectType.SlideTo, Effect.EffectEvent.Release, .15f); slideTo.setElement(this); slideTo.setEffectDestination(destination); screen.getEffectManager().applyEffect(slideTo); } else { setPosition(destination); } originalPosition = destination.clone(); } } else { if (useSpringBack) { Vector2f destination = originalPosition.clone(); if (useSpringBackEffect) { slideTo = new Effect(Effect.EffectType.SlideTo, Effect.EffectEvent.Release, .15f); slideTo.setElement(this); slideTo.setEffectDestination(destination); screen.getEffectManager().applyEffect(slideTo); } else { setPosition(destination); } } } } @Override public void onMouseRightPressed(MouseButtonEvent evt) { } @Override public void onMouseRightReleased(MouseButtonEvent evt) { } public abstract void onDragStart(MouseButtonEvent evt); public abstract boolean onDragEnd(MouseButtonEvent evt, Element dropElement); }
package com.exedio.cope; import java.util.Collections; import java.util.List; import com.exedio.cope.testmodel.AttributeItem; import com.exedio.cope.testmodel.EmptyItem; public class SearchTest extends TestmodelTest { public void testSearch() { // test conditions final AttributeItem x = null; assertEquals( Cope.and(x.someString.equal("a"),x.someNotNullString.equal("b")), Cope.and(x.someString.equal("a"),x.someNotNullString.equal("b"))); assertNotEquals( Cope.and(x.someString.equal("aX"),x.someNotNullString.equal("b")), Cope.and(x.someString.equal("a"),x.someNotNullString.equal("b"))); assertNotEquals( Cope.and(x.someString.equal("a"),x.someNotNullString.like("b")), Cope.and(x.someString.equal("a"),x.someNotNullString.equal("b"))); assertNotEquals( // not commutative Cope.and(x.someString.equal("a"),x.someNotNullString.equal("b")), Cope.and(x.someNotNullString.equal("b"),x.someString.equal("a"))); final Query<EmptyItem> illegalQuery = EmptyItem.TYPE.newQuery(x.someInteger.equal(0)); try { illegalQuery.search(); fail(); } catch(IllegalArgumentException e) { assertEquals("AttributeItem.someInteger does not belong to a type of the query: " + illegalQuery, e.getMessage()); } try { illegalQuery.countWithoutLimit(); fail(); } catch(IllegalArgumentException e) { assertEquals("AttributeItem.someInteger does not belong to a type of the query: " + illegalQuery, e.getMessage()); } try { Cope.and((Condition[])null); fail(); } catch(NullPointerException e) { assertEquals("conditions must not be null", e.getMessage()); } try { Cope.and((List<Condition>)null); fail(); } catch(NullPointerException e) { assertEquals(null/*TODO*/, e.getMessage()); } try { Cope.or((Condition[])null); fail(); } catch(NullPointerException e) { assertEquals("conditions must not be null", e.getMessage()); } try { Cope.or((List<Condition>)null); fail(); } catch(NullPointerException e) { assertEquals(null/*TODO*/, e.getMessage()); } try { Cope.and(new Condition[0]); fail(); } catch(IllegalArgumentException e) { assertEquals("composite condition must have at least one subcondition", e.getMessage()); } try { Cope.and(Collections.<Condition>emptyList()); fail(); } catch(IllegalArgumentException e) { assertEquals("composite condition must have at least one subcondition", e.getMessage()); } try { Cope.or(new Condition[0]); fail(); } catch(IllegalArgumentException e) { assertEquals("composite condition must have at least one subcondition", e.getMessage()); } try { Cope.or(Collections.<Condition>emptyList()); fail(); } catch(IllegalArgumentException e) { assertEquals("composite condition must have at least one subcondition", e.getMessage()); } final EmptyItem someItem = new EmptyItem(); final AttributeItem item = new AttributeItem("someString", 5, 6l, 2.2, true, someItem, AttributeItem.SomeEnum.enumValue1); final AttributeItem item2 = new AttributeItem("someString2", 5, 6l, 2.2, false, someItem, AttributeItem.SomeEnum.enumValue2); item.setSomeNotNullInteger(0); assertContainsUnmodifiable(item, item.TYPE.search(item.someNotNullInteger.equal(0))); assertContainsUnmodifiable(item2, item.TYPE.search(item.someNotNullInteger.equal(0).not())); assertContainsUnmodifiable(item, item2, item.TYPE.search()); assertContainsUnmodifiable(item, item2, item.TYPE.search(null)); assertContainsUnmodifiable(item, item2, item.TYPE.search( Cope.or( item.someNotNullString.equal("someString"), item.someNotNullString.equal("someString2")))); assertContainsUnmodifiable( item.TYPE.search( Cope.and( item.someNotNullString.equal("someString"), item.someNotNullString.equal("someString2")))); // test Query#searchSingleton assertEquals(null, item.TYPE.searchSingleton(item.someNotNullString.equal("someStringx"))); assertEquals(item, item.TYPE.searchSingleton(item.someNotNullString.equal("someString"))); final Query q = item.TYPE.newQuery(); q.setOrderBy(item.TYPE.getThis(), true); try { q.searchSingleton(); fail(); } catch(IllegalArgumentException e) { assertEquals("expected result of size one or less, but was " + list(item, item2) + " for query: select " + item.TYPE.getThis() + " from AttributeItem order by " + item.TYPE.getThis(), e.getMessage()); } assertDelete(item); assertDelete(item2); assertDelete(someItem); } }
package com.exedio.cope; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Date; import java.util.List; import com.exedio.cope.function.LengthView; import com.exedio.cope.function.UppercaseView; import com.exedio.cope.testmodel.StringItem; public class StringTest extends TestmodelTest { boolean supports; String emptyString; StringItem item, item2; int numberOfItems; @Override public void setUp() throws Exception { super.setUp(); supports = model.supportsEmptyStrings(); emptyString = supports ? "" : null; item = deleteOnTearDown(new StringItem("StringTest")); item2 = deleteOnTearDown(new StringItem("StringTest2")); numberOfItems = 2; } public void testStrings() { // test model assertEquals(item.TYPE, item.any.getType()); assertEquals("any", item.any.getName()); assertEquals(false, item.any.isMandatory()); assertEqualsUnmodifiable(list(), item.any.getPatterns()); assertEquals(0, item.any.getMinimumLength()); assertEquals(StringField.DEFAULT_LENGTH, item.any.getMaximumLength()); assertEquals(item.TYPE, item.mandatory.getType()); assertEquals("mandatory", item.mandatory.getName()); assertEquals(true, item.mandatory.isMandatory()); assertEquals(4, item.min4.getMinimumLength()); assertEquals(StringField.DEFAULT_LENGTH, item.min4.getMaximumLength()); assertEquals(0, item.max4.getMinimumLength()); assertEquals(4, item.max4.getMaximumLength()); assertEquals(4, item.min4Max8.getMinimumLength()); assertEquals(8, item.min4Max8.getMaximumLength()); assertEquals(6, item.exact6.getMinimumLength()); assertEquals(6, item.exact6.getMaximumLength()); assertEquals(item.TYPE, item.min4Upper.getType()); assertEquals("min4Upper", item.min4Upper.getName()); { final StringField orig = new StringField().optional(); assertEquals(false, orig.isFinal()); assertEquals(false, orig.isMandatory()); assertEquals(0, orig.getMinimumLength()); assertEquals(StringField.DEFAULT_LENGTH, orig.getMaximumLength()); final StringField copy = orig.copy(); assertEquals(false, copy.isFinal()); assertEquals(false, copy.isMandatory()); assertEquals(0, copy.getMinimumLength()); assertEquals(StringField.DEFAULT_LENGTH, copy.getMaximumLength()); } { final StringField orig = new StringField().toFinal().optional().lengthMin(10); assertEquals(true, orig.isFinal()); assertEquals(false, orig.isMandatory()); assertNull(orig.getImplicitUniqueConstraint()); assertEquals(10, orig.getMinimumLength()); assertEquals(StringField.DEFAULT_LENGTH, orig.getMaximumLength()); final StringField copy = orig.copy(); assertEquals(true, copy.isFinal()); assertEquals(false, copy.isMandatory()); assertNull(copy.getImplicitUniqueConstraint()); assertEquals(10, copy.getMinimumLength()); assertEquals(StringField.DEFAULT_LENGTH, copy.getMaximumLength()); } { final StringField orig = new StringField().toFinal().optional().unique().lengthMin(20); assertEquals(true, orig.isFinal()); assertEquals(false, orig.isMandatory()); assertNotNull(orig.getImplicitUniqueConstraint()); assertEquals(20, orig.getMinimumLength()); assertEquals(StringField.DEFAULT_LENGTH, orig.getMaximumLength()); final StringField copy = orig.copy(); assertEquals(true, copy.isFinal()); assertEquals(false, copy.isMandatory()); assertNotNull(copy.getImplicitUniqueConstraint()); assertEquals(20, copy.getMinimumLength()); assertEquals(StringField.DEFAULT_LENGTH, copy.getMaximumLength()); } { final StringField orig = new StringField().lengthRange(10, 20); assertEquals(false, orig.isFinal()); assertEquals(true, orig.isMandatory()); assertEquals(10, orig.getMinimumLength()); assertEquals(20, orig.getMaximumLength()); final StringField copy = orig.copy(); assertEquals(false, copy.isFinal()); assertEquals(true, copy.isMandatory()); assertEquals(10, copy.getMinimumLength()); assertEquals(20, copy.getMaximumLength()); } assertWrongLength(-1, 20, "mimimum length must be positive, but was -1."); assertWrongLength( 0, 0, "maximum length must be greater zero, but was 0."); assertWrongLength(20, 10, "maximum length must be greater or equal mimimum length, but was 10 and 20."); // test conditions assertEquals(item.any.equal("hallo"), item.any.equal("hallo")); assertNotEquals(item.any.equal("hallo"), item.any.equal("bello")); assertNotEquals(item.any.equal("hallo"), item.any.equal((String)null)); assertNotEquals(item.any.equal("hallo"), item.any.like("hallo")); assertEquals(item.any.equal(item.mandatory), item.any.equal(item.mandatory)); assertNotEquals(item.any.equal(item.mandatory), item.any.equal(item.any)); // test convenience for conditions assertEquals(item.any.startsWith("hallo"), item.any.like("hallo%")); assertEquals(item.any.endsWith("hallo"), item.any.like("%hallo")); assertEquals(item.any.contains("hallo"), item.any.like("%hallo%")); assertEquals(item.any.equalIgnoreCase("hallo"), item.any.toUpperCase().equal("HALLO")); assertEquals(item.any.likeIgnoreCase("hallo%"), item.any.toUpperCase().like("HALLO%")); assertEquals(item.any.startsWithIgnoreCase("hallo"), item.any.toUpperCase().like("HALLO%")); assertEquals(item.any.endsWithIgnoreCase("hallo"), item.any.toUpperCase().like("%HALLO")); assertEquals(item.any.containsIgnoreCase("hallo"), item.any.toUpperCase().like("%HALLO%")); // any item.setAny("1234"); assertEquals("1234", item.getAny()); item.setAny("123"); assertEquals("123", item.getAny()); // standard tests item.setAny(null); assertString(item, item2, item.any); assertString(item, item2, item.long1K); assertString(item, item2, item.long1M); { final StringItem itemEmptyInit = deleteOnTearDown(new StringItem("", false)); numberOfItems++; assertEquals(emptyString, itemEmptyInit.getAny()); restartTransaction(); assertEquals(emptyString, itemEmptyInit.getAny()); } // mandatory assertEquals("StringTest", item.getMandatory()); item.setMandatory("someOtherString"); assertEquals("someOtherString", item.getMandatory()); try { item.setMandatory(null); fail(); } catch(MandatoryViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.mandatory, e.getFeature()); assertEquals(item.mandatory, e.getFeature()); assertEquals("mandatory violation on " + item + " for " + item.mandatory, e.getMessage()); } assertEquals("someOtherString", item.getMandatory()); assertEquals(numberOfItems, item.TYPE.search(null).size()); try { new StringItem((String)null); fail(); } catch(MandatoryViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.mandatory, e.getFeature()); assertEquals(item.mandatory, e.getFeature()); assertEquals("mandatory violation on a newly created item for " + item.mandatory, e.getMessage()); } assertEquals(numberOfItems, item.TYPE.search(null).size()); assertEquals(numberOfItems, item.TYPE.search(null).size()); try { new StringItem(new SetValue[]{}); fail(); } catch(MandatoryViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.mandatory, e.getFeature()); assertEquals(item.mandatory, e.getFeature()); assertEquals("mandatory violation on a newly created item for " + item.mandatory, e.getMessage()); } assertEquals(numberOfItems, item.TYPE.search(null).size()); // mandatory and empty string try { item.setMandatory(""); if(supports) assertEquals("", item.getMandatory()); else fail(); } catch(MandatoryViolationException e) { assertTrue(!supports); assertEquals(item.mandatory, e.getFeature()); assertEquals(item.mandatory, e.getFeature()); assertEquals(item, e.getItem()); assertEquals("mandatory violation on " + item + " for " + item.mandatory, e.getMessage()); assertEquals("someOtherString", item.getMandatory()); } StringItem item3 = null; assertEquals(numberOfItems, item.TYPE.search(null).size()); try { item3 = deleteOnTearDown(new StringItem("", 0.0)); numberOfItems++; if(supports) assertEquals("", item3.getMandatory()); else fail(); } catch(MandatoryViolationException e) { assertTrue(!supports); assertEquals(item3.mandatory, e.getFeature()); assertEquals(item3.mandatory, e.getFeature()); assertEquals(item3, e.getItem()); assertEquals("mandatory violation on a newly created item for " + item.mandatory, e.getMessage()); } assertEquals(numberOfItems, item.TYPE.search(null).size()); // min4 try { item.setMin4("123"); fail(); } catch(LengthViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.min4, e.getFeature()); assertEquals(item.min4, e.getFeature()); assertEquals("123", e.getValue()); assertEquals(true, e.isTooShort()); assertEquals( "length violation on " + item + ", " + "'123' is too short for " + item.min4 + ", " + "must be at least 4 characters, but was 3.", e.getMessage()); } assertEquals(null, item.getMin4()); restartTransaction(); assertEquals(null, item.getMin4()); item.setMin4("1234"); assertEquals("1234", item.getMin4()); // max4 item.setMax4("1234"); assertEquals("1234", item.getMax4()); try { item.setMax4("12345"); fail(); } catch(LengthViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.max4, e.getFeature()); assertEquals(item.max4, e.getFeature()); assertEquals("12345", e.getValue()); assertEquals(false, e.isTooShort()); assertEquals( "length violation on " + item + ", " + "'12345' is too long for " + item.max4 + ", " + "must be at most 4 characters, but was 5.", e.getMessage()); } assertEquals("1234", item.getMax4()); restartTransaction(); assertEquals("1234", item.getMax4()); assertEquals(numberOfItems, item.TYPE.search(null).size()); try { new StringItem("12345", (Date)null); fail(); } catch(LengthViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.max4, e.getFeature()); assertEquals(item.max4, e.getFeature()); assertEquals("12345", e.getValue()); assertEquals( "length violation on a newly created item, " + "'12345' is too long for " + item.max4 + ", " + "must be at most 4 characters, but was 5.", e.getMessage()); } assertEquals(numberOfItems, item.TYPE.search(null).size()); try { StringItem.TYPE.newItem( item.mandatory.map("defaultByMax4"), item.max4.map("12345") ); fail(); } catch(LengthViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.max4, e.getFeature()); assertEquals(item.max4, e.getFeature()); assertEquals("12345", e.getValue()); assertEquals( "length violation on a newly created item, " + "'12345' is too long for " + item.max4 + ", " + "must be at most 4 characters, but was 5.", e.getMessage()); } assertEquals(numberOfItems, item.TYPE.search(null).size()); // min4max8 try { item.setMin4Max8("123"); fail(); } catch(LengthViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.min4Max8, e.getFeature()); assertEquals(item.min4Max8, e.getFeature()); assertEquals("123", e.getValue()); assertEquals(true, e.isTooShort()); assertEquals( "length violation on " + item + ", " + "'123' is too short for " + item.min4Max8 + ", " + "must be at least 4 characters, but was 3.", e.getMessage()); } assertEquals(null, item.getMin4Max8()); restartTransaction(); assertEquals(null, item.getMin4Max8()); item.setMin4Max8("1234"); assertEquals("1234", item.getMin4Max8()); item.setMin4Max8("12345678"); assertEquals("12345678", item.getMin4Max8()); restartTransaction(); assertEquals("12345678", item.getMin4Max8()); try { item.setMin4Max8("123456789"); fail(); } catch(LengthViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.min4Max8, e.getFeature()); assertEquals(item.min4Max8, e.getFeature()); assertEquals("123456789", e.getValue()); assertEquals(false, e.isTooShort()); assertEquals( "length violation on " + item + ", " + "'123456789' is too long for " + item.min4Max8 + ", " + "must be at most 8 characters, but was 9.", e.getMessage()); } assertEquals("12345678", item.getMin4Max8()); restartTransaction(); assertEquals("12345678", item.getMin4Max8()); // exact6 try { item.setExact6("12345"); fail(); } catch(LengthViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.exact6, e.getFeature()); assertEquals(item.exact6, e.getFeature()); assertEquals("12345", e.getValue()); assertEquals(true, e.isTooShort()); assertEquals( "length violation on " + item + ", " + "'12345' is too short for " + item.exact6 + ", " + "must be at least 6 characters, but was 5.", e.getMessage()); } assertEquals(null, item.getExact6()); restartTransaction(); assertEquals(null, item.getExact6()); item.setExact6("123456"); assertEquals("123456", item.getExact6()); restartTransaction(); assertEquals("123456", item.getExact6()); try { item.setExact6("1234567"); fail(); } catch(LengthViolationException e) { assertEquals(item, e.getItem()); assertEquals(item.exact6, e.getFeature()); assertEquals(item.exact6, e.getFeature()); assertEquals("1234567", e.getValue()); assertEquals(false, e.isTooShort()); assertEquals( "length violation on " + item + ", " + "'1234567' is too long for " + item.exact6 + ", " + "must be at most 6 characters, but was 7.", e.getMessage()); } assertEquals("123456", item.getExact6()); restartTransaction(); assertEquals("123456", item.getExact6()); assertEquals(numberOfItems, item.TYPE.search(null).size()); try { new StringItem("1234567", 40); fail(); } catch(LengthViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.exact6, e.getFeature()); assertEquals(item.exact6, e.getFeature()); assertEquals("1234567", e.getValue()); assertEquals(false, e.isTooShort()); assertEquals( "length violation on a newly created item, " + "'1234567' is too long for " + item.exact6 + ", " + "must be at most 6 characters, but was 7.", e.getMessage()); } assertEquals(numberOfItems, item.TYPE.search(null).size()); try { StringItem.TYPE.newItem( item.mandatory.map("defaultByExact6"), item.exact6.map("1234567") ); fail(); } catch(LengthViolationException e) { assertEquals(null, e.getItem()); assertEquals(item.exact6, e.getFeature()); assertEquals(item.exact6, e.getFeature()); assertEquals("1234567", e.getValue()); assertEquals(false, e.isTooShort()); assertEquals( "length violation on a newly created item, " + "'1234567' is too long for " + item.exact6 + ", " + "must be at most 6 characters, but was 7.", e.getMessage()); } assertEquals(numberOfItems, item.TYPE.search(null).size()); model.checkUnsupportedConstraints(); } @SuppressWarnings("unchecked") // OK: test bad API usage public void testUnchecked() { try { item.set((FunctionField)item.any, Integer.valueOf(10)); fail(); } catch(ClassCastException e) { assertEquals("expected a " + String.class.getName() + ", " + "but was a " + Integer.class.getName() + " for " + item.any + '.', e.getMessage()); } } void assertWrongLength(final int minimumLength, final int maximumLength, final String message) { try { new StringField().optional().lengthRange(minimumLength, maximumLength); fail(); } catch(IllegalArgumentException e) { assertEquals(message, e.getMessage()); } } static final String makeString(final int length) { final int segmentLength = length/20 + 1; final char[] buf = new char[length]; char val = 'A'; for(int i = 0; i<length; i+=segmentLength) Arrays.fill(buf, i, Math.min(i+segmentLength, length), val++); final String lengthString = String.valueOf(length) + ':'; System.arraycopy(lengthString.toCharArray(), 0, buf, 0, Math.min(lengthString.length(), length)); final String result = new String(buf); return result; } void assertString(final Item item, final Item item2, final StringField sa) { final Type<? extends Item> type = item.getCopeType(); assertEquals(type, item2.getCopeType()); final String VALUE = "someString"; final String VALUE2 = VALUE+"2"; final String VALUE_UPPER = "SOMESTRING"; final String VALUE2_UPPER = "SOMESTRING2"; final UppercaseView saup = sa.toUpperCase(); final LengthView saln = sa.length(); assertEquals(null, sa.get(item)); assertEquals(null, saup.get(item)); assertEquals(null, saln.get(item)); assertEquals(null, sa.get(item2)); assertEquals(null, saup.get(item2)); assertEquals(null, saln.get(item2)); assertContains(item, item2, type.search(sa.isNull())); sa.set(item, VALUE); assertEquals(VALUE, sa.get(item)); assertEquals(VALUE_UPPER, saup.get(item)); assertEquals(Integer.valueOf(VALUE.length()), saln.get(item)); sa.set(item2, VALUE2); assertEquals(VALUE2, sa.get(item2)); assertEquals(VALUE2_UPPER, saup.get(item2)); assertEquals(Integer.valueOf(VALUE2.length()), saln.get(item2)); if(!oracle||sa.getMaximumLength()<4000) { assertContains(item, type.search(sa.equal(VALUE))); assertContains(item2, type.search(sa.notEqual(VALUE))); assertContains(type.search(sa.equal(VALUE_UPPER))); assertContains(item, type.search(sa.like(VALUE))); assertContains(item, item2, type.search(sa.like(VALUE+"%"))); assertContains(item2, type.search(sa.like(VALUE2+"%"))); assertContains(item, type.search(saup.equal(VALUE_UPPER))); assertContains(item2, type.search(saup.notEqual(VALUE_UPPER))); assertContains(type.search(saup.equal(VALUE))); assertContains(item, type.search(saup.like(VALUE_UPPER))); assertContains(item, item2, type.search(saup.like(VALUE_UPPER+"%"))); assertContains(item2, type.search(saup.like(VALUE2_UPPER+"%"))); assertContains(item, type.search(saln.equal(VALUE.length()))); assertContains(item2, type.search(saln.notEqual(VALUE.length()))); assertContains(type.search(saln.equal(VALUE.length()+2))); assertContains(VALUE, VALUE2, search(sa)); assertContains(VALUE, search(sa, sa.equal(VALUE))); // TODO allow functions for select //assertContains(VALUE_UPPER, search(saup, sa.equal(VALUE))); } restartTransaction(); assertEquals(VALUE, sa.get(item)); assertEquals(VALUE_UPPER, saup.get(item)); assertEquals(Integer.valueOf(VALUE.length()), saln.get(item)); { sa.set(item, ""); assertEquals(emptyString, sa.get(item)); restartTransaction(); assertEquals(emptyString, sa.get(item)); assertEquals(list(item), type.search(sa.equal(emptyString))); if(!oracle||sa.getMaximumLength()<4000) { assertEquals(list(), type.search(sa.equal("x"))); assertEquals(supports ? list(item) : list(), type.search(sa.equal(""))); } } assertStringSet(item, sa, " trim "); // ensure that leading/trailing white space is not removed assertStringSet(item, sa, "Auml \u00c4; " + "Ouml \u00d6; " + "Uuml \u00dc; " + "auml \u00e4; " + "ouml \u00f6; " + "uuml \u00fc; " + "szlig \u00df; "); assertStringSet(item, sa, "paragraph \u00a7; " + "kringel \u00b0; " //+ "abreve \u0102; " //+ "hebrew \u05d8 " + "euro \u20ac"); // byte C5 in several encodings assertStringSet(item, sa, "Aringabove \u00c5;" // ISO-8859-1/4/9/10 (Latin1/4/5/6) + "Lacute \u0139;" // ISO-8859-2 (Latin2) + "Cdotabove \u010a;" // ISO-8859-3 (Latin3) + "ha \u0425;" // ISO-8859-5 (Cyrillic) + "AlefHamzaBelow \u0625;" // ISO-8859-6 (Arabic) + "Epsilon \u0395;" // ISO-8859-7 (Greek) ); // test SQL injection // if SQL injection is not prevented properly, // the following lines will throw a SQLException // due to column "hijackedColumn" not found assertStringSet(item, sa, "value',hijackedColumn='otherValue"); // TODO use streams for oracle assertStringSet(item, sa, makeString(Math.min(sa.getMaximumLength(), oracle ? (1300/*32766-1*/) : (4 * 1000 * 1000)))); sa.set(item, null); assertEquals(null, sa.get(item)); assertEquals(null, saup.get(item)); assertEquals(null, saln.get(item)); assertContains(item, type.search(sa.isNull())); sa.set(item2, null); assertEquals(null, sa.get(item2)); assertEquals(null, saup.get(item2)); assertEquals(null, saln.get(item2)); assertContains(item, item2, type.search(sa.isNull())); } private void assertStringSet(final Item item, final StringField sa, final String value) { final Type type = item.getCopeType(); sa.set(item, value); assertEquals(value, sa.get(item)); restartTransaction(); assertEquals(value, sa.get(item)); if(!oracle||sa.getMaximumLength()<4000) // TODO should work without condition { assertEquals(list(item), type.search(sa.equal(value))); assertEquals(list(), type.search(sa.equal(value+"x"))); } // test length view final Integer valueChars = value.length(); final String message; try { message = value+'('+valueChars+','+value.getBytes("utf8").length+')'; } catch(UnsupportedEncodingException e) { throw new RuntimeException(e); } assertEquals(message, valueChars, sa.length().get(item)); assertEquals(message, valueChars, new Query<Integer>(sa.length(), Cope.equalAndCast(item.getCopeType().getThis(), item)).searchSingletonStrict()); } protected static List<? extends Object> search(final FunctionField<? extends Object> selectAttribute) { return search(selectAttribute, null); } protected static List<? extends Object> search(final FunctionField<? extends Object> selectAttribute, final Condition condition) { return new Query<Object>(selectAttribute, condition).search(); } }
package io.norberg.rut; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static io.norberg.rut.RadixTrie.Node.fanout; import static java.lang.Math.max; final class RadixTrie<T> { private static final Charset ASCII = Charset.forName("US-ASCII"); private static final byte CAPTURE_SEG = -128; private static final byte CAPTURE_PATH = -127; private static final byte SLASH = '/'; private static final byte QUERY = '?'; private final Node<T> root; private final int captures; RadixTrie(final Node<T> root) { this.root = root; this.captures = root.captures(); } T lookup(final CharSequence path) { return lookup(path, captor()); } T lookup(final CharSequence path, final Captor captor) { captor.reset(); return fanout(root, path, 0, captor, 0); } int captures() { return captures; } Captor captor() { return captor(captures); } static Captor captor(final int captures) { return new Captor(captures); } static <T> Builder<T> builder() { return new Builder<T>(); } @SuppressWarnings("UnusedParameters") static <T> Builder<T> builder(Class<T> clazz) { return new Builder<T>(); } static final class Node<T> { private final byte head; private final byte[] tail; private final Node<T> sibling; private final Node<T> edge; private final T value; private Node(final byte head, final byte[] tail, final Node<T> sibling, final Node<T> edge, final T value) { this.head = head; this.tail = tail; this.sibling = sibling; this.edge = edge; this.value = value; // Verify that match siblings are ordered if (sibling != null && head > 0 && sibling.head > 0 && head > sibling.head) { throw new IllegalArgumentException("unordered sibling"); } // Verify that sibling heads are unique if (sibling != null && head == sibling.head) { throw new IllegalArgumentException("duplicate sibling head"); } // Verify that the seg capture is last or followed by path capture if (head == CAPTURE_SEG && sibling != null && sibling.head != CAPTURE_PATH) { throw new IllegalArgumentException("seg capture must be last or followed by path capture"); } // Verify that the path capture is last if (head == CAPTURE_PATH && sibling != null) { throw new IllegalArgumentException("path capture must be last sibling"); } // Verify that terminal nodes have values if (value == null && edge == null) { throw new IllegalArgumentException("terminal node without value"); } } private int captures() { final int captures = (head < 0) ? 1 : 0; final int edgeCaptures = (edge == null) ? 0 : edge.captures(); final int siblingCaptures = (sibling == null) ? 0 : sibling.captures(); return captures + max(edgeCaptures, siblingCaptures); } static <T> T fanout(final Node<T> root, final CharSequence path, final int i, final Captor captor, final int capture) { if (root == null) { return null; } if (i == path.length()) { return terminalFanout(root, captor, capture); } final char c = path.charAt(i); if (c == QUERY) { return terminalFanout(root, captor, capture); } Node<T> node = root; byte head; // Seek single potential matching node. This will be at any place in the ordered list. do { head = node.head; if (head < 0) { break; } if (head == c) { final T value = node.match(path, i, captor, capture); if (value != null) { return value; } break; } if (node.sibling == null) { break; } node = node.sibling; } while (true); // Seek potential capture nodes. These can be the second two last nodes in the list, // with the seg capture node before the path capture node. do { if (node.head == CAPTURE_SEG) { final T value = node.captureSeg(path, i, captor, capture); if (value != null) { return value; } } if (node.head == CAPTURE_PATH) { return node.capturePath(path, i, captor, capture); } node = node.sibling; } while (node != null); return null; } private static <T> T terminalFanout(Node<T> node, final Captor captor, final int capture) { if (!captor.optionalTrailingSlash) { return null; } // Trailing slash in prefix? byte head; do { head = node.head; if (head < 0) { break; } if (head == SLASH && node.tail == null) { if (node.value != null) { captor.match(capture); } return node.value; } node = node.sibling; } while (node != null); return null; } private T match(final CharSequence path, final int index, final Captor captor, final int capture) { // Match prefix final int length = path.length(); final int next; if (tail == null) { next = index + 1; } else { next = index + 1 + tail.length; if (next > length) { // Trailing slash in prefix? if (value != null && captor.optionalTrailingSlash && tail[tail.length - 1] == SLASH && next == length + 1) { captor.match(capture); return value; } return null; } for (int i = 0; i < tail.length; i++) { if (tail[i] != path.charAt(index + 1 + i)) { // Trailing slash in path? if (value != null && captor.optionalTrailingSlash && i == tail.length - 1 && tail[tail.length - 1] == SLASH && path.charAt(index + 1 + i) == QUERY) { captor.query(index + 2 + i, length); captor.match(capture); return value; } return null; } } } // Terminal? if (next == length) { if (value != null) { captor.match(capture); return value; } return terminalFanout(edge, captor, capture); } // Query? final char c = path.charAt(next); if (c == QUERY) { if (value != null) { captor.query(next + 1, length); captor.match(capture); return value; } final T value = terminalFanout(edge, captor, capture); if (value != null) { captor.query(next + 1, length); return value; } return null; } // Edge fanout final T value = fanout(edge, path, next, captor, capture); if (value != null) { return value; } // Trailing slash in path? if (this.value != null && captor.optionalTrailingSlash && c == SLASH) { if (next + 1 == length) { captor.match(capture); return this.value; } else if (path.charAt(next + 1) == QUERY) { captor.match(capture); captor.query(next + 2, length); return this.value; } } return null; } private T capturePath(final CharSequence path, final int index, final Captor captor, final int capture) { // value != null int i; char c; // Find capture bound final int length = path.length(); for (i = index; i < length; i++) { c = path.charAt(i); if (c == QUERY) { captor.query(i + 1, length); break; } } captor.match(capture + 1); captor.capture(capture, index, i); return value; } private T captureSeg(final CharSequence path, final int index, final Captor captor, final int capture) { int i; char c; // Find capture bound final int length = path.length(); boolean terminal = true; for (i = index; i < length; i++) { c = path.charAt(i); if (c == SLASH) { terminal = false; break; } if (c == QUERY) { captor.query(i + 1, length); break; } } final int limit = i; // Terminal? if (value != null) { if (terminal) { captor.match(capture + 1); captor.capture(capture, index, limit); return value; } // Trailing slash in path? if (captor.optionalTrailingSlash) { if (limit + 1 == length) { captor.match(capture + 1); captor.capture(capture, index, limit); return value; } else if (path.charAt(limit + 1) == QUERY) { captor.match(capture + 1); captor.capture(capture, index, i); captor.query(limit + 2, length); return value; } } } // Fanout if (edge != null) { for (i = limit; i >= index; i final T value = fanout(edge, path, i, captor, capture + 1); if (value != null) { captor.capture(capture, index, i); return value; } } } return null; } private String prefix() { if (head == CAPTURE_SEG) { return "<*>"; } else { if (tail == null) { return String.valueOf((char) head); } else { final StringBuilder b = new StringBuilder().append((char) head); for (final byte c : tail) { b.append((char) c); } return b.toString(); } } } @Override public String toString() { return "Node{'" + prefix() + "\': " + "e=" + prefixes(edge) + ", v=" + (value == null ? "" : value.toString()) + '}'; } static <T> Node<T> captureSeg(final Node<T> sibling, final Node<T> edge, final T value) { return new Node<T>(CAPTURE_SEG, null, sibling, edge, value); } static <T> Node<T> capturePath(final Node<T> sibling, final T value) { return new Node<T>(CAPTURE_PATH, null, sibling, null, value); } static <T> Node<T> match(final CharSequence prefix, final Node<T> sibling, final Node<T> edge, final T value) { final byte head = (byte) prefix.charAt(0); final byte[] tail = prefix.length() == 1 ? null : prefix.subSequence(1, prefix.length()).toString().getBytes(ASCII); return new Node<T>(head, tail, sibling, edge, value); } } private static <T> String prefixes(Node<T> node) { final List<String> prefixes = new ArrayList<String>(); while (node != null) { prefixes.add(node.prefix()); node = node.sibling; } return prefixes.toString(); } @Override public String toString() { return "RadixTrie{" + root + "}"; } final static class Builder<T> { private Builder() { } private final Trie<T> trie = new Trie<T>(); Builder<T> insert(final CharSequence path, final T value) { trie.insert(path, value); return this; } Builder<T> insert(final CharSequence path, final Trie.Visitor<T> visitor) { trie.insert(path, visitor); return this; } RadixTrie<T> build() { return trie.compress(); } @Override public String toString() { return "Builder{" + "trie=" + trie + '}'; } } final static class Captor { private final int[] start; private final int[] end; private boolean match; private int captured; private int queryStart; private int queryEnd; private boolean optionalTrailingSlash; Captor(final int captures) { this.start = new int[captures]; this.end = new int[captures]; } void optionalTrailingSlash(final boolean optionalTrailingSlash) { this.optionalTrailingSlash = optionalTrailingSlash; } private void reset() { match = false; captured = 0; queryStart = -1; queryEnd = -1; } private void capture(final int i, final int start, final int end) { this.start[i] = start; this.end[i] = end; } private void match(final int captured) { match = true; this.captured = captured; } boolean isMatch() { return match; } int values() { return captured; } int valueStart(final int i) { if (!match) { throw new IllegalStateException("not matched"); } if (i >= captured) { throw new IndexOutOfBoundsException(); } return start[i]; } int valueEnd(final int i) { if (!match) { throw new IllegalStateException("not matched"); } if (i >= captured) { throw new IndexOutOfBoundsException(); } return end[i]; } CharSequence value(final CharSequence haystack, final int i) { if (!match) { throw new IllegalStateException("not matched"); } if (i >= captured) { throw new IndexOutOfBoundsException(); } return haystack.subSequence(start[i], end[i]); } private void query(final int start, final int end) { this.queryStart = start; this.queryEnd = end; } public int queryStart() { return queryStart; } public int queryEnd() { return queryEnd; } public CharSequence query(final CharSequence haystack) { if (queryStart == -1) { return null; } return haystack.subSequence(queryStart, queryEnd); } } }
package mathsquared.resultswizard2; /** * An immutable object that represents a proper fraction. Can support improper fractions intermittently as well. * * Note that any post-conditions on any methods of this class only apply after the constructor has successfully completed, as several clean-up methods are required to ensure that a Fraction is represented in a canonical form. * * @author MathSquared * */ public class Fraction { // TODO write unit tests private int unit; private boolean unitValid = false; // Turns true when a unit is calculated and false when it is extracted private int numerator; private int denominator; public Fraction (int num, int den) { if (den == 0) { throw new ArithmeticException("Denominator must not be equal to 0"); } numerator = num; denominator = den; canonicalizeDenominator(); calculateUnit(); matchUnitNumeratorSign(); simplify(); } // Setup methods // /* * Setup methods; called in constructor Before these methods are called, the Fraction may be in a non-canonical state. */ /** * If the denominator of a fraction is negative, switches the sign of both the numerator and denominator. This way, the denominator is always positive. */ private void canonicalizeDenominator () { if (denominator < 0) { numerator = -numerator; denominator = -denominator; } } /** * Calculates the unit of a fraction based on the numerator and denominator. This has the effect that the fraction represented by the numerator and denominator becomes proper. */ private void calculateUnit () { unit += numerator / denominator; // += in case there are already any other units that we want to remain valid--5u3/2 is 6u1/2 numerator %= denominator; // % picks sign based on numerator, so numerator keeps current sign unitValid = true; } /** * Ensures that the sign of the unit and numerator match. */ private void matchUnitNumeratorSign () { // If signs match, or if either quantity is 0 (which has no sign), we don't need to do anything if ((unit > 0 && numerator > 0) || (unit < 0 && numerator < 0) || (unit == 0 || numerator == 0)) { // last || is intentionally different return; } // Simply convert to improper and back numerator = getImproperNumerator(); unit = 0; unitValid = false; calculateUnit(); } /** * Simplifies a fraction to its lowest terms. */ private void simplify () { int gcd = GcdUtils.gcd(numerator, denominator); numerator /= gcd; denominator /= gcd; } // Accessors // /** * Returns the unit currently associated with this fraction. If the unit is {@linkplain #isUnitValid() invalid}, this method returns 0. If the fraction represents a negative quantity, the value returned by this method will be negative. * * @return the unit of this fraction */ public int getUnit () { return (unitValid ? unit : 0); } /** * Discards the unit of this fraction, returning the number discarded. After this method is called, {@link #getUnit()} returns 0 and {@link #isUnitValid()} returns false. If the fraction represents a negative quantity, the value returned by this method will be negative. * * @return the unit of this fraction */ public int extractUnit () { int temp = unit; unitValid = false; unit = 0; return temp; } /** * Returns whether the unit of this fraction will be used in future arithmetic calculations. * * <p> * The {@linkplain #getUnit() unit} mechanism was created to facilitate chaining of operations, especially additions. Since units are factored into calculations as long as they are valid, the unit can be disabled by the user when it is no longer needed. This method returns whether the unit will still be used in mathematical calculations. * </p> * * @return whether the current unit is valid */ public boolean isUnitValid () { return unitValid; } /** * Returns the numerator of the proper portion of this fraction. If the fraction represents a negative quantity, the value returned by this method will be negative. * * @return the numerator */ public int getNumerator () { return numerator; } /** * Returns the numerator of this fraction expressed as an improper fraction. If the unit is {@linkplain #isUnitValid() valid}, this is defined to be equal to <code>(numerator + unit*denominator)</code>; if the unit is invalid, this returns the same result as {@link #getNumerator()}. * * @return the improper numerator */ // USE THIS METHOD FOR ARITHMETIC TO SUPPORT OPERATION CHAINING; DO NOT DIRECTLY EMPLOY numerator public int getImproperNumerator () { return numerator + (unitValid ? unit : 0) * denominator; } /** * Returns the denominator of this fraction. This method always returns a positive quantity; the sign is unambiguously determined by the {@linkplain #getNumerator() numerator}. * * @return the denominator */ public int getDenominator () { return denominator; } // Arithmetic // /** * Negates a Fraction (finds its additive inverse). This is equivalent to multiplication by -1. * * @return a new Fraction representing the negative of this Fraction */ public Fraction negative () { return new Fraction(-getImproperNumerator(), denominator); } /** * Multiplies a Fraction by an integer. * * @param multiplier the number by which to multiply * @return a new Fraction multiplied by the multiplier */ public Fraction multiply (int multiplier) { return new Fraction(getImproperNumerator() * multiplier, denominator); } /** * Multiplies two Fractions together. * * @param multiplier the Fraction by which to multiply * @return a new Fraction multiplied by the multiplier */ public Fraction multiply (Fraction multiplier) { return new Fraction(getImproperNumerator() * multiplier.getImproperNumerator(), denominator * multiplier.getDenominator()); } /** * Divides a Fraction by an integer. * * @param divisor the number by which to divide * @return a new Fraction divided by the divisor * @throws ArithmeticException if the divisor is 0 */ public Fraction divide (int divisor) { if (divisor == 0) { throw new ArithmeticException("divisor must not be 0"); } return new Fraction(getImproperNumerator(), denominator * divisor); } /** * Divides a Fraction by another. This is equivalent to multiplication by the divisor's reciprocal. * * @param divisor the Fraction by which to divide * @return a new Fraction divided by the divisor * @throws ArithmeticException if the numerator of the divisor is 0 */ public Fraction divide (Fraction divisor) { if (divisor.getImproperNumerator() == 0) { throw new IllegalArgumentException("numerator of the divisor must not be 0"); } return new Fraction(getImproperNumerator() * divisor.getDenominator(), denominator * divisor.getImproperNumerator()); } /** * Raises a Fraction to a power. * * <p> * This method assumes that any fraction raised to the 0 power is equal to 1. If the given exponent is negative, this method acts as if <code>this.reciprocal().pow(-exponent)</code> was called. * * @param exponent the power to which to raise this Fraction * @return a new Fraction raised to the given power */ public Fraction pow (int exponent) { // Math.pow will return non-integer results for negative exponents, so we take the reciprocal here first if (exponent < 0) { return reciprocal().pow(-exponent); } if (exponent == 0) { return new Fraction(1, 1); } return new Fraction((int) Math.pow(getImproperNumerator(), exponent), (int) Math.pow(denominator, exponent)); } /** * Finds the reciprocal (multiplicative inverse) of a Fraction. The new Fraction is canonicalized, so it may be the case that <code>fraction.getNumerator() != fraction.reciprocal().getDenominator()</code>. * * @return a new Fraction representing the denominator of this Fraction divided by the numerator */ public Fraction reciprocal () { return new Fraction(denominator, getImproperNumerator()); } /** * Adds an integer to a Fraction. * * @param augend the integer to add to this Fraction * @return a new Fraction representing the result of <code>(this + augend)</code> */ public Fraction add (int augend) { return new Fraction(getImproperNumerator() + augend * denominator, denominator); } /** * Adds two Fractions together. * * @param augend the Fraction to which to add this one * @return a new Fraction representing the result of <code>(this + augend)</code> */ public Fraction add (Fraction augend) { int lcm = GcdUtils.lcm(denominator, augend.getDenominator()); int multiplyA = lcm / denominator; int multiplyB = lcm / augend.getDenominator(); int numA = getImproperNumerator(); int numB = augend.getImproperNumerator(); return new Fraction(numA * multiplyA + numB * multiplyB, lcm); } /** * Subtracts an integer from a Fraction. * * @param subtrahend the integer to subtract from this Fraction * @return a new Fraction representing the result of <code>(this - subtrahend)</code> */ public Fraction subtract (int subtrahend) { return add(-subtrahend); } /** * Subtracts two Fractions. * * @param subtrahend the Fraction to subtract from this Fraction * @return a new Fraction representing the result of <code>(this - subtrahend)</code> */ public Fraction subtract (Fraction subtrahend) { return add(subtrahend.negative()); } }
package com.zbar.lib; /** * * : zbar */ public class ZbarManager { static { // System.loadLibrary("zbar"); System.load("data/data/com.vondear.rxtools/lib/libzbar.so"); System.load("data/data/com.vondear.rxtools/lib/libZBarDecoder.so"); } public native String decode(byte[] data, int width, int height, boolean isCrop, int x, int y, int cwidth, int cheight); }
package org.xdi.oxauth.auth; import java.io.Serializable; import java.security.Principal; import java.util.List; import java.util.Map; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import org.apache.commons.lang.StringUtils; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.contexts.Context; import org.jboss.seam.contexts.Contexts; import org.jboss.seam.core.Events; import org.jboss.seam.faces.FacesManager; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.international.StatusMessage.Severity; import org.jboss.seam.log.Log; import org.jboss.seam.security.Identity; import org.jboss.seam.security.SimplePrincipal; import org.xdi.model.AuthenticationScriptUsageType; import org.xdi.model.custom.script.conf.CustomScriptConfiguration; import org.xdi.oxauth.model.common.SessionId; import org.xdi.oxauth.model.common.SessionIdState; import org.xdi.oxauth.model.common.User; import org.xdi.oxauth.model.config.ConfigurationFactory; import org.xdi.oxauth.model.config.Constants; import org.xdi.oxauth.model.jwt.JwtClaimName; import org.xdi.oxauth.model.session.OAuthCredentials; import org.xdi.oxauth.service.AuthenticationService; import org.xdi.oxauth.service.ClientService; import org.xdi.oxauth.service.SessionIdService; import org.xdi.oxauth.service.external.ExternalAuthenticationService; import org.xdi.util.StringHelper; /** * Authenticator component * * @author Javier Rojas Blum * @author Yuriy Movchan * @version 0.9 January 29, 2015 */ @Name("authenticator") @Scope(ScopeType.EVENT) // Do not change scope, we try to keep server without http sessions public class Authenticator implements Serializable { private static final long serialVersionUID = 669395320060928092L; @Logger private Log log; @In private Identity identity; @In private OAuthCredentials credentials; @In private ClientService clientService; @In private SessionIdService sessionIdService; @In private AuthenticationService authenticationService; @In private ExternalAuthenticationService externalAuthenticationService; @In private FacesMessages facesMessages; private String authAcr; private Integer authStep; private boolean addedErrorMessage; /** * Tries to authenticate an user, returns <code>true</code> if the * authentication succeed * * @return Returns <code>true</code> if the authentication succeed */ public boolean authenticate() { if (!authenticateImpl(Contexts.getEventContext(), true, false)) { return authenticationFailed(); } else { return true; } } public String authenticateWithOutcome() { boolean result = authenticateImpl(Contexts.getEventContext(), true, false); if (result) { return Constants.RESULT_SUCCESS; } else { return Constants.RESULT_FAILURE; } } public boolean authenticateWebService(boolean skipPassword) { return authenticateImpl(getWebServiceContext(), false, skipPassword); } public boolean authenticateWebService() { return authenticateImpl(getWebServiceContext(), false, false); } public Context getWebServiceContext() { return Contexts.getEventContext(); } public boolean authenticateImpl(Context context, boolean interactive, boolean skipPassword) { boolean authenticated = false; try { if (StringHelper.isNotEmpty(credentials.getUsername()) && (skipPassword || StringHelper.isNotEmpty(credentials.getPassword())) && credentials.getUsername().startsWith("@!")) { authenticated = clientAuthentication(context, interactive, skipPassword); } else { if (interactive) { authenticated = userAuthenticationInteractive(); } else { authenticated = userAuthenticationService(); } } } catch (Exception ex) { log.error(ex.getMessage(), ex); } if (authenticated) { log.trace("Authentication successfully for '{0}'", credentials.getUsername()); return true; } log.info("Authentication failed for '{0}'", credentials.getUsername()); return false; } private boolean clientAuthentication(Context context, boolean interactive, boolean skipPassword) { boolean isServiceUsesExternalAuthenticator = !interactive && externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.SERVICE); if (isServiceUsesExternalAuthenticator) { CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService .determineCustomScriptConfiguration(AuthenticationScriptUsageType.SERVICE, 1, this.authAcr); if (customScriptConfiguration == null) { log.error("Failed to get CustomScriptConfiguration. acr: '{0}'", this.authAcr); } else { this.authAcr = customScriptConfiguration.getCustomScript().getName(); boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, null, 1); log.info("Authentication result for user '{0}', result: '{1}'", credentials.getUsername(), result); if (result) { authenticationService.configureSessionClient(context); log.info("Authentication success for client: '{0}'", credentials.getUsername()); return true; } } } boolean loggedIn = skipPassword; if (!loggedIn) { loggedIn = clientService.authenticate(credentials.getUsername(), credentials.getPassword()); } if (loggedIn) { authenticationService.configureSessionClient(context); log.info("Authentication success for Client: '{0}'", credentials.getUsername()); return true; } return false; } private boolean userAuthenticationInteractive() { SessionId sessionId = sessionIdService.getSessionId(); Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId); if (sessionIdAttributes == null) { log.error("Failed to get session attributes"); authenticationFailedSessionInvalid(); return false; } // Set in event context sessionAttributes to allow access them from external authenticator Context eventContext = Contexts.getEventContext(); eventContext.set("sessionAttributes", sessionIdAttributes); initCustomAuthenticatorVariables(sessionIdAttributes); boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE); if (useExternalAuthenticator && !StringHelper.isEmpty(this.authAcr)) { initCustomAuthenticatorVariables(sessionIdAttributes); if ((this.authStep == null) || StringHelper.isEmpty(this.authAcr)) { log.error("Failed to determine authentication mode"); authenticationFailedSessionInvalid(); return false; } ExternalContext extCtx = FacesContext.getCurrentInstance().getExternalContext(); CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, this.authAcr); if (customScriptConfiguration == null) { log.error("Failed to get CustomScriptConfiguration for acr: '{1}', auth_step: '{0}'", this.authAcr, this.authStep); return false; } // Check if all previous steps had passed boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep); if (!passedPreviousSteps) { log.error("There are authentication steps not marked as passed. acr: '{1}', auth_step: '{0}'", this.authAcr, this.authStep); return false; } boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, extCtx.getRequestParameterValuesMap(), this.authStep); log.debug("Authentication result for user '{0}'. auth_step: '{1}', result: '{2}'", credentials.getUsername(), this.authStep, result); if (!result) { return false; } int countAuthenticationSteps = externalAuthenticationService.executeExternalGetCountAuthenticationSteps(customScriptConfiguration); if (this.authStep < countAuthenticationSteps) { final int nextStep = this.authStep + 1; String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, nextStep); if (StringHelper.isEmpty(redirectTo)) { return false; } // Store/Update extra parameters in session attributes map List<String> extraParameters = externalAuthenticationService.executeExternalGetExtraParametersForStep(customScriptConfiguration, nextStep); if (extraParameters != null) { for (String extraParameter : extraParameters) { String extraParameterValue = authenticationService.getParameterValue(extraParameter); sessionIdAttributes.put(extraParameter, extraParameterValue); } } // Update auth_step sessionIdAttributes.put("auth_step", Integer.toString(nextStep)); // Mark step as passed markAuthStepAsPassed(sessionIdAttributes, this.authStep); if (sessionId != null) { sessionId.setSessionAttributes(sessionIdAttributes); boolean updateResult = sessionIdService.updateSessionId(sessionId, true, true); if (!updateResult) { log.debug("Failed to update session entry: '{0}'", sessionId.getId()); return false; } } log.trace("Redirect to page: '{0}'", redirectTo); FacesManager.instance().redirect(redirectTo, null, false); return false; } if (this.authStep == countAuthenticationSteps) { authenticationService.configureSessionUser(sessionId, sessionIdAttributes); Principal principal = new SimplePrincipal(credentials.getUsername()); identity.acceptExternallyAuthenticatedPrincipal(principal); identity.quietLogin(); // Redirect to authorization workflow if (Events.exists()) { log.debug("Sending event to trigger user redirection: '{0}'", credentials.getUsername()); Events.instance().raiseEvent(Constants.EVENT_OXAUTH_CUSTOM_LOGIN_SUCCESSFUL); } log.info("Authentication success for User: '{0}'", credentials.getUsername()); return true; } } else { if (StringHelper.isNotEmpty(credentials.getUsername())) { boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword()); if (authenticated) { authenticationService.configureSessionUser(sessionId, sessionIdAttributes); // Redirect to authorization workflow if (Events.exists()) { log.debug("Sending event to trigger user redirection: '{0}'", credentials.getUsername()); Events.instance().raiseEvent(Constants.EVENT_OXAUTH_CUSTOM_LOGIN_SUCCESSFUL); } log.info("Authentication success for User: '{0}'", credentials.getUsername()); return true; } } } return false; } private boolean userAuthenticationService() { if (externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.SERVICE)) { CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService .determineCustomScriptConfiguration(AuthenticationScriptUsageType.SERVICE, 1, this.authAcr); if (customScriptConfiguration == null) { log.error("Failed to get CustomScriptConfiguration. auth_step: '{0}', acr: '{1}'", this.authStep, this.authAcr); } else { this.authAcr = customScriptConfiguration.getName(); boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, null, 1); log.info("Authentication result for '{0}'. auth_step: '{1}', result: '{2}'", credentials.getUsername(), this.authStep, result); if (result) { authenticateExternallyWebService(credentials.getUsername()); authenticationService.configureEventUser(); log.info("Authentication success for User: '{0}'", credentials.getUsername()); return true; } } } if (StringHelper.isNotEmpty(credentials.getUsername())) { boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword()); if (authenticated) { authenticateExternallyWebService(credentials.getUsername()); authenticationService.configureEventUser(); log.info("Authentication success for User: '{0}'", credentials.getUsername()); return true; } } return false; } public String prepareAuthenticationForStep() { SessionId sessionId = sessionIdService.getSessionId(); Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId); if (sessionIdAttributes == null) { log.error("Failed to get attributes from session"); return Constants.RESULT_EXPIRED; } // Set in event context sessionAttributs to allow access them from external authenticator Context eventContext = Contexts.getEventContext(); eventContext.set("sessionAttributes", sessionIdAttributes); if (!externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE)) { return Constants.RESULT_SUCCESS; } initCustomAuthenticatorVariables(sessionIdAttributes); if (StringHelper.isEmpty(this.authAcr)) { return Constants.RESULT_SUCCESS; } if ((this.authStep == null) || (this.authStep < 1)) { return Constants.RESULT_NO_PERMISSIONS; } CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration( AuthenticationScriptUsageType.INTERACTIVE, this.authAcr); if (customScriptConfiguration == null) { log.error("Failed to get CustomScriptConfiguration. auth_step: '{0}', acr: '{1}'", this.authStep, this.authAcr); return Constants.RESULT_FAILURE; } String currentauthAcr = customScriptConfiguration.getName(); customScriptConfiguration = externalAuthenticationService.determineExternalAuthenticatorForWorkflow( AuthenticationScriptUsageType.INTERACTIVE, customScriptConfiguration); if (customScriptConfiguration == null) { return Constants.RESULT_FAILURE; } else { String determinedauthAcr = customScriptConfiguration.getName(); if (!StringHelper.equalsIgnoreCase(currentauthAcr, determinedauthAcr)) { // Redirect user to alternative login workflow String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, this.authStep); if (StringHelper.isEmpty(redirectTo)) { redirectTo = "/login.xhtml"; } CustomScriptConfiguration determinedCustomScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration( AuthenticationScriptUsageType.INTERACTIVE, determinedauthAcr); if (determinedCustomScriptConfiguration == null) { log.error("Failed to get determined CustomScriptConfiguration. auth_step: '{0}', acr: '{1}'", this.authStep, this.authAcr); return Constants.RESULT_FAILURE; } log.debug("Redirect to page: '{0}'. Force to use acr: '{1}'", redirectTo, determinedauthAcr); determinedauthAcr = determinedCustomScriptConfiguration.getName(); String determinedAuthLevel = Integer.toString(determinedCustomScriptConfiguration.getLevel()); sessionIdAttributes.put("acr", determinedauthAcr); sessionIdAttributes.put("auth_level", determinedAuthLevel); sessionIdAttributes.put("auth_step", Integer.toString(1)); if (sessionId != null) { sessionId.setSessionAttributes(sessionIdAttributes); boolean updateResult = sessionIdService.updateSessionId(sessionId, true, true); if (!updateResult) { log.debug("Failed to update session entry: '{0}'", sessionId.getId()); return Constants.RESULT_EXPIRED; } } FacesManager.instance().redirect(redirectTo, null, false); return Constants.RESULT_SUCCESS; } } // Check if all previous steps had passed boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep); if (!passedPreviousSteps) { log.error("There are authentication steps not marked as passed. acr: '{1}', auth_step: '{0}'", this.authAcr, this.authStep); return Constants.RESULT_FAILURE; } ExternalContext extCtx = FacesContext.getCurrentInstance().getExternalContext(); Boolean result = externalAuthenticationService.executeExternalPrepareForStep(customScriptConfiguration, extCtx.getRequestParameterValuesMap(), this.authStep); if ((result != null) && result) { return Constants.RESULT_SUCCESS; } else { return Constants.RESULT_FAILURE; } } public void authenticateExternallyWebService(String userName) { org.jboss.seam.resteasy.Application application = (org.jboss.seam.resteasy.Application) Component.getInstance(org.jboss.seam.resteasy.Application.class); if ((application != null) && !application.isDestroySessionAfterRequest()) { Principal principal = new SimplePrincipal(userName); identity.acceptExternallyAuthenticatedPrincipal(principal); identity.quietLogin(); } } public boolean authenticateBySessionId(String p_sessionId) { if (StringUtils.isNotBlank(p_sessionId) && ConfigurationFactory.instance().getConfiguration().getSessionIdEnabled()) { try { SessionId sessionId = sessionIdService.getSessionId(p_sessionId); return authenticateBySessionId(sessionId); } catch (Exception e) { log.trace(e.getMessage(), e); } } return false; } public boolean authenticateBySessionId(SessionId sessionId) { if (sessionId == null) { return false; } String p_sessionId = sessionId.getId(); log.trace("authenticateBySessionId, sessionId = '{0}', session = '{1}', state= '{2}'", p_sessionId, sessionId, sessionId.getState()); // IMPORTANT : authenticate by session id only if state of session is authenticated! if (SessionIdState.AUTHENTICATED == sessionId.getState()) { final User user = authenticationService.getUserOrRemoveSession(sessionId); if (user != null) { try { authenticateExternallyWebService(user.getUserId()); authenticationService.configureEventUser(sessionId); } catch (Exception e) { log.trace(e.getMessage(), e); } return true; } } return false; } private void initCustomAuthenticatorVariables(Map<String, String> sessionIdAttributes) { if (sessionIdAttributes == null) { log.error("Failed to restore attributes from session attributes"); return; } this.authStep = StringHelper.toInteger(sessionIdAttributes.get("auth_step"), null); this.authAcr = sessionIdAttributes.get(JwtClaimName.AUTHENTICATION_METHOD_REFERENCES); } private boolean authenticationFailed() { if (!this.addedErrorMessage) { facesMessages.addFromResourceBundle(Severity.ERROR, "login.errorMessage"); } return false; } private void authenticationFailedSessionInvalid() { this.addedErrorMessage = true; facesMessages.addFromResourceBundle(Severity.ERROR, "login.errorSessionInvalidMessage"); FacesManager.instance().redirect("/error.xhtml"); } private void markAuthStepAsPassed(Map<String, String> sessionIdAttributes, Integer authStep) { String key = String.format("auth_step_passed_%d", authStep); sessionIdAttributes.put(key, Boolean.TRUE.toString()); } private boolean isAuthStepPassed(Map<String, String> sessionIdAttributes, Integer authStep) { String key = String.format("auth_step_passed_%d", authStep); if (sessionIdAttributes.containsKey(key) && Boolean.parseBoolean(sessionIdAttributes.get(key))) { return true; } return false; } private boolean isPassedPreviousAuthSteps(Map<String, String> sessionIdAttributes, Integer authStep) { for (int i = 1; i < authStep; i++) { boolean isAuthStepPassed = isAuthStepPassed(sessionIdAttributes, i); if (!isAuthStepPassed) { return false; } } return true; } }
package org.xdi.oxauth.auth; import java.io.Serializable; import java.security.Principal; import java.util.List; import java.util.Map; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import org.apache.commons.lang.StringUtils; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.web.RequestParameter; import org.jboss.seam.contexts.Context; import org.jboss.seam.contexts.Contexts; import org.jboss.seam.core.Events; import org.jboss.seam.faces.FacesManager; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.international.StatusMessage.Severity; import org.jboss.seam.log.Log; import org.jboss.seam.security.Identity; import org.jboss.seam.security.SimplePrincipal; import org.xdi.model.AuthenticationScriptUsageType; import org.xdi.model.custom.script.conf.CustomScriptConfiguration; import org.xdi.oxauth.model.common.SessionId; import org.xdi.oxauth.model.common.SessionIdState; import org.xdi.oxauth.model.common.User; import org.xdi.oxauth.model.config.ConfigurationFactory; import org.xdi.oxauth.model.config.Constants; import org.xdi.oxauth.model.jwt.JwtClaimName; import org.xdi.oxauth.model.session.OAuthCredentials; import org.xdi.oxauth.service.AuthenticationService; import org.xdi.oxauth.service.ClientService; import org.xdi.oxauth.service.SessionIdService; import org.xdi.oxauth.service.UserService; import org.xdi.oxauth.service.external.ExternalAuthenticationService; import org.xdi.util.StringHelper; /** * Authenticator component * * @author Javier Rojas Blum * @author Yuriy Movchan * @version 0.9 January 29, 2015 */ @Name("authenticator") @Scope(ScopeType.EVENT) // Do not change scope, we try to keep server without http sessions public class Authenticator implements Serializable { private static final long serialVersionUID = 669395320060928092L; @Logger private Log log; @In private Identity identity; @In private OAuthCredentials credentials; @In private UserService userService; @In private ClientService clientService; @In private SessionIdService sessionIdService; @In private AuthenticationService authenticationService; @In private ExternalAuthenticationService externalAuthenticationService; @In private FacesMessages facesMessages; @RequestParameter("auth_level") private String authLevel; @RequestParameter("auth_mode") private String authMode; @RequestParameter(JwtClaimName.AUTHENTICATION_METHOD_REFERENCES) private String authAcr; private Integer authStep; private boolean addedErrorMessage; /** * Tries to authenticate an user, returns <code>true</code> if the * authentication succeed * * @return Returns <code>true</code> if the authentication succeed */ public boolean authenticate() { if (!authenticateImpl(Contexts.getEventContext(), true)) { return authenticationFailed(); } else { return true; } } public String authenticateWithOutcome() { boolean result = authenticateImpl(Contexts.getEventContext(), true); if (result) { return Constants.RESULT_SUCCESS; } else { return Constants.RESULT_FAILURE; } } public boolean authenticateWebService() { return authenticateImpl(getWebServiceContext(), false); } public Context getWebServiceContext() { return Contexts.getEventContext(); } public boolean authenticateImpl(Context context, boolean interactive) { if (!interactive) { setAuthModeFromAcr(); } boolean authenticated = false; try { if (StringHelper.isNotEmpty(credentials.getUsername()) && StringHelper.isNotEmpty(credentials.getPassword()) && credentials.getUsername().startsWith("@!")) { authenticated = clientAuthentication(context, interactive); } else { if (interactive) { authenticated = userAuthenticationInteractive(); } else { authenticated = userAuthenticationService(); } } } catch (Exception ex) { log.error(ex.getMessage(), ex); } if (authenticated) { log.trace("Authentication successfully for '{0}'", credentials.getUsername()); return true; } log.info("Authentication failed for '{0}'", credentials.getUsername()); return false; } private boolean clientAuthentication(Context context, boolean interactive) { boolean isServiceUsesExternalAuthenticator = !interactive && externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.SERVICE); if (isServiceUsesExternalAuthenticator) { CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService .determineCustomScriptConfiguration(AuthenticationScriptUsageType.SERVICE, 1, this.authLevel, this.authMode); if (customScriptConfiguration == null) { log.error("Failed to get CustomScriptConfiguration. auth_mode: '{0}', auth_level: '{1}'", this.authMode, authLevel); } else { this.authMode = customScriptConfiguration.getCustomScript().getName(); boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, null, 1); log.info("Authentication result for user '{0}', result: '{1}'", credentials.getUsername(), result); if (result) { authenticationService.configureSessionClient(context); log.info("Authentication success for client: '{0}'", credentials.getUsername()); return true; } } } boolean loggedIn = clientService.authenticate(credentials.getUsername(), credentials.getPassword()); if (loggedIn) { authenticationService.configureSessionClient(context); log.info("Authentication success for Client: '{0}'", credentials.getUsername()); return true; } return false; } private boolean userAuthenticationInteractive() { SessionId sessionId = sessionIdService.getSessionId(); Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId); if (sessionIdAttributes == null) { log.error("Failed to get session attributes"); authenticationFailedSessionInvalid(); return false; } if (externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE)) { initCustomAuthenticatorVariables(sessionIdAttributes); if ((this.authStep == null) || StringHelper.isEmpty(this.authMode)) { log.error("Failed to determine authentication mode"); authenticationFailedSessionInvalid(); return false; } ExternalContext extCtx = FacesContext.getCurrentInstance().getExternalContext(); CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, this.authMode); if (customScriptConfiguration == null) { log.error("Failed to get CustomScriptConfiguration for auth_mode: '{1}', auth_step: '{0}'", this.authMode, this.authStep); return false; } // Check if all previous steps had passed boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep); if (!passedPreviousSteps) { log.error("There are authentication steps not marked as passed. auth_mode: '{1}', auth_step: '{0}'", this.authMode, this.authStep); return false; } // Set in event context sessionAttributs to allow access them from external authenticator Context eventContext = Contexts.getEventContext(); eventContext.set("sessionAttributes", sessionIdAttributes); boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, extCtx.getRequestParameterValuesMap(), this.authStep); log.debug("Authentication result for user '{0}'. auth_step: '{1}', result: '{2}'", credentials.getUsername(), this.authStep, result); if (!result) { return false; } int countAuthenticationSteps = externalAuthenticationService.executeExternalGetCountAuthenticationSteps(customScriptConfiguration); if (this.authStep < countAuthenticationSteps) { final int nextStep = this.authStep + 1; String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, nextStep); if (StringHelper.isEmpty(redirectTo)) { return false; } // Store/Update extra parameters in session attributes map List<String> extraParameters = externalAuthenticationService.executeExternalGetExtraParametersForStep(customScriptConfiguration, nextStep); if (extraParameters != null) { for (String extraParameter : extraParameters) { String extraParameterValue = authenticationService.getParameterValue(extraParameter); sessionIdAttributes.put(extraParameter, extraParameterValue); } } // Update auth_step sessionIdAttributes.put("auth_step", Integer.toString(nextStep)); // Mark step as passed markAuthStepAsPassed(sessionIdAttributes, this.authStep); if (sessionId != null) { sessionId.setSessionAttributes(sessionIdAttributes); boolean updateResult = sessionIdService.updateSessionId(sessionId, true, true); if (!updateResult) { log.debug("Failed to update session entry: '{0}'", sessionId.getId()); return false; } } log.trace("Redirect to page: '{0}'", redirectTo); FacesManager.instance().redirect(redirectTo, null, false); return false; } if (this.authStep == countAuthenticationSteps) { authenticationService.configureSessionUser(sessionId, sessionIdAttributes); Principal principal = new SimplePrincipal(credentials.getUsername()); identity.acceptExternallyAuthenticatedPrincipal(principal); identity.quietLogin(); // Redirect to authorization workflow if (Events.exists()) { log.debug("Sending event to trigger user redirection: '{0}'", credentials.getUsername()); Events.instance().raiseEvent(Constants.EVENT_OXAUTH_CUSTOM_LOGIN_SUCCESSFUL); } log.info("Authentication success for User: '{0}'", credentials.getUsername()); return true; } } else { if (StringHelper.isNotEmpty(credentials.getUsername())) { boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword()); if (authenticated) { authenticationService.configureSessionUser(sessionId, sessionIdAttributes); // Redirect to authorization workflow if (Events.exists()) { log.debug("Sending event to trigger user redirection: '{0}'", credentials.getUsername()); Events.instance().raiseEvent(Constants.EVENT_OXAUTH_CUSTOM_LOGIN_SUCCESSFUL); } log.info("Authentication success for User: '{0}'", credentials.getUsername()); return true; } } } return false; } private boolean userAuthenticationService() { if (externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.SERVICE)) { CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService .determineCustomScriptConfiguration(AuthenticationScriptUsageType.SERVICE, 1, this.authLevel, this.authMode); if (customScriptConfiguration == null) { log.error("Failed to get CustomScriptConfiguration. auth_step: '{0}', auth_mode: '{1}', auth_level: '{2}'", this.authStep, this.authMode, authLevel); } else { this.authMode = customScriptConfiguration.getName(); boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, null, 1); log.info("Authentication result for '{0}'. auth_step: '{1}', result: '{2}'", credentials.getUsername(), this.authStep, result); if (result) { authenticateExternallyWebService(credentials.getUsername()); authenticationService.configureEventUser(); log.info("Authentication success for User: '{0}'", credentials.getUsername()); return true; } } } if (StringHelper.isNotEmpty(credentials.getUsername())) { boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword()); if (authenticated) { authenticateExternallyWebService(credentials.getUsername()); authenticationService.configureEventUser(); log.info("Authentication success for User: '{0}'", credentials.getUsername()); return true; } } return false; } public String prepareAuthenticationForStep() { if (!externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE)) { return Constants.RESULT_SUCCESS; } SessionId sessionId = sessionIdService.getSessionId(); Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId); if (sessionIdAttributes == null) { log.error("Failed to get attributes from session"); return Constants.RESULT_EXPIRED; } initCustomAuthenticatorVariables(sessionIdAttributes); if (StringHelper.isEmpty(this.authMode)) { return Constants.RESULT_SUCCESS; } if ((this.authStep == null) || (this.authStep < 1)) { return Constants.RESULT_NO_PERMISSIONS; } CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration( AuthenticationScriptUsageType.INTERACTIVE, this.authMode); if (customScriptConfiguration == null) { log.error("Failed to get CustomScriptConfiguration. auth_step: '{0}', auth_mode: '{1}'", this.authStep, this.authMode); return Constants.RESULT_FAILURE; } String currentAuthMode = customScriptConfiguration.getName(); customScriptConfiguration = externalAuthenticationService.determineExternalAuthenticatorForWorkflow( AuthenticationScriptUsageType.INTERACTIVE, customScriptConfiguration); if (customScriptConfiguration == null) { return Constants.RESULT_FAILURE; } else { // Set in event context sessionAttributs to allow access them from external authenticator Context eventContext = Contexts.getEventContext(); eventContext.set("sessionAttributes", sessionIdAttributes); String determinedAuthMode = customScriptConfiguration.getName(); if (!StringHelper.equalsIgnoreCase(currentAuthMode, determinedAuthMode)) { // Redirect user to alternative login workflow String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, this.authStep); if (StringHelper.isEmpty(redirectTo)) { redirectTo = "/login.xhtml"; } CustomScriptConfiguration determinedCustomScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration( AuthenticationScriptUsageType.INTERACTIVE, determinedAuthMode); if (determinedCustomScriptConfiguration == null) { log.error("Failed to get determined CustomScriptConfiguration. auth_step: '{0}', auth_mode: '{1}'", this.authStep, this.authMode); return Constants.RESULT_FAILURE; } log.debug("Redirect to page: '{0}'. Force to use auth_mode: '{1}'", redirectTo, determinedAuthMode); determinedAuthMode = determinedCustomScriptConfiguration.getName(); String determinedAuthLevel = Integer.toString(determinedCustomScriptConfiguration.getLevel()); sessionIdAttributes.put("auth_mode", determinedAuthMode); sessionIdAttributes.put("auth_level", determinedAuthLevel); sessionIdAttributes.put("auth_step", Integer.toString(1)); if (sessionId != null) { sessionId.setSessionAttributes(sessionIdAttributes); boolean updateResult = sessionIdService.updateSessionId(sessionId, true, true); if (!updateResult) { log.debug("Failed to update session entry: '{0}'", sessionId.getId()); return Constants.RESULT_EXPIRED; } } FacesManager.instance().redirect(redirectTo, null, false); return Constants.RESULT_SUCCESS; } } // Check if all previous steps had passed boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep); if (!passedPreviousSteps) { log.error("There are authentication steps not marked as passed. auth_mode: '{1}', auth_step: '{0}'", this.authMode, this.authStep); return Constants.RESULT_FAILURE; } ExternalContext extCtx = FacesContext.getCurrentInstance().getExternalContext(); Boolean result = externalAuthenticationService.executeExternalPrepareForStep(customScriptConfiguration, extCtx.getRequestParameterValuesMap(), this.authStep); if ((result != null) && result) { return Constants.RESULT_SUCCESS; } else { return Constants.RESULT_FAILURE; } } public void authenticateExternallyWebService(String userName) { org.jboss.seam.resteasy.Application application = (org.jboss.seam.resteasy.Application) Component.getInstance(org.jboss.seam.resteasy.Application.class); if ((application != null) && !application.isDestroySessionAfterRequest()) { Principal principal = new SimplePrincipal(userName); identity.acceptExternallyAuthenticatedPrincipal(principal); identity.quietLogin(); } } public boolean authenticateBySessionId(String p_sessionId) { if (StringUtils.isNotBlank(p_sessionId) && ConfigurationFactory.getConfiguration().getSessionIdEnabled()) { try { SessionId sessionId = sessionIdService.getSessionId(p_sessionId); return authenticateBySessionId(sessionId); } catch (Exception e) { log.trace(e.getMessage(), e); } } return false; } public boolean authenticateBySessionId(SessionId sessionId) { String p_sessionId = sessionId.getId(); log.trace("authenticateBySessionId, sessionId = '{0}', session = '{1}', state= '{2}'", p_sessionId, sessionId, sessionId != null ? sessionId.getState() : ""); // IMPORTANT : authenticate by session id only if state of session is authenticated! if (sessionId != null && (SessionIdState.AUTHENTICATED == sessionId.getState())) { final User user = authenticationService.getUserOrRemoveSession(sessionId); if (user != null) { try { authenticateExternallyWebService(user.getUserId()); authenticationService.configureEventUser(sessionId); } catch (Exception e) { log.trace(e.getMessage(), e); } return true; } } return false; } private void initCustomAuthenticatorVariables(Map<String, String> sessionIdAttributes) { if (sessionIdAttributes == null) { log.error("Failed to restore attributes from session attributes"); return; } this.authStep = StringHelper.toInteger(sessionIdAttributes.get("auth_step"), null); this.authMode = sessionIdAttributes.get("auth_mode"); this.authLevel = null; } private boolean authenticationFailed() { if (!this.addedErrorMessage) { facesMessages.addFromResourceBundle(Severity.ERROR, "login.errorMessage"); } return false; } private void authenticationFailedSessionInvalid() { this.addedErrorMessage = true; facesMessages.addFromResourceBundle(Severity.ERROR, "login.errorSessionInvalidMessage"); FacesManager.instance().redirect("/error.xhtml"); } private void setAuthModeFromAcr() { if (StringHelper.isNotEmpty(this.authAcr)) { this.authMode = this.authAcr; } } private void markAuthStepAsPassed(Map<String, String> sessionIdAttributes, Integer authStep) { String key = String.format("auth_step_passed_%d", authStep); sessionIdAttributes.put(key, Boolean.TRUE.toString()); } private boolean isAuthStepPassed(Map<String, String> sessionIdAttributes, Integer authStep) { String key = String.format("auth_step_passed_%d", authStep); if (sessionIdAttributes.containsKey(key) && Boolean.parseBoolean(sessionIdAttributes.get(key))) { return true; } return false; } private boolean isPassedPreviousAuthSteps(Map<String, String> sessionIdAttributes, Integer authStep) { for (int i = 1; i < authStep; i++) { boolean isAuthStepPassed = isAuthStepPassed(sessionIdAttributes, i); if (!isAuthStepPassed) { return false; } } return true; } }
package com.simplepl.grammar; import com.simplepl.grammar.matchers.JavaUnicodeMatcherStartString; import com.simplepl.grammar.matchers.JavaUnicodeMatcherString; import org.parboiled.Rule; /** * @author Dmitry */ public class MainParser extends MainParserActions { public Rule main() { return ZeroOrMore(line()); } public Rule line() { return expression(); } public Rule functionRule() { return Sequence( functionDeclaration(), FirstOf( expressionsBlock(), actionFail("Expected function body {...} after function declaration") ) ); } public Rule testFunctionRule() { return Sequence(functionRule(), EOI); } public Rule expressionsBlock() { return Sequence( openCurleyBracket(), expressionsEndsWithSemicolon(), closeCurleyBracket() ); } public Rule expressionsEndsWithSemicolon() { return ZeroOrMore( Sequence( expression(), FirstOf( semicolon(), actionFail("Expected ';' after the expression") ) ) ); } public Rule expressionsSeparatedWithComma() { return Optional( Sequence( expression(), ZeroOrMore( comma(), expression() ) ) ); } public Rule expression() { return FirstOf( functionRule(), structure(), declareArray(), declareVariableAndAssign(), declareVariable(), checkExpression() // actionFail("Cannot parse the expression") ); } public Rule testFunctionCall() { return Sequence(functionCall(), EOI); } public Rule functionCall() { return Sequence( identifier(), openBracket(), expressionsSeparatedWithComma(), closeBracket() ); } public Rule functionDeclaration() { return Sequence( keyword(FUN), FirstOf( identifier(), actionFail("Expected function name") ), FirstOf( openBracket(), actionFail("Expected open bracket") ), argumentList(), FirstOf( closeBracket(), actionFail("Expected close bracket") ) ); } public Rule testDeclareVariable() { return Sequence(declareVariable(), EOI); } public Rule declareVariable() { return Sequence( typeIdentifier(), identifier() ); } public Rule declareVariableWithSemicolon() { return Sequence(declareVariable(), semicolon()); } public Rule testDeclareArray() { return Sequence(declareArray(), EOI); } public Rule declareArray() { return Sequence( typeIdentifier(), arrayDeclarerSquares(), FirstOf( identifier(), actionFail("Expected variable name of the array") ) ); } public Rule declareVariableAndAssign() { return Sequence( declareVariable(), assign(), FirstOf( expression(), actionFail("Expected expression assigned to variable") ) ); } public Rule arrayDeclarerSquares() { return OneOrMore( openSquareBracket(), FirstOf( closeSquareBracket(), actionFail("Expected ']' that closes array mark") ) ); } public Rule number() { return Sequence( Sequence( Optional('-'), OneOrMore(Digit()), Optional('.', OneOrMore(Digit())) ), possibleSpace() ).suppressSubnodes(); } public Rule Digit() { return Sequence(possibleSpace(), OneOrMore(CharRange('0', '9')), possibleSpace()); } public Rule testGenericStringRule() { return Sequence(genericStringRule(), EOI); } public Rule genericStringRule() { return Sequence( '"', ZeroOrMore( FirstOf( Sequence( EOI, actionFail("Found end of line while reading string")), Escape(), Sequence(TestNot("\""), ANY) ) ).suppressSubnodes(), '"' ); } public Rule testRawStringRule() { return Sequence(rawStringRule(), EOI); } public Rule rawStringRule() { return Sequence( "\"\"\"", ZeroOrMore( FirstOf( Sequence( EOI, actionFail("Found end of line while reading string") ), Sequence(TestNot("\"\"\""), ANY) ) ).suppressSubnodes(), "\"\"\"" ); } Rule Escape() { return Sequence( '\\', AnyOf("btnfr\"\'\\") ); } public Rule argumentList() { return Optional( Sequence( declareVariable(), ZeroOrMore( comma(), FirstOf( declareVariable(), actionFail("Expected argument declaration") ) ) ) ); } public Rule checkExpression() { return FirstOf( Sequence( keyword("!"), FirstOf( checkExpression(), actionFail("Expected expression after 'not'") ) ), Sequence( equalRule(), ZeroOrMore( FirstOf( keyword("&&"), keyword("||") ), pushHelperString("and/or_operation"), FirstOf( equalRule(), actionFail("after 'and'/'or' should be another expression") ) ) ) ); } public Rule equalRule() { return Sequence( sumRule(), ZeroOrMore( FirstOf(keyword("!="), keyword("="), keyword(">="), keyword("<="), keyword(">"), keyword("<")), FirstOf( sumRule(), actionFail("Expected expression after comparing operation") ) ) ); } public Rule sumRule() { return Sequence( term(), ZeroOrMore( FirstOf(keyword("+"), keyword("-")), FirstOf( term(), actionFail("Expected expression after +/-") ) ) ); } public Rule term() { return Sequence( atom(), ZeroOrMore( FirstOf(keyword("*"), keyword("/")), pushHelperString("* or / operation"), FirstOf( atom(), actionFail("Expected expression after * or /") ) ) ); } public Rule atom() { return FirstOf( number(), booleanValueRule(), functionCall(), variable(), rawStringRule(), genericStringRule(), parens() ); } public Rule variable() { return FirstOf( structVariable(), identifier()); } public Rule simpleVariable() { return identifier(); } public Rule structVariable() { return Sequence( identifier(), OneOrMore( Sequence( keyword("."), identifier() ) ) ); } public Rule booleanValueRule() { return FirstOf( keyword("true"), keyword("false") ); } public Rule parens() { return Sequence( openBracket(), checkExpression(), FirstOf( closeBracket(), actionFail("Expected closing bracket") ) ); } public Rule testStructure() { return Sequence(structure(), EOI); } public Rule structure() { return Sequence( keyword("structure"), FirstOf( identifier(), actionFail("Expected structure name") ), FirstOf( openCurleyBracket(), actionFail("Expected '{' after structure name") ), FirstOf( elementsOfStructure(), actionFail("Expected structure elements inside structure body") ), FirstOf( closeCurleyBracket(), actionFail("Expected '}' at the end of the structure") ) ); } public Rule elementsOfStructure() { return Sequence( declareVariableWithSemicolon(), ZeroOrMore( declareVariableWithSemicolon() ) ); } public Rule oneSpaceCharacter() { return FirstOf(' ', '\t', '\r', '\n'); } public Rule ensureSpace() { return OneOrMore(oneSpaceCharacter()); } public Rule possibleSpace() { return ZeroOrMore(oneSpaceCharacter()); } public Rule identifier() { return Sequence( possibleSpace(), new JavaUnicodeMatcherStartString(), ZeroOrMore( new JavaUnicodeMatcherString()), possibleSpace() ).suppressSubnodes(); } public Rule typeIdentifier() { return identifier(); } public Rule keyword(String val) { return Sequence(possibleSpace(), val, possibleSpace()).suppressSubnodes(); } public Rule openBracket() { return keyword("("); } public Rule closeBracket() { return keyword(")"); } public Rule openCurleyBracket() { return keyword("{"); } public Rule closeCurleyBracket() { return keyword("}"); } public Rule openSquareBracket() { return keyword("["); } public Rule closeSquareBracket() { return keyword("]"); } public Rule assign() { return keyword("="); } public Rule semicolon() { return keyword(";"); } public Rule comma() { return keyword(","); } public Rule STR_TERMINAL(char... character) { return Sequence(ZeroOrMore(NoneOf(character)), character); } public String FUN = "fun"; }
package io.tetrapod.core; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import static io.tetrapod.protocol.core.TetrapodContract.ERROR_UNKNOWN_ENTITY_ID; import java.io.File; import java.io.IOException; import java.security.SecureRandom; import java.util.*; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.buffer.ByteBuf; import io.netty.channel.socket.SocketChannel; import io.tetrapod.core.Session.RelayHandler; import io.tetrapod.core.pubsub.Topic; import io.tetrapod.core.registry.*; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.serialize.datasources.ByteBufDataSource; import io.tetrapod.core.storage.*; import io.tetrapod.core.utils.*; import io.tetrapod.core.web.*; import io.tetrapod.protocol.core.*; import io.tetrapod.protocol.raft.*; import io.tetrapod.protocol.storage.*; /** * The tetrapod service is the core cluster service which handles message routing, cluster management, service discovery, and load balancing * of client connections */ public class TetrapodService extends DefaultService implements TetrapodContract.API, StorageContract.API, RaftContract.API, RelayHandler, EntityRegistry.RegistryBroadcaster { public static final Logger logger = LoggerFactory.getLogger(TetrapodService.class); public final SecureRandom random = new SecureRandom(); private Topic clusterTopic; private Topic servicesTopic; private Topic adminTopic; private final TetrapodWorker worker; protected final TetrapodCluster cluster = new TetrapodCluster(this); public final EntityRegistry registry = new EntityRegistry(this, cluster); private AdminAccounts adminAccounts; private final List<Server> servers = new ArrayList<>(); private final List<Server> httpServers = new ArrayList<>(); private long lastStatsLog; private final LinkedList<Integer> clientSessionsCounter = new LinkedList<>(); public TetrapodService() throws IOException { super(new TetrapodContract()); worker = new TetrapodWorker(this); addContracts(new StorageContract()); addContracts(new RaftContract()); // add tetrapod web routes for (WebRoute r : contract.getWebRoutes()) { getWebRoutes().setRoute(r.path, r.contractId, r.structId); } // add the tetrapod admin web root cluster.getWebRootDirs().put("tetrapod", new WebRootLocalFilesystem("/", new File("webContent"))); addSubscriptionHandler(new TetrapodContract.Registry(), registry); } @Override public void startNetwork(ServerAddress address, String token, Map<String, String> otherOpts) throws Exception { logger.info("***** Start Network ***** "); logger.info("Joining Cluster: {} {}", address.dump(), otherOpts); this.startPaused = otherOpts.get("paused").equals("true"); this.token = token; cluster.init(); scheduleHealthCheck(); } /** * Bootstrap a new cluster by claiming the first id and self-registering */ public void registerSelf(int myEntityId, long reclaimToken) { try { registry.setParentId(myEntityId); this.parentId = this.entityId = myEntityId; this.token = EntityToken.encode(entityId, reclaimToken); EntityInfo me = cluster.getEntity(entityId); if (me == null) { throw new RuntimeException("Not in registry"); } else { this.token = EntityToken.encode(entityId, me.reclaimToken); logger.info(String.format("SELF-REGISTERED: 0x%08X %s", entityId, me)); // update status? } clusterTopic = publishTopic(); servicesTopic = publishTopic(); adminTopic = publishTopic(); // Establish a special loopback connection to ourselves // connects to self on localhost on our clusterport clusterClient.connect("localhost", getClusterPort(), dispatcher).sync(); } catch (Exception ex) { fail(ex); } } @Override public boolean dependenciesReady() { return cluster.isReady(); } /** * We need to override the connectToCluster in superclass because that one tries to reconnect to other tetrapods, but the clusterClient * connection is a special loopback connection in the tetrapod, so we should only ever reconnect back to ourselves. */ @Override protected void connectToCluster(int retrySeconds) { if (!isShuttingDown() && !clusterClient.isConnected()) { try { clusterClient.connect("localhost", getClusterPort(), dispatcher).sync(); } catch (Exception ex) { // something is seriously awry if we cannot connect to ourselves fail(ex); } } } @Override public String getServiceIcon() { return "media/lizard.png"; } @Override public ServiceCommand[] getServiceCommands() { return new ServiceCommand[] { new ServiceCommand("Log Registry Stats", null, LogRegistryStatsRequest.CONTRACT_ID, LogRegistryStatsRequest.STRUCT_ID, false) }; } @Override public byte getEntityType() { return Core.TYPE_TETRAPOD; } public int getServicePort() { return Util.getProperty("tetrapod.service.port", DEFAULT_SERVICE_PORT); } public int getClusterPort() { return Util.getProperty("tetrapod.cluster.port", DEFAULT_CLUSTER_PORT); } public int getPublicPort() { return Util.getProperty("tetrapod.public.port", DEFAULT_PUBLIC_PORT); } public int getHTTPPort() { return Util.getProperty("tetrapod.http.port", DEFAULT_HTTP_PORT); } public int getHTTPSPort() { return Util.getProperty("tetrapod.https.port", DEFAULT_HTTPS_PORT); } @Override public long getCounter() { return cluster.getNumSessions() + servers.stream().mapToInt(Server::getNumSessions).sum(); } private class TypedSessionFactory extends WireSessionFactory { private TypedSessionFactory(byte type) { super(TetrapodService.this, type, new Session.Listener() { @Override public void onSessionStop(Session ses) { onEntityDisconnected(ses); } @Override public void onSessionStart(Session ses) {} }); } /** * Session factory for our sessions from clients and services */ @Override public Session makeSession(SocketChannel ch) { final Session ses = super.makeSession(ch); ses.setRelayHandler(TetrapodService.this); return ses; } } private class WebSessionFactory implements SessionFactory { public WebSessionFactory(Map<String, WebRoot> contentRootMap, String webSockets) { this.webSockets = webSockets; this.contentRootMap = contentRootMap; } final String webSockets; final Map<String, WebRoot> contentRootMap; @Override public Session makeSession(SocketChannel ch) { TetrapodService pod = TetrapodService.this; Session ses = null; ses = new WebHttpSession(ch, pod, contentRootMap, webSockets); ses.setRelayHandler(pod); ses.setMyEntityId(getEntityId()); ses.setMyEntityType(Core.TYPE_TETRAPOD); ses.setTheirEntityType(Core.TYPE_CLIENT); ses.addSessionListener(new Session.Listener() { @Override public void onSessionStop(Session ses) { onEntityDisconnected(ses); } @Override public void onSessionStart(Session ses) {} }); return ses; } } public void onEntityDisconnected(Session ses) { if (ses instanceof WebHttpSession) { logger.debug("Session Stopped: {}", ses); } else { logger.info("Session Stopped: {}", ses); } if (ses.getTheirEntityId() != 0) { final EntityInfo e = registry.getEntity(ses.getTheirEntityId()); if (e != null) { registry.setGone(e); } } } private void importClusterPropertiesIntoRaft() { if (!Util.getProperty("props.init", false)) { logger.warn(" Properties props = new Properties(); Launcher.loadClusterProperties(props); String importFile = Util.getProperty("raft.import.properties"); if (importFile != null) { Launcher.loadProperties(importFile, props); } for (Object key : props.keySet()) { cluster.setClusterProperty(new ClusterProperty(key.toString(), false, props.getProperty(key.toString()))); } // secrets String secrets = props.getProperty("secrets"); props = new Properties(); if (secrets != null) { props.put("secrets", secrets); Launcher.loadSecretProperties(props); } String importSecretsFile = Util.getProperty("raft.import.secret.properties"); if (importSecretsFile != null) { Launcher.loadProperties(importSecretsFile, props); } for (Object key : props.keySet()) { cluster.setClusterProperty(new ClusterProperty(key.toString(), true, props.getProperty(key.toString()))); } // save property indicating we've imported cluster.setClusterProperty(new ClusterProperty("props.init", false, "true")); Util.sleep(1000); } } /** * As a Tetrapod service, we can't start serving as one until we've registered & fully sync'ed with the cluster, or self-registered if we * are the first one. We call this once this criteria has been reached */ @Override public void onReadyToServe() { logger.info(" ***** READY TO SERVE ***** "); if (isStartingUp()) { importClusterPropertiesIntoRaft(); try { AdminAuthToken.setSecret(getSharedSecret()); adminAccounts = new AdminAccounts(cluster); // FIXME: // Ensure we have all of the needed WebRootDir files installed before we open http ports // create servers Server httpServer = (new Server(getHTTPPort(), new WebSessionFactory(cluster.getWebRootDirs(), "/sockets"), dispatcher)); servers.add((httpServer)); httpServers.add(httpServer); // create secure port servers, if configured if (sslContext != null) { httpServer = new Server(getHTTPSPort(), new WebSessionFactory(cluster.getWebRootDirs(), "/sockets"), dispatcher, sslContext, false); servers.add((httpServer)); httpServers.add(httpServer); } servers.add(new Server(getPublicPort(), new TypedSessionFactory(Core.TYPE_ANONYMOUS), dispatcher, sslContext, false)); servers.add(new Server(getServicePort(), new TypedSessionFactory(Core.TYPE_SERVICE), dispatcher, sslContext, false)); // start listening for (Server s : servers) { s.start().sync(); } } catch (Exception e) { fail(e); } // scheduleHealthCheck(); } } // Pause will close the HTTP and HTTPS ports on the tetrapod service @Override public void onPaused() { for (Server httpServer : httpServers) { httpServer.close(); } } // Purge will boot all non-admin sessions from the tetrapod service @Override public void onPurged() { for (Server httpServer : httpServers) { httpServer.purge(); } } // UnPause will restart the HTTP listeners on the tetrapod service. @Override public void onUnpaused() { for (Server httpServer : httpServers) { try { httpServer.start().sync(); } catch (Exception e) { fail(e); } } } @Override public void onShutdown(boolean restarting) { logger.info("Shutting Down Tetrapod"); if (!Util.isLocal()) { // sleep a bit so other services getting a kill signal can shutdown cleanly Util.sleep(1500); } if (cluster != null) { cluster.shutdown(); } } /** * Extract a shared secret key for seeding server HMACs */ public String getSharedSecret() { String secret = Util.getProperty(AdminAuthToken.SHARED_SECRET_KEY); if (secret == null) { secret = AuthToken.generateSharedSecret(); cluster.setClusterProperty(new ClusterProperty(AdminAuthToken.SHARED_SECRET_KEY, true, secret)); } return secret; } private Session findSession(final EntityInfo entity) { if (entity.parentId == getEntityId()) { return entity.getSession(); } else { if (entity.isTetrapod()) { return cluster.getSession(entity.entityId); } final EntityInfo parent = registry.getEntity(entity.parentId); if (parent != null) { assert (parent != null); return cluster.getSession(parent.entityId); } else { logger.warn("Could not find parent entity {} for {}", entity.parentId, entity); return null; } } } @Override public int getAvailableService(int contractId) { final EntityInfo entity = registry.getRandomAvailableService(contractId); if (entity != null) { return entity.entityId; } return 0; } @Override public boolean isServiceExistant(int entityId) { EntityInfo info = registry.getEntity(entityId); if (info != null) { return info.isService(); } return false; } /** * Validates a long-polling session to an entityId */ @Override public boolean validate(int entityId, long token) { final EntityInfo e = registry.getEntity(entityId); if (e != null) { if (e.reclaimToken == token) { // HACK: as a side-effect, we update last contact time e.setLastContact(System.currentTimeMillis()); if (e.isGone()) { registry.updateStatus(e, e.status & ~Core.STATUS_GONE); } return true; } } return false; } @Override public Session getRelaySession(int entityId, int contractId) { EntityInfo entity = null; if (entityId == Core.UNADDRESSED) { entity = registry.getRandomAvailableService(contractId); } else { entity = registry.getEntity(entityId); if (entity == null) { int parentEntity = entityId & TetrapodContract.PARENT_ID_MASK; if (parentEntity != entityId && parentEntity != getEntityId()) { return getRelaySession(parentEntity, contractId); } else { logger.debug("Could not find an entity for {}", entityId); } } } if (entity != null) { return findSession(entity); } return null; } @Override public void relayMessage(final MessageHeader header, final ByteBuf buf, final boolean isBroadcast) throws IOException { final EntityInfo sender = registry.getEntity(header.fromId); if (sender != null) { buf.retain(); sender.queue(() -> { try { if (header.topicId != 0) { if (isBroadcast) { broadcastTopic(sender, header, buf); } } else if ((header.flags & MessageHeader.FLAGS_ALTERNATE) != 0) { if (isBroadcast) { broadcastAlt(sender, header, buf); } } else { final Session ses = getRelaySession(header.toId, header.contractId); if (ses != null) { ses.sendRelayedMessage(header, buf, false); } } } catch (Throwable e) { logger.error(e.getMessage(), e); } finally { // FIXME: This is fragile -- if we delete an entity with queued work, we need to make sure we // release all the buffers in the queued work items. buf.release(); } }); worker.kick(); } else { logger.error("Could not find sender entity {} for {}", header.fromId, header.dump()); } } private void broadcastTopic(final EntityInfo publisher, final MessageHeader header, final ByteBuf buf) throws IOException { if (header.toId == UNADDRESSED || header.toId == getEntityId()) { final RegistryTopic topic = publisher.getTopic(header.topicId); if (topic != null) { synchronized (topic) { for (final Subscriber s : topic.getSubscribers()) { broadcastTopic(publisher, s, topic, header, buf); } } } else { logger.error("Could not find topic {} for entity {} : {}", header.topicId, publisher, header.dump()); } } else { // relay to destination final Session ses = getRelaySession(header.toId, header.contractId); if (ses != null) { ses.sendRelayedMessage(header, buf, true); } } } private void broadcastAlt(final EntityInfo publisher, final MessageHeader header, final ByteBuf buf) throws IOException { final int myId = getEntityId(); final boolean myChildOriginated = publisher.parentId == myId; final boolean toAll = header.toId == UNADDRESSED; for (EntityInfo e : registry.getEntities()) { if (e.isTetrapod() && e.entityId != myId) { if (myChildOriginated) broadcastToAlt(e, header, buf); continue; } if (e.isService()) { continue; } if (toAll || e.getAlternateId() == header.toId) { broadcastToAlt(e, header, buf); } } } private void broadcastTopic(final EntityInfo publisher, final Subscriber sub, final RegistryTopic topic, final MessageHeader header, final ByteBuf buf) throws IOException { final int ri = buf.readerIndex(); final EntityInfo e = registry.getEntity(sub.entityId); if (e != null) { if (e.entityId == getEntityId()) { // dispatch to self ByteBufDataSource reader = new ByteBufDataSource(buf); final Object obj = StructureFactory.make(header.contractId, header.structId); final Message msg = (obj instanceof Message) ? (Message) obj : null; if (msg != null) { msg.read(reader); clusterClient.getSession().dispatchMessage(header, msg); } else { logger.warn("Could not read message for self-dispatch {}", header.dump()); } buf.readerIndex(ri); } else { if (!e.isGone() && (e.parentId == getEntityId() || e.isTetrapod())) { final Session session = findSession(e); if (session != null) { // rebroadcast this message if it was published by one of our children and we're sending it to another tetrapod final boolean keepBroadcasting = e.isTetrapod() && publisher.parentId == getEntityId(); session.sendRelayedMessage(header, buf, keepBroadcasting); buf.readerIndex(ri); } else { logger.error("Could not find session for {} {}", e, header.dump()); } } } } else { logger.error("Could not find subscriber {} for topic {}", sub.entityId, topic); } } private void broadcastToAlt(final EntityInfo e, final MessageHeader header, final ByteBuf buf) throws IOException { final int ri = buf.readerIndex(); if (!e.isGone()) { final Session session = findSession(e); if (session != null) { final boolean keepBroadcasting = e.isTetrapod(); session.sendRelayedMessage(header, buf, keepBroadcasting); buf.readerIndex(ri); } else { logger.error("Could not find session for {} {}", e, header.dump()); } } } @Override public WebRoutes getWebRoutes() { return cluster.getWebRoutes(); } @Override public void broadcastServicesMessage(Message msg) { if (servicesTopic != null) { servicesTopic.broadcast(msg); } } public void broadcastClusterMessage(Message msg) { if (clusterTopic != null) { clusterTopic.broadcast(msg); } } public void broadcast(Message msg, RegistryTopic topic) { if (topic != null) { synchronized (topic) { // OPTIMIZE: call broadcast() directly instead of through loop-back Session ses = clusterClient.getSession(); if (ses != null) { ses.sendTopicBroadcastMessage(msg, 0, topic.topicId); } else { logger.error("broadcast failed: no session for loopback connection"); } } } } public void broadcastAdminMessage(Message msg) { if (adminTopic != null) { adminTopic.broadcast(msg); } } private void scheduleHealthCheck() { if (!isShuttingDown()) { dispatcher.dispatch(1, TimeUnit.SECONDS, () -> { if (dispatcher.isRunning()) { try { healthCheck(); } catch (Throwable e) { logger.error(e.getMessage(), e); } finally { scheduleHealthCheck(); } } }); } } private void healthCheck() { cluster.service(); final long now = System.currentTimeMillis(); if (now - lastStatsLog > Util.ONE_MINUTE) { registry.logStats(false); lastStatsLog = System.currentTimeMillis(); final int clients = registry.getNumActiveClients(); synchronized (clientSessionsCounter) { clientSessionsCounter.addLast(clients); if (clientSessionsCounter.size() > 1440) { clientSessionsCounter.removeFirst(); } } } for (final EntityInfo e : registry.getChildren()) { healthCheck(e); } } private void healthCheck(final EntityInfo e) { final long now = System.currentTimeMillis(); if (e.isGone()) { if (now - e.getGoneSince() > Util.ONE_MINUTE) { logger.info("Reaping: {}", e); registry.unregister(e); } } else { // special check for long-polling clients if (e.getLastContact() != null) { if (now - e.getLastContact() > Util.ONE_MINUTE) { e.setLastContact(null); registry.setGone(e); } } // push through a dummy request to help keep dispatch pool metrics fresh if (e.isService()) { if (!e.isAvailable()) { logger.info("Checking health on {} : {} : {}", e, e.getSession(), e.isPendingRegistration()); } final Session ses = e.getSession(); if (ses != null && now - ses.getLastHeardFrom() > 1153) { final long t0 = System.currentTimeMillis(); sendRequest(new DummyRequest(), e.entityId).handle((res) -> { final long tf = System.currentTimeMillis() - t0; if (tf > 1000) { logger.warn("Round trip to dispatch {} took {} ms", e, tf); } }); } if (ses == null && !e.isPendingRegistration()) { registry.setGone(e); } } } } public void subscribeToCluster(Session ses, int toEntityId) { assert (clusterTopic != null); synchronized (cluster) { subscribe(clusterTopic.topicId, toEntityId); cluster.sendClusterDetails(ses, toEntityId, clusterTopic.topicId); } } @Override public void messageClusterMember(ClusterMemberMessage m, MessageContext ctx) { // synchronized (cluster) { // if (cluster.addMember(m.entityId, m.host, m.servicePort, m.clusterPort, null)) { // broadcast(new ClusterMemberMessage(m.entityId, m.host, m.servicePort, m.clusterPort, m.uuid), clusterTopic); } public void subscribeToAdmin(Session ses, int toEntityId) { assert (adminTopic != null); synchronized (cluster) { subscribe(adminTopic.topicId, toEntityId); cluster.sendAdminDetails(ses, toEntityId, adminTopic.topicId); } } @Override public Response requestKeepAlive(KeepAliveRequest r, RequestContext ctx) { return Response.SUCCESS; } @Override public Response requestRegister(RegisterRequest r, final RequestContext ctxA) { final SessionRequestContext ctx = (SessionRequestContext) ctxA; if (getEntityId() == 0) { return new Error(ERROR_SERVICE_UNAVAILABLE); } EntityInfo info = null; final EntityToken t = EntityToken.decode(r.token); if (t != null) { info = registry.getEntity(t.entityId); if (info != null) { if (info.reclaimToken != t.nonce) { info = null; // return error instead? } } } if (info == null) { info = new EntityInfo(); info.version = ctx.header.version; info.build = r.build; info.host = r.host; info.name = r.name; info.reclaimToken = random.nextLong(); info.contractId = r.contractId; } info.status = r.status &= ~Core.STATUS_GONE; info.parentId = getEntityId(); info.type = ctx.session.getTheirEntityType(); if (info.type == Core.TYPE_ANONYMOUS) { info.type = Core.TYPE_CLIENT; // clobber their reported host with their IP info.host = ctx.session.getPeerHostname(); } // register/reclaim //registry.register(info); if (info.entityId == 0) { info.entityId = registry.issueId(); } if (info.type == Core.TYPE_TETRAPOD) { info.parentId = info.entityId; ////////// HACK ////////// if (cluster.getEntity(info.entityId) != null) { // update & store session ctx.session.setTheirEntityId(info.entityId); ctx.session.setTheirEntityType(info.type); info.setSession(ctx.session); // deliver them their entityId immediately to avoid some race conditions with the response ctx.session.sendMessage(new EntityMessage(info.entityId), Core.UNADDRESSED); return new RegisterResponse(info.entityId, getEntityId(), EntityToken.encode(info.entityId, info.reclaimToken)); } } // for a client, we don't use raft to sync them, as they are a locally issued, non-replicated client if (info.type == Core.TYPE_CLIENT) { // update & store session ctx.session.setTheirEntityId(info.entityId); ctx.session.setTheirEntityType(info.type); info.setSession(ctx.session); // deliver them their entityId immediately to avoid some race conditions with the response ctx.session.sendMessage(new EntityMessage(info.entityId), Core.UNADDRESSED); registry.onAddEntityCommand(info); return new RegisterResponse(info.entityId, getEntityId(), EntityToken.encode(info.entityId, info.reclaimToken)); } final int entityId = info.entityId; final AsyncResponder responder = new AsyncResponder(ctx); logger.info("Registering: {} type={}", info, info.type); // execute a raft registration command cluster.executeCommand(new AddEntityCommand(info), entry -> { if (entry != null) { logger.info("Waited for local entityId-{} : {} : {}", entityId, entry, cluster.getCommitIndex()); // get the real entity object after we've processed the command final EntityInfo entity = cluster.getEntity(entityId); // update & store session ctx.session.setTheirEntityId(entity.entityId); ctx.session.setTheirEntityType(entity.type); entity.setSession(ctx.session); // deliver them their entityId immediately to avoid some race conditions with the response ctx.session.sendMessage(new EntityMessage(entity.entityId), Core.UNADDRESSED); if (entity.isService() && entity.entityId != getEntityId()) { subscribeToCluster(ctx.session, entity.entityId); } responder.respondWith( new RegisterResponse(entity.entityId, getEntityId(), EntityToken.encode(entity.entityId, entity.reclaimToken))); } else { responder.respondWith(Response.error(ERROR_UNKNOWN)); } } , true); return Response.PENDING; } @Override public Response requestUnregister(UnregisterRequest r, RequestContext ctx) { if (r.entityId != ctx.header.fromId && ctx.header.fromType != Core.TYPE_ADMIN) { return new Error(ERROR_INVALID_RIGHTS); } final EntityInfo info = registry.getEntity(r.entityId); if (info == null) { return new Error(ERROR_INVALID_ENTITY); } registry.unregister(info); return Response.SUCCESS; } @Override public Response requestServicesSubscribe(ServicesSubscribeRequest r, RequestContext ctxA) { SessionRequestContext ctx = (SessionRequestContext) ctxA; if (servicesTopic == null) { return new Error(ERROR_UNKNOWN); } if (!ctx.isFromService()) { if (adminAccounts == null) { return new Error(ERROR_SERVICE_UNAVAILABLE); } if (!adminAccounts.isValidAdminRequest(ctx, r.adminToken, Admin.RIGHTS_CLUSTER_READ)) { return new Error(ERROR_INVALID_RIGHTS); } } synchronized (servicesTopic) { subscribe(servicesTopic.topicId, ctx.header.fromId); // send all current entities for (EntityInfo e : registry.getServices()) { ctx.session.sendMessage(new ServiceAddedMessage(e), ctx.header.fromId); } } return Response.SUCCESS; } @Override public Response requestServicesUnsubscribe(ServicesUnsubscribeRequest r, RequestContext ctx) { // TODO: validate synchronized (servicesTopic) { unsubscribe(servicesTopic.topicId, ctx.header.fromId); } return Response.SUCCESS; } @Override public Response requestServiceStatusUpdate(ServiceStatusUpdateRequest r, RequestContext ctx) { // TODO: don't allow certain bits to be set from a request if (ctx.header.fromId != 0) { final EntityInfo e = registry.getEntity(ctx.header.fromId); if (e != null) { registry.updateStatus(e, r.status); } else { return new Error(ERROR_INVALID_ENTITY); } } return Response.SUCCESS; } @Override public Response requestAddServiceInformation(AddServiceInformationRequest req, RequestContext ctx) { // for (WebRoute r : req.routes) { // webRoutes.setRoute(r.path, r.contractId, r.structId); // logger.debug("Setting Web route [{}] for {}", r.path, r.contractId); cluster.registerContract(req.info); return Response.SUCCESS; } @Override protected void registerServiceInformation() { // do nothing, our protocol is known by all tetrapods } @Override public Response requestLogRegistryStats(LogRegistryStatsRequest r, RequestContext ctx) { registry.logStats(true); cluster.logRegistry(); return Response.SUCCESS; } @Override public Response requestStorageGet(StorageGetRequest r, RequestContext ctx) { return new StorageGetResponse(cluster.get(r.key)); } @Override public Response requestStorageSet(StorageSetRequest r, RequestContext ctx) { cluster.put(r.key, r.value); return Response.SUCCESS; } @Override public Response requestStorageDelete(StorageDeleteRequest r, RequestContext ctx) { cluster.delete(r.key); return Response.SUCCESS; } @Override public Response requestAdminAuthorize(AdminAuthorizeRequest r, RequestContext ctxA) { return adminAccounts.requestAdminAuthorize(r, ctxA); } @Override public Response requestAdminLogin(AdminLoginRequest r, RequestContext ctxA) { return adminAccounts.requestAdminLogin(r, ctxA); } @Override public Response requestAdminSessionToken(AdminSessionTokenRequest r, RequestContext ctx) { return adminAccounts.requestAdminSessionToken(r, ctx); } @Override public Response requestAdminChangePassword(final AdminChangePasswordRequest r, RequestContext ctxA) { return adminAccounts.requestAdminChangePassword(r, ctxA); } @Override public Response requestAdminResetPassword(AdminResetPasswordRequest r, RequestContext ctx) { return adminAccounts.requestAdminResetPassword(r, ctx); } @Override public Response requestAdminChangeRights(AdminChangeRightsRequest r, RequestContext ctx) { return adminAccounts.requestAdminChangeRights(r, ctx); } @Override public Response requestAdminCreate(AdminCreateRequest r, RequestContext ctx) { return adminAccounts.requestAdminCreate(r, ctx); } @Override public Response requestAdminDelete(AdminDeleteRequest r, RequestContext ctx) { return adminAccounts.requestAdminDelete(r, ctx); } @Override public Response requestGetServiceBuildInfo(GetServiceBuildInfoRequest r, RequestContext ctx) { return new GetServiceBuildInfoResponse(Builder.getServiceInfo()); } @Override public Response requestExecuteBuildCommand(ExecuteBuildCommandRequest r, RequestContext ctx) { for (BuildCommand command : r.commands) { boolean success = Builder.executeCommand(command, this); if (!success) return Response.error(ERROR_UNKNOWN); } return Response.SUCCESS; } @Override public Response requestSetAlternateId(SetAlternateIdRequest r, RequestContext ctx) { EntityInfo e = registry.getEntity(r.entityId); if (e != null) { e.setAlternateId(r.alternateId); return Response.SUCCESS; } return Response.error(ERROR_INVALID_ENTITY); } @Override public Response requestVerifyEntityToken(VerifyEntityTokenRequest r, RequestContext ctx) { EntityToken t = EntityToken.decode(r.token); if (t.entityId == r.entityId) { EntityInfo e = registry.getEntity(r.entityId); if (e != null) { synchronized (e) { if (e.reclaimToken == t.nonce) return Response.SUCCESS; } } } return Response.error(ERROR_INVALID_TOKEN); } @Override public Response requestGetEntityInfo(GetEntityInfoRequest r, RequestContext ctx) { final EntityInfo e = registry.getEntity(r.entityId); if (e != null) { synchronized (e) { final Session s = e.getSession(); if (s != null) { if (e.isClient() && s instanceof WebHttpSession) { WebHttpSession ws = (WebHttpSession) s; return new GetEntityInfoResponse(e.build, e.name, s.getPeerHostname(), ws.getHttpReferrer(), ws.getDomain()); } return new GetEntityInfoResponse(e.build, e.name, s.getPeerHostname(), null, null); } else { return new GetEntityInfoResponse(e.build, e.name, null, null, null); } } } return Response.error(ERROR_UNKNOWN_ENTITY_ID); } @Override public Response requestSetEntityReferrer(SetEntityReferrerRequest r, RequestContext ctx) { final EntityInfo e = registry.getEntity(ctx.header.fromId); if (e != null) { synchronized (e) { final Session s = e.getSession(); if (s != null && s instanceof WebHttpSession) { ((WebHttpSession) s).setHttpReferrer(r.referrer); return Response.SUCCESS; } else { return Response.error(ERROR_INVALID_DATA); } } } return Response.error(ERROR_UNKNOWN_ENTITY_ID); } /////////////// RAFT /////////////// @Override public Response requestClusterJoin(ClusterJoinRequest r, RequestContext ctxA) { SessionRequestContext ctx = (SessionRequestContext) ctxA; if (ctx.session.getTheirEntityType() != Core.TYPE_TETRAPOD) { return new Error(ERROR_INVALID_RIGHTS); } return cluster.requestClusterJoin(r, clusterTopic, ctx); } @Override public Response requestAppendEntries(AppendEntriesRequest r, RequestContext ctx) { return cluster.requestAppendEntries(r, ctx); } @Override public Response requestVote(VoteRequest r, RequestContext ctx) { return cluster.requestVote(r, ctx); } @Override public Response requestInstallSnapshot(InstallSnapshotRequest r, RequestContext ctx) { return cluster.requestInstallSnapshot(r, ctx); } @Override public Response requestIssueCommand(IssueCommandRequest r, RequestContext ctx) { return cluster.requestIssueCommand(r, ctx); } @Override public Response requestRaftStats(RaftStatsRequest r, RequestContext ctx) { return cluster.requestRaftStats(r, ctx); } @Override public Response requestDelClusterProperty(DelClusterPropertyRequest r, RequestContext ctx) { if (!adminAccounts.isValidAdminRequest(ctx, r.adminToken, Admin.RIGHTS_CLUSTER_WRITE)) { return new Error(ERROR_INVALID_RIGHTS); } cluster.delClusterProperty(r.key); return Response.SUCCESS; } @Override public Response requestSetClusterProperty(SetClusterPropertyRequest r, RequestContext ctx) { if (!adminAccounts.isValidAdminRequest(ctx, r.adminToken, Admin.RIGHTS_CLUSTER_WRITE)) { return new Error(ERROR_INVALID_RIGHTS); } cluster.setClusterProperty(r.property); return Response.SUCCESS; } @Override public Response requestAdminSubscribe(AdminSubscribeRequest r, RequestContext ctx) { if (!adminAccounts.isValidAdminRequest(ctx, r.adminToken, Admin.RIGHTS_CLUSTER_READ)) { return new Error(ERROR_INVALID_RIGHTS); } subscribeToAdmin(((SessionRequestContext) ctx).session, ctx.header.fromId); return Response.SUCCESS; } @Override public Response requestSetWebRoot(SetWebRootRequest r, RequestContext ctx) { if (!adminAccounts.isValidAdminRequest(ctx, r.adminToken, Admin.RIGHTS_CLUSTER_WRITE)) { return new Error(ERROR_INVALID_RIGHTS); } if (r.def != null) { cluster.setWebRoot(r.def); return Response.SUCCESS; } return new Error(ERROR_INVALID_DATA); } @Override public Response requestDelWebRoot(DelWebRootRequest r, RequestContext ctx) { if (!adminAccounts.isValidAdminRequest(ctx, r.adminToken, Admin.RIGHTS_CLUSTER_WRITE)) { return new Error(ERROR_INVALID_RIGHTS); } if (r.name != null) { cluster.delWebRoot(r.name); return Response.SUCCESS; } return new Error(ERROR_INVALID_DATA); } @Override public Response requestLock(LockRequest r, RequestContext ctx) { final DistributedLock lock = cluster.getLock(r.key); if (lock.lock(r.leaseMillis, r.leaseMillis + 10000)) { return new LockResponse(lock.uuid); } return Response.error(ERROR_TIMEOUT); } @Override public Response requestUnlock(UnlockRequest r, RequestContext ctx) { final DistributedLock lock = new DistributedLock(r.key, r.uuid, cluster); lock.unlock(); return Response.SUCCESS; } @Override public Response requestSnapshot(SnapshotRequest r, RequestContext ctx) { if (!adminAccounts.isValidAdminRequest(ctx, r.adminToken, Admin.RIGHTS_CLUSTER_WRITE)) { return new Error(ERROR_INVALID_RIGHTS); } cluster.snapshot(); return Response.SUCCESS; } @Override public Response requestClaimOwnership(ClaimOwnershipRequest r, RequestContext ctx) { if (ctx.header.fromType != TYPE_SERVICE) return new Error(ERROR_INVALID_RIGHTS); return cluster.requestClaimOwnership(r, (SessionRequestContext) ctx); } @Override public Response requestRetainOwnership(RetainOwnershipRequest r, RequestContext ctx) { if (ctx.header.fromType != TYPE_SERVICE) return new Error(ERROR_INVALID_RIGHTS); return cluster.requestRetainOwnership(r, (SessionRequestContext) ctx); } @Override public Response requestReleaseOwnership(ReleaseOwnershipRequest r, RequestContext ctx) { if (ctx.header.fromType != TYPE_SERVICE) return new Error(ERROR_INVALID_RIGHTS); return cluster.requestReleaseOwnership(r, (SessionRequestContext) ctx); } @Override public Response requestSubscribeOwnership(SubscribeOwnershipRequest r, RequestContext ctx) { if (ctx.header.fromType != TYPE_SERVICE) return new Error(ERROR_INVALID_RIGHTS); return cluster.requestSubscribeOwnership(r, (SessionRequestContext) ctx); } @Override public Response requestUnsubscribeOwnership(UnsubscribeOwnershipRequest r, RequestContext ctx) { if (ctx.header.fromType != TYPE_SERVICE) return new Error(ERROR_INVALID_RIGHTS); return cluster.requestUnsubscribeOwnership(r, ctx); } @Override public Response requestTetrapodClientSessions(TetrapodClientSessionsRequest r, RequestContext ctx) { synchronized (clientSessionsCounter) { return new TetrapodClientSessionsResponse(Util.toIntArray(clientSessionsCounter)); } } }
package edu.wustl.catissuecore.util.global; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Map; import edu.wustl.common.util.logger.Logger; /** * Utility Class contain general methods used through out the application. * @author kapil_kaveeshwar */ public class Utility { /** * Parses the string format of date in the given format and returns the Data object. * @param date the string containing date. * @param pattern the pattern in which the date is present. * @return the string format of date in the given format and returns the Data object. * @throws ParseException */ public static Date parseDate(String date,String pattern) throws ParseException { if(date!=null && !date.trim().equals("")) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); Date dateObj = dateFormat.parse(date); return dateObj; } catch(Exception e) { throw new ParseException("Date '"+date+"' is not in format of "+pattern,0); } } else { return null; } } /** * Parses the Date in given format and returns the string representation. * @param date the Date to be parsed. * @param pattern the pattern of the date. * @return */ public static String parseDateToString(Date date, String pattern) { String d = ""; //TODO Check for null if(date!=null) { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); d = dateFormat.format(date); } return d; } public static String toString(Object obj) { if(obj == null) return ""; return obj.toString(); } public static String[] getTime(Date date) { String []time =new String[2]; Calendar cal = Calendar.getInstance(); cal.setTime(date); time[0]= Integer.toString(cal.get(Calendar.HOUR_OF_DAY)); time[1]= Integer.toString(cal.get(Calendar.MINUTE)); return time; } public static Long[] toLongArray(Collection collection) { Logger.out.debug(collection.toArray().getClass().getName()); Long obj[] = new Long[collection.size()]; int index = 0; Iterator it = collection.iterator(); while(it.hasNext()) { obj[index] = (Long)it.next(); Logger.out.debug("obj[index] "+obj[index].getClass().getName()); index++; } return obj; } public static int toInt(Object obj) { int value=0; if(obj == null) return value; else { Integer intObj = (Integer)obj; value=intObj.intValue() ; return value; } } public static double toDouble(Object obj) { double value=0; if(obj == null) return value; else { Double dblObj = (Double)obj; value=dblObj.doubleValue() ; return value; } } public static Object[] addElement(Object[] array, Object obj) { Object newObjectArr[] = new Object[array.length+1]; if(array instanceof String[]) newObjectArr = new String[array.length+1]; for (int i = 0; i < array.length; i++) { newObjectArr[i] = array[i]; } newObjectArr[newObjectArr.length-1] = obj; return newObjectArr; } /** * checking whether key's value is persisted or not * */ public static boolean isPersistedValue(Map map,String key){ Object obj = map.get(key); String val=null; if (obj!=null) { val = obj.toString(); } if((val!= null && !(val.equals("0"))) && !(val.equals(""))) return true; else return false; } // public static void main(String[] args) // try{ // String date = "2005-10-22"; // String pattern = "yyyy-MM-dd HH:mm aa"; // Date d = parseDate(date,pattern); // String dd = parseDateToString(d,pattern); // System.out.println("Date........."+d); // System.out.println("String......."+dd); // catch(ParseException pexcp) // System.out.println("Exception"+pexcp.getMessage()); /** * Parses the fully qualified classname and returns only the classname. * @param fullyQualifiedName The fully qualified classname. * @return The classname. */ public static String parseClassName(String fullyQualifiedName) { try { return fullyQualifiedName.substring(fullyQualifiedName .lastIndexOf(".") + 1); } catch (Exception e) { return fullyQualifiedName; } } }
package edu.wustl.query.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.query.factory.AbstractQueryUIManagerFactory; import edu.wustl.common.querysuite.queryobject.IParameterizedQuery; import edu.wustl.common.util.logger.Logger; import edu.wustl.query.actionForm.CategorySearchForm; import edu.wustl.query.enums.QueryType; import edu.wustl.query.flex.dag.DAGConstant; import edu.wustl.query.util.global.Constants; import edu.wustl.query.util.querysuite.AbstractQueryUIManager; import edu.wustl.query.util.querysuite.QueryModuleUtil; /** * Action is called when user clicks on QueryGetCount link on search tab. * @author pallavi_mistry * */ public class QueryGetCountAction extends Action { private static org.apache.log4j.Logger logger = Logger.getLogger(QueryGetCountAction.class); /** * This method loads the data required for GetCounts.jsp * @param mapping mapping * @param form form * @param request request * @param response response * @throws Exception Exception * @return ActionForward actionForward */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); CategorySearchForm searchForm = (CategorySearchForm) form; String currentPage = (String) request.getAttribute("currentPage"); if ((Constants.EDIT_QUERY.equalsIgnoreCase(currentPage))) { IParameterizedQuery parameterizedQuery = (IParameterizedQuery) request.getSession() .getAttribute(Constants.QUERY_OBJECT); request.setAttribute("isQuery", "true"); searchForm.setQueryTitle(parameterizedQuery.getName()); logger.info("In QueryGetCountQueryAction Query opened in Edit mode : "+ parameterizedQuery.getId()); } else { session.removeAttribute(Constants.QUERY_OBJECT); session.removeAttribute(Constants.SELECTED_COLUMN_META_DATA); session.removeAttribute(Constants.IS_SAVED_QUERY); session.removeAttribute(edu.wustl.common.util.global.Constants.IS_SIMPLE_SEARCH); session.removeAttribute(DAGConstant.ISREPAINT); session.removeAttribute(DAGConstant.TQUIMap); session.removeAttribute(Constants.EXPORT_DATA_LIST); session.removeAttribute(Constants.ENTITY_IDS_MAP); session.removeAttribute(Constants.MAIN_ENTITY_EXPRESSIONS_MAP); session.removeAttribute(Constants.MAIN_EXPRESSION_TO_ADD_CONTAINMENTS); session.removeAttribute(Constants.ALL_ADD_LIMIT_EXPRESSIONS); session.removeAttribute(Constants.MAIN_EXPRESSIONS_ENTITY_EXP_ID_MAP); session.removeAttribute(Constants.MAIN_ENTITY_LIST); session.removeAttribute(Constants.Query_Type); } searchForm = QueryModuleUtil.setDefaultSelections(searchForm); String pageOf = request.getParameter(Constants.PAGE_OF); if (pageOf != null && pageOf.equals(Constants.PAGE_OF_WORKFLOW)) { request.setAttribute(Constants.IS_WORKFLOW, Constants.TRUE); String workflowName = (String) request.getSession().getAttribute( Constants.WORKFLOW_NAME); request.setAttribute(Constants.WORKFLOW_NAME, workflowName); } //Added a Default session data bean......Need to be removed when there query will have login SessionDataBean sessionBean = (SessionDataBean) session .getAttribute(Constants.SESSION_DATA); Long userId = null; if (sessionBean == null) { // HttpSession newSession = request.getSession(true); userId = 1L; String ipAddress = request.getRemoteAddr(); SessionDataBean sessionData = new SessionDataBean(); sessionData.setUserName("admin@admin.com"); sessionData.setIpAddress(ipAddress); sessionData.setUserId(userId); sessionData.setFirstName("admin@admin.com"); sessionData.setLastName("admin@admin.com"); sessionData.setAdmin(true); sessionData.setSecurityRequired(false); session.setAttribute(Constants.SESSION_DATA, sessionData); } else { userId = sessionBean.getUserId(); } QueryType qtype = QueryType.GET_COUNT; session.setAttribute(Constants.Query_Type, qtype.type); //Retrieve the Project list AbstractQueryUIManager qUIManager = AbstractQueryUIManagerFactory .getDefaultAbstractUIQueryManager(); List<NameValueBean> projectList = qUIManager.getObjects(userId); if (projectList != null) { searchForm.setProjectsNameValueBeanList(projectList); } return mapping.findForward(edu.wustl.query.util.global.Constants.SUCCESS); } }
package so.doo.app.plugins; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; @SuppressLint("HandlerLeak") public class Apps extends CordovaPlugin { private Context ctx; public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); ctx = cordova.getActivity().getApplicationContext(); } private JSONArray list() { PackageManager packageMgr = ctx.getPackageManager(); Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> resovleInfos = packageMgr.queryIntentActivities(mainIntent, 0); ArrayList<String> list = new ArrayList<String>(); for (ResolveInfo resolve : resovleInfos) { String packageName = resolve.activityInfo.packageName; String strAppName = resolve.activityInfo.loadLabel(packageMgr).toString(); list.add(packageName); list.add(strAppName); } List<String> ulist = new ArrayList<String>(new HashSet<String>(list)); return new JSONArray(ulist); } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false otherwise. * @throws JSONException */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { // list if (action.equals("list")) { JSONArray json = list(); callbackContext.success(json.toString()); return true; } return false; } }
package so.doo.app.plugins; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; @SuppressLint("HandlerLeak") public class Apps extends CordovaPlugin { private Context ctx; public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); ctx = cordova.getActivity().getApplicationContext(); } private JSONArray list() { PackageManager packageMgr = ctx.getPackageManager(); Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> resovleInfos = packageMgr.queryIntentActivities(mainIntent, 0); ArrayList<String> list = new ArrayList<String>(); for (ResolveInfo resolve : resovleInfos) { String packageName = resolve.activityInfo.packageName; list.add(packageName); } for (ResolveInfo resolve : resovleInfos) { String strAppName = resolve.activityInfo.applicationInfo.loadLabel(packageMgr).toString(); list.add(strAppName); String id = resolve.activityInfo.applicationInfo.uid; list.add(id); } List<String> ulist = new ArrayList<String>(new HashSet<String>(list)); return new JSONArray(ulist); } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false otherwise. * @throws JSONException */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { // list if (action.equals("list")) { JSONArray json = list(); callbackContext.success(json.toString()); return true; } return false; } }
package so.doo.app.plugins; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; @SuppressLint("HandlerLeak") public class Apps extends CordovaPlugin { private Context ctx; public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); ctx = cordova.getActivity().getApplicationContext(); } private JSONArray list() { PackageManager packageMgr = ctx.getPackageManager(); Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> resovleInfos = packageMgr.queryIntentActivities(mainIntent, 0); ArrayList<String> list = new ArrayList<String>(); for (ResolveInfo resolve : resovleInfos) { String packageName = resolve.activityInfo.packageName; String strAppName = resolve.activityInfo.applicationInfo.loadLabel(packageName).toString(); list.add(packageName); list.add(strAppName); } List<String> ulist = new ArrayList<String>(new HashSet<String>(list)); return new JSONArray(ulist); } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false otherwise. * @throws JSONException */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { // list if (action.equals("list")) { JSONArray json = list(); callbackContext.success(json.toString()); return true; } return false; } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public final class MainPanel extends JPanel { private final String[] columnNames = {"user", "rwx"}; private final Object[][] data = { {"owner", EnumSet.allOf(Permissions.class)}, {"group", EnumSet.of(Permissions.READ)}, {"other", EnumSet.noneOf(Permissions.class)} }; private final DefaultTableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; private final JTable table = new JTable(model); private final JLabel label = new JLabel(); public MainPanel() { super(new BorderLayout()); table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); if (System.getProperty("java.version").startsWith("1.6.0")) { //1.6.0_xx bug? column header click -> edit cancel? table.getTableHeader().addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (table.isEditing()) { table.getCellEditor().stopCellEditing(); } } }); } TableColumn c = table.getColumnModel().getColumn(1); c.setCellRenderer(new CheckBoxesRenderer()); c.setCellEditor(new CheckBoxesEditor()); final EnumMap<Permissions, Integer> map = new EnumMap<>(Permissions.class); map.put(Permissions.READ, 1 << 2); map.put(Permissions.WRITE, 1 << 1); map.put(Permissions.EXECUTE, 1 << 0); JPanel p = new JPanel(new BorderLayout()); p.add(label); p.add(new JButton(new AbstractAction("ls -l (chmod)") { private static final String M = "-"; @Override public void actionPerformed(ActionEvent e) { StringBuilder nbuf = new StringBuilder(3); StringBuilder buf = new StringBuilder(9); for (int i = 0; i < model.getRowCount(); i++) { EnumSet<?> v = (EnumSet<?>) model.getValueAt(i, 1); int flg = 0; if (v.contains(Permissions.READ)) { flg |= map.get(Permissions.READ); buf.append('r'); } else { buf.append(M); } if (v.contains(Permissions.WRITE)) { flg |= map.get(Permissions.WRITE); buf.append('w'); } else { buf.append(M); } if (v.contains(Permissions.EXECUTE)) { flg |= map.get(Permissions.EXECUTE); buf.append('x'); } else { buf.append(M); } nbuf.append(flg); } label.setText(String.format(" %s %s%s", nbuf, M, buf)); } }), BorderLayout.EAST); add(new JScrollPane(table)); add(p, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } enum Permissions { EXECUTE, WRITE, READ; } class CheckBoxesPanel extends JPanel { protected final String[] title = {"r", "w", "x"}; public JCheckBox[] buttons; protected CheckBoxesPanel() { super(); setOpaque(false); setBackground(new Color(0x0, true)); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); initButtons(); } private void initButtons() { buttons = new JCheckBox[title.length]; for (int i = 0; i < buttons.length; i++) { JCheckBox b = new JCheckBox(title[i]); b.setOpaque(false); b.setFocusable(false); b.setRolloverEnabled(false); b.setBackground(new Color(0x0, true)); buttons[i] = b; add(b); add(Box.createHorizontalStrut(5)); } } protected void updateButtons(Object v) { removeAll(); initButtons(); EnumSet<?> f = v instanceof EnumSet ? (EnumSet<?>) v : EnumSet.noneOf(Permissions.class); buttons[0].setSelected(f.contains(Permissions.READ)); buttons[1].setSelected(f.contains(Permissions.WRITE)); buttons[2].setSelected(f.contains(Permissions.EXECUTE)); } } class CheckBoxesRenderer extends CheckBoxesPanel implements TableCellRenderer { @Override public void updateUI() { super.updateUI(); setName("Table.cellRenderer"); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { updateButtons(value); return this; } //public static class UIResource extends CheckBoxesRenderer implements javax.swing.plaf.UIResource {} } class CheckBoxesEditor extends CheckBoxesPanel implements TableCellEditor { protected transient ChangeEvent changeEvent; protected CheckBoxesEditor() { super(); ActionMap am = getActionMap(); for (int i = 0; i < buttons.length; i++) { //buttons[i].addActionListener(al); final String t = title[i]; am.put(t, new AbstractAction(t) { @Override public void actionPerformed(ActionEvent e) { for (JCheckBox b: buttons) { if (b.getText().equals(t)) { b.doClick(); break; } } fireEditingStopped(); } }); } InputMap im = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0), title[0]); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), title[1]); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, 0), title[2]); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { updateButtons(value); return this; } @Override public Object getCellEditorValue() { EnumSet<Permissions> f = EnumSet.noneOf(Permissions.class); if (buttons[0].isSelected()) { f.add(Permissions.READ); } if (buttons[1].isSelected()) { f.add(Permissions.WRITE); } if (buttons[2].isSelected()) { f.add(Permissions.EXECUTE); } return f; } //Copied from AbstractCellEditor //protected EventListenerList listenerList = new EventListenerList(); //protected transient ChangeEvent changeEvent; @Override public boolean isCellEditable(EventObject e) { return true; } @Override public boolean shouldSelectCell(EventObject anEvent) { return true; } @Override public boolean stopCellEditing() { fireEditingStopped(); return true; } @Override public void cancelCellEditing() { fireEditingCanceled(); } @Override public void addCellEditorListener(CellEditorListener l) { listenerList.add(CellEditorListener.class, l); } @Override public void removeCellEditorListener(CellEditorListener l) { listenerList.remove(CellEditorListener.class, l); } public CellEditorListener[] getCellEditorListeners() { return listenerList.getListeners(CellEditorListener.class); } protected void fireEditingStopped() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { // Lazily create the event: if (Objects.isNull(changeEvent)) { changeEvent = new ChangeEvent(this); } ((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent); } } } protected void fireEditingCanceled() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { // Lazily create the event: if (Objects.isNull(changeEvent)) { changeEvent = new ChangeEvent(this); } ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent); } } } }
package press; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import play.Play; import play.cache.Cache; import play.vfs.VirtualFile; import press.io.CompressedFile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PlayLessEngine { private static final Logger logger = LoggerFactory.getLogger(PlayLessEngine.class); NodeLessEngine lessEngine; static Pattern importPattern = Pattern.compile("@import\\s*[\"'](.*?)[\"']"); public PlayLessEngine() { if (!Play.usePrecompiled && !NodeLessEngine.canBeUsed()) throw new RuntimeException("Cannot use lessc, not installed?"); lessEngine = new NodeLessEngine(); } /** * Get the CSS for this less file either from the cache, or compile it. */ public String get(File lessFile, boolean compress) { File precompiled = new File(lessFile.getPath() + ".css"); if (precompiled.exists()) { logger.debug("Serving precompiled {}", precompiled); return VirtualFile.open(precompiled).contentAsString(); } String cacheKey = lessFile.getName() + "." + latestModified(lessFile); CompressedFile cachedFile = CompressedFile.create(cacheKey, PluginConfig.css.compressedDir); if (cachedFile.exists()) { try (InputStream is = cachedFile.inputStream()) { return IOUtils.toString(is, "UTF-8"); } catch (IOException e) { throw new RuntimeException(e); } } logger.debug("Compiling {}", lessFile); String css = compile(lessFile, compress); try { Writer out = cachedFile.startWrite(); out.write(css); return css; } catch (IOException e) { throw new RuntimeException(e); } finally { cachedFile.close(); } } /** * Returns the latest of the last modified dates of this file and all files * it imports */ public long latestModified(File lessFile) { long lastModified = lessFile.lastModified(); for (File imported : getAllImports(lessFile)) { lastModified = Math.max(lastModified, imported.lastModified()); } return lastModified; } /** * Returns a set composed of the file itself, followed by all files that it * imports, the files they import, etc */ public static Set<File> getAllImports(File lessFile) { Set<File> imports = new HashSet<>(); getAllImports(lessFile, imports); return imports; } protected static void getAllImports(File lessFile, Set<File> imports) { imports.add(lessFile); for (File imported : getImportsFromCacheOrFile(VirtualFile.open(lessFile))) { if (!imports.contains(imported)) { getAllImports(imported, imports); } } } @SuppressWarnings("unchecked") protected static Set<File> getImportsFromCacheOrFile(VirtualFile lessFile) { String cacheKey = "less_imports_" + lessFile.getRealFile() + lessFile.lastModified(); Set<File> files = Cache.get(cacheKey, Set.class); if (files == null) { try { files = getImportsFromFile(lessFile); Cache.set(cacheKey, files); } catch (IOException e) { logger.error("IOException trying to determine imports in LESS file", e); files = new HashSet<>(); } } return files; } protected static Set<File> getImportsFromFile(VirtualFile lessFile) throws IOException { if (!lessFile.exists()) { return Collections.emptySet(); } String content = lessFile.contentAsString(); Set<File> files = new HashSet<>(); String virtualParentPath = lessFile.relativePath().replaceFirst("^\\{.*?\\}", "").replaceFirst("/[^/]*$", ""); Matcher m = importPattern.matcher(content); while (m.find()) { VirtualFile file = Play.getVirtualFile(virtualParentPath + "/" + m.group(1)); if (file == null && !m.group(1).endsWith(".less")) file = Play.getVirtualFile(virtualParentPath + "/" + m.group(1) + ".less"); if (file != null) { files.add(file.getRealFile()); files.addAll(getImportsFromCacheOrFile(file)); } } return files; } public String compile(File lessFile, boolean compress) { try { return lessEngine.compile(lessFile, compress); } catch (LessException e) { return handleException(lessFile, e); } } protected String handleException(File lessFile, LessException e) { logger.error("Less error: {}", e.getMessage()); return formatLessError(e.getMessage()); } protected String formatLessError(String error) { return "body:before {display: block; color: #c00; white-space: pre; font-family: monospace; background: #FDD9E1; border-top: 1px solid pink; border-bottom: 1px solid pink; padding: 10px; content: \"[LESS ERROR] " + error + "\"; }"; } }
import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Map; import java.util.List; import java.net.URL; import java.lang.Character.UnicodeBlock; import org.yaml.snakeyaml.*; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.nodes.*; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.parser.PdfReaderContentParser; import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy; import com.itextpdf.text.pdf.parser.TextExtractionStrategy; import com.itextpdf.text.pdf.parser.RenderListener; import com.itextpdf.text.pdf.parser.ImageRenderInfo; import com.itextpdf.text.pdf.parser.TextRenderInfo; import com.itextpdf.text.pdf.parser.Vector; import com.itextpdf.text.pdf.parser.LineSegment; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfSmartCopy; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.BaseColor; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.Phrase; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.ColumnText; import com.itextpdf.text.pdf.PdfPTableEvent; /* * Class that directly serve deserialization of JSON data. */ class Rect { public Integer page; public ArrayList<Double> rect; // result output mode public ArrayList<String> lines; }; class ExtractTextSpec { public String input; public Boolean yamlOutput; public ArrayList<Rect> rects; public String stampedOutput; /* * YAML is compatible with JSON (at least with the JSON we generate). * * It was the simplest method to read in JSON values. */ public static Yaml getYaml() { Constructor constructor = new Constructor(ExtractTextSpec.class); constructor.setPropertyUtils(constructor.getPropertyUtils()); constructor.getPropertyUtils().setSkipMissingProperties(true); /* * Java reflection is missing some crucial information about * elements of containers. Add this information here. */ TypeDescription extractTextDesc = new TypeDescription(ExtractTextSpec.class); extractTextDesc.putListPropertyType("rects", Rect.class); constructor.addTypeDescription(extractTextDesc); Yaml yaml = new Yaml(constructor); return yaml; } public static ExtractTextSpec loadFromFile(String fileName) throws IOException { InputStream input = new FileInputStream(new File(fileName)); Yaml yaml = getYaml(); return (ExtractTextSpec)yaml.load(input); } } class ExtractTextsRenderListener implements RenderListener { /* * Java does not support multiple results from functions, so treat * these as results from 'find'. * * foundText is not null if text was found (taking into account * requested index). If this is null then foundTextCount should * say how many texts were found on the page. This should be less * than index. It should be substracted from index and used on the * next page as limit. */ public ArrayList<String> foundText; public class CharPos { /* * This is Unicode code point as used by java.String, so it * may be a surrogate pair or some other crap. As soon as we * enter markets that need this we need to move to full * Unicode support. This requires involed changes everywhere * so beware to test this properly once we are there. */ String c; /* * Coordinates as returned by iText. We know that y is font * baseline coordinate. * * bx, by are coordinates of lower left corner. ex, ey are * coordinates of upper right corner. [bx by ex ey] is the * bounding box for this character. */ double x, y, bx, by, ex, ey; public String toString() { return c + "," + x + "," + y + "," + bx + "," + by + "," + ex + "," + ey; } }; public ArrayList<CharPos> allCharacters; ExtractTextsRenderListener() { allCharacters = new ArrayList<CharPos>(); } public void beginTextBlock() { } public void endTextBlock() { } public void renderImage(ImageRenderInfo renderInfo) { } public void renderText(TextRenderInfo renderInfo) { List<TextRenderInfo> individualCharacters = renderInfo.getCharacterRenderInfos(); for( TextRenderInfo tri: individualCharacters ) { String text = tri.getText(); CharPos cp = new CharPos(); cp.c = text; LineSegment line = tri.getBaseline(); Vector p = line.getStartPoint(); cp.x = p.get(Vector.I1); cp.y = p.get(Vector.I2); line = tri.getDescentLine(); p = line.getStartPoint(); cp.bx = p.get(Vector.I1); cp.by = p.get(Vector.I2); line = tri.getAscentLine(); p = line.getEndPoint(); cp.ex = p.get(Vector.I1); cp.ey = p.get(Vector.I2); allCharacters.add(cp); } } /* * Params l, b, r, t are in PDF points coordinates. Those take * into account that crop box does not have to begin in 0,0. * * Character is considered to be in a rect if point in the middle * of its baseline falls within rect (including border equality). */ public void find(double l, double b, double r, double t) { foundText = new ArrayList<String>(); int i; CharPos last = null; for( i=0; i<allCharacters.size(); i++ ) { CharPos cp = allCharacters.get(i); double x = (cp.bx + cp.ex)/2; if( x>=l && x<=r && (cp.y>=b && cp.y<=t || cp.y>=t && cp.y<=b) && cp.c.codePointAt(0)>=32 ) { if( last==null || last.y != cp.y ) { foundText.add(""); } int idx = foundText.size()-1; foundText.set(idx, foundText.get(idx)+cp.c); last = cp; } } } }; public class ExtractTexts { /* * MyRepresenter exists for the sole purpose of putting strings in * double quotes. * * Using DumperOptions.ScalarStyle.DOUBLE_QUOTED had this additional * feature of putting also numbers (ints and floats) in quotes and * tagging them with tags. To get around this I have to write this * function. * * This has also the nice property of putting key names in double * quotes producing well formed json. */ private static class MyRepresenter extends Representer { protected Node representScalar(Tag tag, String value, Character c) { if( tag==Tag.STR ) { return super.representScalar(tag,value,DumperOptions.ScalarStyle.DOUBLE_QUOTED.getChar()); } else { return super.representScalar(tag,value,c); } } }; public static void execute(String specFile, String inputOverride) throws IOException, DocumentException { ExtractTextSpec spec = ExtractTextSpec.loadFromFile(specFile); if( inputOverride!=null ) { spec.input = inputOverride; } /* DumperOptions options = new DumperOptions(); Yaml yaml = new Yaml(options); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); System.out.println(yaml.dump(spec)); */ execute(spec); } public static void stampRects(PdfReader reader, ExtractTextSpec spec) throws IOException, DocumentException { PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(spec.stampedOutput)); for (int i = 1; i <= reader.getNumberOfPages(); i++) { for(Rect rect : spec.rects ) { if( rect.page==i ) { Rectangle crop = reader.getPageSizeWithRotation(rect.page); double l = rect.rect.get(0)*crop.getWidth() + crop.getLeft(); double t = (1-rect.rect.get(1))*crop.getHeight() + crop.getBottom(); double r = rect.rect.get(2)*crop.getWidth() + crop.getLeft(); double b = (1-rect.rect.get(3))*crop.getHeight() + crop.getBottom(); PdfContentByte canvas = stamper.getOverContent(i); Rectangle frame = new Rectangle((float)l,(float)b,(float)r,(float)t); frame.setBorderColor(new BaseColor(0f, 1f, 0f)); frame.setBorderWidth(0.1f); frame.setBorder(15); canvas.rectangle(frame); } } } stamper.close(); } public static void execute(ExtractTextSpec spec) throws IOException, DocumentException { PdfReader reader = new PdfReader(spec.input); PdfReaderContentParser parser = new PdfReaderContentParser(reader); ExtractTextsRenderListener charsForPages[] = new ExtractTextsRenderListener[reader.getNumberOfPages()]; /* * Some pages may have no rectangles to find text in. This * avoids parsing of pages that are not required. */ for(Rect rect : spec.rects ) { if( rect.page>=1 && rect.page<reader.getNumberOfPages()) { ExtractTextsRenderListener rl = charsForPages[rect.page-1]; if( rl == null ) { rl = new ExtractTextsRenderListener(); parser.processContent(rect.page, rl); charsForPages[rect.page-1] = rl; } Rectangle crop = reader.getPageSizeWithRotation(rect.page); double l = rect.rect.get(0)*crop.getWidth() + crop.getLeft(); double t = (1-rect.rect.get(1))*crop.getHeight() + crop.getBottom(); double r = rect.rect.get(2)*crop.getWidth() + crop.getLeft(); double b = (1-rect.rect.get(3))*crop.getHeight() + crop.getBottom(); rl.find(l,b,r,t); rect.lines = new ArrayList<String>(); for( String line : rl.foundText ) { line = line.replaceAll("\\A[ \t\n\u000B\f\r\u00A0\uFEFF\u200B]+",""); line = line.replaceAll("[ \t\n\u000B\f\r\u00A0\uFEFF\u200B]\\z",""); line = line.replaceAll("[ \t\n\u000B\f\r\u00A0\uFEFF\u200B]+"," "); if( !line.equals("")) { rect.lines.add(line); } } } } if( spec.stampedOutput != null ) { stampRects(reader, spec); } reader.close(); DumperOptions options = new DumperOptions(); if( spec.yamlOutput!=null && spec.yamlOutput.equals(true)) { // output in yaml mode, useful for testing options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); } else { // output in json mode options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); } options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN ); options.setPrettyFlow(false); options.setWidth(Integer.MAX_VALUE); //Yaml yaml = new Yaml(options); Representer representer = new MyRepresenter(); representer.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); Yaml yaml = new Yaml(representer, options); String json = yaml.dump(spec); // Yaml generates a type marker !!FindTextSpec in output // that I have no idea how to suppress. I'm going to remove // it now. int k = json.indexOf("{"); if( k>0 ) { json = json.substring(k); } // We need to force utf-8 encoding here. PrintStream out = new PrintStream(System.out, true, "utf-8"); out.println(json); } }
import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class MySQLWrapper implements IWrapper{ private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://localhost/stockDB"; private static final String USER = "root"; private static final String PASS = "4thegalaxytabs"; private ANN neuralNetwork; public static void main(String[] arg){ MySQLWrapper a = new MySQLWrapper(); a.trainNetwork(); } public MySQLWrapper() { int [] h = {15,15,15}; neuralNetwork = new ANN(10, h, 1); } @Override public void trainNetwork() { Connection conn = null; Statement stmt = null; Map<String, Double[]>trainingData = new HashMap<String, Double[]>(); try{ // Set up and connect to the database Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT symbol, close_p FROM price"; ResultSet rs = stmt.executeQuery(sql); ArrayList<Double> tickerPrices = null; String ticker = null; while(rs.next()){ if (!rs.getString("symbol").equals(ticker)){ //does not contain the key if (tickerPrices != null && ticker != null){ Double[] tickerArray = new Double[tickerPrices.size()]; for (int ii = 0; ii < tickerArray.length; ii++){ tickerArray[ii] = tickerPrices.get(ii); } trainingData.put(ticker, tickerArray); } tickerPrices = new ArrayList<Double>(); } ticker = rs.getString("symbol"); Double closingP = rs.getDouble("close_p"); tickerPrices.add(closingP); } rs.close(); stmt.close(); conn.close(); } catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try int historyLength = 10; List<Double> buffer = new ArrayList<Double>(); for (Double[] s : trainingData.values()){ double max = Double.MIN_VALUE; double min = Double.MAX_VALUE; buffer = new ArrayList<Double>(); if (s.length > historyLength) { for(double d: s){ buffer.add(d); double[] values = new double[10]; if(buffer.size() > 10){ for(int i = 0; i < 10; i++){ values[i] = buffer.get(i); } double[] ele= {Math.max(0, Math.min(1.0, (buffer.get(10) - min)/(max-min)))}; double[] out = neuralNetwork.test(values, ele); System.out.println("batch end " + out[0] + " : " + out[1] + " : " + out[2] + " : " + ele[0] + " "+max+" "+min); if (Double.isNaN(ele[0])) System.exit(1); buffer.remove(0); // System.out.println(neuralNetwork.toStringWeights()); // System.out.println(d); } max = Math.max(max, d); min = Math.min(min, d); } } } } @Override public int predict() { return 0; } }
package dr.xml; import java.util.Collections; import java.util.Set; import java.util.TreeSet; /** * A syntax rule to ensure that exactly one of the given element * appears as a child. * * @version $Id: ElementRule.java,v 1.22 2005/05/24 20:26:01 rambaut Exp $ * * @author Alexei Drummond * @author Andrew Rambaut */ public class ElementRule implements XMLSyntaxRule { /** * Creates a required element rule. */ public ElementRule(Class type) { this(type, null, null, 1, 1); } /** * Creates a required element rule. */ public ElementRule(Class type, boolean optional) { this(type, null, null, (optional ? 0 : 1), 1); } /** * Creates a required element rule. */ public ElementRule(Class type, String description) { this(type, description, null, 1, 1); } /** * Creates a required element rule. */ public ElementRule(Class type, int min, int max) { this(type, null, null, min, max); } /** * Creates a required element rule. */ public ElementRule(Class type, String description, String example) { this(type, description, example, 1, 1); } /** * Creates a required element rule. */ public ElementRule(Class type, String description, int min, int max) { this(type, description, null, min, max); } /** * Creates a required element rule. */ public ElementRule(Class type, String description, String example, int min, int max) { if (type == null) throw new IllegalArgumentException("Class cannot be null!"); this.c = type; this.min = min; this.max = max; this.description = description; this.example = example; } /** * Creates a required element rule. */ public ElementRule(String name, Class type) { this.name = name; this.rules = new XMLSyntaxRule[] { new ElementRule(type)}; } /** * Creates a required element rule. */ public ElementRule(String name, Class type, String description) { this.name = name; this.description = description; this.rules = new XMLSyntaxRule[] { new ElementRule(type)}; } /** * Creates a required element rule. */ public ElementRule(String name, Class type, String description, boolean optional) { this.name = name; this.description = description; this.rules = new XMLSyntaxRule[] { new ElementRule(type)}; this.min = 1; this.max = 1; if (optional) this.min = 0; } /** * Creates a required element rule. */ public ElementRule(String name, Class type, String description, int min, int max) { this.name = name; this.description = description; this.rules = new XMLSyntaxRule[] { new ElementRule(type)}; this.min = min; this.max = max; } /** * Creates a required element rule. */ public ElementRule(String name, XMLSyntaxRule[] rules) { this.name = name; this.rules = rules; } /** * Creates an element rule. */ public ElementRule(String name, XMLSyntaxRule[] rules, boolean optional) { this.name = name; this.rules = rules; this.min = 1; this.max = 1; if (optional) this.min = 0; } /** * Creates an element rule. */ public ElementRule(String name, XMLSyntaxRule[] rules, int min, int max) { this.name = name; this.rules = rules; this.min = min; this.max = max; } /** * Creates a required element rule. */ public ElementRule(String name, XMLSyntaxRule[] rules, String description) { this.name = name; this.rules = rules; this.description = description; } /** * Creates an element rule. */ public ElementRule(String name, XMLSyntaxRule[] rules, String description, int min, int max) { this.name = name; this.rules = rules; this.description = description; this.min = min; this.max = max; } public Class getElementClass() { return c; } public String getDescription() { return description; } public boolean hasDescription() { return description != null; } public String getExample() { return example; } public boolean hasExample() { return example != null; } /** * @return true if the required attribute of the correct type is present. */ public boolean isSatisfied(XMLObject xo) { // first check if no matches and its optional int nameCount = 0; for (int i = 0; i < xo.getChildCount(); i++) { Object xoc = xo.getChild(i); if (xoc instanceof XMLObject && ((XMLObject)xoc).getName().equals(name)) { nameCount += 1; } } if (min == 0 && nameCount == 0) return true; // if !optional or nameCount > 0 then check if exactly one match exists int matchCount = 0; for (int i = 0; i < xo.getChildCount(); i++) { Object xoc = xo.getChild(i); if (isCompatible(xoc)) { matchCount += 1; } } return (matchCount >= min && matchCount <= max); } public boolean containsAttribute(String name) { return false; } /** * @return a string describing the rule. */ public String ruleString() { if (c != null) { return "ELEMENT of type " + getTypeName() + " REQUIRED"; } else { String howMany; if( min == 1 && max == 1 ) { howMany = "Exactly one"; } else if( (min <= 1) && max == Integer.MAX_VALUE ) { howMany = "Any number of"; } else { howMany = "between " + min + " and " + max; } StringBuffer buffer = new StringBuffer(howMany + " ELEMENT of name " + name + " REQUIRED containing"); for (XMLSyntaxRule rule : rules) { buffer.append("\n ").append(rule.ruleString()); } return buffer.toString(); } } /** * @return a string describing the rule. */ public String htmlRuleString(XMLDocumentationHandler handler) { if (c != null) { String html = "<div class=\"" + (min == 0 ? "optional" : "required") + "rule\">" + handler.getHTMLForClass(c); if (max > 1) { html += " elements ("; if (min == 0) { html += "zero"; } else if (min == 1) { html += "one"; } else if (min == max) { html += "exactly " + min; } if (max != min) { if (max < Integer.MAX_VALUE) { html += " to " + max; } else { html += " or more"; } } } else { html += " element ("; if (min == 0) { html += "zero or one"; } else { html += "exactly one"; } } html += ")"; if (hasDescription()) { html += "<div class=\"description\">" + getDescription() + "</div>\n"; } return html + "</div>\n"; } else { StringBuffer buffer = new StringBuffer("<div class=\"" + (min == 0 ? "optional" : "required") + "compoundrule\">Element named <span class=\"elemname\">" + name + "</span> containing:"); for (XMLSyntaxRule rule : rules) { buffer.append(rule.htmlRuleString(handler)); } if (hasDescription()) { buffer.append("<div class=\"description\">").append(getDescription()).append("</div>\n"); } buffer.append("</div>\n"); return buffer.toString(); } } public String wikiRuleString(XMLDocumentationHandler handler, String prefix) { if (c != null) { String wiki = prefix + handler.getHTMLForClass(c); if (max > 1) { wiki += " elements ("; if (min == 0) { wiki += "zero"; } else if (min == 1) { wiki += "one"; } else if (min == max) { wiki += "exactly " + min; } if (max != min) { if (max < Integer.MAX_VALUE) { wiki += " to " + max; } else { wiki += " or more"; } } } else { wiki += " element ("; if (min == 0) { wiki += "zero or one"; } else { wiki += "exactly one"; } } wiki += ")\n"; if (hasDescription()) { wiki += prefix + ":''" + getDescription() + "''\n"; } else { wiki += prefix + ":\n"; } return wiki; } else { StringBuffer buffer = new StringBuffer(prefix + "Element named <code>&lt;" + name + "&gt;</code> containing:\n"); for (XMLSyntaxRule rule : rules) { buffer.append(rule.wikiRuleString(handler, prefix + "*")); } if (hasDescription()) { buffer.append(prefix).append("*:''").append(getDescription()).append("''\n"); } else { buffer.append(prefix).append("*:\n"); } return buffer.toString(); } } /** * @return a string describing the rule. */ public String ruleString(XMLObject xo) { return ruleString(); } public boolean isAttributeRule() { return false; } public String getName() { return name; } public XMLSyntaxRule[] getRules() { return rules; } /** * @return true if the given object is compatible with the required class. */ private boolean isCompatible(Object o) { if (rules != null) { if (o instanceof XMLObject) { XMLObject xo = (XMLObject)o; if (xo.getName().equals(name)) { for (XMLSyntaxRule rule : rules) { if (!rule.isSatisfied(xo)) { return false; } } return true; } } } else { if (c == null) { return true; } if (c.isInstance(o)) { return true; } if (o instanceof String) { if (c == Double.class) { try { Double.parseDouble((String)o); return true; } catch (NumberFormatException nfe) { return false; } } if (c == Integer.class) { try { Integer.parseInt((String)o); return true; } catch (NumberFormatException nfe) { return false; } } if (c == Float.class) { try { Float.parseFloat((String)o); return true; } catch (NumberFormatException nfe) { return false; } } if (c == Boolean.class) { return (o.equals("true") || o.equals("false")); } if (c == Number.class) { try { Double.parseDouble((String)o); return true; } catch (NumberFormatException nfe) { return false; } } } } return false; } /** * @return a pretty name for a class. */ private String getTypeName() { if (c == null) return "Object"; String name = c.getName(); return name.substring(name.lastIndexOf('.')+1); } /** * @return a set containing the required types of this rule. */ public Set<Class> getRequiredTypes() { if (c != null) { return Collections.singleton(c); } else { Set<Class> set = new TreeSet<Class>(ClassComparator.INSTANCE); for (XMLSyntaxRule rule : rules) { set.addAll(rule.getRequiredTypes()); } return set; } } public int getMin() { return min; } public int getMax() { return max; } public String toString() { return ruleString(); } private Class c = null; private String name = null; private XMLSyntaxRule[] rules = null; private int min = 1; private int max = 1; private String description = null; private String example = null; }
package editor; import game.DataHandler; import game.GamePanel; import java.awt.Point; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import structures.Ball; import structures.Level; import structures.Point2d; /** * Utility for computing the solutions of levels in parallel. The main method * can be used as a command line utility that will output the data to pre-set * file paths. * @author Sean Lewis */ public class LevelSolver { /** * Args input syntax: * - put "GG all" to output all standard GG level data. * * - put "GG" if standard game levels are being solved: * - if so, place numbers afterwards for which levels * - ex: GG 1 2 3 4 5 * - this solves the first 5 levels * * - otherwise, put "OTHER" as the first command * - the 2nd command should be the input file * - the 3rd command should be the output directory destination * - then place the file name where levels are being read from * - place numbers the same was as in standard input * - NOTE: the first level will be level 0 */ public static void main(String[] args) throws IOException { if(args[0].equals("GG") && args[1].equals("all")) { System.out.println("Reading all stanard input levels."); List<Level> levels = new DataHandler().getLevelData("levels/levels.txt"); for(int i = 0; i < levels.size(); i++) { System.out.println("Reading level " + (i+1) + "."); File f = new File("levels/data/level" + (i+1) + ".txt"); PrintWriter pw = new PrintWriter(f); LevelSolver.printSolutionSet(levels.get(i), pw); pw.close(); } } else if(args[0].equals("GG")) { System.out.println("Reading stanard input levels."); List<Level> levels = new DataHandler().getLevelData("levels/levels.txt"); for(int i = 1; i < args.length; i++) { int level = Integer.parseInt(args[i]); System.out.println("Reading level " + level + "."); File f = new File("levels/data/level" + level + ".txt"); PrintWriter pw = new PrintWriter(f); LevelSolver.printSolutionSet(levels.get(level - 1), pw); pw.close(); } } else { System.out.println("Reading non-stanard input levels."); List<Level> levels = new DataHandler().getLevelData(args[1]); String outDir = args[2]; for(int i = 2; i < args.length; i++) { int level = Integer.parseInt(args[i]); System.out.println("Reading level " + level + "."); File f = new File(outDir + "/level" + level + ".txt"); PrintWriter pw = new PrintWriter(f); LevelSolver.printSolutionSet(levels.get(i), pw); pw.close(); } } System.out.println("Finished."); } private static final int MAX = GamePanel.MaxInitialMagnitude; /** * Computes all solutions to the level and returns in the points in a List. * @param level the level to solve * @return all points such that level.possibleWin(p) returns true */ public static Collection<java.awt.Point> getSolutionSet(Level level) { Ball ball = level.getBall(); List<Task> tasks = new ArrayList<Task>(); // iterate over all possible x values int leftX = (int) (ball.getCenter().x - MAX); int rightX = (int) (ball.getCenter().x + MAX); for (int x = leftX; x <= rightX; x++) { if (xOutOfBounds(level, x)) { continue; } // iterate over all possible y values int bottomY = (int) (ball.getCenter().y - MAX); int topY = (int) (ball.getCenter().y + MAX); List<Point2d> points = new ArrayList<Point2d>(); for (int y = bottomY; y <= topY; y++) { points.add(new Point2d(x, y)); } tasks.add(new LevelSolver().new Task(level, points)); } // parallel computations: ExecutorService executor = Executors.newCachedThreadPool(); for (Task t : tasks) executor.execute(t); executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException e) { e.printStackTrace(); } List<java.awt.Point> solutions = new ArrayList<java.awt.Point>(); for(Task t : tasks) solutions.addAll(t.getSolutions()); return solutions; } /* * Inner class for computing a list of test points. */ private class Task implements Runnable { private static final double sqr = MAX * MAX; private List<Point2d> inputPoints; private List<Point> solutionPoints; private Level level; public Task(Level level, List<Point2d> inputPoints) { this.level = level; this.inputPoints = inputPoints; solutionPoints = new ArrayList<Point>(); } public void run() { Ball ball = level.getBall(); for (Point2d point : inputPoints) { double x = point.getX(); double y = point.getY(); boolean outOfBounds = yOutOfBounds(level, y) || isOutOfBounds(level, ball.getCenter()); boolean inShotRange = Math.pow(x - ball.getCenter().x, 2) + Math.pow(y - ball.getCenter().y, 2) <= sqr; if (!outOfBounds && inShotRange) { if (level.possibleWin(point, MAX)) { solutionPoints.add(point.getIntegerPoint()); } } } } public Collection<Point> getSolutions() { return solutionPoints; } } /** * Prints a solution set through a PrintWriter. * @param solutions the solution set to print * @param pw the PrintWriter to print through */ public static void printSolutionSet(Collection<java.awt.Point> solutions, PrintWriter pw) { for (java.awt.Point p : solutions) { pw.println(p.x + " " + p.y); } pw.close(); } /** * Computes the level data and then prints the information to a PrintWriter. * @param level the Level to solve * @param pw the PrintWriter to print through */ public static void printSolutionSet(Level level, PrintWriter pw) { printSolutionSet(getSolutionSet(level), pw); } /** * Reads in a solution set from a file. * @param fileName the file to read from * @return a List of solution points for the level * @throws FileNotFoundException if the file was not found */ public static Collection<java.awt.Point> readSolutionSet(String fileName) throws FileNotFoundException { List<java.awt.Point> solutions = new ArrayList<java.awt.Point>(); Scanner infile = new Scanner(new File(fileName)); while (infile.hasNext()) { int x = infile.nextInt(); int y = infile.nextInt(); java.awt.Point p = new java.awt.Point(x, y); solutions.add(p); } infile.close(); return solutions; } private static boolean xOutOfBounds(Level level, double x) { boolean onLeft = x + level.getScreenXShift() < 0; boolean onRight = x + level.getScreenXShift() > GamePanel.Width; return onLeft || onRight; } private static boolean yOutOfBounds(Level level, double y) { boolean onTop = y + level.getScreenYShift() < 0; boolean onBottom = y + level.getScreenYShift() > GamePanel.Height - 20; return onTop || onBottom; } private static boolean isOutOfBounds(Level level, Point2d center) { return xOutOfBounds(level, center.getX()) || yOutOfBounds(level, center.getY()); } }
package arena; // Libraries import scenario.*; import stackable.*; import exception.*; import parameters.*; import players.Base; import operation.Operation; /** * <b>Action</b><br> * Decide when a robot may * (or not) make an action, * changing the arena * accordingly to it. * @see World * * @author Karina Suemi Awoki * @author Renato Cordeiro Ferreira * @author Vinicius Nascimento Silva */ public class Action implements Game { /** * Given a map, a robot and an operation, * calls the method for this operation to * the correspondent robot and map, returning * the answer to the caller. * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) * * @throws InvalidOperationException */ static Stackable[] ctrl (Map map, Robot turn, Operation op) throws InvalidOperationException { Stackable[] stackable = null; boolean can = false; switch(op.getAction()) { case "MOVE" : can = MOVE (map, turn, op); break; case "DRAG" : can = DRAG (map, turn, op); break; case "DROP" : can = DROP (map, turn, op); break; case "SKIP" : can = SKIP (map, turn, op); break; case "HIT" : can = HIT (map, turn, op); break; case "LOOK" : stackable = LOOK (map, turn, op); break; case "SEE" : stackable = SEE (map, turn, op); break; case "ASK" : stackable = ASK (map, turn, op); break; } if(stackable == null) { stackable = new Stackable[1]; stackable[0] = new Num( (can) ? 1 : 0 ); } return stackable; } /** * Operation MOVE.<br> * Move, if possible, the robot to the selected * position in the map. * @see robot.Syst#MOVE * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) */ static boolean MOVE (Map map, Robot turn, Operation op) { // Extract direction info from operation Stackable[] s = op.getArgument(); Direction d = (Direction) s[0]; int[] update = d.get(turn.i); int newI = turn.i + update[0]; int newJ = turn.j + update[1]; if(newI >= MAP_SIZE || newJ >= MAP_SIZE || newI < 0 || newJ < 0 || map.map[newI][newJ].scenario != null) return false; // Takes out from original position Robot robot = (Robot) map.map[turn.i][turn.j].removeScenario(); // Update robot attributes turn.i = newI; turn.j = newJ; // Goes to the new position in the map map.map[turn.i][turn.j].setScenario(robot); return true; } /** * Operation DRAG.<br> * Drag, if possible, an item in the selected * position in the map, storing it inside the * robot. * @see robot.Syst#DRAG * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) */ static boolean DRAG (Map map, Robot turn, Operation op) { // Extract direction info from operation Stackable[] s = op.getArgument(); Direction d = (Direction) s[0]; int[] update = d.get(turn.i); int lookI = turn.i + update[0]; int lookJ = turn.j + update[1]; int cont = 0; if(lookI >= MAP_SIZE || lookJ >= MAP_SIZE || lookI < 0 || lookJ < 0 || map.map[lookI][lookJ].item == null) return false; for(int i = 0; i < turn.slots.length && turn.slots[i] != null; i++) cont++; if(cont >= turn.slots.length) return false; Debugger.say(" [DRAG]", map.map[lookI][lookJ] ); turn.slots[cont] = map.map[lookI][lookJ].removeItem(); Debugger.say(" [DRAG]", map.map[lookI][lookJ] ); return true; } /** * Operation DROP.<br> * Drop, if possible, an item in the selected * position in the map, taking it from inside * robot. * @see robot.Syst#DROP * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) */ static boolean DROP (Map map, Robot turn, Operation op) { Stackable[] s = op.getArgument(); Direction d = (Direction) s[0]; int[] update = d.get(turn.i); int lookI = turn.i + update[0]; int lookJ = turn.j + update[1]; int cont = 0; if(lookI >= MAP_SIZE || lookJ >= MAP_SIZE || lookI < 0 || lookJ < 0 || map.map[lookI][lookJ].item != null) return false; // Takes out from original position Robot robot = (Robot) map.map[turn.i][turn.j].scenario; for(int i = 0; i < turn.slots.length && robot.slots[i] != null; i++) cont++; if(cont == 0) return false; Debugger.say(" [DROP]", map.map[lookI][lookJ]); boolean allow = false; if(map.map[lookI][lookJ].scenario instanceof Base) { // If the scenario is a base, throw the crystal on it Base b = (Base) map.map[lookI][lookJ].scenario; robot.removeSlots(cont - 1); allow = b.addCrystal(turn); } else { // Otherwise, just throws the item (if possible) if(map.map[lookI][lookJ].item != null) { robot.removeSlots(cont - 1); allow = true; } } Debugger.say(" [DROP]", map.map[lookI][lookJ]); return allow; } /** * Operation SKIP.<br> * Make no operation (skip turn). * @see robot.Syst#SKIP * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) */ static boolean SKIP (Map map, Robot turn, Operation op) { Debugger.say(" [SKIP]"); // Debug return true; } /** * Operation HIT.<br> * Hit, if exists, the scenario in the selected * position in the map, making the damage of the * atack made by the robot. * @see robot.Syst#HIT * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) */ static boolean HIT (Map map, Robot turn, Operation op) { String pre = " [HIT]"; Stackable[] s = op.getArgument(); Attack atk = (Attack) s[0]; Num num = (Num) s[1]; Direction[] dirs = new Direction[(int)num.getNumber()]; int damage = 0; int distance = (int) num.getNumber(); // If we add more commands to HIT, we // need to change this +2. for(int i = 0; i < distance; i++) dirs[i] = (Direction) s[i + 2]; switch (atk.getAttack()) { case "MELEE" : damage = turn.damageMelee; if(distance > 1) return false; break; case "RANGED": damage = turn.damageRange; if(distance > turn.maxRange) return false; break; } // Debug String directions = ""; for(Direction d: dirs) directions += d.toString() + " "; Debugger.say(" [HIT]", "[", atk.getAttack() + "]"); Debugger.say(" [HIT]", " ", directions); int lookI = turn.i; int lookJ = turn.j; Scenario thing = null; for(Direction d: dirs) { int[] update = d.get(lookI); lookI += update[0]; lookJ += update[1]; // Debug Debugger.say(" [HIT]", map.map[lookI][lookJ]); if(lookI >= MAP_SIZE || lookJ >= MAP_SIZE || lookI < 0 || lookJ < 0) return false; thing = map.map[lookI][lookJ].getScenario(); if(thing != null) { // No attacks agains allies! if(thing.getTeam() == turn.getTeam()) { Debugger.say(" [HIT]", "[NONE]"); Debugger.say(" [HIT] ", thing, " is an ally"); return false; } int done = thing.takeDamage(damage); Debugger.say(" [HIT]", "[FIGHT]"); Debugger.say(" [DAMAGE:", damage, "]"); Debugger.say(" [REMAIN:", done , "]"); if(thing.getHP() <= 0) { Debugger.say(" [HIT]", "[DESTROYED]"); World.destroy(lookI, lookJ); } break; } } if(thing == null) { Debugger.say(" [HIT]", "[EMPTY]"); return false; } return true; } /** * Operation LOOK.<br> * Scans the terrain in a given position, to be * analysed by the robot virtual machine. * @see robot.Syst#LOOK * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) */ static Stackable[] LOOK (Map map, Robot turn, Operation op) { // Extract direction info from operation Stackable[] s = op.getArgument(); Direction d = (Direction) s[0]; int[] update = d.get(turn.i); int lookI = turn.i + update[0]; int lookJ = turn.j + update[1]; if(lookI > MAP_SIZE) lookI %= MAP_SIZE; else if(lookI < 0) lookI += MAP_SIZE; if(lookJ > MAP_SIZE) lookJ %= MAP_SIZE; else if(lookJ < 0) lookJ += MAP_SIZE; // Debug Debugger.say(" [LOOK] ", "dir: " , d); Debugger.say(" [LOOK] ", "pos: I: ", lookI); Debugger.say(" [LOOK] ", "pos: J: ", lookJ); if(lookI >= MAP_SIZE || lookJ >= MAP_SIZE || lookI < 0 || lookJ < 0) return null; // Debug Debugger.say(" [LOOK] ", "ter: ", map.map[lookI][lookJ]); Stackable[] st = new Stackable[1]; st[0] = map.map[lookI][lookJ]; // Takes out from original position return st; } /** * Operation SEE.<br> * Scans the neighborhood of the robot (accordingly * to its position in the map and its sight). * @see robot.Syst#SEE * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) * * @throws InvalidOperationException */ static Stackable[] SEE (Map map, Robot turn, Operation op) throws InvalidOperationException { Direction d; Stackable[] st = new Stackable[1]; int nTerrain; if(turn.sight == 1) nTerrain = 7; else nTerrain = 19; Terrain[] ter = new Terrain[nTerrain]; int lookI; int lookJ; for(int i = 0; i < nTerrain; i++) { d = new Direction(0, i); int[] update = d.get(turn.i); lookI = turn.i + update[0]; lookJ = turn.j + update[1]; if(lookI >= MAP_SIZE || lookJ >= MAP_SIZE || lookI < 0 || lookJ < 0) ter[i] = null; else { if(i < 7) ter[i] = map.map[lookI][lookJ]; else { d = new Direction(1, i); update = d.get(lookI); lookI += update[0]; lookJ += update[1]; if(lookI >= MAP_SIZE || lookJ >= MAP_SIZE || lookI < 0 || lookJ < 0) ter[i] = null; else ter[i] = map.map[lookI][lookJ]; } } } Around a = new Around(ter); st[0] = (Stackable) a; return st; } /** * Operation ASK.<br> * Passes an information to the robot, about * its own 'body' placed in the world (position). * @see robot.Syst#ASK * * @param map Map of the arena * @param turn Robot that may do the action * @param op Operation to be executed (or not) */ static Stackable[] ASK (Map map, Robot turn, Operation op) { Stackable[] s = op.getArgument(); Text t = (Text) s[0]; switch (t.getText()) { case "position": case "Position": Num one = new Num(1); Num x = new Num(turn.i); Num y = new Num(turn.j); s = new Stackable[3]; s[2] = one; s[1] = x; s[0] = y; break; default: Num zero = new Num(0); s = new Stackable[1]; s[0] = zero; break; } // Debug Debugger.say(" [ASK] ", t); return s; } }
package sampleview.views; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.eclipse.core.expressions.ElementHandler; import org.eclipse.core.expressions.EvaluationContext; import org.eclipse.core.expressions.EvaluationResult; import org.eclipse.core.expressions.Expression; import org.eclipse.core.expressions.ExpressionConverter; import org.eclipse.core.expressions.IEvaluationContext; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.part.ViewPart; import samplemodel.SampleModel; import samplemodel.SampleModelOperation; public class SampleView extends ViewPart { /** * The ID of the view as specified by the extension. */ public static final String ID = "sampleview.views.SampleView"; private ListViewer viewer; private IConfigurationElement[] configurationElements; private List<Object> myData; /** * The constructor. */ public SampleView() { } /** * This is a callback that will allow us to create the viewer and initialize it. */ public void createPartControl(Composite parent) { viewer = new ListViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new ArrayContentProvider()); myData = createSampleData(); viewer.setInput(myData); hookContextMenu(); } private List<Object> createSampleData() { List<Object> res = new ArrayList<Object>(); res.add(new SampleModel(12)); res.add(new SampleModel("A String Object")); res.add(new SampleModel(133.4)); res.add(new SampleModel("... another one")); res.add(new Date()); res.add(new SampleModel(332.3)); res.add(new SampleModel("Another string")); res.add(new SampleModel("smiles")); res.add(new SampleModel(1)); res.add(new SampleModel(5)); return res; } private void hookContextMenu() { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { SampleView.this.fillContextMenu(manager); } }); Menu menu = menuMgr.createContextMenu(viewer.getControl()); viewer.getControl().setMenu(menu); getSite().registerContextMenu(menuMgr, viewer); } private void fillContextMenu(final IMenuManager manager) { final IConfigurationElement[] operations = getContributedOperations(); final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection(); EvaluationContext context = new EvaluationContext(null, selection); final Object[] items = selection.toArray(); for (IConfigurationElement operation : operations) { boolean applicable = isApplicable(operation, context); if (applicable) { final String name = operation.getAttribute("name"); final IConfigurationElement cfg = operation; manager.add(new Action(name) { @Override public void run() { try { SampleModelOperation operation = (SampleModelOperation) cfg.createExecutableExtension("class"); Object result = operation.execute(items); MessageDialog.openInformation(getSite().getShell(), name, name + " operation result is " + result.toString()); } catch (CoreException e) { e.printStackTrace(); } } }); } } } private boolean isApplicable(IConfigurationElement configElement, IEvaluationContext evaluationContext) { boolean applicable = true; IConfigurationElement[] children = configElement.getChildren("applicable"); final ElementHandler elementHandler = ElementHandler.getDefault(); final ExpressionConverter converter = ExpressionConverter.getDefault(); if (children.length > 0) { IConfigurationElement applicableElement = children[0]; final IConfigurationElement[] expressionElements = applicableElement.getChildren(); if (expressionElements.length > 0) { final IConfigurationElement expressionElement = expressionElements[0]; try { Expression applicableExpression = elementHandler.create(converter, expressionElement); applicable = applicableExpression.evaluate(evaluationContext).equals( EvaluationResult.TRUE); } catch (CoreException e) { e.printStackTrace(); } } } return applicable; } private IConfigurationElement[] getContributedOperations() { if (configurationElements == null) { // lazy initialization configurationElements = Platform.getExtensionRegistry().getConfigurationElementsFor( "sampleModel.SampleModelOperation"); } return configurationElements; } /** * Passing the focus request to the viewer's control. */ public void setFocus() { viewer.getControl().setFocus(); } }
import java.util.Date; import java.util.Arrays; /** * A fix-sized array of students * array length should always be equal to the number of stored elements * after the element was removed the size of the array should be equal to the number of stored elements * after the element was added the size of the array should be equal to the number of stored elements * null elements are not allowed to be stored in the array * * You may add new methods, fields to this class, but DO NOT RENAME any given class, interface or method * DO NOT PUT any classes into packages * */ public class StudentGroup implements StudentArrayOperation { private Student[] students; Student[] b; /** * DO NOT remove or change this constructor, it will be used during task check * @param length */ public StudentGroup(int length) { this.students = new Student[length]; } @Override public Student[] getStudents() { // Add your implementation here return this.students; } @Override public void setStudents(Student[] students) { this.students = students;// Add your implementation here } @Override public Student getStudent(int index) { if(index<0 || index >= students.length) throw new IllegalArgumentException("invalid index"); else return this.students[index]; } @Override public void setStudent(Student student, int index) { if(student == null || index<0 || index >= this.students.length) throw new IllegalArgumentException("invalid index"); else { this.students[index] = student; } } @Override public void addFirst(Student student) { if (student==null) { throw new IllegalArgumentException("invalid data"); } else { for(int i = students.length;i>0;i { students[i] =students[i-1]; } students[0] = student; b=Arrays.copyOf(students,students.length); students=b; } } @Override public void addLast(Student student) { if (student==null) { throw new IllegalArgumentException("invalid data"); } else { students[students.length]=student; } } @Override public void add(Student student, int index) { if(student == null || index<0 || index >= students.length) throw new IllegalArgumentException("invalid arguments"); else { for(int i = students.length;i>index;i { students[i] =students[i-1]; } students[index] = student; b=Arrays.copyOf(students,students.length); students=b; } } @Override public void remove(int index) { if( index<0 || index >= this.students.length) throw new IllegalArgumentException("invalid arguments"); else { for(int i = index; i<this.students.length-1; i++) { this.students[i] =this.students[i+1]; } this.students[i+1] = null; b=Arrays.copyOf(this.students,this.students.length); this.students=b; } } @Override public void remove(Student student) { // Add your implementation here } @Override public void removeFromIndex(int index) { // Add your implementation here } @Override public void removeFromElement(Student student) { // Add your implementation here } @Override public void removeToIndex(int index) { // Add your implementation here } @Override public void removeToElement(Student student) { // Add your implementation here } @Override public void bubbleSort() { // Add your implementation here } @Override public Student[] getByBirthDate(Date date) { int j=-1, flag=0, n = students.length; Student[] stu= new Student[n]; if(date==null) throw new IllegalArgumentException("invalid arguments"); else { for(int i=0; i<n; i++) { } if(j==-1) { throw new IllegalArgumentException("not found in the array"); } else return stu; } } @Override public Student[] getBetweenBirthDates(Date firstDate, Date lastDate) { // Add your implementation here return null; } @Override public Student[] getNearBirthDate(Date date, int days) { // Add your implementation here return null; } @Override public int getCurrentAgeByDate(int indexOfStudent) { // Add your implementation here return 0; } @Override public Student[] getStudentsByAge(int age) { // Add your implementation here return null; } @Override public Student[] getStudentsWithMaxAvgMark() { int n; float max; return null; } @Override public Student getNextStudent(Student student) { int flag=0,j= students.length-1; if(student == null) throw new IllegalArgumentException("invalid parameter"); else { for(int i = 0 ; i<j;i++) { if(students[i] == student) { flag = 1; j = i+1; break; } } if(flag==0) throw new IllegalArgumentException("do not exists"); else return students[j]; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "LATENCY", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for feeding, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2021-09-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag( "hide-shared-routing-endpoint", false, List.of("tokle", "bjormel"), "2020-12-02", "2021-09-01", "Whether the controller should hide shared routing layer endpoint", "Takes effect immediately", APPLICATION_ID ); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2022-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ORCHESTRATE_MISSING_PROXIES = defineFeatureFlag( "orchestrate-missing-proxies", true, List.of("hakonhall"), "2021-08-05", "2021-10-05", "Whether the Orchestrator can assume any missing proxy services are down.", "Takes effect on first (re)start of config server"); public static final UnboundBooleanFlag GROUP_SUSPENSION = defineFeatureFlag( "group-suspension", true, List.of("hakon"), "2021-01-22", "2021-08-22", "Allow all content nodes in a hierarchical group to suspend at the same time", "Takes effect on the next suspension request to the Orchestrator.", APPLICATION_ID); public static final UnboundBooleanFlag ENCRYPT_DIRTY_DISK = defineFeatureFlag( "encrypt-dirty-disk", false, List.of("hakonhall"), "2021-05-14", "2021-10-05", "Allow migrating an unencrypted data partition to being encrypted when (de)provisioned.", "Takes effect on next host-admin tick."); public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag( "enable-feed-block-in-distributor", true, List.of("geirst"), "2021-01-27", "2021-09-01", "Enables blocking of feed in the distributor if resource usage is above limit on at least one content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag DEDICATED_CLUSTER_CONTROLLER_FLAVOR = defineStringFlag( "dedicated-cluster-controller-flavor", "", List.of("jonmv"), "2021-02-25", "2021-08-25", "Flavor as <vpu>-<memgb>-<diskgb> to use for dedicated cluster controller nodes", "Takes effect immediately, for subsequent provisioning", APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2021-12-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag( "generate-non-mtls-endpoint", true, List.of("tokle"), "2021-02-18", "2021-10-01", "Whether to generate the non-mtls endpoint", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2021-09-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag NUM_DISTRIBUTOR_STRIPES = defineIntFlag( "num-distributor-stripes", 0, List.of("geirst", "vekterli"), "2021-04-20", "2021-09-01", "Specifies the number of stripes used by the distributor. When 0, legacy single stripe behavior is used.", "Takes effect after distributor restart", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 16, List.of("balder", "vekterli"), "2021-06-06", "2021-09-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 1024, List.of("balder", "vekterli"), "2021-06-06", "2021-09-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_EXTERNAL_RANK_EXPRESSION = defineFeatureFlag( "use-external-rank-expression", false, List.of("baldersheim"), "2021-05-24", "2021-09-01", "Whether to use distributed external rank expression or inline in rankproperties", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag DISTRIBUTE_EXTERNAL_RANK_EXPRESSION = defineFeatureFlag( "distribute-external-rank-expression", false, List.of("baldersheim"), "2021-05-27", "2021-09-01", "Whether to use distributed external rank expression files by filedistribution", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag LARGE_RANK_EXPRESSION_LIMIT = defineIntFlag( "large-rank-expression-limit", 0x10000, List.of("baldersheim"), "2021-06-09", "2021-09-01", "Limit for size of rank expressions distributed by filedistribution", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_ENCRYPTING_HOSTS = defineIntFlag( "max-encrypting-hosts", 0, List.of("mpolden", "hakonhall"), "2021-05-27", "2021-10-01", "The maximum number of hosts allowed to encrypt their disk concurrently", "Takes effect on next run of HostEncrypter, but any currently encrypting hosts will not be cancelled when reducing the limit"); public static final UnboundBooleanFlag REQUIRE_CONNECTIVITY_CHECK = defineFeatureFlag( "require-connectivity-check", true, List.of("arnej"), "2021-06-03", "2021-09-01", "Require that config-sentinel connectivity check passes with good quality before starting services", "Takes effect on next restart", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag THROW_EXCEPTION_IF_RESOURCE_LIMITS_SPECIFIED = defineFeatureFlag( "throw-exception-if-resource-limits-specified", false, List.of("hmusum"), "2021-06-07", "2021-09-07", "Whether to throw an exception in hosted Vespa if the application specifies resource limits in services.xml", "Takes effect on next deployment through controller", APPLICATION_ID); public static final UnboundBooleanFlag DRY_RUN_ONNX_ON_SETUP = defineFeatureFlag( "dry-run-onnx-on-setup", false, List.of("baldersheim"), "2021-06-23", "2021-09-01", "Whether to dry run onnx models on setup for better error checking", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundListFlag<String> DEFER_APPLICATION_ENCRYPTION = defineListFlag( "defer-application-encryption", List.of(), String.class, List.of("mpolden", "hakonhall"), "2021-06-23", "2021-10-01", "List of applications where encryption of their host should be deferred", "Takes effect on next run of HostEncrypter"); public static final UnboundBooleanFlag PODMAN3 = defineFeatureFlag( "podman3", true, List.of("mpolden"), "2021-07-05", "2021-09-01", "Whether to use Podman 3 on supported hosts", "Takes effect on host-admin restart"); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2021-10-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_SERVICE_VIEW_APIS = defineListFlag( "allowed-service-view-apis", List.of("state/v1/"), String.class, List.of("mortent"), "2021-08-05", "2021-11-01", "Apis allowed to proxy through the service view api", "Takes effect immediately"); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package org.apache.cordova; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.cordova.api.LOG; import org.apache.cordova.api.PluginManager; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.content.res.XmlResourceParser; import android.util.AttributeSet; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebSettings.LayoutAlgorithm; import android.app.Activity; public class CordovaWebView extends WebView { public static final String TAG = "CordovaWebView"; /** The authorization tokens. */ private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>(); /** The whitelist **/ private ArrayList<Pattern> whiteList = new ArrayList<Pattern>(); private HashMap<String, Boolean> whiteListCache = new HashMap<String,Boolean>(); protected PluginManager pluginManager; public CallbackServer callbackServer; /** Actvities and other important classes **/ private Context mCtx; CordovaWebViewClient viewClient; private CordovaChromeClient chromeClient; //This is for the polyfil history private String url; String baseUrl; private Stack<String> urls = new Stack<String>(); protected int loadUrlTimeout; protected long loadUrlTimeoutValue; public CordovaWebView(Context context) { super(context); mCtx = context; setup(); } public CordovaWebView(Context context, AttributeSet attrs) { super(context, attrs); mCtx = context; setup(); } public CordovaWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mCtx = context; setup(); } public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) { super(context, attrs, defStyle, privateBrowsing); mCtx = context; setup(); } private void setup() { this.setInitialScale(0); this.setVerticalScrollBarEnabled(false); this.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); //Set the nav dump for HTC settings.setNavDump(true); // Enable database settings.setDatabaseEnabled(true); String databasePath = mCtx.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); //Setup the WebChromeClient and WebViewClient setWebViewClient(new CordovaWebViewClient(mCtx, this)); setWebChromeClient(new CordovaChromeClient(mCtx, this)); // Enable DOM storage settings.setDomStorageEnabled(true); // Enable built-in geolocation settings.setGeolocationEnabled(true); //Start up the plugin manager this.pluginManager = new PluginManager(this, mCtx); } //This sets it up so that we can save copies of the clients that we might need later. public void setWebViewClient(CordovaWebViewClient client) { viewClient = client; super.setWebViewClient(client); } public void setWebChromeClient(CordovaChromeClient client) { chromeClient = client; super.setWebChromeClient(client); } /** * Sets the authentication token. * * @param authenticationToken * the authentication token * @param host * the host * @param realm * the realm */ public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) { if(host == null) { host = ""; } if(realm == null) { realm = ""; } authenticationTokens.put(host.concat(realm), authenticationToken); } /** * Removes the authentication token. * * @param host * the host * @param realm * the realm * @return the authentication token or null if did not exist */ public AuthenticationToken removeAuthenticationToken(String host, String realm) { return authenticationTokens.remove(host.concat(realm)); } /** * Gets the authentication token. * * In order it tries: * 1- host + realm * 2- host * 3- realm * 4- no host, no realm * * @param host * the host * @param realm * the realm * @return the authentication token */ public AuthenticationToken getAuthenticationToken(String host, String realm) { AuthenticationToken token = null; token = authenticationTokens.get(host.concat(realm)); if(token == null) { // try with just the host token = authenticationTokens.get(host); // Try the realm if(token == null) { token = authenticationTokens.get(realm); } // if no host found, just query for default if(token == null) { token = authenticationTokens.get(""); } } return token; } /** * Clear all authentication tokens. */ public void clearAuthenticationTokens() { authenticationTokens.clear(); } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ public void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile(".*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?"))); } else { whiteList.add(Pattern.compile("^https?://(.*\\.)?"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://"))); } else { whiteList.add(Pattern.compile("^https?://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ public boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } @Override public void loadUrl(String url) { if (!url.startsWith("javascript:")) { this.url = url; if (this.baseUrl == null) { int i = url.lastIndexOf('/'); if (i > 0) { this.baseUrl = url.substring(0, i+1); } else { this.baseUrl = this.url + "/"; } } // Create callback server and plugin manager if (callbackServer == null) { callbackServer = new CallbackServer(); callbackServer.init(url); } else { callbackServer.reinit(url); } pluginManager.init(); this.urls.push(url); } super.loadUrl(url); } public void sendJavascript(String statement) { callbackServer.sendJavascript(statement); } public void postMessage(String id, String data) { pluginManager.postMessage(id, data); } /** * Returns the top url on the stack without removing it from * the stack. */ public String peekAtUrlStack() { if (urls.size() > 0) { return urls.peek(); } return ""; } /** * Add a url to the stack * * @param url */ public void pushUrl(String url) { urls.push(url); } }
/** * @brief A test class for OthRules * @details * * OthRules.winCondition is tested 3 times. * * OthRules.checkValidSet is tested 1 time(s). * during this test, methods: * OthRules.checkAvailableMatch * OthRules.checkVerticalDown * OthRules.checkVerticalUp * OthRules.checkRowsRight * OthRules.checkRowsLeft * OthRules.checkDiagonalUpRight * OthRules.checkDiagonalUpLeft * OthRules.checkDiagonalDownRight * OthRules.checkDiagonalDownLeft * are also called. * * OthRules.flipCounters is tested one time(s). * during this test, methods: * OthRules.flipVerticalDown * OthRules.flipVerticalUp * OthRules.flipRowsRight * OthRules.flipRowsLeft * OthRules.flipDiagonalUpRight * OthRules.flipDiagonalUpLeft * OthRules.flipDiagonalDownRight * OthRules.flipDiagonalDownLeft * are also called. * * @author Tom * */ public class TestOthRules { private static final int COLUMN = 8; private static final int ROW = 8; private static final int NO_MATCH = 0; private static final int PLAYER_ONE = 1; private static final int PLAYER_TWO = 2; private static final int FLIP_COL = 5; private static final int FLIP_ROW = 4; private static final int CHECK_COL = 4; private static final int CHECK_ROW = 4; private static OthGame othGame; private static OthRules othRules; public static void main(String args[]) { /* * OthRules.winCondition Test One: * Filled board of PLAYER_ONE counters */ othRules = new OthRules(); OthCounter[][] m_testBoard1 = new OthCounter[COLUMN][ROW]; for(int i = 0; i < COLUMN; i++) { for(int j = 0; j < ROW; j++) { OthCounter counter = new OthCounter(1); m_testBoard1[i][j] = counter; } } if(othRules.winCondition(m_testBoard1) == PLAYER_ONE) { System.out.println("OthRules.winCondition Test One Evaluated: Correct"); } else { System.out.println("OthRules.winCondition Test One Evaluated: Incorrect"); } /* * OthRules.winCondition Test Two: * Filled board of PLAYER_TWO counters */ othRules = new OthRules(); OthCounter[][] m_testBoard2 = new OthCounter[COLUMN][ROW]; for(int i = 0; i < COLUMN; i++) { for(int j = 0; j < ROW; j++) { OthCounter counter = new OthCounter(2); m_testBoard2[i][j] = counter; } } if(othRules.winCondition(m_testBoard2) == PLAYER_TWO) { System.out.println("OthRules.winCondition Test Two Evaluated: Correct"); } else { System.out.println("OthRules.winCondition Test Two Evaluated: Incorrect"); } /* * OthRules.winCondition Test Two: * Empty board (counters of player 0 are not visible) */ othRules = new OthRules(); OthCounter[][] m_testBoard3 = new OthCounter[COLUMN][ROW]; for(int i = 0; i < COLUMN; i++) { for(int j = 0; j < ROW; j++) { OthCounter counter = new OthCounter(0); m_testBoard3[i][j] = counter; } } if(othRules.winCondition(m_testBoard3) == NO_MATCH) { System.out.println("OthRules.winCondition Test Three Evaluated: Correct"); } else { System.out.println("OthRules.winCondition Test Three Evaluated: Incorrect"); } /* * OthRules.checkValidSet Test One: * Testing the filled board of PLAYER_ONE counters * All positions filled, so no valid moves should be possible */ othRules = new OthRules(); int[][] validSet1 = othRules.checkValidSet(m_testBoard1); boolean correct1 = true; for(int i = 0; i < COLUMN; i++) { for(int j = 0; j < ROW; j++) { if(validSet1[i][j] != 0) { correct1 = false; } } } if(correct1 == true) { System.out.println("OthRules.checkValidSet Test One Evaluated: Correct"); } else { System.out.println("OthRules.checkValidSet Test One Evaluated: Incorrect"); } /* * OthRules.flipCounters Test One * Constructs an OthGame with default counter setup, * then places a specific counter at [FLIP_COL][FLIP_ROW] and tests expected result. */ othRules = new OthRules(); othGame = new OthGame(); othRules.flipCounters(othGame.getInPlayCounters(), FLIP_COL, FLIP_ROW, PLAYER_ONE); if(othGame.getInPlayCounters()[CHECK_COL][CHECK_ROW].getPlayer() == PLAYER_ONE) { System.out.println("OthRules.flipCounters Test One Evaluated: Correct"); } else { System.out.println("OthRules.flipCounters Test One Evaluated: Incorrect"); } } }
package mod._sc; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.SOfficeFactory; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XIndexAccess; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sheet.XNamedRanges; import com.sun.star.sheet.XSpreadsheet; import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.sheet.XSpreadsheets; import com.sun.star.table.CellAddress; import com.sun.star.table.CellRangeAddress; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; /** * Test for object which is represented by service * <code>com.sun.star.sheet.NamedRanges</code>. <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::sheet::XNamedRanges</code></li> * <li> <code>com::sun::star::container::XNameAccess</code></li> * <li> <code>com::sun::star::container::XElementAccess</code></li> * </ul> * @see com.sun.star.sheet.NamedRanges * @see com.sun.star.sheet.XNamedRanges * @see com.sun.star.container.XNameAccess * @see com.sun.star.container.XElementAccess * @see ifc.sheet._XNamedRanges * @see ifc.container._XNameAccess * @see ifc.container._XElementAccess */ public class ScNamedRangesObj extends TestCase { static XSpreadsheetDocument xSheetDoc = null; /** * Creates Spreadsheet document. */ protected void initialize( TestParameters tParam, PrintWriter log ) { SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() ); try { log.println( "creating a Spreadsheet document" ); xSheetDoc = SOF.createCalcDoc(null); } catch ( com.sun.star.uno.Exception e ) { // Some exception occures.FAILED e.printStackTrace( log ); throw new StatusException( "Couldn't create document", e ); } } /** * Disposes Spreadsheet document. */ protected void cleanup( TestParameters tParam, PrintWriter log ) { log.println( " disposing xSheetDoc " ); XComponent oComp = (XComponent) UnoRuntime.queryInterface (XComponent.class, xSheetDoc) ; util.DesktopTools.closeDoc(oComp); } /** * Creating a Testenvironment for the interfaces to be tested. * Retrieves a collection of spreadsheets from a document * and takes one of them. Obtains the value of the property * <code>'NamedRanges'</code> that is the collection of named ranges. * This collection is the instance of the service * <code>com.sun.star.sheet.NamedRanges</code>. Creates and adds new range to * the collection. * Object relations created : * <ul> * <li> <code>'SHEET'</code> for * {@link ifc.sheet._XNamedRanges} (the retrieved spreadsheet) </li> * </ul> * @see com.sun.star.sheet.NamedRanges */ protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) { XInterface oObj = null; // creation of testobject here // first we write what we are intend to do to log file log.println( "Creating a test environment" ); XSpreadsheet oSheet = null; log.println("Getting test object "); XSpreadsheets oSheets = xSheetDoc.getSheets(); XIndexAccess oIndexSheets = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class, oSheets); try { oSheet = (XSpreadsheet) AnyConverter.toObject( new Type(XSpreadsheet.class),oIndexSheets.getByIndex(0)); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(log); throw new StatusException( "Couldn't get a spreadsheet", e); } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(log); throw new StatusException( "Couldn't get a spreadsheet", e); } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace(log); throw new StatusException( "Couldn't get a spreadsheet", e); } // Getting named ranges. XPropertySet docProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xSheetDoc); Object ranges = null; try { ranges = docProps.getPropertyValue("NamedRanges"); } catch(com.sun.star.lang.WrappedTargetException e){ e.printStackTrace(log); throw new StatusException("Couldn't get NamedRanges", e); } catch(com.sun.star.beans.UnknownPropertyException e){ e.printStackTrace(log); throw new StatusException("Couldn't get NamedRanges", e); } XNamedRanges xNamedRanges = (XNamedRanges) UnoRuntime.queryInterface(XNamedRanges.class, ranges); CellRangeAddress DataArea = new CellRangeAddress((short)0, 0, 0, 2, 2); CellAddress base = new CellAddress(DataArea.Sheet, DataArea.StartColumn, DataArea.StartRow); xNamedRanges.addNewByName("ANamedRange", "A1:B2", base, 0); CellAddress listOutputPosition = new CellAddress((short)0, 1, 1); xNamedRanges.outputList(listOutputPosition); oObj = xNamedRanges; TestEnvironment tEnv = new TestEnvironment( oObj ); // Other parameters required for interface tests tEnv.addObjRelation("SHEET", oSheet); return tEnv; } }
import java.util.List; import java.util.Iterator; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.io.InputStream; import java.io.IOException; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; // Builds a Track from a string. public class TrackBuilder extends TrackBaseListener { // channelsInTrack and channelDecls are List<String> rather than the actual // types they represent because we might not have reached the part of the // tree that contains the channel or block they reference yet; however // blocks do contain all the info necessary to make a Note, so they are // stored as a Map<String, Block> private List<String> channelsInTrack = new ArrayList<>(); private Map<String, List<String>> channelDecls = new HashMap<>(); private Map<String, List<Note>> blockDecls = new HashMap<>(); private Map<String, Waveform> channelWaveforms = new HashMap<>(); private String currentChannel = null; private String currentBlock = null; private TrackBuilder() { super(); } public static Track build(InputStream input) throws IOException { // oh what a wonderful API ANTLRInputStream inputStream = new ANTLRInputStream(input); TrackLexer lexer = new TrackLexer(inputStream); CommonTokenStream tokens = new CommonTokenStream(lexer); TrackParser parser = new TrackParser(tokens); ParserRuleContext tree = parser.track(); ParseTreeWalker walker = new ParseTreeWalker(); TrackBuilder builder = new TrackBuilder(); walker.walk(builder, tree); return builder.toTrack(); } public Track toTrack() { Map<String, Block> blocks = constructBlocks(); Map<String, Channel> channels = constructChannels(blocks); List<Channel> filteredChannels = getWhereKeyIn(channels, channelsInTrack); return new Track(filteredChannels); } private Map<String, Block> constructBlocks() { Map<String, Block> retval = new HashMap<>(); Iterator<String> iter = blockDecls.keySet().iterator(); while (iter.hasNext()) { String blockName = iter.next(); List<Note> notes = blockDecls.get(blockName); retval.put(blockName, new Block(notes)); } return retval; } private Map<String, Channel> constructChannels( Map<String, Block> blockMap) { Map<String, Channel> retval = new HashMap<>(); Iterator<String> iter = channelDecls.keySet().iterator(); while (iter.hasNext()) { String channelName = iter.next(); List<String> blockNames = channelDecls.get(channelName); List<Block> blocks = convertEachToBlock(blockNames, blockMap, channelName); Waveform wf = channelWaveforms.get(channelName); retval.put(channelName, new Channel(wf, blocks)); } return retval; } // Convert a list of strings (block names) to a list of blocks. // Arguments: // blockNames: names of blocks to convert // blockMap: where to look for blocks // channelName: the channel where these blocks occur. Used for error // messages. private List<Block> convertEachToBlock( List<String> blockNames, Map<String, Block> blockMap, String channelName) { List<Block> retval = new ArrayList<>(); Iterator<String> iter = blockNames.iterator(); while (iter.hasNext()) { String blockName = iter.next(); Block block = blockMap.get(blockName); if (block == null) throw new TrackException(String.format( "Unknown block '%s' in declaration for channel '%s'", blockName, channelName)); else retval.add(block); } return retval; } private List<Channel> getWhereKeyIn( Map<String, Channel> map, List<String> whitelist) { List<Channel> retval = new ArrayList<>(); Iterator<String> iter = map.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); if (whitelist.contains(key)) retval.add(map.get(key)); } return retval; } // Inside the track declaration public void enterChannel_name(TrackParser.Channel_nameContext ctx) { String channelName = ctx.ID().getSymbol().getText(); this.channelsInTrack.add(channelName); } public void enterChannel_decl(TrackParser.Channel_declContext ctx) { String channelName = ctx.ID().getSymbol().getText(); this.currentChannel = channelName; if (channelDecls.containsKey(channelName)) { throw new TrackException(String.format( "Multiple declarations of channel '%s'", channelName)); } else { this.channelDecls.put( this.currentChannel, new ArrayList<String>()); } String waveformName = ctx.WAVE().getSymbol().getText(); Waveform waveform = WaveformParser.parse(waveformName); this.channelWaveforms.put(channelName, waveform); } public void enterBlock_name(TrackParser.Block_nameContext ctx) { String blockName = ctx.ID().getSymbol().getText(); this.channelDecls.get(this.currentChannel).add(blockName); } public void exitChannel_decl(TrackParser.Channel_declContext ctx) { this.currentChannel = null; } public void enterBlock_decl(TrackParser.Block_declContext ctx) { String blockName = ctx.ID().getSymbol().getText(); this.currentBlock = blockName; if (blockDecls.containsKey(blockName)) { throw new TrackException(String.format( "Multiple declarations of block '%s'", blockName)); } else { this.blockDecls.put( this.currentBlock, new ArrayList<Note>()); } } public void enterNote(TrackParser.NoteContext ctx) { String noteName = ctx.NOTENAME().getSymbol().getText(); int octave = getOctave(ctx); String length = getLength(ctx); Note note = makeNote(noteName, octave, length); this.blockDecls.get(this.currentBlock).add(note); } private int getOctave(TrackParser.NoteContext ctx) { String octave = getTextWithDefault(ctx.OCTAVE(), "4"); return Integer.parseInt(octave); } private String getLength(TrackParser.NoteContext ctx) { return getTextWithDefault(ctx.LENGTH(), ""); } private String getTextWithDefault(TerminalNode node, String def) { if (node == null) return def; else return node.getSymbol().getText(); } private Note makeNote(String noteNameStr, int octave, String length) { NoteValue noteValue = lengthToValue(length); NoteName noteName = NoteName.parse(noteNameStr); if (noteName == null) return Note.Rest(noteValue); else { Pitch pitch = new Pitch(noteName, octave); return new Note(noteValue, pitch); } } private NoteValue lengthToValue(String str) { // Default note length is crotchet double value = 1.0/4; for (int i = 0; i < str.length(); i++) { char next = str.charAt(i); switch (next) { case '+': value *= 2; break; case '-': value /= 2; break; case '.': value *= 1.5; break; default: break; } } return new NoteValue(value); } public void exitBlock_decl(TrackParser.Block_declContext ctx) { this.currentBlock = null; } }
import java.net.*; import java.util.*; /** * @author jens3048 * */ public class UIController { private CommandProcessor commandProcessor; private boolean done; private IncomingPacketQueue incomingPacketQueue; private OutgoingPacketQueue outgoingPacketQueue; private DatagramReceiver receiveFromPeer; private DatagramSender sendToPeer; /** * @param incomingPortNumber * @param outgoingPortNumber * @param packetSize */ public UIController(PortNumber portNumber, int packetSize) { InetSocketAddress socketAddress; socketAddress = new InetSocketAddress(portNumber.get()); incomingPacketQueue = new IncomingPacketQueue(); outgoingPacketQueue = new OutgoingPacketQueue(); try { receiveFromPeer = new DatagramReceiver(socketAddress, incomingPacketQueue, packetSize); } catch(SocketException e) { System.out.println("Caught socket exception " + e.getMessage()); } try { sendToPeer = new DatagramSender(socketAddress, outgoingPacketQueue, packetSize); } catch(SocketException e) { System.out.println("Caught socket exception " + e.getMessage()); } done = false; commandProcessor = new CommandProcessor(new CommandError(), new CommandNone()); } public void start() { UIControllerCommand command; Scanner scanner; String commandType; scanner = new Scanner(System.in); while(!done) { System.out.println("Type in a type of command to send or done"); commandType = scanner.nextLine(); command = null; if(commandType.toLowerCase().equals("done")) { done = true; } if(commandType.toLowerCase().equals("error")) { command = new CommandError(); } if(commandType.toLowerCase().equals("none")) { command = new CommandNone(); } if(commandType.toLowerCase().equals("help")) { command = new CommandHelp(); } if(command != null) { command.sendToPeer(); } } scanner.close(); } /** * @author jens3048 * */ public abstract class UIControllerCommand extends Command { public UIControllerCommand() { super(); } /** * @param commandName * @param description */ public UIControllerCommand(String commandName, String description) { super(commandName, description); } /** * @return */ public CommandProcessor getCommandProcessor() { return commandProcessor; } /** * @return */ public boolean getDoneFlag() { return done; } /* (non-Javadoc) * @see Command#print(java.lang.String) */ public void print(String message) { super.print(message); } /* (non-Javadoc) * @see Command#println() */ public void println() { super.println(); } /* (non-Javadoc) * @see Command#println(java.lang.String) */ public void println(String data) { super.println(data); } /** * @param flag */ public void setDoneFlag(boolean flag) { done = flag; } public void sendToPeer() { // int size = this.commandName.getBytes().length(); // DatagramPacket dp = new DatagramPacket(this.commandName.getBytes(),size); // outgoingPacketQueue.enQueue(dp); // sendToPeer.action(); } } /** * @author jens3048 * A command depicting an error */ public class CommandError extends UIControllerCommand { /** * Creates the command */ public CommandError() { super("error", "An error command"); } /** * Informs the user that there is an error somewhere. */ public void execute() { println("You are seeing this message because an errenous message was received. Fix that."); setDoneFlag(true); } // /** // * Always goes first, unless there is another error or a help command // */ // public int compareTo(Object o) // int result; // result = 1; // if(((Command)o).getCommandName().equals("Error") || ((Command)o).getCommandName().equals("Help")) // result = 0; // return result; } /** * @author jens3048 * A command requesting help. */ public class CommandHelp extends UIControllerCommand { /** * Creates the command. */ public CommandHelp() { super("help", "A help command"); } /** * TODO come up with a help message */ public void execute() { } /** * Always goes first, unless there is an error or another request for help */ // @Override // public int compareTo(Object o) // int result; // result = 1; // if(((Command)o).getCommandName().equals("Error") || ((Command)o).getCommandName().equals("Help")) // result = 0; // return result; } /** * @author jens3048 * A command that does nothing */ public class CommandNone extends UIControllerCommand { /** * Creates the command */ public CommandNone() { super(); } /** * Does nothing */ public void execute() { setDoneFlag(true); } // /** // * Order doesn't matter // */ // public int compareTo(Object o) // return 0; } } // TODO implement start, stop, get, find
package raptor.pref; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.preference.PreferenceStore; import org.eclipse.jface.resource.StringConverter; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; import raptor.Quadrant; import raptor.Raptor; import raptor.chat.ChatEvent; import raptor.chat.ChatType; import raptor.international.L10n; import raptor.layout.ClassicLayout; import raptor.service.SeekService.SeekType; import raptor.service.ThemeService; import raptor.service.ThemeService.Theme; import raptor.swt.BugPartners; import raptor.swt.GamesWindowItem; import raptor.swt.SWTUtils; import raptor.swt.SeekTableWindowItem; import raptor.swt.chess.SquareBackgroundImageEffect; import raptor.swt.chess.controller.InactiveMouseAction; import raptor.swt.chess.controller.ObservingMouseAction; import raptor.swt.chess.controller.PlayingMouseAction; import raptor.util.OSUtils; import raptor.util.RaptorLogger; import raptor.util.RaptorStringUtils; /** * The RaptorPreferenceStore. Automatically loads and saves itself at * Raptor.USER_RAPTOR_DIR/raptor.properties . Had additional data type support. */ public class RaptorPreferenceStore extends PreferenceStore implements PreferenceKeys { private static final RaptorLogger LOG = RaptorLogger .getLog(RaptorPreferenceStore.class); public static final String PREFERENCE_PROPERTIES_FILE = "raptor.properties"; public static final File RAPTOR_PROPERTIES = new File( Raptor.USER_RAPTOR_DIR, "raptor.properties"); protected String defaultMonospacedFontName; protected String defaultFontName; protected int defaultLargeFontSize; protected int defaultSmallFontSize; protected int defaultMediumFontSize; protected int defaultTinyFontSize; private IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String key = event.getProperty(); if (key.endsWith("color")) { Raptor.getInstance() .getColorRegistry() .put(key, PreferenceConverter.getColor( RaptorPreferenceStore.this, key)); } else if (key.endsWith("font")) { // Adjust all the zoomed fonts, as well as the font being // changed, // in the FontRegistry. // Add all the fonts to change to a list to avoid the // concurrency issues. List<String> fontKeysToChange = new ArrayList<String>(); for (Object fontRegistryKey : Raptor.getInstance() .getFontRegistry().getKeySet()) { String fontKey = fontRegistryKey.toString(); if (fontKey.startsWith(key)) { fontKeysToChange.add(fontKey); } } for (String fontKey : fontKeysToChange) { if (fontKey.equals(key)) { Raptor.getInstance() .getFontRegistry() .put(key, PreferenceConverter .getFontDataArray( RaptorPreferenceStore.this, key)); } else { double zoomFactor = Double.parseDouble(fontKey .substring(key.length() + 1)); Raptor.getInstance().getFontRegistry() .put(fontKey, zoomFont(key, zoomFactor)); } } } } }; protected void resetChessSetIfDeleted() { String chessSet = getString(BOARD_CHESS_SET_NAME); File file = new File(Raptor.RESOURCES_DIR + "set/" + chessSet); if (!file.exists() || !file.isDirectory()) { setValue(BOARD_CHESS_SET_NAME, getDefaultString(BOARD_CHESS_SET_NAME)); } } public RaptorPreferenceStore() { super(); FileInputStream fileIn = null; FileOutputStream fileOut = null; try { LOG.info("Loading RaptorPreferenceStore store " + PREFERENCE_PROPERTIES_FILE); loadDefaults(); if (RAPTOR_PROPERTIES.exists()) { load(fileIn = new FileInputStream(RAPTOR_PROPERTIES)); resetChessSetIfDeleted(); } else { RAPTOR_PROPERTIES.getParentFile().mkdir(); RAPTOR_PROPERTIES.createNewFile(); save(fileOut = new FileOutputStream(RAPTOR_PROPERTIES), "Last saved on " + new Date()); } } catch (Exception e) { LOG.error("Error reading or writing to file ", e); throw new RuntimeException(e); } finally { if (fileIn != null) { try { fileIn.close(); } catch (Throwable t) { } } if (fileOut != null) { try { fileOut.flush(); fileOut.close(); } catch (Throwable t) { } } } addPropertyChangeListener(propertyChangeListener); LOG.info("Loaded preferences from " + RAPTOR_PROPERTIES.getAbsolutePath()); } /** * Returns null for CHANNEL_TELL type. */ public Color getColor(ChatType type) { String key = null; if (type == ChatType.CHANNEL_TELL) { return null; } else { key = getKeyForChatType(type); } return getColorForKeyWithoutDefault(key); } protected Color getColorForKeyWithoutDefault(String key) { Color result = null; try { if (!Raptor.getInstance().getColorRegistry().hasValueFor(key)) { // We don't want the default color if not found we want to // return null, so use // StringConverter instead of PreferenceConverter. String value = getString(key); if (StringUtils.isNotBlank(value)) { RGB rgb = StringConverter.asRGB(value, null); if (rgb != null) { Raptor.getInstance().getColorRegistry().put(key, rgb); } else { return null; } } else { return null; } } result = Raptor.getInstance().getColorRegistry().get(key); } catch (Throwable t) { result = null; } return result; } /** * Returns the foreground color to use for the specified chat event. Returns * null if no special color should be used. */ public Color getColor(ChatEvent event) { String key = null; if (event.getType() == ChatType.CHANNEL_TELL) { key = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + event.getType() + "-" + event.getChannel() + "-color"; } else { key = getKeyForChatType(event.getType()); } return getColorForKeyWithoutDefault(key); } /** * Returns null for CHANNEL_TELL type. * * @return */ public String getKeyForChatType(ChatType type) { String result = null; if (type == ChatType.CHANNEL_TELL) { result = null; } else if (type == ChatType.BUGWHO_AVAILABLE_TEAMS || type == ChatType.BUGWHO_GAMES || type == ChatType.BUGWHO_UNPARTNERED_BUGGERS) { result = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.BUGWHO_ALL + "-color"; } else if (type == ChatType.NOTIFICATION_DEPARTURE) { result = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.NOTIFICATION_ARRIVAL + "-color"; } else { result = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + type + "-color"; } return result; } /** * Returns the color for the specified key. Returns BLACK if the key was not * found. */ public Color getColor(String key) { try { if (!Raptor.getInstance().getColorRegistry().hasValueFor(key)) { RGB rgb = PreferenceConverter.getColor(this, key); if (rgb != null) { Raptor.getInstance().getColorRegistry().put(key, rgb); } } return Raptor.getInstance().getColorRegistry().get(key); } catch (Throwable t) { LOG.error("Error in getColor(" + key + ") Returning black.", t); return new Color(Display.getCurrent(), new RGB(0, 0, 0)); } } public Rectangle getCurrentLayoutRectangle(String key) { key = "app-" + getString(APP_LAYOUT) + "-" + key; return getRectangle(key); } public int[] getCurrentLayoutSashWeights(String key) { key = "app-" + getString(APP_LAYOUT) + "-" + key; return getIntArray(key); } public RGB getDefaultColor(String key) { return PreferenceConverter.getDefaultColor(this, key); } public int[] getDefaultIntArray(String key) { return RaptorStringUtils.intArrayFromString(getDefaultString(key)); } public String[] getDefaultStringArray(String key) { return RaptorStringUtils.stringArrayFromString(getDefaultString(key)); } public String getDefaultMonospacedFont() { FontData[] fonts = Raptor.getInstance().getDisplay() .getFontList(null, true); String[] preferredFontNames = null; String osName = System.getProperty("os.name"); if (osName.startsWith("Mac OS")) { preferredFontNames = SWTUtils.OSX_MONOSPACED_FONTS; } else if (osName.startsWith("Windows")) { preferredFontNames = SWTUtils.WINDOWS_MONOSPACED_FONTS; } else { preferredFontNames = SWTUtils.OTHER_MONOSPACED_FONTS; } String result = null; outer: for (int i = 0; i < preferredFontNames.length; i++) { for (FontData fontData : fonts) { if (fontData.getName().equalsIgnoreCase(preferredFontNames[i])) { result = preferredFontNames[i]; break outer; } } } if (result == null) { result = "Courier"; } return result; } protected FontData[] zoomFont(String key, double zoomFactor) { FontData[] fontData = PreferenceConverter.getFontDataArray(this, key); // Convert font to zoom factor. for (int i = 0; i < fontData.length; i++) { fontData[i].setHeight((int) (fontData[i].getHeight() * zoomFactor)); } return fontData; } protected String getZoomFontKey(String key, double zoomFactor) { return key + "-" + zoomFactor; } public Font getFont(String key, boolean isAdjustingForZoomFactor) { try { String adjustedKey = key; if (isAdjustingForZoomFactor) { double zoomFactor = getDouble(APP_ZOOM_FACTOR); adjustedKey = getZoomFontKey(key, zoomFactor); } if (!Raptor.getInstance().getFontRegistry() .hasValueFor(adjustedKey)) { FontData[] fontData = null; if (!isAdjustingForZoomFactor) { fontData = PreferenceConverter.getFontDataArray(this, key); } else { fontData = zoomFont(key, getDouble(APP_ZOOM_FACTOR)); } Raptor.getInstance().getFontRegistry() .put(adjustedKey, fontData); } return Raptor.getInstance().getFontRegistry().get(adjustedKey); } catch (Throwable t) { LOG.error("Error in getFont(" + key + ") Returning default font.", t); return Raptor.getInstance().getFontRegistry().defaultFont(); } } /** * Returns the font for the specified key. Returns the default font if key * was not found. * * Fonts returned from this method will be adjusted to the APP_ZOOM_FACTOR * preference. */ public Font getFont(String key) { return getFont(key, true); } public int[] getIntArray(String key) { return RaptorStringUtils.intArrayFromString(getString(key)); } public Point getPoint(String key) { return PreferenceConverter.getPoint(this, key); } public Quadrant getQuadrant(String key) { return Quadrant.valueOf(getString(key)); } public Rectangle getRectangle(String key) { return PreferenceConverter.getRectangle(this, key); } public String[] getStringArray(String key) { return RaptorStringUtils.stringArrayFromString(getString(key)); } public void applyDefaultTheme() { Theme theme = ThemeService.getInstance().getTheme("Raptor"); for (String propertyName : theme.getProperties().keySet()) { setDefault(propertyName, theme.getProperties().get(propertyName)); } } public void applyDefaultLayout() { Map<String, String> map = new ClassicLayout() .getPreferenceAdjustments(); for (String key : map.keySet()) { String value = map.get(key); if (value == null) { setToDefault(key); } else { setDefault(key, map.get(key)); } } } public void loadDefaults() { defaultFontName = Raptor.getInstance().getFontRegistry().defaultFont() .getFontData()[0].getName(); defaultMonospacedFontName = getDefaultMonospacedFont(); setDefaultMonitorBasedSizes(); // Action setDefault(ACTION_SEPARATOR_SEQUENCE, 400); // App settings. setDefault(APP_NAME, "Raptor .98u1"); setDefault(APP_IS_SHOWING_CHESS_PIECE_UNICODE_CHARS, !OSUtils.isLikelyWindowsXP()); setDefault(APP_SASH_WIDTH, 8); PreferenceConverter.setDefault(this, APP_PING_FONT, new FontData[] { new FontData(defaultFontName, defaultSmallFontSize, 0) }); PreferenceConverter.setDefault(this, APP_PING_COLOR, new RGB(0, 0, 0)); PreferenceConverter.setDefault(this, APP_STATUS_BAR_FONT, new FontData[] { new FontData(defaultFontName, defaultSmallFontSize, 0) }); PreferenceConverter.setDefault(this, APP_STATUS_BAR_COLOR, new RGB(0, 0, 0)); setDefault(APP_HOME_URL, "http://code.google.com/p/raptor-chess-interface/"); setDefault(APP_SOUND_ENABLED, true); setDefault(APP_USER_TAGS, "+Partner,-Partner,Cool,Dupe,Friend,Jerk,Lagger,Noob,Premover,Troll,Strange"); setDefault(APP_PGN_FILE, Raptor.USER_RAPTOR_HOME_PATH + "/games/raptorGames.pgn"); setDefault(APP_LAYOUT, "Layout1"); setDefault(APP_OPEN_LINKS_IN_EXTERNAL_BROWSER, false); setDefault(APP_BROWSER_QUADRANT, Quadrant.II); setDefault(APP_CHESS_BOARD_QUADRANTS, new String[] { Quadrant.II.toString(), Quadrant.III.toString(), Quadrant.IV.toString(), Quadrant.V.toString() }); setDefault(APP_PGN_RESULTS_QUADRANT, Quadrant.III); setDefault(APP_IS_LAUNCHNG_HOME_PAGE, true); setDefault(APP_WINDOW_ITEM_POLL_INTERVAL, 5); setDefault(APP_IS_LOGGING_CONSOLE, false); setDefault(APP_IS_LOGGING_PERSON_TELLS, false); setDefault(APP_IS_LOGGING_CHANNEL_TELLS, false); setDefault(PreferenceKeys.APP_SHOW_STATUS_BAR, false); // Layout 1 settings. setDefault(APP_WINDOW_BOUNDS, new Rectangle(0, 0, -1, -1)); // setDefault(APP_QUAD9_QUAD12345678_SASH_WEIGHTS, new int[] { 10, 90 // setDefault(APP_QUAD1_QUAD2345678_SASH_WEIGHTS, new int[] { 50, 50 }); // setDefault(APP_QUAD2345_QUAD678_SASH_WEIGHTS, new int[] { 70, 30 }); // setDefault(APP_QUAD2_QUAD3_QUAD4_QUAD5_SASH_WEIGHTS, new int[] { 25, // 25, 25, 25 }); // setDefault(APP_QUAD67_QUAD8_SASH_WEIGHTS, new int[] { 70, 30 }); // setDefault(APP_QUAD6_QUAD7_SASH_WEIGHTS, new int[] { 50, 50 }); setDefault(APP_ZOOM_FACTOR, 1.0); if (OSUtils.isLikelyWindows() && !OSUtils.isLikelyWindows7()) { setDefault(SPEECH_PROCESS_NAME, "SayStatic"); } if (OSUtils.isLikelyLinux()) { try { if (Runtime.getRuntime().exec(new String[] { "which", "play" }) .waitFor() == 0) { setDefault(PreferenceKeys.SOUND_PROCESS_NAME, "aplay"); } else if (Runtime.getRuntime() .exec(new String[] { "which", "aplay" }).waitFor() == 0) { setDefault(PreferenceKeys.SOUND_PROCESS_NAME, "play"); } } catch (Throwable t) { LOG.warn( "Error launching which to determine sound process in linux.", t); } } // Board setDefault(BOARD_ALLOW_MOUSE_WHEEL_NAVIGATION_WHEEL_PLAYING, false); setDefault(BOARD_SHOW_PLAYING_GAME_STATS_ON_GAME_END, true); setDefault(BOARD_PLAY_CHALLENGE_SOUND, true); setDefault(BOARD_PLAY_ABORT_REQUEST_SOUND, true); setDefault(BOARD_PLAY_DRAW_OFFER_SOUND, true); setDefault(BOARD_USER_MOVE_INPUT_MODE, "DragAndDrop"); setDefault(BOARD_SHOW_BUGHOUSE_SIDE_UP_TIME, true); setDefault(BOARD_PIECE_JAIL_LABEL_PERCENTAGE, 40); setDefault(BOARD_COOLBAR_MODE, true); setDefault(BOARD_COOLBAR_ON_TOP, true); setDefault(BOARD_CHESS_SET_NAME, "Alpha"); setDefault(BOARD_SQUARE_BACKGROUND_NAME, "GreenMarble"); setDefault(BOARD_IS_SHOW_COORDINATES, true); setDefault(BOARD_PIECE_SIZE_ADJUSTMENT, .06); setDefault(BOARD_IS_SHOWING_PIECE_JAIL, false); setDefault(BOARD_CLOCK_SHOW_MILLIS_WHEN_LESS_THAN, Integer.MIN_VALUE); setDefault(BOARD_CLOCK_SHOW_SECONDS_WHEN_LESS_THAN, 1000L * 60L * 60L + 1L); setDefault(BOARD_IS_PLAYING_10_SECOND_COUNTDOWN_SOUNDS, true); setDefault(BOARD_PREMOVE_ENABLED, true); setDefault(BOARD_PLAY_MOVE_SOUND_WHEN_OBSERVING, true); setDefault(BOARD_QUEUED_PREMOVE_ENABLED, false); setDefault(BOARD_IS_USING_CROSSHAIRS_CURSOR, false); setDefault(BOARD_LAYOUT, "raptor.swt.chess.layout.RightOrientedLayout"); setDefault(BOARD_TAKEOVER_INACTIVE_GAMES, true); setDefault(BOARD_PIECE_JAIL_SHADOW_ALPHA, 30); setDefault(BOARD_PIECE_SHADOW_ALPHA, 40); setDefault(BOARD_COORDINATES_SIZE_PERCENTAGE, 26); setDefault(BOARD_ANNOUNCE_CHECK_WHEN_OPPONENT_CHECKS_ME, false); setDefault(BOARD_ANNOUNCE_CHECK_WHEN_I_CHECK_OPPONENT, false); setDefault(BOARD_SPEAK_MOVES_OPP_MAKES, false); setDefault(BOARD_SPEAK_MOVES_I_MAKE, false); setDefault(BOARD_SPEAK_WHEN_OBSERVING, false); setDefault(BOARD_SPEAK_RESULTS, false); setDefault(BOARD_IGNORE_OBSERVED_GAMES_IF_PLAYING, false); setDefault(BOARD_MOVE_LIST_CLASS, "raptor.swt.chess.movelist.TextAreaMoveList"); setDefault(BOARD_IS_USING_SOLID_BACKGROUND_COLORS, false); setDefault(BOARD_SQUARE_BACKGROUND_IMAGE_EFFECT, SquareBackgroundImageEffect.RandomCrop.toString()); setDefault(BOARD_TRAVERSE_WITH_MOUSE_WHEEL, true); PreferenceConverter .setDefault(this, BOARD_LIGHT_SQUARE_SOLID_BACKGROUND_COLOR, new RGB(178, 180, 78)); PreferenceConverter.setDefault(this, BOARD_DARK_SQUARE_SOLID_BACKGROUND_COLOR, new RGB(94, 145, 91)); PreferenceConverter.setDefault(this, BOARD_COORDINATES_FONT, new FontData[] { new FontData(defaultFontName, defaultMediumFontSize, 0) }); PreferenceConverter .setDefault(this, BOARD_CLOCK_FONT, new FontData[] { new FontData( defaultMonospacedFontName, 24, 0) }); PreferenceConverter.setDefault(this, BOARD_LAG_FONT, new FontData[] { new FontData(defaultFontName, defaultTinyFontSize, 0) }); PreferenceConverter.setDefault(this, BOARD_PLAYER_NAME_FONT, new FontData[] { new FontData(defaultFontName, defaultLargeFontSize, 0) }); PreferenceConverter.setDefault(this, BOARD_PIECE_JAIL_FONT, new FontData[] { new FontData(defaultFontName, defaultMediumFontSize, 0) }); PreferenceConverter.setDefault(this, BOARD_OPENING_DESC_FONT, new FontData[] { new FontData(defaultFontName, defaultTinyFontSize, 0) }); PreferenceConverter.setDefault(this, BOARD_STATUS_FONT, new FontData[] { new FontData(defaultFontName, defaultTinyFontSize, 0) }); PreferenceConverter.setDefault(this, BOARD_GAME_DESCRIPTION_FONT, new FontData[] { new FontData(defaultFontName, defaultTinyFontSize, 0) }); PreferenceConverter.setDefault(this, BOARD_PREMOVES_FONT, new FontData[] { new FontData(defaultFontName, defaultTinyFontSize, 0) }); // Controller button preferences. setDefault(PLAYING_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION, PlayingMouseAction.None.toString()); setDefault(PLAYING_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION, PlayingMouseAction.PopupMenu.toString()); setDefault(PLAYING_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION, PlayingMouseAction.SmartMove.toString()); setDefault(PLAYING_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION, PlayingMouseAction.None.toString()); setDefault(PLAYING_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION, PlayingMouseAction.None.toString()); setDefault(PLAYING_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION, PlayingMouseAction.None.toString()); setDefault(OBSERVING_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION, ObservingMouseAction.MakePrimaryGame.toString()); setDefault(OBSERVING_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION, ObservingMouseAction.AddGameChatTab.toString()); setDefault(OBSERVING_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION, ObservingMouseAction.MatchWinner.toString()); setDefault(OBSERVING_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION, ObservingMouseAction.None.toString()); setDefault(OBSERVING_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION, ObservingMouseAction.None.toString()); setDefault( OBSERVING_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION, ObservingMouseAction.None.toString()); setDefault(INACTIVE_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION, InactiveMouseAction.None.toString()); setDefault(INACTIVE_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION, InactiveMouseAction.None.toString()); setDefault(INACTIVE_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION, InactiveMouseAction.Rematch.toString()); setDefault(INACTIVE_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION, InactiveMouseAction.None.toString()); setDefault(INACTIVE_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION, InactiveMouseAction.None.toString()); setDefault(INACTIVE_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION, InactiveMouseAction.None.toString()); // BugArena setDefault(BUG_ARENA_PARTNERS_INDEX, 0); setDefault(BUG_ARENA_MAX_PARTNERS_INDEX, BugPartners.getRatings().length - 1); setDefault(BUG_ARENA_TEAMS_INDEX, 0); setDefault(BUG_ARENA_TEAMS_IS_RATED, true); setDefault(BUG_ARENA_SELECTED_TAB, 0); setDefault(BUG_ARENA_HI_LOW_INDEX, 0); setDefault(BUGHOUSE_SHOW_BUGWHO_ON_PARTNERSHIP, true); setDefault(SEEK_OUTPUT_TYPE, SeekType.FormulaFiltered.toString()); // SeekTable setDefault(SEEK_TABLE_RATINGS_INDEX, 0); setDefault(SEEK_TABLE_MAX_RATINGS_INDEX, SeekTableWindowItem.getRatings().length - 1); setDefault(SEEK_TABLE_RATED_INDEX, 0); setDefault(SEEK_TABLE_SHOW_COMPUTERS, true); setDefault(SEEK_TABLE_SHOW_LIGHTNING, true); setDefault(SEEK_TABLE_SHOW_BLITZ, true); setDefault(SEEK_TABLE_SHOW_STANDARD, true); setDefault(SEEK_TABLE_SHOW_CRAZYHOUSE, true); setDefault(SEEK_TABLE_SHOW_FR, true); setDefault(SEEK_TABLE_SHOW_WILD, true); setDefault(SEEK_TABLE_SHOW_ATOMIC, true); setDefault(SEEK_TABLE_SHOW_SUICIDE, true); setDefault(SEEK_TABLE_SHOW_LOSERS, true); setDefault(SEEK_TABLE_SHOW_UNTIMED, true); setDefault(SEEK_TABLE_SELECTED_TAB, 2); PreferenceConverter.setDefault(this, SEEK_GRAPH_COMPUTER_COLOR, new RGB(0, 0, 255)); PreferenceConverter.setDefault(this, SEEK_GRAPH_MANY_COLOR, new RGB( 255, 255, 102)); PreferenceConverter.setDefault(this, SEEK_GRAPH_RATED_COLOR, new RGB(0, 255, 0)); PreferenceConverter.setDefault(this, SEEK_GRAPH_UNRATED_COLOR, new RGB( 255, 0, 0)); // Games table setDefault(GAMES_TABLE_SELECTED_TAB, 1); setDefault(GAMES_TABLE_RATINGS_INDEX, 0); setDefault(GAMES_TABLE_MAX_RATINGS_INDEX, GamesWindowItem.getRatings().length - 1); setDefault(GAMES_TABLE_RATED_INDEX, 0); setDefault(GAMES_TABLE_SHOW_BUGHOUSE, true); setDefault(GAMES_TABLE_SHOW_LIGHTNING, true); setDefault(GAMES_TABLE_SHOW_BLITZ, true); setDefault(GAMES_TABLE_SHOW_STANDARD, true); setDefault(GAMES_TABLE_SHOW_CRAZYHOUSE, true); setDefault(GAMES_TABLE_SHOW_EXAMINED, true); setDefault(GAMES_TABLE_SHOW_WILD, true); setDefault(GAMES_TABLE_SHOW_ATOMIC, true); setDefault(GAMES_TABLE_SHOW_SUICIDE, true); setDefault(GAMES_TABLE_SHOW_LOSERS, true); setDefault(GAMES_TABLE_SHOW_UNTIMED, true); setDefault(GAMES_TABLE_SHOW_NONSTANDARD, true); setDefault(GAMES_TABLE_SHOW_PRIVATE, true); // Arrows // PreferenceConverter.setDefault(this, ARROW_OBS_OPP_COLOR, new // RGB(255, // 0, 255)); // PreferenceConverter // .setDefault(this, ARROW_MY_COLOR, new RGB(0, 0, 255)); // PreferenceConverter.setDefault(this, ARROW_PREMOVE_COLOR, new RGB(0, // 255)); // PreferenceConverter.setDefault(this, ARROW_OBS_COLOR, // new RGB(0, 0, 255)); setDefault(ARROW_SHOW_ON_OBS_AND_OPP_MOVES, true); setDefault(ARROW_SHOW_ON_MOVE_LIST_MOVES, true); setDefault(ARROW_SHOW_ON_MY_PREMOVES, true); setDefault(ARROW_SHOW_ON_MY_MOVES, false); setDefault(ARROW_ANIMATION_DELAY, 1000L); setDefault(ARROW_FADE_AWAY_MODE, true); setDefault(ARROW_WIDTH_PERCENTAGE, 15); // Highlights // PreferenceConverter.setDefault(this, HIGHLIGHT_OBS_OPP_COLOR, new // RGB( // 255, 0, 255)); // PreferenceConverter.setDefault(this, HIGHLIGHT_MY_COLOR, new RGB(0, // 255)); // PreferenceConverter.setDefault(this, HIGHLIGHT_PREMOVE_COLOR, new // RGB( // 0, 0, 255)); // PreferenceConverter.setDefault(this, HIGHLIGHT_OBS_COLOR, new RGB(0, // 255)); setDefault(HIGHLIGHT_SHOW_ON_OBS_AND_OPP_MOVES, true); setDefault(HIGHLIGHT_SHOW_ON_MOVE_LIST_MOVES, true); setDefault(HIGHLIGHT_SHOW_ON_MY_PREMOVES, true); setDefault(HIGHLIGHT_SHOW_ON_MY_MOVES, false); setDefault(HIGHLIGHT_FADE_AWAY_MODE, false); setDefault(HIGHLIGHT_ANIMATION_DELAY, 1000L); setDefault(HIGHLIGHT_WIDTH_PERCENTAGE, 3); // Game Results // PreferenceConverter.setDefault(this, RESULTS_COLOR, new RGB(255, 0, PreferenceConverter.setDefault(this, RESULTS_FONT, new FontData[] { new FontData(defaultMonospacedFontName, 40, SWT.BOLD) }); setDefault(RESULTS_IS_SHOWING, true); setDefault(RESULTS_FADE_AWAY_MODE, true); setDefault(RESULTS_ANIMATION_DELAY, 2000L); setDefault(RESULTS_WIDTH_PERCENTAGE, 80); // Chat setDefault(CHAT_MAX_CONSOLE_CHARS, 100000); setDefault(CHAT_TIMESTAMP_CONSOLE, false); setDefault(CHAT_TIMESTAMP_CONSOLE_FORMAT, "'['hh:mma']'"); setDefault(CHAT_IS_PLAYING_CHAT_ON_PTELL, true); setDefault(CHAT_IS_PLAYING_CHAT_ON_PERSON_TELL, true); setDefault(CHAT_IS_SMART_SCROLL_ENABLED, true); setDefault(CHAT_OPEN_CHANNEL_TAB_ON_CHANNEL_TELLS, false); setDefault(CHAT_OPEN_PERSON_TAB_ON_PERSON_TELLS, false); setDefault(CHAT_OPEN_PARTNER_TAB_ON_PTELLS, false); setDefault(CHAT_REMOVE_SUB_TAB_MESSAGES_FROM_MAIN_TAB, true); setDefault(CHAT_UNDERLINE_URLS, true); setDefault(CHAT_UNDERLINE_QUOTED_TEXT, true); setDefault(CHAT_UNDERLINE_SINGLE_QUOTES, false); setDefault(CHAT_PLAY_NOTIFICATION_SOUND_ON_ARRIVALS, true); setDefault(CHAT_PLAY_NOTIFICATION_SOUND_ON_DEPARTURES, false); setDefault(CHAT_UNDERLINE_COMMANDS, true); setDefault(CHAT_COMMAND_LINE_SPELL_CHECK, !OSUtils.isLikelyLinux()); PreferenceConverter.setDefault(this, CHAT_INPUT_FONT, new FontData[] { new FontData(defaultMonospacedFontName, defaultLargeFontSize, 0) }); PreferenceConverter.setDefault(this, CHAT_OUTPUT_FONT, new FontData[] { new FontData(defaultMonospacedFontName, defaultMediumFontSize, 0) }); applyDefaultTheme(); applyDefaultLayout(); // PreferenceConverter.setDefault(this, BOARD_BACKGROUND_COLOR, new // RGB(0, // 0, 0)); // PreferenceConverter.setDefault(this, BOARD_COORDINATES_COLOR, new // RGB( // 0, 0, 0)); // PreferenceConverter.setDefault(this, BOARD_ACTIVE_CLOCK_COLOR, new // RGB( // 0, 255, 0)); // PreferenceConverter.setDefault(this, BOARD_INACTIVE_CLOCK_COLOR, // new RGB(128, 128, 128)); // PreferenceConverter.setDefault(this, BOARD_CONTROL_COLOR, new // RGB(128, // 128, 128)); // PreferenceConverter.setDefault(this, BOARD_LAG_OVER_20_SEC_COLOR, // new RGB(255, 0, 0)); // PreferenceConverter.setDefault(this, BOARD_PIECE_JAIL_LABEL_COLOR, // new RGB(0, 255, 0)); // PreferenceConverter.setDefault(this, // BOARD_PIECE_JAIL_BACKGROUND_COLOR, // new RGB(0, 0, 0)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHALLENGE // + "-color", new RGB(100, 149, 237)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CSHOUT // + "-color", new RGB(221, 160, 221)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.SHOUT // + "-color", new RGB(221, 160, 221)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.KIBITZ // + "-color", new RGB(100, 149, 237)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.WHISPER // + "-color", new RGB(100, 149, 237)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.OUTBOUND // + "-color", new RGB(128, 128, 128)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.PARTNER_TELL // + "-color", new RGB(255, 0, 0)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.DRAW_REQUEST // + "-color", new RGB(255, 0, 0)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.ABORT_REQUEST // + "-color", new RGB(255, 0, 0)); // PreferenceConverter // .setDefault(this, CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO // + ChatType.TELL + "-color", new RGB(255, 0, 0)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL // + "-" + 1 + "-color", new RGB(255, 200, 0)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL // + "-" + 4 + "-color", new RGB(0, 255, 0)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL // + "-" + 50 + "-color", new RGB(255, 175, 175)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL // + "-" + 53 + "-color", new RGB(255, 0, 255)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.INTERNAL // + "-color", new RGB(255, 0, 0)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO // + ChatType.PLAYING_STATISTICS + "-color", new RGB(100, // 149, 237)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.QTELL // + "-color", new RGB(128, 128, 128)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.FINGER // + "-color", new RGB(128, 128, 128)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.HISTORY // + "-color", new RGB(128, 128, 128)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.GAMES // + "-color", new RGB(128, 128, 128)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.BUGWHO_ALL // + "-color", new RGB(128, 128, 128)); // PreferenceConverter.setDefault(this, // CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO // + ChatType.NOTIFICATION_ARRIVAL + "-color", new RGB( // 255, 0, 0)); // PreferenceConverter.setDefault(this, CHAT_PROMPT_COLOR, new RGB(128, // 128, 128)); // PreferenceConverter.setDefault(this, CHAT_QUOTE_UNDERLINE_COLOR, // new RGB(0, 255, 0)); // PreferenceConverter.setDefault(this, CHAT_LINK_UNDERLINE_COLOR, // new RGB(11, 133, 238)); // Bug house buttons settings. PreferenceConverter.setDefault(this, BUG_BUTTONS_FONT, new FontData[] { new FontData(defaultFontName, defaultSmallFontSize, SWT.BOLD) }); // Bug house setDefault(BUGHOUSE_PLAYING_OPEN_PARTNER_BOARD, true); setDefault(BUGHOUSE_OBSERVING_OPEN_PARTNER_BOARD, true); setDefault(BUGHOUSE_SPEAK_COUNTDOWN_ON_PARTNER_BOARD, true); setDefault(BUGHOUSE_SPEAK_PARTNER_TELLS, true); setDefault(BUGHOUSE_IS_PLAYING_PARTNERSHIP_OFFERED_SOUND, true); // Fics setDefault(FICS_KEEP_ALIVE, false); setDefault(FICS_AUTO_CONNECT, false); setDefault(FICS_LOGIN_SCRIPT, "set seek 0\nset autoflag 1\n"); setDefault(FICS_AUTO_CONNECT, false); setDefault(FICS_PROFILE, "Primary"); setDefault(FICS_CLOSE_TABS_ON_DISCONNECT, false); setDefault(FICS_SHOW_BUGBUTTONS_ON_PARTNERSHIP, true); setDefault(FICS_NO_WRAP_ENABLED, true); setDefault(FICS_CHANNEL_COMMANDS, "+channel $channel,-channel $channel,in $channel"); setDefault(FICS_PERSON_QUICK_COMMANDS, "finger $person,follow $person,partner $person"); setDefault( FICS_PERSON_COMMANDS, "history $person,journal $person," + "observe $person,oldpstat $userName $person,pstat $userName $person," + "stored $person,variables $person,separator," + "+censor $person,-censor $person,+gnotify $person,-gnotify $person,+noplay $person,-noplay $person,+notify $person,-notify $person,separator," + "match $person 1 0,match $person 3 0,match $person 5 0,match $person 15 0"); setDefault(FICS_GAME_COMMANDS, "observe $gameId,allobservers $gameId,moves $gameId"); setDefault( FICS_REGULAR_EXPRESSIONS_TO_BLOCK, "defprompt set\\.,gameinfo set\\.,ms set\\.,startpos set\\.," + "pendinfo set\\.,nowrap set\\.,smartmove set\\.,premove set\\.," + "Style 12 set\\.,Your prompt will now not show the time\\.," + "You will not see seek ads\\.,You will not see seek ads.\\.," + "Auto-flagging enabled\\.,lock set\\.,set seek 0,set autoflag 1," + "allresults set\\.,Bell off\\.,set interface Raptor .*," + "You are not examining or setting up a game\\."); setDefault(FICS_SEEK_GAME_TYPE, ""); setDefault(FICS_SEEK_MINUTES, "5"); setDefault(FICS_SEEK_INC, "0"); setDefault(FICS_SEEK_MIN_RATING, "Any"); setDefault(FICS_SEEK_MAX_RATING, "Any"); setDefault(FICS_SEEK_MANUAL, false); setDefault(FICS_SEEK_FORMULA, true); setDefault(FICS_SEEK_RATED, true); setDefault(FICS_SEEK_COLOR, ""); setDefault(FICS_KEEP_ALIVE_COMMAND, "set busy is away from the keyboard."); // Fics Primary setDefault(FICS_PRIMARY_USER_NAME, ""); setDefault(FICS_PRIMARY_PASSWORD, ""); setDefault(FICS_PRIMARY_IS_NAMED_GUEST, false); setDefault(FICS_PRIMARY_IS_ANON_GUEST, false); setDefault(FICS_PRIMARY_SERVER_URL, "freechess.org"); setDefault(FICS_PRIMARY_PORT, 5000); setDefault(FICS_PRIMARY_TIMESEAL_ENABLED, true); // Fics Secondary setDefault(FICS_SECONDARY_USER_NAME, ""); setDefault(FICS_SECONDARY_PASSWORD, ""); setDefault(FICS_SECONDARY_IS_NAMED_GUEST, false); setDefault(FICS_SECONDARY_IS_ANON_GUEST, false); setDefault(FICS_SECONDARY_SERVER_URL, "freechess.org"); setDefault(FICS_SECONDARY_PORT, 5000); setDefault(FICS_SECONDARY_TIMESEAL_ENABLED, true); // Fics Tertiary setDefault(FICS_TERTIARY_USER_NAME, ""); setDefault(FICS_TERTIARY_PASSWORD, ""); setDefault(FICS_TERTIARY_IS_NAMED_GUEST, false); setDefault(FICS_TERTIARY_IS_ANON_GUEST, false); setDefault(FICS_TERTIARY_SERVER_URL, "freechess.org"); setDefault(FICS_TERTIARY_PORT, 5000); setDefault(FICS_TERTIARY_TIMESEAL_ENABLED, true); setDefault(FICS_REMOVE_BLANK_LINES, false); // Fics Timeseal // Timeseal 2 forced for OSX, Timeseal 1 for other OSes. // For some reason windows/linux have timeseal2 issues. setDefault(FICS_TIMESEAL_IS_TIMESEAL_2, OSUtils.isLikelyOSX()); // Bics setDefault(BICS_KEEP_ALIVE, false); setDefault(BICS_AUTO_CONNECT, false); setDefault(BICS_LOGIN_SCRIPT, "set autoflag 1\n\n"); setDefault(BICS_AUTO_CONNECT, false); setDefault(BICS_PROFILE, "Primary"); setDefault(BICS_CLOSE_TABS_ON_DISCONNECT, false); setDefault(BICS_SHOW_BUGBUTTONS_ON_PARTNERSHIP, true); setDefault(BICS_KEEP_ALIVE_COMMAND, "set busy is away from the keyboard."); setDefault(BICS_CHANNEL_COMMANDS, "+channel $channel,-channel $channel,in $channel"); setDefault(BICS_PERSON_QUICK_COMMANDS, "finger $person,follow $person,partner $person"); setDefault( BICS_PERSON_COMMANDS, "history $person,journal $person," + "observe $person,oldpstat $userName $person,pstat $userName $person," + "stored $person,variables $person,separator," + "+censor $person,-censor $person,+gnotify $person,-gnotify $person,+noplay $person,-noplay $person,+notify $person,-notify $person,separator," + "match $person 1 0 zh,match $person 3 0 zh,match $person 1 0 zh fr,match $person 3 0 zh fr,match $person 2 0 bughouse," + "match $person 2 0 bughouse fr, match $person 2 0 bughouse w5"); setDefault(BICS_GAME_COMMANDS, "observe $gameId,allobservers $gameId,moves $gameId"); setDefault( BICS_REGULAR_EXPRESSIONS_TO_BLOCK, "defprompt set\\.,gameinfo set\\.,ms set\\.,startpos set\\.," + "pendinfo set\\.,nowrap set\\.,smartmove set\\.,premove set\\.," + "Style 12 set\\.,Your prompt will now not show the time\\.," + "You will not see seek ads\\.,You will not see seek ads.\\.," + "Auto-flagging enabled\\.,lock set\\."); // Bics Primary setDefault(BICS_PRIMARY_USER_NAME, ""); setDefault(BICS_PRIMARY_PASSWORD, ""); setDefault(BICS_PRIMARY_IS_NAMED_GUEST, false); setDefault(BICS_PRIMARY_IS_ANON_GUEST, false); setDefault(BICS_PRIMARY_SERVER_URL, "chess.sipay.ru"); setDefault(BICS_PRIMARY_PORT, 5000); setDefault(BICS_PRIMARY_TIMESEAL_ENABLED, true); // Bics Secondary setDefault(BICS_SECONDARY_USER_NAME, ""); setDefault(BICS_SECONDARY_PASSWORD, ""); setDefault(BICS_SECONDARY_IS_NAMED_GUEST, false); setDefault(BICS_SECONDARY_IS_ANON_GUEST, false); setDefault(BICS_SECONDARY_SERVER_URL, "chess.sipay.ru"); setDefault(BICS_SECONDARY_PORT, 5000); setDefault(BICS_SECONDARY_TIMESEAL_ENABLED, true); // Bics Tertiary setDefault(BICS_TERTIARY_USER_NAME, ""); setDefault(BICS_TERTIARY_PASSWORD, ""); setDefault(BICS_TERTIARY_IS_NAMED_GUEST, false); setDefault(BICS_TERTIARY_IS_ANON_GUEST, false); setDefault(BICS_TERTIARY_SERVER_URL, "chess.sipay.ru"); setDefault(BICS_TERTIARY_PORT, 5000); setDefault(BICS_TERTIARY_TIMESEAL_ENABLED, true); setDefault(BICS_REMOVE_BLANK_LINES, false); // Quadrant settings. setDefault("fics-" + MAIN_TAB_QUADRANT, Quadrant.VI); setDefault("fics-" + CHANNEL_TAB_QUADRANT, Quadrant.VI); setDefault("fics-" + PERSON_TAB_QUADRANT, Quadrant.VI); setDefault("fics-" + REGEX_TAB_QUADRANT, Quadrant.VI); setDefault("fics-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VI); setDefault("fics-" + BUG_WHO_QUADRANT, Quadrant.VIII); setDefault("fics-" + SEEK_TABLE_QUADRANT, Quadrant.VIII); setDefault("fics-" + BUG_BUTTONS_QUADRANT, Quadrant.IX); setDefault("fics-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VI); setDefault("fics-" + GAMES_TAB_QUADRANT, Quadrant.VIII); setDefault("fics-" + GAME_BOT_QUADRANT, Quadrant.VIII); setDefault("fics2-" + MAIN_TAB_QUADRANT, Quadrant.VII); setDefault("fics2-" + CHANNEL_TAB_QUADRANT, Quadrant.VII); setDefault("fics2-" + PERSON_TAB_QUADRANT, Quadrant.VII); setDefault("fics2-" + REGEX_TAB_QUADRANT, Quadrant.VII); setDefault("fics2-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VII); setDefault("fics2-" + BUG_WHO_QUADRANT, Quadrant.VIII); setDefault("fics2-" + SEEK_TABLE_QUADRANT, Quadrant.VIII); setDefault("fics2-" + BUG_BUTTONS_QUADRANT, Quadrant.IX); setDefault("fics2-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VII); setDefault("fics2-" + GAMES_TAB_QUADRANT, Quadrant.VIII); setDefault("fics2-" + GAME_BOT_QUADRANT, Quadrant.VIII); setDefault("bics-" + MAIN_TAB_QUADRANT, Quadrant.VI); setDefault("bics-" + CHANNEL_TAB_QUADRANT, Quadrant.VI); setDefault("bics-" + PERSON_TAB_QUADRANT, Quadrant.VI); setDefault("bics-" + REGEX_TAB_QUADRANT, Quadrant.VI); setDefault("bics-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VI); setDefault("bics-" + BUG_WHO_QUADRANT, Quadrant.VIII); setDefault("bics-" + SEEK_TABLE_QUADRANT, Quadrant.VIII); setDefault("bics-" + BUG_BUTTONS_QUADRANT, Quadrant.IX); setDefault("bics-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VI); setDefault("bics-" + GAMES_TAB_QUADRANT, Quadrant.VIII); setDefault("bics2-" + MAIN_TAB_QUADRANT, Quadrant.VII); setDefault("bics2-" + CHANNEL_TAB_QUADRANT, Quadrant.VII); setDefault("bics2-" + PERSON_TAB_QUADRANT, Quadrant.VII); setDefault("bics2-" + REGEX_TAB_QUADRANT, Quadrant.VII); setDefault("bics2-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VII); setDefault("bics2-" + BUG_WHO_QUADRANT, Quadrant.VIII); setDefault("bics2-" + SEEK_TABLE_QUADRANT, Quadrant.VIII); setDefault("bics2-" + BUG_BUTTONS_QUADRANT, Quadrant.IX); setDefault("bics2-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VII); setDefault("bics2-" + GAMES_TAB_QUADRANT, Quadrant.VIII); LOG.info("Loaded defaults " + PREFERENCE_PROPERTIES_FILE); } @Override public void save() { FileOutputStream fileOut = null; try { save(fileOut = new FileOutputStream(RAPTOR_PROPERTIES), "Last saved on " + new Date()); fileOut.flush(); } catch (IOException ioe) { LOG.error("Error saving raptor preferences:", ioe); throw new RuntimeException(ioe); } finally { try { fileOut.close(); } catch (Throwable t) { } } } public void setDefault(String key, Font font) { PreferenceConverter.setValue(this, key, font.getFontData()); } public void setDefault(String key, FontData[] fontData) { PreferenceConverter.setValue(this, key, fontData); } public void setDefault(String key, int[] values) { setDefault(key, RaptorStringUtils.toString(values)); } public void setDefault(String key, Point point) { PreferenceConverter.setValue(this, key, point); } public void setDefault(String key, Quadrant quadrant) { setDefault(key, quadrant.name()); } public void setDefault(String key, Rectangle rectangle) { PreferenceConverter.setDefault(this, key, rectangle); } public void setDefault(String key, RGB rgb) { PreferenceConverter.setValue(this, key, rgb); } public void setDefault(String key, String[] values) { setDefault(key, RaptorStringUtils.toString(values)); } public void setValue(String key, Font font) { PreferenceConverter.setValue(this, key, font.getFontData()); } public void setValue(String key, FontData[] fontData) { PreferenceConverter.setValue(this, key, fontData); } public void setValue(String key, int[] values) { setValue(key, RaptorStringUtils.toString(values)); } public void setValue(String key, Point point) { PreferenceConverter.setValue(this, key, point); } public void setValue(String key, Quadrant quadrant) { setValue(key, quadrant.name()); } public void setValue(String key, Rectangle rectangle) { PreferenceConverter.setValue(this, key, rectangle); } public void setValue(String key, RGB rgb) { PreferenceConverter.setValue(this, key, rgb); } public void setValue(String key, String[] values) { setValue(key, RaptorStringUtils.toString(values)); } protected void setDefaultMonitorBasedSizes() { Rectangle fullViewBounds = Display.getCurrent().getPrimaryMonitor() .getBounds(); int toolbarPieceSize = 12; String iconSize = "tiny"; defaultLargeFontSize = 12; defaultMediumFontSize = 10; defaultSmallFontSize = 8; defaultTinyFontSize = 6; if (fullViewBounds.height >= 1200) { iconSize = "large"; toolbarPieceSize = 24; defaultLargeFontSize = 18; defaultMediumFontSize = 16; defaultSmallFontSize = 14; defaultTinyFontSize = 12; } else if (fullViewBounds.height >= 1024) { iconSize = "medium"; toolbarPieceSize = 20; defaultLargeFontSize = 16; defaultMediumFontSize = 14; defaultSmallFontSize = 12; defaultTinyFontSize = 10; } else if (fullViewBounds.height >= 670) { iconSize = "small"; toolbarPieceSize = 16; defaultLargeFontSize = 14; defaultMediumFontSize = 12; defaultSmallFontSize = 10; defaultTinyFontSize = 8; } getDefaultMonospacedFont(); setDefault(PreferenceKeys.APP_ICON_SIZE, iconSize); setDefault(PreferenceKeys.APP_TOOLBAR_PIECE_SIZE, toolbarPieceSize); } }
package org.ligi.snackengage; public class Dependencies { public static class Android { public static final String APPLICATION_ID = "org.ligi.snackengage"; public static final String BUILD_TOOLS_VERSION = "29.0.3"; public static final int MIN_SDK_VERSION = 14; public static final int COMPILE_SDK_VERSION = 29; public static final int TARGET_SDK_VERSION = 29; public static final int VERSION_CODE = 24; public static final String VERSION_NAME = "0.24"; } public static class GradlePlugins { public static final String ANDROID = "com.android.tools.build:gradle:4.0.1"; public static final String MAVEN = "com.github.dcendents:android-maven-gradle-plugin:2.1"; public static final String VERSIONS = "com.github.ben-manes:gradle-versions-plugin:0.33.0"; } public static class Libs { public static final String ANNOTATION = "androidx.annotation:annotation:1.1.0"; public static final String APPCOMPAT = "androidx.appcompat:appcompat:1.2.0"; public static final String ASSERTJ_ANDROID = "com.squareup.assertj:assertj-android:1.2.0"; public static final String JUNIT = "junit:junit:4.13.1"; public static final String MATERIAL = "com.google.android.material:material:1.2.0"; public static final String MOCKITO = "org.mockito:mockito-core:3.5.0"; } }
package ucar.nc2.iosp.grid; import ucar.ma2.*; import ucar.nc2.*; import ucar.nc2.dt.fmr.FmrcCoordSys; import ucar.nc2.iosp.AbstractIOServiceProvider; import ucar.nc2.util.CancelTask; import ucar.unidata.io.RandomAccessFile; import ucar.grid.GridIndex; import ucar.grid.GridRecord; import java.io.IOException; import java.util.List; /** * An IOSP for Gempak Grid data * * @author IDV Development Team * @version $Revision: 1.3 $ */ public abstract class GridServiceProvider extends AbstractIOServiceProvider { /** FMRC coordinate system */ protected FmrcCoordSys fmrcCoordSys; /** The netCDF file */ protected NetcdfFile ncfile; /** the file we are reading */ protected RandomAccessFile raf; /** should file be synced or extended */ protected boolean syncExtend = false; /* to use or not to use cache first */ protected static boolean alwaysInCache = false; /* to extend the index */ public static boolean extendMode = false; /** place to store debug stuff */ protected StringBuilder parseInfo = new StringBuilder(); /** debug flags */ protected static boolean debugOpen = false, debugMissing = false, debugMissingDetails = false, debugProj = false, debugTiming = false, debugVert = false; /** flag for using maximal coordinate system */ static public boolean useMaximalCoordSys = false; /** * Set whether to use the maximal coordinate system or not * * @param b true to use */ static public void useMaximalCoordSys(boolean b) { useMaximalCoordSys = b; } /** * Set the debug flags * * @param debugFlag debug flags */ static public void setDebugFlags(ucar.nc2.util.DebugFlags debugFlag) { debugOpen = debugFlag.isSet("Grid/open"); debugMissing = debugFlag.isSet("Grid/missing"); debugMissingDetails = debugFlag.isSet("Grid/missingDetails"); debugProj = debugFlag.isSet("Grid/projection"); debugVert = debugFlag.isSet("Grid/vertical"); debugTiming = debugFlag.isSet("Grid/timing"); } /** * Open the index and create the netCDF file from that * * @param index GridIndex to use * @param cancelTask cancel task * * @throws IOException problem reading the file */ protected abstract void open(GridIndex index, CancelTask cancelTask) throws IOException; /** * Open the service provider for reading. * @param raf file to read from * @param ncfile netCDF file we are writing to (memory) * @param cancelTask task for cancelling * * @throws IOException problem reading file */ public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask) throws IOException { this.raf = raf; this.ncfile = ncfile; } /** * Close this IOSP * * @throws IOException problem closing file */ public void close() throws IOException { raf.close(); } /** * Sync and extend * * @return syncExtend */ public boolean syncExtend() { return syncExtend; } /** * Sync and extend * * @return syncExtend */ public void setSyncExtend( boolean se ) { syncExtend = se; } /** * alwaysInCache * * @return alwaysInCache */ public static boolean alwaysInCache() { return alwaysInCache; } /** * alwaysInCache * * @param aic */ public static void setAlwaysInCache( boolean aic ) { alwaysInCache = aic; } /** * extendMode * * @return extendMode */ public static boolean extendMode() { return extendMode; } /** * extendMode * * @param em */ public static void setExtendMode( boolean em ) { extendMode = em; } /** * Get the detail information * * @return the detail info */ public String getDetailInfo() { return parseInfo.toString(); } /** * Send an IOSP message * * @param special isn't that special? */ public Object sendIospMessage( Object special) { if (special instanceof FmrcCoordSys) { fmrcCoordSys = (FmrcCoordSys) special; } return null; } /** * Read the data for the variable * @param v2 Variable to read * @param section section infomation * @return Array of data * * @throws IOException problem reading from file * @throws InvalidRangeException invalid Range */ public Array readData(Variable v2, Section section) throws IOException, InvalidRangeException { long start = System.currentTimeMillis(); Array dataArray = Array.factory(DataType.FLOAT, section.getShape()); GridVariable pv = (GridVariable) v2.getSPobject(); int count = 0; Range timeRange = section.getRange(count++); Range levRange = pv.hasVert() ? section.getRange(count++) : null; Range yRange = section.getRange(count++); Range xRange = section.getRange(count); IndexIterator ii = dataArray.getIndexIteratorFast(); // loop over time for (int timeIdx = timeRange.first(); timeIdx <= timeRange.last(); timeIdx += timeRange.stride()) { if (pv.hasVert()) { readLevel(v2, timeIdx, levRange, yRange, xRange, ii); } else { readXY(v2, timeIdx, 0, yRange, xRange, ii); } } if (debugTiming) { long took = System.currentTimeMillis() - start; System.out.println(" read data took=" + took + " msec "); } return dataArray; } // loop over level /** * Read a level * * @param v2 variable to put the data into * @param timeIdx time index * @param levelRange level range * @param yRange x range * @param xRange y range * @param ii index iterator * * @throws IOException problem reading the file * @throws InvalidRangeException invalid range */ private void readLevel(Variable v2, int timeIdx, Range levelRange, Range yRange, Range xRange, IndexIterator ii) throws IOException, InvalidRangeException { for (int levIdx = levelRange.first(); levIdx <= levelRange.last(); levIdx += levelRange.stride()) { readXY(v2, timeIdx, levIdx, yRange, xRange, ii); } } /** * read one product * * @param v2 variable to put the data into * @param timeIdx time index * @param levIdx level index * @param yRange x range * @param xRange y range * @param ii index iterator * * @throws IOException problem reading the file * @throws InvalidRangeException invalid range */ private void readXY(Variable v2, int timeIdx, int levIdx, Range yRange, Range xRange, IndexIterator ii) throws IOException, InvalidRangeException { Attribute att = v2.findAttribute("missing_value"); float missing_value = (att == null) ? -9999.0f : att.getNumericValue() .floatValue(); GridVariable pv = (GridVariable) v2.getSPobject(); GridHorizCoordSys hsys = pv.getHorizCoordSys(); int nx = hsys.getNx(); GridRecord record = pv.findRecord(timeIdx, levIdx); if (record == null) { int xyCount = yRange.length() * xRange.length(); for (int j = 0; j < xyCount; j++) { ii.setFloatNext(missing_value); } return; } // otherwise read it float[] data= _readData(record); for (int y = yRange.first(); y <= yRange.last(); y += yRange.stride()) { for (int x = xRange.first(); x <= xRange.last(); x += xRange.stride()) { int index = y * nx + x; ii.setFloatNext(data[index]); } } } /** * Is this XY level missing? * * @param v2 Variable * @param timeIdx time index * @param levIdx level index * * @return true if missing * * @throws InvalidRangeException invalid range */ private boolean isMissingXY(Variable v2, int timeIdx, int levIdx) throws InvalidRangeException { GridVariable pv = (GridVariable) v2.getSPobject(); if (null == pv) System.out.println("HEY"); if ((timeIdx < 0) || (timeIdx >= pv.getNTimes())) { throw new InvalidRangeException("timeIdx=" + timeIdx); } if ((levIdx < 0) || (levIdx >= pv.getVertNlevels())) { throw new InvalidRangeException("levIdx=" + levIdx); } return (null == pv.findRecord(timeIdx, levIdx)); } /** * Read the data for this GridRecord * * @param gr grid identifier * * @return the data (or null) * * @throws IOException problem reading the data */ protected abstract float[] _readData(GridRecord gr) throws IOException; } // end GribServiceProvider
package com.yunkuent.sdk; import com.gokuai.base.RequestMethod; import com.gokuai.base.utils.Util; import java.util.HashMap; public class EntManager extends OauthEngine { private final String URL_API_GET_GROUPS = HostConfig.API_ENT_HOST + "/1/ent/get_groups"; private final String URL_API_GET_MEMBERS = HostConfig.API_ENT_HOST + "/1/ent/get_members"; private final String URL_API_GET_MEMBER = HostConfig.API_ENT_HOST + "/1/ent/get_member"; private final String URL_API_GET_ROLES = HostConfig.API_ENT_HOST + "/1/ent/get_roles"; // private final String URL_API_SYNC_MEMBER = HostConfig.API_ENT_HOST + "/1/ent/sync_member"; private final String URL_API_GET_MEMBER_FILE_LINK = HostConfig.API_ENT_HOST + "/1/ent/get_member_file_link"; // private final String URL_API_GET_MEMBER_BY_OUT_ID = HostConfig.API_ENT_HOST + "/1/ent/get_member_by_out_id"; private final String URL_API_ADD_SYNC_MEMBER = HostConfig.API_ENT_HOST + "/1/ent/add_sync_member"; private final String URL_API_DEL_SYNC_MEMBER = HostConfig.API_ENT_HOST + "/1/ent/del_sync_member"; private final String URL_API_ADD_SYNC_GROUP = HostConfig.API_ENT_HOST + "/1/ent/add_sync_group"; private final String URL_API_DEL_SYNC_GROUP = HostConfig.API_ENT_HOST + "/1/ent/del_sync_group"; private final String URL_API_ADD_SYNC_GROUP_MEMBER = HostConfig.API_ENT_HOST + "/1/ent/add_sync_group_member"; private final String URL_API_DEL_SYNC_GROUP_MEMBER = HostConfig.API_ENT_HOST + "/1/ent/del_sync_group_member"; private final String URL_API_DEL_SYNC_MEMBER_GROUP = HostConfig.API_ENT_HOST + "/1/ent/del_sync_member_group"; private final String URL_API_GET_GROUP_MEMBERS = HostConfig.API_ENT_HOST + "/1/ent/get_group_members"; private final String ADD_SYNC_ADMIN = HostConfig.API_ENT_HOST + "/1/ent/add_sync_admin"; private final String MEMBER_LOGIN_REPORT = HostConfig.API_ENT_HOST + "/1/ent/member_login_report"; public EntManager(String clientId, String clientSecret) { super(clientId, clientSecret, true); } private EntManager(String clientId, String clientSecret, boolean isEnt, String token) { super(clientId, clientSecret, isEnt, token); } /** * * * @return */ public String getRoles() { String url = URL_API_GET_ROLES; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync(); } /** * * * @param start * @param size * @return */ public String getMembers(int start, int size) { String url = URL_API_GET_MEMBERS; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("start", start + ""); params.put("size", size + ""); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync(); } private String getMember(int memberId, String outId, String account, boolean showGroups) { String url = URL_API_GET_MEMBER; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); if (memberId > 0) { params.put("member_id", memberId + ""); } params.put("out_id", outId); params.put("account", account); if (showGroups) { params.put("show_groups", "1"); } params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync(); } /** * id * * @param memberId * @param showGroups * @return */ public String getMemberById(int memberId, boolean showGroups) { return getMember(memberId, null, null, showGroups); } /** * id * * @param outId * @param showGroups * @return */ public String getMemberByOutId(String outId, boolean showGroups) { return getMember(0, outId, null, showGroups); } /** * * * @param account * @param showGroups * @return */ public String getMemberByAccount(String account, boolean showGroups) { return getMember(0, null, account, showGroups); } /** * * * @return */ public String getGroups() { String url = URL_API_GET_GROUPS; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync(); } /** * id * * @param memberId * @return */ public String getMemberFileLink(int memberId, boolean fileOnly) { String url = URL_API_GET_MEMBER_FILE_LINK; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("member_id", memberId + ""); if (fileOnly) { params.put("file", "1"); } params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync(); } // /** // * id // * // * @return // */ // public String getMemberByOutid(String outIds[]) { // if (outIds == null) { // throw new NullPointerException("outIds is null"); // return getMemberByIds(null, outIds); // /** // * // * // * @return // */ // public String getMemberByUserId(String[] userIds) { // if (userIds == null) { // throw new NullPointerException("userIds is null"); // return getMemberByIds(userIds, null); // private String getMemberByIds(String[] userIds, String[] outIds) { // String method = "GET"; // String url = URL_API_GET_MEMBER_BY_OUT_ID; // ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); // params.add(new BasicNameValuePair("client_id", mClientId)); // params.add(new BasicNameValuePair("dateline", Util.getUnixDateline() + "")); // if (outIds != null) { // params.add(new BasicNameValuePair("out_ids", Util.strArrayToString(outIds, ",") + "")); // } else { // params.add(new BasicNameValuePair("user_ids", Util.strArrayToString(userIds, ",") + "")); // params.add(new BasicNameValuePair("sign", generateSign(paramSorted(params)))); // return NetConnection.sendRequest(url, method, params, null); /** * * * @param outId * @param memberName * @param account * @param memberEmail * @param memberPhone * @param password , * @return */ public String addSyncMember(String outId, String memberName, String account, String memberEmail, String memberPhone, String password, String state) { String url = URL_API_ADD_SYNC_MEMBER; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("out_id", outId); params.put("member_name", memberName); params.put("account", account); params.put("member_email", memberEmail); params.put("member_phone", memberPhone); params.put("password", password); params.put("state", state); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param oudId * @return */ public String setSyncMemberState(String oudId, boolean state) { String url = URL_API_ADD_SYNC_MEMBER; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("out_id", oudId); params.put("state", state ? "1" : "0"); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param members * @return */ public String delSyncMember(String[] members) { String url = URL_API_DEL_SYNC_MEMBER; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("members", Util.strArrayToString(members, ",")); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param outId * @param name * @param parentOutId * @return */ public String addSyncGroup(String outId, String name, String parentOutId) { String url = URL_API_ADD_SYNC_GROUP; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("out_id", outId); params.put("name", name); params.put("parent_out_id", parentOutId); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param groups * @return */ public String delSyncGroup(String[] groups) { String url = URL_API_DEL_SYNC_GROUP; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("groups", Util.strArrayToString(groups, ",")); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param groupOutId * @param members * @return */ public String addSyncGroupMember(String groupOutId, String[] members) { String url = URL_API_ADD_SYNC_GROUP_MEMBER; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("group_out_id", groupOutId); params.put("members", Util.strArrayToString(members, ",")); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param groupOutId * @param members * @return */ public String delSyncGroupMember(String groupOutId, String[] members) { String url = URL_API_DEL_SYNC_GROUP_MEMBER; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("group_out_id", groupOutId); params.put("members", Util.strArrayToString(members, ",")); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param groupId * @param start * @param size * @param showChild * @return */ public String getGroupMembers(int groupId, int start, int size, boolean showChild) { String url = URL_API_GET_GROUP_MEMBERS; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("group_id", groupId + ""); params.put("start", start + ""); params.put("size", size + ""); params.put("show_child", (showChild ? 1 : 0) + ""); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync(); } /** * * * @param members * @return */ public String delSyncMemberGroup(String[] members) { String url = URL_API_DEL_SYNC_MEMBER_GROUP; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("members", Util.strArrayToString(members, ",")); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param outId * @param memberEmail * @param isSuperAdmin * @return */ public String addSyncAdmin(String outId, String memberEmail, boolean isSuperAdmin) { String url = ADD_SYNC_ADMIN; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("out_id", outId); params.put("member_email", memberEmail); params.put("type", (isSuperAdmin ? 1 : 0) + ""); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.POST).executeSync(); } /** * * * @param startDate * @param enDdate * @return */ public String memberLoginReport(String startDate, String enDdate) { String url = MEMBER_LOGIN_REPORT; HashMap<String, String> params = new HashMap<String, String>(); addAuthParams(params); params.put("start_date", startDate); params.put("end_date", enDdate); params.put("sign", generateSign(params)); return new RequestHelper().setParams(params).setUrl(url).setMethod(RequestMethod.GET).executeSync(); } /** * EntManager * * @return */ public EntManager clone() { return new EntManager(mClientId, mClientSecret, mIsEnt, mToken); } }
package com.github.thomasridd.flatsy.operations.operators; import com.github.thomasridd.flatsy.FlatsyFlatFileDatabase; import com.github.thomasridd.flatsy.query.FlatsyCursor; import com.github.thomasridd.flatsy.util.FlatsyUtil; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class OperatorCommandLineParser { public static void applyFromCommand(FlatsyCursor cursor, String command) { applyFromCommand(cursor, command, System.out); } public static void applyFromCommand(FlatsyCursor cursor, String command, OutputStream defaultOut) { List<String> args = FlatsyUtil.commandArguments(command); String action = args.get(0); if (action.equalsIgnoreCase("copy")) { // copy objects to a new filesystem cursor.apply(new Copy(new FlatsyFlatFileDatabase(Paths.get(args.get(1))))); } else if (action.equalsIgnoreCase("copy_to")) { // replace text in each object cursor.apply(new CopyTo(new FlatsyFlatFileDatabase(Paths.get(args.get(1))), args.get(2))); } else if (action.equalsIgnoreCase("folder_copy")) { // replace text in each object cursor.apply(new Copy(new FlatsyFlatFileDatabase(Paths.get(args.get(1))), true)); } else if (action.equalsIgnoreCase("folder_copy_to")) { // replace text in each object cursor.apply(new CopyTo(new FlatsyFlatFileDatabase(Paths.get(args.get(1))), args.get(2), true)); } else if (action.equalsIgnoreCase("replace")) { // replace text in each object cursor.apply(new Replace(args.get(1), args.get(2))); } else if (action.equalsIgnoreCase("list")) { // list all matching objects if (args.size() > 1) { try (OutputStream stream = Files.newOutputStream(Paths.get(args.get(1)))) { cursor.apply(new UriToOutput(stream)); } catch (IOException e) { e.printStackTrace(); } } else { cursor.apply(new UriToOutput(defaultOut)); } } else if (action.equalsIgnoreCase("table")) { List<String> paths = args.subList(1, args.size()); // list all matching objects if (paths.get(0).startsWith("$") == false) { try (OutputStream stream = Files.newOutputStream(Paths.get(paths.get(0)))) { cursor.apply(new JSONPathsToOutput(stream, paths.subList(1, paths.size()))); } catch (IOException e) { e.printStackTrace(); } } else { cursor.apply(new JSONPathsToOutput(defaultOut, paths)); } } else if (action.equalsIgnoreCase("jsonpath")) { String jsonpath = args.get(1); String jsonAction = args.get(2); if (jsonAction.equalsIgnoreCase("add")) { if (args.size() >= 5) { String jsonField = args.get(3); String jsonValue = args.get(4); cursor.apply(new JSONPathAdd(jsonpath, jsonField, jsonValue)); } } else if (jsonAction.equalsIgnoreCase("put")) { if (args.size() >= 5) { String jsonField = args.get(3); String jsonValue = args.get(4); cursor.apply(new JSONPathPut(jsonpath, jsonField, jsonValue)); } } } } }
package com.uservoice.uservoicesdk.ui; import java.util.Locale; import android.annotation.SuppressLint; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.v4.app.FragmentActivity; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebSettings.PluginState; import android.webkit.WebView; import android.widget.ImageView; import android.widget.TextView; import android.graphics.Color; import com.uservoice.uservoicesdk.R; import com.uservoice.uservoicesdk.Session; import com.uservoice.uservoicesdk.activity.TopicActivity; import com.uservoice.uservoicesdk.dialog.ArticleDialogFragment; import com.uservoice.uservoicesdk.dialog.SuggestionDialogFragment; import com.uservoice.uservoicesdk.model.Article; import com.uservoice.uservoicesdk.model.BaseModel; import com.uservoice.uservoicesdk.model.Suggestion; import com.uservoice.uservoicesdk.model.Topic; public class Utils { @SuppressLint("SetJavaScriptEnabled") public static void displayArticle(WebView webView, Article article) { String styles = "iframe, img { width: 100%; }"; String html = String.format("<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"http://cdn.uservoice.com/stylesheets/vendor/typeset.css\"/><style>%s</style></head><body class=\"typeset\" style=\"font-family: sans-serif; margin: 1em\"><h3>%s</h3>%s</body></html>", styles, article.getTitle(), article.getHtml()); webView.setWebChromeClient(new WebChromeClient()); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setPluginState(PluginState.ON); webView.loadUrl(String.format("data:text/html;charset=utf-8,%s", Uri.encode(html))); } @SuppressLint("DefaultLocale") public static String getQuantityString(View view, int id, int count) { return String.format("%,d %s", count, view.getContext().getResources().getQuantityString(id, count)); } public static boolean hasActionBar() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static void displayInstantAnswer(View view, BaseModel model) { TextView title = (TextView) view.findViewById(R.id.title); TextView detail = (TextView) view.findViewById(R.id.detail); View suggestionDetails = view.findViewById(R.id.suggestion_details); ImageView image = (ImageView) view.findViewById(R.id.icon); if (model instanceof Article) { Article article = (Article) model; image.setImageResource(R.drawable.uv_article); title.setText(article.getTitle()); if (article.getTopicName() != null) { detail.setVisibility(View.VISIBLE); detail.setText(article.getTopicName()); } else { detail.setVisibility(View.GONE); } suggestionDetails.setVisibility(View.GONE); } else if (model instanceof Suggestion) { Suggestion suggestion = (Suggestion) model; image.setImageResource(R.drawable.uv_idea); title.setText(suggestion.getTitle()); detail.setVisibility(View.VISIBLE); detail.setText(suggestion.getForumName()); if (suggestion.getStatus() != null) { View statusColor = suggestionDetails.findViewById(R.id.suggestion_status_color); TextView status = (TextView) suggestionDetails.findViewById(R.id.suggestion_status); int color = Color.parseColor(suggestion.getStatusColor()); suggestionDetails.setVisibility(View.VISIBLE); status.setText(suggestion.getStatus().toUpperCase(Locale.getDefault())); status.setTextColor(color); statusColor.setBackgroundColor(color); } else { suggestionDetails.setVisibility(View.GONE); } } } public static void showModel(FragmentActivity context, BaseModel model) { if (model instanceof Article) { ArticleDialogFragment fragment = new ArticleDialogFragment((Article) model); fragment.show(context.getSupportFragmentManager(), "ArticleDialogFragment"); } else if (model instanceof Suggestion) { SuggestionDialogFragment fragment = new SuggestionDialogFragment((Suggestion) model); fragment.show(context.getSupportFragmentManager(), "SuggestionDialogFragment"); } else if (model instanceof Topic) { Session.getInstance().setTopic((Topic) model); context.startActivity(new Intent(context, TopicActivity.class)); } } }
package com.wandrell.tabletop.business.model.punkapocalyptic.unit; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collection; import java.util.Collections; import java.util.EventObject; import java.util.LinkedHashSet; import javax.swing.event.EventListenerList; import com.wandrell.tabletop.business.model.punkapocalyptic.event.ValorationListener; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Armor; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Equipment; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Weapon; import com.wandrell.tabletop.business.model.punkapocalyptic.ruleset.SpecialRule; import com.wandrell.tabletop.business.model.valuehandler.ModularDerivedValueHandler; import com.wandrell.tabletop.business.model.valuehandler.ValueHandler; import com.wandrell.tabletop.business.util.tag.punkapocalyptic.UnitAware; public final class MutantUnitWrapper implements MutantUnit { private final EventListenerList listeners = new EventListenerList(); private final Collection<Mutation> mutations = new LinkedHashSet<>(); private final Unit unit; public MutantUnitWrapper(final MutantUnitWrapper unit) { super(); checkNotNull(unit, "Received a null pointer as unit"); this.unit = unit.unit.createNewInstance(); this.unit.addValorationListener(new ValorationListener() { @Override public final void valorationChanged(final EventObject e) { fireValorationChangedEvent(new EventObject(this)); } }); ((UnitAware) ((ModularDerivedValueHandler) this.unit.getValoration()) .getStore()).setUnit(this); } public MutantUnitWrapper(final Unit unit) { super(); checkNotNull(unit, "Received a null pointer as unit"); this.unit = unit; this.unit.addValorationListener(new ValorationListener() { @Override public final void valorationChanged(final EventObject e) { fireValorationChangedEvent(new EventObject(this)); } }); ((UnitAware) ((ModularDerivedValueHandler) this.unit.getValoration()) .getStore()).setUnit(this); } @Override public final void addEquipment(final Equipment equipment) { getWrappedUnit().addEquipment(equipment); } @Override public final void addMutation(final Mutation mutation) { getMutationsModifiable().add(mutation); fireValorationChangedEvent(new EventObject(this)); } @Override public final void addValorationListener(final ValorationListener listener) { getWrappedUnit().addValorationListener(listener); getListeners().add(ValorationListener.class, listener); } @Override public final void addWeapon(final Weapon weapon) { getWrappedUnit().addWeapon(weapon); } @Override public final void clearEquipment() { getWrappedUnit().clearEquipment(); } @Override public final void clearMutations() { getMutationsModifiable().clear(); } @Override public final void clearWeapons() { getWrappedUnit().clearWeapons(); } @Override public final MutantUnitWrapper createNewInstance() { return new MutantUnitWrapper(this); } @Override public final Integer getActions() { return getWrappedUnit().getActions(); } @Override public final Integer getAgility() { return getWrappedUnit().getAgility(); } @Override public final Armor getArmor() { return getWrappedUnit().getArmor(); } @Override public final Integer getBaseCost() { return getWrappedUnit().getBaseCost(); } @Override public final Integer getCombat() { return getWrappedUnit().getCombat(); } @Override public final Collection<Equipment> getEquipment() { return getWrappedUnit().getEquipment(); } @Override public final Collection<Mutation> getMutations() { return Collections.unmodifiableCollection(getMutationsModifiable()); } @Override public final Integer getPrecision() { return getWrappedUnit().getPrecision(); } @Override public final Collection<SpecialRule> getSpecialRules() { return getWrappedUnit().getSpecialRules(); } @Override public final Integer getStrength() { return getWrappedUnit().getStrength(); } @Override public final Integer getTech() { return getWrappedUnit().getTech(); } @Override public final Integer getToughness() { return getWrappedUnit().getToughness(); } @Override public final String getUnitName() { return getWrappedUnit().getUnitName(); } @Override public final ValueHandler getValoration() { return getWrappedUnit().getValoration(); } @Override public final Collection<Weapon> getWeapons() { return getWrappedUnit().getWeapons(); } @Override public final void removeEquipment(final Equipment equipment) { getWrappedUnit().removeEquipment(equipment); } @Override public final void removeMutation(final Mutation mutation) { getMutationsModifiable().remove(mutation); fireValorationChangedEvent(new EventObject(this)); } @Override public final void removeValorationListener(final ValorationListener listener) { getWrappedUnit().removeValorationListener(listener); getListeners().remove(ValorationListener.class, listener); } @Override public final void removeWeapon(final Weapon weapon) { getWrappedUnit().removeWeapon(weapon); } @Override public final void setArmor(final Armor armor) { getWrappedUnit().setArmor(armor); } private final void fireValorationChangedEvent(final EventObject evt) { final ValorationListener[] listnrs; listnrs = getListeners().getListeners(ValorationListener.class); for (final ValorationListener l : listnrs) { l.valorationChanged(evt); } } private final EventListenerList getListeners() { return listeners; } private final Collection<Mutation> getMutationsModifiable() { return mutations; } private final Unit getWrappedUnit() { return unit; } }
package com.worldcretornica.plotme_abstractgenerator.bukkit; import com.worldcretornica.configuration.ConfigAccessor; import com.worldcretornica.configuration.ConfigurationSection; import com.worldcretornica.configuration.file.FileConfiguration; import com.worldcretornica.plotme_abstractgenerator.AbstractGenerator; import com.worldcretornica.plotme_core.AbstractSchematicUtil; import com.worldcretornica.plotme_core.bukkit.PlotMe_CorePlugin; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.mcstats.Metrics; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; public abstract class BukkitAbstractGenerator extends JavaPlugin implements AbstractGenerator { private final Map<String, ConfigurationSection> worldConfigs = new HashMap<>(); private final File configFolder = new File(new File("plugins", "PlotMe"), getName()); public ConfigurationSection mainWorldsSection; public PlotMe_CorePlugin plotMePlugin = null; private ConfigAccessor configCA; private AbstractSchematicUtil schematicutil; @Override public final void onEnable() { setupConfigFolders(); setupConfig(); PluginManager pm = Bukkit.getPluginManager(); plotMePlugin = (PlotMe_CorePlugin) pm.getPlugin("PlotMe"); if (plotMePlugin != null) { initialize(plotMePlugin); } setupMetrics(); } public AbstractSchematicUtil getSchematicUtil() { return this.schematicutil; } protected void setSchematicUtil(AbstractSchematicUtil schematicutil) { this.schematicutil = schematicutil; } /** * Called when this plugin is enabled. * @param plotMePlugin PlotMe-Core */ public abstract void initialize(PlotMe_CorePlugin plotMePlugin); @Override public final void onDisable() { } private void setupConfigFolders() { //noinspection ResultOfMethodCallIgnored configFolder.mkdirs(); } @Override public File getPluginFolder() { return configFolder; } @Override public void reloadConfig() { configCA.reloadFile(); } /** * Gets a {@link FileConfiguration} for this plugin, read through * "config.yml" * <p/> * If there is a default config.yml embedded in this plugin, it will be * provided as a default for this Configuration. * * @return Plugin configuration */ public FileConfiguration getConfiguration() { return configCA.getConfig(); } /** * Saves the {@link FileConfiguration} retrievable by {@link #getConfiguration()}. */ public void saveConfigFile() { configCA.saveConfig(); } /** * Discards any data in {@link #getConfiguration()} and reloads from disk. */ private void setupConfig() { // Set the config accessor for the main config.yml configCA = new ConfigAccessor(getPluginFolder(), "config.yml"); if (getConfiguration().contains("worlds")) { mainWorldsSection = getConfiguration().getConfigurationSection("worlds"); } else { mainWorldsSection = getConfiguration().createSection("worlds"); } configCA.saveConfig(); } private void setupMetrics() { try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException ignored) { } } public ConfigurationSection putWGC(String world, ConfigurationSection worldGenConfig) { return worldConfigs.put(world.toLowerCase(), worldGenConfig); } public ConfigurationSection getWGC(String world) { return worldConfigs.get(world.toLowerCase()); } }
package fi.csc.microarray.client.visualisation.methods.gbrowser.track; import java.awt.Color; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import fi.csc.microarray.client.visualisation.methods.gbrowser.DataSource; import fi.csc.microarray.client.visualisation.methods.gbrowser.View; import fi.csc.microarray.client.visualisation.methods.gbrowser.dataFetcher.AreaRequestHandler; import fi.csc.microarray.client.visualisation.methods.gbrowser.drawable.Drawable; import fi.csc.microarray.client.visualisation.methods.gbrowser.drawable.RectDrawable; import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.ColumnType; import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.FileParser; import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.Strand; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.AreaResult; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.BpCoord; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.RegionContent; public class SeqBlockTrack extends Track { private static final int MAX_STACKING_DEPTH = 10; public static final String DUMMY_SEQUENCE = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; private static final int SPACE_BETWEEN_READS = 2; private static final Color[] charColors = new Color[] { new Color(64, 192, 64, 128), new Color(64, 64, 192, 128), new Color(128, 128, 128, 128), new Color(192, 64, 64, 128) }; private Collection<RegionContent> reads = new TreeSet<RegionContent>(); private List<Integer> occupiedSpace = new ArrayList<Integer>(); private long maxBpLength; private long minBpLength; private Color fontColor; private boolean wasLastConsised = true; public SeqBlockTrack(View view, DataSource file, Class<? extends AreaRequestHandler> handler, FileParser inputParser, Color fontColor, long minBpLength, long maxBpLength) { super(view, file, handler, inputParser); this.minBpLength = minBpLength; this.maxBpLength = maxBpLength; this.fontColor = fontColor; } @Override public Collection<Drawable> getDrawables() { Collection<Drawable> drawables = getEmptyDrawCollection(); occupiedSpace.clear(); // iterate over RegionContent objects (one object corresponds to one read) if (reads != null) { Iterator<RegionContent> iter = reads.iterator(); while (iter.hasNext()) { RegionContent read = iter.next(); // remove those that are not in this view if (!read.region.intercepts(getView().getBpRegion())) { iter.remove(); continue; } // collect relevant data for this read Color blockColor = Color.gray; int height = 2; // (int) (getView().getTrackHeight() / 2 * limited / 255f); BpCoord startBp = read.region.start; BpCoord endBp = read.region.end; String seq = ((String) read.values.get(ColumnType.SEQUENCE)); if (seq != null) { // we have sequence seq = seq.trim(); } else { // we don't have a sequence, generate something int seqLength = (int) (endBp.minus(startBp) + 1); if (seqLength > 128) { // TODO what happened? seqLength = 0; } seq = DUMMY_SEQUENCE.substring(0, seqLength); } // create rectangle covering the correct screen area (x-axis) Rectangle rect = new Rectangle(); rect.x = getView().bpToTrack(startBp); rect.width = getView().bpToTrack(endBp) - rect.x; // reads are drawn in order and placed in layers int layer = 0; while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) { layer++; } // read reserves the space of the layer from end to left corner of the screen int end = rect.x + rect.width; if (occupiedSpace.size() > layer) { occupiedSpace.set(layer, end); } else { occupiedSpace.add(end); } // check maximum stacking depth if (layer > MAX_STACKING_DEPTH) { continue; } // now we can decide the y-axis rect.y = (int) (getView().getTrackHeight() - ((layer + 1) * (height + SPACE_BETWEEN_READS))); rect.height = height; // reverse the read if on reverse strand if ((Strand) read.values.get(ColumnType.STRAND) == Strand.REVERSED) { StringBuffer buf = new StringBuffer(seq).reverse(); seq = buf.toString(); } if (rect.width < seq.length()) { Color color = blockColor; // mark last line that will be drawn if (layer == MAX_STACKING_DEPTH) { color = color.darker(); } // no space to draw actual sequence drawables.add(new RectDrawable(rect, color, null)); } else { // enough space to show the actual sequence // draw arrow if (read.values.get(ColumnType.STRAND) == Strand.REVERSED) { drawables.addAll(getArrowDrawables(rect.x, rect.y, -rect.height, rect.height)); } else { drawables.addAll(getArrowDrawables(rect.x + rect.width, rect.y, rect.height, rect.height)); } // prepare to draw single nucleotides float x = rect.x; float increment = (rect.width) / ((float) seq.length()); // draw something for each nucleotide for (int j = 0; j < seq.length(); j++) { char letter = seq.charAt(j); // if (rect.width > seq.length() * CHAR_WIDTH) { // drawables.add(new TextDrawable((int) x + 1, rect.y + // 10, "" + letter, fontColor)); // // drawables.add(new TextDrawable((int)x, rect.y - 8, // // "" + letter, Color.black)); Color bg = Color.white; if (letter == 'A') { bg = charColors[0]; } else if (letter == 'C') { bg = charColors[1]; } else if (letter == 'G') { bg = charColors[2]; } else if (letter == 'T') { bg = charColors[3]; } // mark last line that will be drawn if (layer == MAX_STACKING_DEPTH) { bg = bg.darker(); } drawables.add(new RectDrawable((int) x + 1, rect.y, (int) increment, height, bg, null)); x += increment; } } } } return drawables; } public void processAreaResult(AreaResult<RegionContent> areaResult) { // check that areaResult has same concised status (currently always false) // and correct strand if (areaResult.status.concise == isConcised() && areaResult.content.values.get(ColumnType.STRAND) == getStrand()) { // add this to queue of RegionContents to be processed this.reads.add(areaResult.content); getView().redraw(); } } @Override public void updateData() { if (wasLastConsised != isConcised()) { reads.clear(); wasLastConsised = isConcised(); } super.updateData(); } @Override public int getMaxHeight() { // the track is hidden if outside given bp length boundaries if (getView().getBpRegion().getLength() > minBpLength && getView().getBpRegion().getLength() <= maxBpLength) { return super.getMaxHeight(); } else { return 0; } } @Override public Collection<ColumnType> getDefaultContents() { return Arrays.asList(new ColumnType[] { ColumnType.SEQUENCE, ColumnType.STRAND, ColumnType.QUALITY }); } @Override public boolean isConcised() { return false; } }
package org.roklib.webapps.uridispatching.mapper; import org.roklib.webapps.uridispatching.URIActionCommand; import org.roklib.webapps.uridispatching.helper.Preconditions; import org.roklib.webapps.uridispatching.parameter.URIParameter; import org.roklib.webapps.uridispatching.parameter.value.CapturedParameterValues; import org.roklib.webapps.uridispatching.parameter.value.CapturedParameterValuesImpl; import org.roklib.webapps.uridispatching.parameter.value.ParameterValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.*; public abstract class AbstractURIPathSegmentActionMapper implements URIPathSegmentActionMapper { private static final long serialVersionUID = 8450975393827044559L; private static final Logger LOG = LoggerFactory.getLogger(AbstractURIPathSegmentActionMapper.class); private Map<String, URIParameter<?>> registeredUriParameters; private Set<String> registeredUriParameterNames; private List<String> actionArgumentOrder; private Map<String, List<Serializable>> actionArgumentMap; protected AbstractURIPathSegmentActionMapper parentMapper; private Class<? extends URIActionCommand> actionCommand; /** * The name of the URI portion for which this action mapper is responsible. */ protected String mapperName; private String actionURI; public AbstractURIPathSegmentActionMapper(String mapperName) { Preconditions.checkNotNull(mapperName); this.mapperName = mapperName; actionURI = mapperName; } public String getMapperName() { return mapperName; } public void setActionCommandClass(Class<? extends URIActionCommand> command) { actionCommand = command; } public Class<? extends URIActionCommand> getActionCommand() { return actionCommand; } public void registerURIParameter(URIParameter<?> parameter) { Preconditions.checkNotNull(parameter); if (registeredUriParameters == null) { registeredUriParameters = new LinkedHashMap<>(); registeredUriParameterNames = new HashSet<>(); } if (registeredUriParameters.containsKey(parameter.getId())) { throw new IllegalArgumentException("Another parameter with the same id is already registered on this mapper."); } parameter.getParameterNames() .stream() .forEach(parameterName -> { if (registeredUriParameterNames.contains(parameterName)) { throw new IllegalArgumentException("Cannot register parameter " + parameter + ". Another parameter with parameter name '" + parameterName + "' is already registered on this mapper."); } registeredUriParameters.put(parameter.getId(), parameter); registeredUriParameterNames.add(parameterName); }); } protected Map<String, URIParameter<?>> getUriParameters() { return registeredUriParameters == null ? Collections.emptyMap() : registeredUriParameters; } protected Set<String> getUriParameterNames() { return registeredUriParameterNames == null ? Collections.emptySet() : registeredUriParameterNames; } public final Class<? extends URIActionCommand> interpretTokens(CapturedParameterValuesImpl capturedParameterValues, List<String> uriTokens, Map<String, List<String>> queryParameters, ParameterMode parameterMode) { if (! getUriParameters().isEmpty()) { ParameterInterpreter interpreter = new ParameterInterpreter(mapperName); if (parameterMode == ParameterMode.QUERY) { interpreter.interpretQueryParameters(getUriParameters(), capturedParameterValues, queryParameters); } else { if (parameterMode == ParameterMode.DIRECTORY_WITH_NAMES) { interpreter.interpretDirectoryParameters(getUriParameterNames(), getUriParameters(), capturedParameterValues, uriTokens); } else if (parameterMode == ParameterMode.DIRECTORY) { interpreter.interpretNamelessDirectoryParameters(getUriParameters(), capturedParameterValues, uriTokens); } } } return interpretTokensImpl(capturedParameterValues, uriTokens, queryParameters, parameterMode); } protected abstract Class<? extends URIActionCommand> interpretTokensImpl(CapturedParameterValuesImpl capturedParameterValues, List<String> uriTokens, Map<String, List<String>> parameters, ParameterMode parameterMode); protected boolean isResponsibleForToken(String uriToken) { return mapperName.equals(uriToken); } protected String urlEncode(String term) { try { return URLEncoder.encode(term, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 encoding not supported on this platform"); } } /** * Returns the full relative action URI for this action mapper. This is the concatenation of all parent mapper * action names going back to the mapper root separated by a slash. For example, if this action mapper's action name * is <code>languageSettings</code>, with its parent's action name <code>configuration</code> and the next parent's * action name <code>admin</code> then the action URI for this mapper evaluates to * <p/> * <pre> * /admin/configuration/languageSettings. * </pre> * <p/> * This String is needed for generating fully configured URIs (this URI together with the corresponding parameter * values) which can be used for rendering links pointing to this action mapper. * * @return the action URI for this action mapper (such as <code>/admin/configuration/languageSettings</code> if this * action mapper's action name is <code>languageSettings</code>). */ public String getActionURI() { return actionURI; } /** * Sets the parent action mapper for this object. An action mapper can only be added as sub-mapper to one action * mapper. In other words, an action mapper can only have one parent. * * @param parent * the parent mapper for this action mapper */ public final void setParent(AbstractURIPathSegmentActionMapper parent) { parentMapper = parent; } public URI getParameterizedHashbangActionURI(boolean clearParametersAfterwards) { return getParameterizedHashbangActionURI(clearParametersAfterwards, ParameterMode.DIRECTORY_WITH_NAMES); } public URI getParameterizedHashbangActionURI(boolean clearParametersAfterwards, ParameterMode parameterMode) { return getParameterizedActionURI(clearParametersAfterwards, parameterMode, true, true); } public URI getParameterizedActionURI(boolean clearParametersAfterwards) { return getParameterizedActionURI(clearParametersAfterwards, ParameterMode.QUERY); } public URI getParameterizedActionURI(boolean clearParametersAfterwards, ParameterMode parameterMode) { return getParameterizedActionURI(clearParametersAfterwards, parameterMode, false); } public URI getParameterizedActionURI(boolean clearParametersAfterwards, ParameterMode parameterMode, boolean addHashMark) { return getParameterizedActionURI(clearParametersAfterwards, parameterMode, addHashMark, false); } private URI getParameterizedActionURI(boolean clearParametersAfterwards, ParameterMode parameterMode, boolean addHashMark, boolean addExclamationMark) { StringBuilder buf = new StringBuilder(); if (addHashMark) { buf.append(' if (addExclamationMark) { buf.append('!'); } buf.append(getActionURI().substring(1)); } else { buf.append(getActionURI()); } boolean removeLastCharacter = false; if (actionArgumentMap != null && ! actionArgumentMap.isEmpty()) { if (parameterMode == ParameterMode.QUERY) { buf.append('?'); for (String argument : actionArgumentOrder) { for (Serializable value : actionArgumentMap.get(argument)) { buf.append(urlEncode(argument)).append('=').append(urlEncode(value.toString())); buf.append('&'); removeLastCharacter = true; } } } else { buf.append('/'); for (String argument : actionArgumentOrder) { for (Serializable value : actionArgumentMap.get(argument)) { if (parameterMode == ParameterMode.DIRECTORY_WITH_NAMES) { buf.append(urlEncode(argument)).append('/'); } buf.append(urlEncode(value.toString())); buf.append('/'); removeLastCharacter = true; } } } } if (removeLastCharacter) { buf.setLength(buf.length() - 1); } try { return new URI(buf.toString()); } catch (URISyntaxException e) { throw new RuntimeException("Unable to create URL object.", e); } finally { if (clearParametersAfterwards) { clearActionArguments(); } } } /** * <code>null</code> argument values are ignored. */ public void addActionArgument(String argumentName, Serializable... argumentValues) { Preconditions.checkNotNull(argumentName); if (actionArgumentMap == null) { actionArgumentMap = new HashMap<>(4); actionArgumentOrder = new LinkedList<>(); } List<Serializable> valueList = actionArgumentMap.get(argumentName); if (valueList == null) { valueList = new LinkedList<>(); actionArgumentMap.put(argumentName, valueList); } for (Serializable value : argumentValues) { if (value != null) { valueList.add(value); } } if (valueList.isEmpty()) { actionArgumentMap.remove(argumentName); } else if (! actionArgumentOrder.contains(argumentName)) { actionArgumentOrder.add(argumentName); } } public void clearActionArguments() { if (actionArgumentMap != null) { actionArgumentMap.clear(); actionArgumentOrder.clear(); } } public void getActionURIOverview(List<String> targetList) { StringBuilder buf = new StringBuilder(); buf.append(getActionURI()); StringJoiner joiner = new StringJoiner(", ", " ? ", ""); getUriParameters().values().stream().forEach(uriParameter -> joiner.add(uriParameter.toString())); buf.append(joiner.toString()); if (buf.length() > 0) { targetList.add(buf.toString()); } for (AbstractURIPathSegmentActionMapper subMapper : getSubMapperMap().values()) { subMapper.getActionURIOverview(targetList); } } /** * Returns a map of all registered sub-mappers for this URI action mapper. This method is only implemented by {@link * DispatchingURIPathSegmentActionMapper} since this is the only URI action mapper implementation in the framework * which can have sub-mappers. All other subclasses of {@link AbstractURIPathSegmentActionMapper} return an empty * map. * * @return map containing a mapping of URI tokens on the corresponding sub-mappers that handle these tokens. */ // TODO: make protected, adapt tests accordingly public Map<String, AbstractURIPathSegmentActionMapper> getSubMapperMap() { return Collections.emptyMap(); } public boolean hasSubMappers() { return ! getSubMapperMap().isEmpty(); } protected void setSubMappersActionURI(AbstractURIPathSegmentActionMapper subMapper) { subMapper.setActionURI(String.format("%s%s%s", getActionURI(), "/", urlEncode(subMapper.mapperName))); if (subMapper.hasSubMappers()) { subMapper.updateActionURIs(); } } protected void updateActionURIs() { setActionURI(parentMapper.getActionURI() + "/" + mapperName); getSubMapperMap().values().forEach(this::setSubMappersActionURI); } protected void setActionURI(String actionURI) { this.actionURI = actionURI; } @Override public String toString() { return String.format("[%s='%s']", getClass().getSimpleName(), mapperName); } public static class ParameterInterpreter implements Serializable { private String mapperName; public ParameterInterpreter(String mapperName) { this.mapperName = mapperName; } public CapturedParameterValues interpretDirectoryParameters(Set<String> registeredUriParameterNames, Map<String, URIParameter<?>> registeredUriParameters, CapturedParameterValuesImpl consumedValues, List<String> uriTokens) { Map<String, List<String>> directoryBasedParameterMap = new HashMap<>(4); for (Iterator<String> it = uriTokens.iterator(); it.hasNext(); ) { String parameterName = it.next(); if (registeredUriParameterNames.contains(parameterName)) { it.remove(); if (it.hasNext()) { List<String> values = directoryBasedParameterMap.computeIfAbsent(parameterName, k -> new LinkedList<>()); values.add(it.next()); it.remove(); } } else { break; } } return interpretQueryParameters(registeredUriParameters, consumedValues, directoryBasedParameterMap); } public CapturedParameterValues interpretNamelessDirectoryParameters(Map<String, URIParameter<?>> registeredUriParameters, CapturedParameterValuesImpl consumedValues, List<String> uriTokens) { Map<String, List<String>> directoryBasedParameterMap = new HashMap<>(4); outerLoop: for (URIParameter<?> parameter : registeredUriParameters.values()) { for (String parameterName : parameter.getParameterNames()) { directoryBasedParameterMap.put(parameterName, Collections.singletonList(uriTokens.remove(0))); if (uriTokens.isEmpty()) { break outerLoop; } } } return interpretQueryParameters(registeredUriParameters, consumedValues, directoryBasedParameterMap); } public CapturedParameterValues interpretQueryParameters(Map<String, URIParameter<?>> registeredUriParameters, CapturedParameterValuesImpl capturedParameterValues, Map<String, List<String>> queryParameters) { registeredUriParameters .values() .stream() .forEach(parameter -> { final ParameterValue<?> consumedParameterValue = parameter.consumeParameters(queryParameters); if (consumedParameterValue != null) { parameter.getParameterNames().stream().forEach(queryParameters::remove); } capturedParameterValues.setValueFor(mapperName, parameter, consumedParameterValue); }); return capturedParameterValues; } } }
package com.dumbster.smtp; import com.dumbster.smtp.SmtpServer; import com.dumbster.smtp.action.*; import org.junit.*; import java.util.Iterator; import com.dumbster.smtp.MailMessage; import com.dumbster.smtp.mailstores.EMLMailStore; import com.dumbster.smtp.mailstores.RollingMailStore; import com.dumbster.smtp.Response; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; import java.util.Date; import java.io.IOException; import static org.junit.Assert.*; public class NewTestCasesTest { private static final int SMTP_PORT = 1081; private final String SERVER = "localhost"; private final String FROM = "sender@here.com"; private final String TO = "baker32@illinois.edu"; private final String SUBJECT = "Test Dumbster"; private final String BODY = "Test Body"; private final int WAIT_TICKS = 10000; private MailMessage message; private ServerOptions options; private MailStore mailStore; private MailStore mailStore2; private SmtpServer server; @Before public void setup() { this.message = new MailMessageImpl(); mailStore = new RollingMailStore(); } /* Message Formatting Utests */ @Test public void testMaxHeaders() { message.addHeader("header1", "value1"); message.addHeader("header2", "value2"); message.addHeader("header3", "value3"); message.addHeader("header4", "value4"); message.addHeader("header5", "value5"); message.addHeader("header6", "value6"); message.addHeader("header7", "value7"); message.addHeader("header8", "value8"); message.addHeader("header9", "value9"); message.addHeader("header10", "value10"); Iterator<String> it = message.getHeaderNames(); int i = 0; while(it.hasNext()) { i++; it.next(); } assertEquals(10, i); } @Test public void testMaxHeadersPlus1() { message.addHeader("header1", "value1"); message.addHeader("header2", "value2"); message.addHeader("header3", "value3"); message.addHeader("header4", "value4"); message.addHeader("header5", "value5"); message.addHeader("header6", "value6"); message.addHeader("header7", "value7"); message.addHeader("header8", "value8"); message.addHeader("header9", "value9"); message.addHeader("header10", "value10"); message.addHeader("header11", "value11"); Iterator<String> it = message.getHeaderNames(); int i = 0; while(it.hasNext()) { i++; it.next(); } assertEquals(11, i); } @Test public void testAppendBadHeader() { message.addHeader("foo", "bar"); message.addHeader("tim", "tam"); message.addHeader("zing", "zang"); message.appendHeader("tim", " tum"); assertEquals("tam tum", message.getFirstHeaderValue("tim")); } /* Server Options Utests */ @Test public void testNegativePort() { String[] args = new String[]{"-1"}; options = new ServerOptions(args); assertEquals(-1, options.port); assertEquals(true, options.threaded); assertEquals(true, options.valid); assertEquals(RollingMailStore.class, options.mailStore.getClass()); } /* Request Utests*/ @Test public void testDataBodyState() { Request request = Request.createRequest(SmtpState.DATA_BODY, "."); assertEquals(".", request.getClientAction().toString()); } @Test public void testDataFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "DATA"); assertEquals("DATA", request.getClientAction().toString()); } @Test public void testQuitFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "QUIT"); assertEquals("QUIT", request.getClientAction().toString()); } @Test public void testHeloInvalidMessage() { Request request = Request.createRequest(null, "HELO"); assertEquals("EHLO", request.getClientAction().toString()); } // This test increases branch coverage @Test public void testListFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "LIST"); assertEquals("LIST", request.getClientAction().toString()); } /* Action Tests */ // This test increases branch coverage @Test public void testListIndexNegative() { List l = new List("-1"); //This Test passes if there is no exception //messageIndex is private, no public method to check its value } //These two tests increase coverage @Test public void testResponseInvalidIndex() { List l = new List("-1"); Response r = l.response(null, mailStore, null); assertEquals("There are 0 message(s).", r.getMessage()); } @Test public void testResponseValidNoMessages() { List l = new List("0"); Response r = l.response(null, mailStore, null); assertEquals("There are 0 message(s).", r.getMessage()); } /* SMTP Server Tests */ //This test increases coverage @Test public void getMessageTest() { MailMessage[] mm = new MailMessage[10]; ServerOptions options = new ServerOptions(); options.port = SMTP_PORT; server = SmtpServerFactory.startServer(options); server.getMessages(); assertEquals(0, server.getEmailCount()); server.stop(); } /* Advanced Test Cases */ @Test public void testUniqueMessagesWithClear() { ServerOptions options = new ServerOptions(); options.port = SMTP_PORT; server = SmtpServerFactory.startServer(options); // Message 1 sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO); server.anticipateMessageCountFor(1, WAIT_TICKS); assertTrue(server.getEmailCount() == 1); MailMessage mm = server.getMessage(0); assertEquals("Test Dumbster", mm.getFirstHeaderValue("Subject")); // Message 2 sendMessage(SMTP_PORT, FROM, SUBJECT, "HELLO!", TO); server.anticipateMessageCountFor(1, WAIT_TICKS); assertTrue(server.getEmailCount() == 2); mm = server.getMessage(1); assertEquals("HELLO!", mm.getBody()); // Messages 3-10 int i; for (i = 3; i <= 10; i++) { sendMessage(SMTP_PORT, FROM, null, Integer.toString(i), TO); assertTrue(server.getEmailCount() == i); } server.clearMessages(); sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO); assertTrue(server.getEmailCount() == 1); server.stop(); } @Test public void testUniqueMessagesMultipleMailStores() { ServerOptions options = new ServerOptions(); options.port = SMTP_PORT; server = SmtpServerFactory.startServer(options); mailStore2 = new RollingMailStore(); // First rolling Mail Store Message MailMessage fm = new MailMessageImpl(); mailStore2.addMessage(fm); // Messages 1-10 int i; for (i = 1; i <= 10; i++) { sendMessage(SMTP_PORT, FROM, null, Integer.toString(i), TO); addAMessage(); assertTrue(server.getEmailCount() == i); } server.clearMessages(); sendMessage(SMTP_PORT, FROM, SUBJECT, BODY, TO); assertTrue(server.getEmailCount() == 1); server.stop(); } /* Final Report Tests */ /* Increase Method Coverage */ @Test public void startServerNoInputs() { server = SmtpServerFactory.startServer(); server.getMessages(); assertEquals(0, server.getEmailCount()); server.stop(); } @Test public void startServerThrowException() { ServerOptions options = new ServerOptions(); options.port = SMTP_PORT; server = SmtpServerFactory.startServer(options); try { throw new IOException(); } } /* Helpers */ private Properties getMailProperties(int port) { Properties mailProps = new Properties(); mailProps.setProperty("mail.smtp.host", "localhost"); mailProps.setProperty("mail.smtp.port", "" + port); mailProps.setProperty("mail.smtp.sendpartial", "true"); return mailProps; } private void sendMessage(int port, String from, String subject, String body, String to) { try { Properties mailProps = getMailProperties(port); Session session = Session.getInstance(mailProps, null); MimeMessage msg = createMessage(session, from, to, subject, body); Transport.send(msg); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception: " + e); } } private MimeMessage createMessage(Session session, String from, String to, String subject, String body) throws MessagingException { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(body); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); return msg; } private void addAMessage() { MailMessage message = new MailMessageImpl(); mailStore2.addMessage(message); } }
package org.pentaho.platform.dataaccess.datasource.wizard.service.impl; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.database.IDatabaseDialect; import org.pentaho.database.dialect.DB2DatabaseDialect; import org.pentaho.database.dialect.GenericDatabaseDialect; import org.pentaho.database.dialect.H2DatabaseDialect; import org.pentaho.database.dialect.Hive2DatabaseDialect; import org.pentaho.database.dialect.HiveDatabaseDialect; import org.pentaho.database.dialect.HypersonicDatabaseDialect; import org.pentaho.database.dialect.ImpalaDatabaseDialect; import org.pentaho.database.dialect.MSSQLServerDatabaseDialect; import org.pentaho.database.dialect.MSSQLServerNativeDatabaseDialect; import org.pentaho.database.dialect.MonetDatabaseDialect; import org.pentaho.database.dialect.MySQLDatabaseDialect; import org.pentaho.database.dialect.OracleDatabaseDialect; import org.pentaho.database.dialect.PostgreSQLDatabaseDialect; import org.pentaho.database.dialect.Vertica5DatabaseDialect; import org.pentaho.database.dialect.VerticaDatabaseDialect; import org.pentaho.database.model.DatabaseType; import org.pentaho.database.model.IDatabaseConnection; import org.pentaho.database.model.IDatabaseType; import org.pentaho.ui.database.event.DefaultDatabaseDialectList; import org.pentaho.ui.database.event.DefaultDatabaseTypesList; import org.pentaho.ui.database.event.IDatabaseDialectList; import org.pentaho.ui.database.event.IDatabaseTypesList; @Path( "/data-access/api/dialect" ) public class DatabaseDialectService { private static final Log logger = LogFactory.getLog( DatabaseDialectService.class ); List<IDatabaseDialect> databaseDialects = new ArrayList<IDatabaseDialect>(); List<IDatabaseType> databaseTypes = new ArrayList<IDatabaseType>(); Map<IDatabaseType, IDatabaseDialect> typeToDialectMap = new HashMap<IDatabaseType, IDatabaseDialect>(); GenericDatabaseDialect genericDialect = new GenericDatabaseDialect(); public DatabaseDialectService() { this( true ); } public DatabaseDialectService( boolean validateClasses ) { // temporary until we have a better approach registerDatabaseDialect( new OracleDatabaseDialect(), validateClasses ); registerDatabaseDialect( new MySQLDatabaseDialect(), validateClasses ); registerDatabaseDialect( new HiveDatabaseDialect(), validateClasses ); registerDatabaseDialect( new Hive2DatabaseDialect(), validateClasses ); registerDatabaseDialect( new HypersonicDatabaseDialect(), validateClasses ); registerDatabaseDialect( new ImpalaDatabaseDialect(), validateClasses ); registerDatabaseDialect( new MSSQLServerDatabaseDialect(), validateClasses ); registerDatabaseDialect( new MSSQLServerNativeDatabaseDialect(), validateClasses ); registerDatabaseDialect( new DB2DatabaseDialect(), validateClasses ); registerDatabaseDialect( new PostgreSQLDatabaseDialect(), validateClasses ); registerDatabaseDialect( new H2DatabaseDialect(), validateClasses ); registerDatabaseDialect( new MonetDatabaseDialect(), validateClasses ); registerDatabaseDialect( new VerticaDatabaseDialect(), validateClasses ); registerDatabaseDialect( new Vertica5DatabaseDialect(), validateClasses ); // the generic service is special, because it plays a role // in generation from a URL and Driver registerDatabaseDialect( genericDialect, validateClasses ); } @POST @Path( "/registerDatabaseDialect" ) @Consumes( { APPLICATION_JSON } ) public Response registerDatabaseDialect( IDatabaseDialect databaseDialect ) { return registerDatabaseDialect( databaseDialect, true ); } /** * * @param databaseDialect * @param validateClassExists */ @POST @Path( "/registerDatabaseDialectWithValidation/{validateClassExists}" ) @Consumes( { APPLICATION_JSON } ) public Response registerDatabaseDialect( IDatabaseDialect databaseDialect, @PathParam( "validateClassExists" ) Boolean validateClassExists ) { try { if ( !validateClassExists || validateJdbcDriverClassExists( databaseDialect.getNativeDriver() ) ) { databaseTypes.add( databaseDialect.getDatabaseType() ); typeToDialectMap.put( databaseDialect.getDatabaseType(), databaseDialect ); databaseDialects.add( databaseDialect ); } } catch ( Throwable e ) { Response.serverError().entity( e ).build(); } return Response.ok().build(); } /** * Attempt to load the JDBC Driver class. If it's not available, return false. * * @param classname * validate that this classname exists in the classpath * * @return true if the class exists */ @POST @Path( "/validateJdbcDriverClassExists" ) @Consumes( { APPLICATION_JSON } ) @Produces( { APPLICATION_JSON } ) public Boolean validateJdbcDriverClassExists( String classname ) { // no need to test if the class exists if it is null if ( classname == null ) { return true; } try { Class.forName( classname ); return true; } catch ( NoClassDefFoundError e ) { if ( logger.isDebugEnabled() ) { logger.debug( "classExists returning false", e ); } } catch ( ClassNotFoundException e ) { if ( logger.isDebugEnabled() ) { logger.debug( "classExists returning false", e ); } } catch ( Exception e ) { if ( logger.isDebugEnabled() ) { logger.debug( "classExists returning false", e ); } } // if we've made it here, an exception has occurred. return false; } @GET @Path( "/getDatabaseTypes" ) @Produces( { APPLICATION_JSON } ) public IDatabaseTypesList getDatabaseTypes() { DefaultDatabaseTypesList value = new DefaultDatabaseTypesList(); value.setDbTypes( databaseTypes ); return value; } @POST @Path( "/getDialectByType" ) @Consumes( { APPLICATION_JSON } ) @Produces( { APPLICATION_JSON } ) public IDatabaseDialect getDialect( DatabaseType databaseType ) { return typeToDialectMap.get( databaseType ); } @POST @Path( "/getDialectByConnection" ) @Consumes( { APPLICATION_JSON } ) @Produces( { APPLICATION_JSON } ) public IDatabaseDialect getDialect( IDatabaseConnection connection ) { return typeToDialectMap.get( connection.getDatabaseType() ); } @GET @Path( "/getDatabaseDialects" ) @Produces( { APPLICATION_JSON } ) public IDatabaseDialectList getDatabaseDialects() { IDatabaseDialectList value = new DefaultDatabaseDialectList(); value.setDialects( databaseDialects ); return value; } }
package com.inductiveautomation.opcua.stack.core.types.builtin; import javax.annotation.Nullable; import com.inductiveautomation.opcua.stack.core.types.enumerated.TimestampsToReturn; public class DataValue { private final Variant value; private final StatusCode status; private final DateTime sourceTime; private final DateTime serverTime; public DataValue(long statusCode) { this(new StatusCode(statusCode)); } public DataValue(StatusCode statusCode) { this(Variant.NullValue, statusCode, DateTime.MinValue); } public DataValue(Variant value) { this(value, StatusCode.Good); } public DataValue(Variant value, StatusCode status) { this(value, status, DateTime.now()); } public DataValue(Variant value, StatusCode status, @Nullable DateTime time) { this(value, status, time, time); } public DataValue(Variant value, StatusCode status, @Nullable DateTime sourceTime, @Nullable DateTime serverTime) { this.value = value; this.status = status; this.sourceTime = sourceTime; this.serverTime = serverTime; } public Variant getValue() { return value; } public StatusCode getStatusCode() { return status; } @Nullable public DateTime getSourceTime() { return sourceTime; } @Nullable public DateTime getServerTime() { return serverTime; } public DataValue withStatus(StatusCode status) { return new DataValue(value, status, sourceTime, serverTime); } public DataValue withSourceTime(@Nullable DateTime sourceTime) { return new DataValue(value, status, sourceTime, serverTime); } public DataValue withServerTime(@Nullable DateTime serverTime) { return new DataValue(value, status, sourceTime, serverTime); } /** * Derive a new {@link DataValue} from a given {@link DataValue}. * * @param from the {@link DataValue} to derive from. * @param timestamps the timestamps to return in the derived value. * @return a derived {@link DataValue}. */ public static DataValue derivedValue(DataValue from, TimestampsToReturn timestamps) { boolean includeSource = timestamps == TimestampsToReturn.Source || timestamps == TimestampsToReturn.Both; boolean includeServer = timestamps == TimestampsToReturn.Server || timestamps == TimestampsToReturn.Both; return new DataValue( from.value, from.status, includeSource ? from.sourceTime : null, includeServer ? from.serverTime : null ); } /** * Derive a new {@link DataValue} from a given {@link DataValue}. * <p> * The value is assumed to be for a non-value Node attribute, and therefore the source timestamp is not returned. * * @param from the {@link DataValue} to derive from. * @param timestamps the timestamps to return in the derived value. * @return a derived {@link DataValue}. */ public static DataValue derivedNonValue(DataValue from, TimestampsToReturn timestamps) { boolean includeServer = timestamps == TimestampsToReturn.Server || timestamps == TimestampsToReturn.Both; return new DataValue( from.value, from.status, null, includeServer ? from.serverTime : null ); } }
package net.fortuna.ical4j.util; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Utility methods relevant to Java timezones. * * @author Ben Fortuna */ public final class TimeZoneUtils { public static final String UTC_ID = "UTC"; /** * Constructor made private to enforce static nature. */ private TimeZoneUtils() { } /** * Determines the first start date of daylight savings for the specified * timezone since January 1, 1970. * * @param timezone * a timezone to determine the start of daylight savings for * @return a date */ public static Date getDaylightStart(final TimeZone timezone) { Calendar calendar = Calendar.getInstance(timezone); calendar.setTime(new Date(0)); if (timezone.useDaylightTime()) { // first find the start of standard time.. while (timezone.inDaylightTime(calendar.getTime())) { calendar.set(Calendar.DAY_OF_YEAR, calendar .get(Calendar.DAY_OF_YEAR) + 1); } // then find the first daylight time after that.. while (!timezone.inDaylightTime(calendar.getTime())) { calendar.set(Calendar.DAY_OF_YEAR, calendar .get(Calendar.DAY_OF_YEAR) + 1); } } return calendar.getTime(); } /** * Determines the first end date of daylight savings for the specified * timezone since January 1, 1970. * * @param timezone * a timezone to determine the end of daylight savings for * @return a date */ public static Date getDaylightEnd(final TimeZone timezone) { Calendar calendar = Calendar.getInstance(timezone); calendar.setTime(new Date(0)); if (timezone.useDaylightTime()) { // first find the start of daylight time.. while (!timezone.inDaylightTime(calendar.getTime())) { calendar.set(Calendar.DAY_OF_YEAR, calendar .get(Calendar.DAY_OF_YEAR) + 1); } // then find the first standard time after that.. while (timezone.inDaylightTime(calendar.getTime())) { calendar.set(Calendar.DAY_OF_YEAR, calendar .get(Calendar.DAY_OF_YEAR) + 1); } } return calendar.getTime(); } /** * Indicates whether the specified timezone is equivalent to * UTC time. * @param timezone * @return true if the timezone is UTC time, otherwise false */ public static boolean isUtc(final TimeZone timezone) { // return timezone.hasSameRules(TimeZone.getTimeZone(UTC_ID)); // return timezone.getRawOffset() == 0; return UTC_ID.equals(timezone.getID()); } }
package com.ml.dataQuality; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import org.json.*; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class DQ_Udacity { public static int PRETTY_PRINT_INDENT_FACTOR = 4; public static void main(String[] args) throws Exception { DQ_Udacity udacity = new DQ_Udacity(); udacity.getNewDataFromUdacity(); //udacity.makeChangesToJSONForEvaluation(); //udacity.checkQualityOfDataFromEdX(); } @SuppressWarnings("unchecked") private void makeChangesToJSONForEvaluation() throws Exception{ JSONParser parser = new JSONParser(); Object obj= parser.parse(new FileReader("D:\\Project\\Udacity\\udacity.json")); JSONObject inner = (JSONObject) obj; JSONArray jArrayForElements = (JSONArray)inner.get("courses"); double count=0; for(Object o: jArrayForElements){ count++; if(Math.random() < 0.9){ JSONObject course = (JSONObject) o; course.put("title", "This is a change in name for course ID"+ course.get("key").toString()); course.put("expected_learning", "<div>This course gives a broad overview of contraceptive methods and explores issues that influence contraceptive choices today. <\\//div>\n<div><\\/div>\\n<div>We will discuss the mechanism of action, effectiveness, risk/benefit, side effects and contraindications for each contraceptive method, as well as ask some questions about contraceptive decision making. What are some of the factors that influence contraception use and decision making?   Are there specific cultural, ethnic, social and environmental factors?  We will also look at the relationship between contraception use and risk of acquiring Sexually Transmitted Infections (STIs). <\\/div>\\n<div><\\/div>"+ course.get("key").toString()); course.put("required_knowledge", "<div>This course gives a broad overview of contraceptive methods and explores issues that influence contraceptive choices today. <\\//div>\n<div><\\/div>\\n<div>We will discuss the mechanism of action, effectiveness, risk/benefit, side effects and contraindications for each contraceptive method, as well as ask some questions about contraceptive decision making. What are some of the factors that influence contraception use and decision making?   Are there specific cultural, ethnic, social and environmental factors?  We will also look at the relationship between contraception use and risk of acquiring Sexually Transmitted Infections (STIs). <\\/div>\\n<div><\\/div>"+ course.get("key").toString()); } } System.out.println(count); inner.put("courses", jArrayForElements); FileWriter fw = new FileWriter("D:\\Project\\Udacity\\udacity_90.json"); fw.write(inner.toString()); fw.flush(); fw.close(); } public void checkQualityOfDataFromEdX() { /* * Loading new JSON file into HashMap * */ try{ JSONParser parser = new JSONParser(); Object obj= parser.parse(new FileReader("D:\\Project\\Udacity\\udacity_90.json")); org.json.simple.JSONObject inner = (org.json.simple.JSONObject) obj; org.json.simple.JSONArray jArrayForElements = (org.json.simple.JSONArray)inner.get("courses"); Map<String,ArrayList<String>> courseMap = new HashMap<String,ArrayList<String>>(); int count=0; for(Object o: jArrayForElements){ JSONObject course = (JSONObject) o; String courseID = course.get("key").toString(); courseMap.put(courseID, null); ArrayList<String> value = new ArrayList<String>(); String name = (String) course.get("title"); value.add(name); courseMap.put(courseID, value); String shortDescription = (String) course.get("expected_learning"); value.add(shortDescription); courseMap.put(courseID, value); String recommendedBackground = (String) course.get("required_knowledge"); value.add(recommendedBackground); courseMap.put(courseID, value); count++; } System.out.println(count); getScore(courseMap); } catch(Exception e ){e.printStackTrace();} } public static void getScore(Map<String,ArrayList<String>> courseMap){ long countOfCoursesDeleted=0; long countOfCoursesWithDetailsChanged=0; Map<String,Map<String,String>> changeInJsonMap = new HashMap<String,Map<String,String>>(); try{ JSONParser parser = new JSONParser(); /* * Loading the old JSON data. */ Object obj= parser.parse(new FileReader("D:\\Project\\Udacity\\udacity.json")); org.json.simple.JSONObject inner = (org.json.simple.JSONObject) obj; org.json.simple.JSONArray jArrayForElements = (org.json.simple.JSONArray)inner.get("courses"); /* * For each old JSON element, compare it with the new JSON file which is already loaded. */ for(Object o: jArrayForElements){ JSONObject course = (JSONObject) o; Map<String,String> courseDetailsChangeMap = new HashMap<String,String>(); String courseID = course.get("key").toString(); if(courseMap.get(courseID)==null){ //This is a course which has been removed since the last run countOfCoursesDeleted++; Map<String,String> dummyMap = new HashMap<>(); dummyMap.put("dummy", "dummy"); changeInJsonMap.put(courseID, dummyMap); //delete this course from the original JSON } else{ int arrayListIterator=0; String name = (String) course.get("title"); if(courseMap.get(courseID).get(arrayListIterator++).equals(name)){} else{ countOfCoursesWithDetailsChanged++; courseDetailsChangeMap.put("title", courseMap.get(courseID).get(arrayListIterator-1)); } String shortDescription = (String) course.get("expected_learning"); if(courseMap.get(courseID).get(arrayListIterator++).equals(shortDescription)){} else{ countOfCoursesWithDetailsChanged++; courseDetailsChangeMap.put("expected_learning", courseMap.get(courseID).get(arrayListIterator-1)); } String recommendedBackground = (String) course.get("required_knowledge"); if(courseMap.get(courseID).get(arrayListIterator++).equals(recommendedBackground)){} else{ countOfCoursesWithDetailsChanged++; courseDetailsChangeMap.put("required_knowledge", courseMap.get(courseID).get(arrayListIterator-1)); } changeInJsonMap.put(courseID, courseDetailsChangeMap); } } } catch(Exception e){ e.printStackTrace(); } changeOriginalJSONAccToScore(changeInJsonMap,(countOfCoursesDeleted+(countOfCoursesWithDetailsChanged/2))); } @SuppressWarnings("unchecked") private static void changeOriginalJSONAccToScore(Map<String, Map<String, String>> mapForChangesToBeMadeInOriginalJson, long score) { try{ JSONParser parser = new JSONParser(); /* Now, update the original JSON file with the changes. * */ Object obj= parser.parse(new FileReader("D:\\Project\\Udacity\\udacity.json")); JSONObject inner = (JSONObject) obj; JSONArray jArrayForElements = (JSONArray)inner.get("courses"); int locationCount = 0; ArrayList<Integer> locationList = new ArrayList<Integer>(); Map<String,String> dummyMap = new HashMap<>(); dummyMap.put("dummy", "dummy"); for(Object o: jArrayForElements){ JSONObject course = (JSONObject) o; String courseID = course.get("key").toString(); if(mapForChangesToBeMadeInOriginalJson.get(courseID)==dummyMap){ //Delete course from JSON file locationList.add(locationCount); } else{ Map<String,String> innerChangesMap = mapForChangesToBeMadeInOriginalJson.get(courseID); for (Map.Entry<String, String> entry : innerChangesMap.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); course.put(key, value); } } locationCount++; } ArrayList<String> list1 = new ArrayList<String>(); int len = jArrayForElements.size(); if (jArrayForElements != null) { for (int i=0;i<len;i++){ list1.add(jArrayForElements.get(i).toString()); } } for(int i=0;i<locationList.size();i++){ int loc = locationList.get(i); list1.remove(loc); } org.json.JSONArray finalJsonArray = new org.json.JSONArray(list1); inner.put("courses", finalJsonArray); FileWriter fw = new FileWriter("D:\\Project\\Udacity\\udacity_90_changed.json"); fw.write(inner.toString()); fw.flush(); fw.close(); } catch(Exception e){ e.printStackTrace(); } } public void getNewDataFromUdacity(){ try { org.json.JSONObject jsonObject = new org.json.JSONObject(IOUtils.toString(new URL("https: long startTime = System.currentTimeMillis(); String jsonPrettyPrintString = jsonObject.toString(PRETTY_PRINT_INDENT_FACTOR); FileWriter fw = new FileWriter("D:\\Project\\Udacity\\udacity.json"); fw.write(jsonPrettyPrintString.toString()); fw.flush(); fw.close(); Thread t = null; t.sleep(200); long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("\n\n"+totalTime); } catch (Exception je) { System.out.println(je.toString()); } } }
package com.googlecode.charts4j; import static com.googlecode.charts4j.Color.*; import static com.googlecode.charts4j.UrlUtil.normalize; import static org.junit.Assert.assertEquals; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Julien Chastang (julien.c.chastang at gmail dot com) */ public class RadarChartTest { @BeforeClass public static void setUpBeforeClass() throws Exception { Logger.global.setLevel(Level.ALL); } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { } /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } /** * Testing radar charts */ @Test public void test0() { Data data = Data.newData(10, 20, 30, 40, 50, 60, 70, 80, 90); final RadarChart chart = GCharts.newRadarChart(Plots.newRadarPlot(data)); chart.setSize(500, 500); Logger.global.info(chart.toURLString()); String expectedString = "http://chart.apis.google.com/chart?cht=r&chs=500x500&chd=e:GaMzTNZmgAmZszzM5m"; assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } /** * Testing radar charts with grids */ @Test public void testGrid() { Data data = Data.newData(10, 20, 30, 40, 50, 60, 70, 80, 90); final RadarChart chart = GCharts.newRadarChart(Plots.newRadarPlot(data)); chart.setSize(500, 500); chart.setGrid(10, 10, 2, 2); Logger.global.info(chart.toURLString()); String expectedString = "http://chart.apis.google.com/chart?chd=e:GaMzTNZmgAmZszzM5m&chg=10.0,10.0,2,2&chs=500x500&cht=r"; assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } /** * Testing radar charts with range markers */ @Test public void testRangeMarker() { Data data = Data.newData(10, 20, 30, 40, 50, 60, 70, 80, 90); final RadarChart chart = GCharts.newRadarChart(Plots.newRadarPlot(data)); chart.setSize(500, 500); chart.addRadialAxisRangeMarker(0, 50, RED); chart.addConcentricAxisRangeMarker(10, 90, GREEN); Logger.global.info(chart.toURLString()); String expectedString = "http://chart.apis.google.com/chart?chd=e:GaMzTNZmgAmZszzM5m&chm=r,008000,0,0.10,0.90|R,FF0000,0,0.00,4.00&chs=500x500&cht=r"; assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } /** * Testing radar charts */ @Test public void test1() { final RadarPlot plot1 = Plots.newRadarPlot(Data.newData(10, 20, 30, 40, 50, 60, 70, 80, 90), GREEN); final RadarPlot plot2 = Plots.newRadarPlot(Data.newData(90, 80, 70, 60, 50, 40, 30, 20, 10), RED); final RadarChart chart = GCharts.newRadarChart(plot1, plot2); chart.setSize(500, 500); chart.addRadialAxisLabels(AxisLabelsFactory.newAxisLabels("0", "45", "90", "135", "180", "225", "270", "315")); chart.setTitle("Cardioid"); Logger.global.info(chart.toURLString()); String expectedString = "http://chart.apis.google.com/chart?cht=r&chs=500x500&chxt=x&chco=008000,FF0000&chd=e:GaMzTNZmgAmZszzM5m,5mzMszmZgAZmTNMzGa&chxl=0:|0|45|90|135|180|225|270|315&chtt=Cardioid"; assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } /** * Testing radar charts */ @Test public void test2() { final RadarPlot plot1 = Plots.newRadarPlot(Data.newData(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100), MAROON); plot1.setLineStyle(LineStyle.newLineStyle(5, 1, 0)); final RadarChart chart = GCharts.newRadarChart(plot1); chart.setSize(500, 500); chart.addConcentricAxisLabels(AxisLabelsFactory.newAxisLabels("0", "50", "100")); Logger.global.info(chart.toURLString()); String expectedString = "http://chart.apis.google.com/chart?cht=r&chs=500x500&chxt=y&chls=5,1,0&chco=800000&chd=e:AAGaMzTNZmgAmZszzM5m..&chxl=0:|0|50|100"; assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } /** * Testing radar charts */ @Test public void test3() { final RadarPlot plot1 = Plots.newRadarPlot(Data.newData(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100), MAROON); plot1.setLineStyle(LineStyle.newLineStyle(5, 1, 0)); final RadarChart chart = GCharts.newRadarChart(plot1); chart.setSize(500, 500); chart.addConcentricAxisLabels(AxisLabelsFactory.newAxisLabels("0", "50", "100")); chart.setSpline(true); chart.setTitle("The Spiral Jetty"); Logger.global.info(chart.toURLString()); String expectedString = "http://chart.apis.google.com/chart?cht=rs&chs=500x500&chxt=y&chls=5,1,0&chco=800000&chd=e:AAGaMzTNZmgAmZszzM5m..&chxl=0:|0|50|100&chtt=The+Spiral+Jetty"; assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } /** * Testing radar charts */ @Test public void test4() { final RadarPlot plot1 = Plots.newRadarPlot(Data.newData(0, 20, 30, 40, 50, 60, 70, 80, 0), ORANGERED); Color color = Color.newColor(BLUE.toString(), 55); plot1.setFillAreaColor(color); final RadarChart chart = GCharts.newRadarChart(plot1); chart.setSpline(true); chart.setTitle("A shell"); chart.setSize(500, 500); chart.addRadialAxisLabels(AxisLabelsFactory.newAxisLabels("0", "45", "90", "135", "180", "225", "270", "315")); Logger.global.info(chart.toURLString()); String expectedString = "http://chart.apis.google.com/chart?cht=rs&chs=500x500&chxt=x&chco=FF4500&chm=B,0000FF8C,0,0,0&chd=e:AAMzTNZmgAmZszzMAA&chxl=0:|0|45|90|135|180|225|270|315&chtt=A+shell"; assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } }
package com.jayantkrish.jklol.lisp; import junit.framework.TestCase; import com.jayantkrish.jklol.ccg.lambda.ExpressionParser; public class AmbEvalTest extends TestCase { AmbEval eval; ExpressionParser<SExpression> parser; public void setUp() { eval = new AmbEval(); parser = ExpressionParser.sExpression(); } public void testAmb() { String value = runTestString("(get-best-assignment (amb (list \"a\" \"b\" \"c\") (list 1 2 1)))"); assertEquals("b", value); } public void testAmb2() { int value = runTestInt("(get-best-assignment (+ 1 (amb (list 1 2 3) (list 1 2 1))))"); assertEquals(3, value); } public void testAmb3() { int value = runTestInt("(get-best-assignment (+ (amb (list 1 2) (list 1 2)) (amb (list 1 2 3) (list 1 2 1))))"); assertEquals(4, value); } public void testAmb4() { Object value = runTest("(get-best-assignment (list (amb (list 1 2) (list 1 2)) (amb (list 1 2 3) (list 1 2 1))))"); Object expected = runTest("(list 2 2)"); assertEquals(expected, value); } public void testAmbIf() { try { runTest("(get-best-assignment (if (= (amb (list 1 2) (list 1 2)) 1) \"true\" \"false\"))"); } catch (Exception e) { return; } fail("Cannot use amb statements in conditionals."); } public void testAmbMarginals1() { Object value = runTest("(get-marginals (amb (list 1 2) (list 2 2)))"); Object expected = runTest("(cons (list 1 2) (list 0.5 0.5))"); assertEquals(expected, value); } public void testVariableElimination() { String program = "(define label-list (list \"DT\" \"NN\" \"JJ\" \"VB\")) " + "(define new-label (lambda () (amb label-list (list 1 1 1 1))))" + "" + "(define transition-factor (lambda (left right root) (begin " + "(add-weight (and (= left \"DT\") (and (= right \"NN\") (= root \"NN\"))) 2)" + "(add-weight (and (= left \"JJ\") (and (= right \"NN\") (= root \"NN\"))) 3))))" + "" + "(define x (new-label))" + "(define y (new-label))" + "(define z (new-label))" + "(transition-factor x y z)" + "(get-best-assignment (list x y z))"; Object value = runTest(program); Object expected = runTest("(list \"JJ\" \"NN\" \"NN\")"); assertEquals(expected, value); } public void testAddWeight1() { int value = runTestInt("(define x (amb (list 1 2) (list 1 2))) (define y (amb (list 1 2) (list 1 2))) (add-weight (not (= (+ x y) 2)) 0) (get-best-assignment x)"); assertEquals(1, value); } public void testAddWeight2() { int value = runTestInt("(define x (amb (list 1 2) (list 1 2))) (define y (amb (list 1 2) (list 1 2))) (add-weight (and (= x 1) (= y 1)) 8) (get-best-assignment x)"); assertEquals(1, value); } public void testAmbLambda() { int value = runTestInt("(define x (amb (list 1 2) (list 1 6))) (define foo (lambda (x) (add-weight (= x 1) 4))) (foo x) (foo x) (get-best-assignment x)"); assertEquals(1, value); } public void testAmbLambda2() { int value = runTestInt("(define x (amb (list 1 2) (list 1 6))) (define foo (lambda (x) (begin (define y (amb (list 1 2) (list 1 4))) (add-weight (not (= (+ x y) 3)) 0)))) (foo x) (foo x) (get-best-assignment x)"); assertEquals(1, value); } public void testAmbLambda3() { int value = runTestInt("(define foo (amb (list (lambda (x) (+ x 1)) (lambda (x) (+ x 2))) (list 1 2))) (define x (foo 1)) (get-best-assignment x)"); assertEquals(3, value); } public void testAmbLambda4() { int value = runTestInt("(define foo (amb (list (lambda (x) (+ x 1)) (lambda (x) (+ x 2))) (list 1 2))) (define x (foo (amb (list 1 2) (list 2 3)))) (add-weight (= x 4) 0) (get-best-assignment x)"); assertEquals(3, value); } public void testAmbLambda5() { int value = runTestInt( // "(define rand-op (lambda () (amb (list + * - (lambda (x y) x) (lambda (x y) y))))) " + "(define rand-op (lambda () (amb (list + * (lambda (x y) x) (lambda (x y) y))))) " + "(define unroll-op (lambda (op-func depth) (begin (define cur-op (op-func)) " + " (if (= depth 1) (lambda (x y) (cur-op x y)) " + " (begin (define unrolled1 (unroll-op op-func (- depth 1))) " + " (define unrolled2 (unroll-op op-func (- depth 1)))" + " (lambda (x y) (cur-op (unrolled1 x y) (unrolled2 x y))))))))" + "(define func-to-learn (unroll-op rand-op 2)) " + "(add-weight (= (func-to-learn 1 2) 4) 2.0)" + "(add-weight (= (func-to-learn 3 2) 8) 2.0)" + "(add-weight (= (func-to-learn 4 7) 35) 2.0)" + "(get-best-assignment (func-to-learn 2 3))"); assertEquals(9, value); } public void testAmbLambda6() { int value = runTestInt( "(define rand-int (lambda () (amb (list 1 2 3 4 5 6 7 8 9 10))))" + "(define poly (lambda (degree) (begin (define cur-root (rand-int)) " + " (if (= degree 1) (lambda (x) (- x cur-root)) " + " (begin (define unrolled (poly (- degree 1))) " + " (lambda (x) (* (- x cur-root) (unrolled x))))))))" + "(define func-to-learn (poly 2)) " + "(add-weight (= (func-to-learn 1) 0) 2.0)" + "(add-weight (= (func-to-learn 2) 0) 2.0)" + "(get-best-assignment (func-to-learn 4))"); assertEquals(6, value); } public void testRecursion() { String program = "(define word-factor (lambda (label word) (begin " + "(add-weight (and (= word \"car\") (= label \"N\")) 2) " + "(add-weight (and (= word \"goes\") (= label \"V\")) 3))))" + "" + "(define transition-factor (lambda (cur-label next-label)" + "(add-weight (and (= next-label \"N\") (= cur-label \"N\")) 2))) " + "" + "(define sequence-tag (lambda (input-seq) (if (nil? input-seq) (list) (begin " + "(define cur-label (amb (list \"N\" \"V\") (list 1 1)))" + "(define next-labels (sequence-tag (cdr input-seq))) " + "(word-factor cur-label (car input-seq))" + "(if (not (nil? (cdr input-seq)))" + " (begin " + " (define next-label (car next-labels))" + " (transition-factor cur-label next-label)" + " (cons cur-label next-labels))" + " (cons cur-label next-labels))))))" + "" + "(define x (get-best-assignment (sequence-tag (list \"car\"))))" + "(define y (get-best-assignment (sequence-tag (list \"goes\" \"car\")))) " + "(define z (get-best-assignment (sequence-tag (list \"the\" \"car\"))))" + "(list x y z)"; Object value = runTest(program); Object expected = runTest("(list (list \"N\") (list \"V\" \"N\") (list \"N\" \"N\"))"); assertEquals(expected, value); } public void testCfg() { String program = "(define label-list (list \"DT\" \"NN\" \"JJ\" \"VB\")) " + "(define new-label (lambda () (amb label-list (list 1 1 1 1))))" + "" + "(define word-factor (lambda (label word) (begin " + "(add-weight (and (= word \"car\") (= label \"NN\")) 2) " + "(add-weight (and (= word \"big\") (= label \"JJ\")) 2) " + "(add-weight (and (= word \"the\") (= label \"JJ\")) 0.5) " + "(add-weight (and (= word \"the\") (= label \"DT\")) 2) " + "(add-weight (and (= word \"goes\") (= label \"VB\")) 3))))" + "" + "(define transition-factor (lambda (left right root) (begin " + "(add-weight (and (= left \"DT\") (and (= right \"NN\") (= root \"NN\"))) 2)" + "(add-weight (and (= left \"JJ\") (and (= right \"NN\") (= root \"NN\"))) 2))))" + "" + "(define first-n (lambda (seq n) (if (= n 0) (list) (cons (car seq) (first-n (cdr seq) (- n 1))))))" + "(define remainder-n (lambda (seq n) (if (= n 0) seq (remainder-n (cdr seq) (- n 1)))))" + "(define 1-to-n (lambda (n) (1-to-n-helper n 1)))" + "(define 1-to-n-helper (lambda (n i) (if (= (+ n 1) i) (list) (cons i (1-to-n-helper n (+ i 1))))))" + "(define get-ith-element (lambda (i seq) (if (= i 0) (car seq) (get-ith-element (- i 1) (cdr seq)))))" + "(define map (lambda (f seq) (if (nil? seq) (list) (cons (f (car seq)) (map f (cdr seq))))))" + "(define length (lambda (seq) (if (nil? seq) 0 (+ (length (cdr seq)) 1))))" + "" + "(define cfg-parse (lambda (input-seq) (begin " + "(define label-var (new-label))" + "(if (= (length input-seq) 1) " + " (begin (word-factor label-var (car input-seq))" + " (list label-var (car input-seq)))" + " (begin " + " (define split-list (1-to-n (- (length input-seq) 1)))" + " (define choice-var (amb split-list))" + " (list label-var choice-var (map (lambda (i) (do-split input-seq i label-var choice-var)) split-list)))))))" + "" + "(define do-split (lambda (seq i root-var choice-var) (begin" + " (define left-seq (first-n seq i))" + " (define right-seq (remainder-n seq i))" + " (define left-parse (cfg-parse left-seq))" + " (define right-parse (cfg-parse right-seq))" + " (define left-parse-root (car left-parse))" + " (define right-parse-root (car right-parse))" + " (define cur-root (new-label))" + " (transition-factor left-parse-root right-parse-root cur-root)" + " (add-weight (and (= choice-var i) (not (= cur-root root-var))) 0)" + " (list cur-root left-parse right-parse))))" + "" + "(define decode-parse (lambda (chart) (if (= (length chart) 2)" + " chart" + " (begin" + " (define chosen-subtree (get-ith-element (- (car (cdr chart)) 1) (car (cdr (cdr chart)))))" + " (list (car chart) (decode-parse (car (cdr chosen-subtree))) (decode-parse (car (cdr (cdr chosen-subtree)))))))))" + "" + "(decode-parse (get-best-assignment (cfg-parse (list \"the\" \"big\" \"car\")) \"junction-tree\"))"; Object value = runTest(program); Object expected = runTest("(list \"NN\" (list \"DT\" \"the\") (list \"NN\" (list \"JJ\" \"big\") (list \"NN\" \"car\")))"); assertEquals(expected, value); // CFGs can't be correctly implemented in this language as is. The above // program includes decisions in un-chosen subtrees in the score of a parse, // which is not correct. fail(); } private Object runTest(String expressionString) { String wrappedExpressionString = "(begin " + expressionString + ")"; return eval.eval(parser.parseSingleExpression(wrappedExpressionString)).getValue(); } private String runTestString(String expressionString) { return (String) runTest(expressionString); } private int runTestInt(String expressionString) { return (Integer) runTest(expressionString); } }
package com.linkedin.thirdeye.dataframe.util; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.linkedin.thirdeye.api.TimeGranularity; import com.linkedin.thirdeye.dashboard.Utils; import com.linkedin.thirdeye.dataframe.DataFrame; import com.linkedin.thirdeye.dataframe.DoubleSeries; import com.linkedin.thirdeye.dataframe.LongSeries; import com.linkedin.thirdeye.dataframe.Series; import com.linkedin.thirdeye.dataframe.StringSeries; import com.linkedin.thirdeye.datalayer.bao.DatasetConfigManager; import com.linkedin.thirdeye.datalayer.bao.MetricConfigManager; import com.linkedin.thirdeye.datalayer.dto.DatasetConfigDTO; import com.linkedin.thirdeye.datalayer.dto.MetricConfigDTO; import com.linkedin.thirdeye.datasource.DAORegistry; import com.linkedin.thirdeye.datasource.MetricExpression; import com.linkedin.thirdeye.datasource.MetricFunction; import com.linkedin.thirdeye.datasource.ThirdEyeCacheRegistry; import com.linkedin.thirdeye.datasource.ThirdEyeRequest; import com.linkedin.thirdeye.datasource.ThirdEyeResponse; import com.linkedin.thirdeye.datasource.ThirdEyeResponseRow; import com.linkedin.thirdeye.datasource.cache.QueryCache; import com.linkedin.thirdeye.datasource.pinot.resultset.ThirdEyeResultSet; import com.linkedin.thirdeye.datasource.pinot.resultset.ThirdEyeResultSetGroup; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; /** * Utility class for ThirdEye-specific parsers and transformers of data related to DataFrame. * */ public class DataFrameUtils { public static final String COL_TIME = "timestamp"; public static final String COL_VALUE = "value"; /** * Returns a Thirdeye response parsed as a DataFrame. The method stores the time values in * {@code COL_TIME} by default, and creates columns for each groupBy attribute and for each * MetricFunction specified in the request. * * @param response thirdeye client response * @return response as dataframe */ public static DataFrame parseResponse(ThirdEyeResponse response) { // builders LongSeries.Builder timeBuilder = LongSeries.builder(); List<StringSeries.Builder> dimensionBuilders = new ArrayList<>(); List<DoubleSeries.Builder> functionBuilders = new ArrayList<>(); for(int i=0; i<response.getGroupKeyColumns().size(); i++) { dimensionBuilders.add(StringSeries.builder()); } for(int i=0; i<response.getMetricFunctions().size(); i++) { functionBuilders.add(DoubleSeries.builder()); } // values for(int i=0; i<response.getNumRows(); i++) { ThirdEyeResponseRow r = response.getRow(i); timeBuilder.addValues(r.getTimeBucketId()); for(int j=0; j<r.getDimensions().size(); j++) { dimensionBuilders.get(j).addValues(r.getDimensions().get(j)); } for(int j=0; j<r.getMetrics().size(); j++) { functionBuilders.get(j).addValues(r.getMetrics().get(j)); } } // dataframe String timeColumn = response.getDataTimeSpec().getColumnName(); DataFrame df = new DataFrame(); df.addSeries(COL_TIME, timeBuilder.build()); df.setIndex(COL_TIME); int i = 0; for(String n : response.getGroupKeyColumns()) { if(!timeColumn.equals(n)) { df.addSeries(n, dimensionBuilders.get(i++).build()); } } int j = 0; for(MetricFunction mf : response.getMetricFunctions()) { df.addSeries(mf.toString(), functionBuilders.get(j++).build()); } return df.sortedBy(COL_TIME); } /** * Returns the DataFrame augmented with a {@code COL_VALUE} column that contains the * evaluation results from computing derived metric expressions. The method performs the * augmentation in-place. * * <br/><b>NOTE:</b> only supports computation of a single MetricExpression. * * @param df thirdeye response dataframe * @param expressions collection of metric expressions * @return augmented dataframe * @throws Exception if the metric expression cannot be computed */ public static DataFrame evaluateExpressions(DataFrame df, Collection<MetricExpression> expressions) throws Exception { if(expressions.size() != 1) throw new IllegalArgumentException("Requires exactly one expression"); MetricExpression me = expressions.iterator().next(); Collection<MetricFunction> functions = me.computeMetricFunctions(); Map<String, Double> context = new HashMap<>(); double[] values = new double[df.size()]; for(int i=0; i<df.size(); i++) { for(MetricFunction f : functions) { // TODO check inconsistency between getMetricName() and toString() context.put(f.getMetricName(), df.getDouble(f.toString(), i)); } values[i] = MetricExpression.evaluateExpression(me, context); } // drop intermediate columns for(MetricFunction f : functions) { df.dropSeries(f.toString()); } return df.addSeries(COL_VALUE, values); } /** * Returns the DataFrame with timestamps aligned to a start offset and an interval. * * @param df thirdeye response dataframe * @param start start offset * @param end end offset * @param interval timestep multiple * @return dataframe with modified timestamps */ public static DataFrame alignTimestamps(DataFrame df, final long start, final long end, final long interval) { return new DataFrame(df).mapInPlace(new Series.LongFunction() { @Override public long apply(long... values) { return (values[0] * interval) + start; } }, COL_TIME); } /** * Returns a Thirdeye response parsed as a DataFrame. The method stores the time values in * {@code COL_TIME} by default, and creates columns for each groupBy attribute and for each * MetricFunction specified in the request. It further evaluates expressions for derived * metrics. * @see DataFrameUtils#makeAggregateRequest(MetricSlice, List, String, MetricConfigManager, DatasetConfigManager) * @see DataFrameUtils#makeTimeSeriesRequest(MetricSlice, String, MetricConfigManager, DatasetConfigManager) * * @param response thirdeye client response * @param rc RequestContainer * @return response as dataframe */ public static DataFrame evaluateResponse(ThirdEyeResponse response, RequestContainer rc) throws Exception { return evaluateExpressions(parseResponse(response), rc.getExpressions()); } /** * Returns a Thirdeye response parsed as a DataFrame. The method stores the time values in * {@code COL_TIME} by default, and creates columns for each groupBy attribute and for each * MetricFunction specified in the request. It evaluates expressions for derived * metrics and offsets timestamp based on the original timeseries request. * @see DataFrameUtils#makeTimeSeriesRequest(MetricSlice, String, MetricConfigManager, DatasetConfigManager) * * @param response thirdeye client response * @param rc TimeSeriesRequestContainer * @return response as dataframe */ public static DataFrame evaluateResponse(ThirdEyeResponse response, TimeSeriesRequestContainer rc) throws Exception { long start = ((rc.start + rc.interval - 1) / rc.interval) * rc.interval; long end = ((rc.end + rc.interval - 1) / rc.interval) * rc.interval; return alignTimestamps(evaluateExpressions(parseResponse(response), rc.getExpressions()), start, end, rc.getInterval()); } /** * Returns a map-transformation of a given DataFrame, assuming that all values can be converted * to Double values. The map is keyed by series names. * * @param df dataframe * @return map transformation of dataframe */ public static Map<String, List<Double>> toMap(DataFrame df) { Map<String, List<Double>> map = new HashMap<>(); for (String series : df.getSeriesNames()) { map.put(series, df.getDoubles(series).toList()); } return map; } /** * Returns a DataFrame wrapping the requested time series at the associated dataset's native * time granularity. * <br/><b>NOTE:</b> this method injects dependencies from the DAO and Cache registries. * @see DataFrameUtils#fetchTimeSeries(MetricSlice, MetricConfigManager, DatasetConfigManager, QueryCache) * * @param slice metric data slice * @return DataFrame with time series * @throws Exception */ public static DataFrame fetchTimeSeries(MetricSlice slice) throws Exception { MetricConfigManager metricDAO = DAORegistry.getInstance().getMetricConfigDAO(); DatasetConfigManager datasetDAO = DAORegistry.getInstance().getDatasetConfigDAO(); QueryCache cache = ThirdEyeCacheRegistry.getInstance().getQueryCache(); return fetchTimeSeries(slice, metricDAO, datasetDAO, cache); } /** * Returns a DataFrame wrapping the requested time series at the associated dataset's native * time granularity. * * @param slice metric data slice * @param metricDAO metric config DAO * @param datasetDAO dataset config DAO * @param cache query cache * @return DataFrame with time series * @throws Exception */ public static DataFrame fetchTimeSeries(MetricSlice slice, MetricConfigManager metricDAO, DatasetConfigManager datasetDAO, QueryCache cache) throws Exception { String ref = String.format("%s-%d-%d", Thread.currentThread().getName(), slice.metricId, System.nanoTime()); RequestContainer req = makeTimeSeriesRequest(slice, ref, metricDAO, datasetDAO); ThirdEyeResponse resp = cache.getQueryResult(req.request); return evaluateExpressions(parseResponse(resp), req.expressions); } /** * Constructs and wraps a request for a metric with derived expressions. Resolves all * required dependencies from the Thirdeye database. * <br/><b>NOTE:</b> this method injects dependencies from the DAO registry. * @see DataFrameUtils#makeTimeSeriesRequest(MetricSlice slice, String, MetricConfigManager, DatasetConfigManager) * * @param slice metric data slice * @param reference unique identifier for request * @return RequestContainer * @throws Exception */ public static TimeSeriesRequestContainer makeTimeSeriesRequest(MetricSlice slice, String reference) throws Exception { MetricConfigManager metricDAO = DAORegistry.getInstance().getMetricConfigDAO(); DatasetConfigManager datasetDAO = DAORegistry.getInstance().getDatasetConfigDAO(); return makeTimeSeriesRequest(slice, reference, metricDAO, datasetDAO); } /** * Constructs and wraps a request for a metric with derived expressions. Resolves all * required dependencies from the Thirdeye database. Also aligns start and end timestamps by * rounding them down (start) and up (end) to align with metric time granularity boundaries. * <br/><b>NOTE:</b> the aligned end timestamp is still exclusive. * * @param slice metric data slice * @param reference unique identifier for request * @param metricDAO metric config DAO * @param datasetDAO dataset config DAO * @return TimeSeriesRequestContainer * @throws Exception */ public static TimeSeriesRequestContainer makeTimeSeriesRequestAligned(MetricSlice slice, String reference, MetricConfigManager metricDAO, DatasetConfigManager datasetDAO) throws Exception { MetricConfigDTO metric = metricDAO.findById(slice.metricId); if(metric == null) throw new IllegalArgumentException(String.format("Could not resolve metric id %d", slice.metricId)); DatasetConfigDTO dataset = datasetDAO.findByDataset(metric.getDataset()); if(dataset == null) throw new IllegalArgumentException(String.format("Could not resolve dataset '%s' for metric id '%d'", metric.getDataset(), metric.getId())); List<MetricExpression> expressions = Utils.convertToMetricExpressions(metric.getName(), metric.getDefaultAggFunction(), metric.getDataset()); TimeGranularity granularity = dataset.bucketTimeGranularity(); if (!MetricSlice.NATIVE_GRANULARITY.equals(slice.granularity)) { granularity = slice.granularity; } long timeGranularity = granularity.toMillis(); long start = (slice.start / timeGranularity) * timeGranularity; long end = ((slice.end + timeGranularity - 1) / timeGranularity) * timeGranularity; MetricSlice alignedSlice = MetricSlice.from(slice.metricId, start, end, slice.filters, slice.granularity); ThirdEyeRequest request = makeThirdEyeRequestBuilder(alignedSlice, metric, dataset, expressions) .setGroupByTimeGranularity(granularity) .build(reference); return new TimeSeriesRequestContainer(request, expressions, start, end, timeGranularity); } /** * Constructs and wraps a request for a metric with derived expressions. Resolves all * required dependencies from the Thirdeye database. * * @param slice metric data slice * @param reference unique identifier for request * @param metricDAO metric config DAO * @param datasetDAO dataset config DAO * @return TimeSeriesRequestContainer * @throws Exception */ public static TimeSeriesRequestContainer makeTimeSeriesRequest(MetricSlice slice, String reference, MetricConfigManager metricDAO, DatasetConfigManager datasetDAO) throws Exception { MetricConfigDTO metric = metricDAO.findById(slice.metricId); if(metric == null) throw new IllegalArgumentException(String.format("Could not resolve metric id %d", slice.metricId)); DatasetConfigDTO dataset = datasetDAO.findByDataset(metric.getDataset()); if(dataset == null) throw new IllegalArgumentException(String.format("Could not resolve dataset '%s' for metric id '%d'", metric.getDataset(), metric.getId())); List<MetricExpression> expressions = Utils.convertToMetricExpressions(metric.getName(), metric.getDefaultAggFunction(), metric.getDataset()); TimeGranularity granularity = dataset.bucketTimeGranularity(); if (!MetricSlice.NATIVE_GRANULARITY.equals(slice.granularity)) { granularity = slice.granularity; } ThirdEyeRequest request = makeThirdEyeRequestBuilder(slice, metric, dataset, expressions) .setGroupByTimeGranularity(granularity) .build(reference); return new TimeSeriesRequestContainer(request, expressions, slice.start, slice.end, granularity.toMillis()); } /** * Constructs and wraps a request for a metric with derived expressions. Resolves all * required dependencies from the Thirdeye database. * * @param slice metric data slice * @param dimensions dimensions to group by * @param reference unique identifier for request * @return RequestContainer * @throws Exception */ public static RequestContainer makeAggregateRequest(MetricSlice slice, List<String> dimensions, String reference) throws Exception { MetricConfigManager metricDAO = DAORegistry.getInstance().getMetricConfigDAO(); DatasetConfigManager datasetDAO = DAORegistry.getInstance().getDatasetConfigDAO(); return makeAggregateRequest(slice, dimensions, reference, metricDAO, datasetDAO); } /** * Constructs and wraps a request for a metric with derived expressions. Resolves all * required dependencies from the Thirdeye database. * * @param slice metric data slice * @param dimensions dimensions to group by * @param reference unique identifier for request * @param metricDAO metric config DAO * @param datasetDAO dataset config DAO * @return RequestContainer * @throws Exception */ public static RequestContainer makeAggregateRequest(MetricSlice slice, List<String> dimensions, String reference, MetricConfigManager metricDAO, DatasetConfigManager datasetDAO) throws Exception { MetricConfigDTO metric = metricDAO.findById(slice.metricId); if(metric == null) throw new IllegalArgumentException(String.format("Could not resolve metric id %d", slice.metricId)); DatasetConfigDTO dataset = datasetDAO.findByDataset(metric.getDataset()); if(dataset == null) throw new IllegalArgumentException(String.format("Could not resolve dataset '%s' for metric id '%d'", metric.getDataset(), metric.getId())); List<MetricExpression> expressions = Utils.convertToMetricExpressions(metric.getName(), metric.getDefaultAggFunction(), metric.getDataset()); ThirdEyeRequest request = makeThirdEyeRequestBuilder(slice, metric, dataset, expressions) .setGroupBy(dimensions) .build(reference); return new RequestContainer(request, expressions); } /** * Helper: Returns a pre-populated ThirdeyeRequestBuilder instance. * * @param slice metric data slice * @param metric metric dto * @param dataset dataset dto * @param expressions metric expressions * @return ThirdeyeRequestBuilder * @throws ExecutionException */ private static ThirdEyeRequest.ThirdEyeRequestBuilder makeThirdEyeRequestBuilder(MetricSlice slice, MetricConfigDTO metric, DatasetConfigDTO dataset, List<MetricExpression> expressions) throws ExecutionException { List<MetricFunction> functions = new ArrayList<>(); for(MetricExpression exp : expressions) { functions.addAll(exp.computeMetricFunctions()); } Multimap<String, String> effectiveFilters = ArrayListMultimap.create(); for (String dimName : slice.filters.keySet()) { if (dataset.getDimensions().contains(dimName)) { effectiveFilters.putAll(dimName, slice.filters.get(dimName)); } } return ThirdEyeRequest.newBuilder() .setStartTimeInclusive(slice.start) .setEndTimeExclusive(slice.end) .setFilterSet(effectiveFilters) .setMetricFunctions(functions) .setDataSource(dataset.getDataSource()); } public static DataFrame fromThirdEyeResult(ThirdEyeResultSetGroup resultSetGroup) { if (resultSetGroup.size() <= 0) throw new IllegalArgumentException("Query did not return any results"); if (resultSetGroup.size() == 1) { ThirdEyeResultSet resultSet = resultSetGroup.getResultSets().get(0); if (resultSet.getColumnCount() == 1 && resultSet.getRowCount() == 0) { // empty result return new DataFrame(); } else if (resultSet.getColumnCount() == 1 && resultSet.getRowCount() == 1 && resultSet.getGroupKeyLength() == 0) { // aggregation result DataFrame df = new DataFrame(); String function = resultSet.getColumnName(0); String value = resultSet.getString(0, 0); df.addSeries(function, DataFrame.toSeries(value)); return df; } else if (resultSet.getColumnCount() >= 1 && resultSet.getGroupKeyLength() == 0) { // selection result DataFrame df = new DataFrame(); for (int i = 0; i < resultSet.getColumnCount(); i++) { df.addSeries(resultSet.getColumnName(i), makeSelectionSeries(resultSet, i)); } return df; } } // group by result ThirdEyeResultSet firstResultSet = resultSetGroup.getResultSets().get(0); String[] groupKeyNames = new String[firstResultSet.getGroupKeyLength()]; for(int i=0; i<firstResultSet.getGroupKeyLength(); i++) { groupKeyNames[i] = firstResultSet.getGroupKeyColumnName(i); } DataFrame df = new DataFrame(); for (String groupKeyName : groupKeyNames) { df.addSeries(groupKeyName, StringSeries.empty()); } df.setIndex(groupKeyNames); for(int i=0; i<resultSetGroup.size(); i++) { ThirdEyeResultSet resultSet = resultSetGroup.getResultSets().get(i); String function = resultSet.getColumnName(0); // group keys DataFrame dfColumn = new DataFrame(); for(int j=0; j<resultSet.getGroupKeyLength(); j++) { dfColumn.addSeries(groupKeyNames[j], makeGroupByGroupSeries(resultSet, j)); } dfColumn.setIndex(groupKeyNames); // values dfColumn.addSeries(function, makeGroupByValueSeries(resultSet)); df = df.joinOuter(dfColumn); } return df; } private static Series makeSelectionSeries(ThirdEyeResultSet resultSet, int colIndex) { int rowCount = resultSet.getRowCount(); if(rowCount <= 0) return StringSeries.empty(); String[] values = new String[rowCount]; for(int i=0; i<rowCount; i++) { values[i] = resultSet.getString(i, colIndex); } return DataFrame.toSeries(values); } private static Series makeGroupByValueSeries(ThirdEyeResultSet resultSet) { int rowCount = resultSet.getRowCount(); if(rowCount <= 0) return StringSeries.empty(); String[] values = new String[rowCount]; for(int i=0; i<rowCount; i++) { values[i] = resultSet.getString(i, 0); } return DataFrame.toSeries(values); } private static Series makeGroupByGroupSeries(ThirdEyeResultSet resultSet, int keyIndex) { int rowCount = resultSet.getRowCount(); if(rowCount <= 0) return StringSeries.empty(); String[] values = new String[rowCount]; for(int i=0; i<rowCount; i++) { values[i] = resultSet.getGroupKeyColumnValue(i, keyIndex); } return DataFrame.toSeries(values); } }
package com.orientechnologies.orient.server.jwt.impl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Date; import java.util.UUID; import javax.crypto.Mac; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.metadata.security.OSecurityUser; import com.orientechnologies.orient.core.metadata.security.OToken; import com.orientechnologies.orient.core.metadata.security.OTokenHandler; import com.orientechnologies.orient.core.metadata.security.jwt.OJwtHeader; import com.orientechnologies.orient.core.metadata.security.jwt.OJwtKeyProvider; import com.orientechnologies.orient.core.metadata.security.jwt.OJwtPayload; import com.orientechnologies.orient.core.serialization.OBase64Utils; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.config.OServerParameterConfiguration; import com.orientechnologies.orient.server.jwt.mixin.OJwtHeaderMixin; import com.orientechnologies.orient.server.jwt.mixin.OJwtPayloadMixin; import com.orientechnologies.orient.server.plugin.OServerPluginAbstract; public class JwtTokenHandler extends OServerPluginAbstract implements OTokenHandler { private static final String JWT_TOKEN_HANDLER = "JwtTokenHandler"; private final ObjectMapper mapper; private static final int JWT_DELIMITER = '.'; // protected final ConcurrentHashMap<String, Class<?>> payloadClasses = new ConcurrentHashMap<String, Class<?>>(); private static final ThreadLocal<Mac> threadLocalMac = new ThreadLocal<Mac>() { @Override protected Mac initialValue() { try { return Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException nsa) { throw new IllegalArgumentException("Can't find algorithm."); } } }; private OServer serverInstance; private OJwtKeyProvider keyProvider; public JwtTokenHandler() { mapper = new ObjectMapper().registerModule(new AfterburnerModule()).configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.addMixInAnnotations(OJwtHeader.class, OJwtHeaderMixin.class); mapper.addMixInAnnotations(OJwtPayload.class, OJwtPayloadMixin.class); // .registerModule(); } // public void registerPayloadClass(String name, Class clazz) { // payloadClasses.put(name, clazz); @Override public void config(final OServer iServer, final OServerParameterConfiguration[] iParams) { serverInstance = iServer; for (OServerParameterConfiguration param : iParams) { if (param.name.equalsIgnoreCase("oAuth2Key")) { byte secret[] = OBase64Utils.decode(param.value, OBase64Utils.URL_SAFE); keyProvider = new DefaultJwtKeyProvider(secret); } } // this.registerPayloadClass("OrientDb", JwtTokenHandler.class); } @Override public OToken parseWebToken(byte[] tokenBytes) throws InvalidKeyException, NoSuchAlgorithmException, IOException { OToken token = null; // / <header>.<payload>.<signature> int firstDot = -1, secondDot = -1; int x; for (x = 0; x < tokenBytes.length; x++) { if (tokenBytes[x] == JWT_DELIMITER) { firstDot = x; // stores reference to first '.' character in JWT token break; } } if (firstDot == -1) return null; for (x = firstDot + 1; x < tokenBytes.length; x++) { if (tokenBytes[x] == JWT_DELIMITER) { secondDot = x; // stores reference to second '.' character in JWT token break; } } if (secondDot == -1) return null; byte[] decodedHeader = OBase64Utils.decode(tokenBytes, 0, firstDot, OBase64Utils.URL_SAFE); JwtHeader header = deserializeWebHeader(decodedHeader); Mac mac = threadLocalMac.get(); try { mac.init(getKeyProvider().getKey(header)); mac.update(tokenBytes, 0, secondDot); byte[] calculatedSignature = mac.doFinal(); byte[] decodedSignature = OBase64Utils.decode(tokenBytes, secondDot + 1, tokenBytes.length, OBase64Utils.URL_SAFE); boolean signatureValid = Arrays.equals(calculatedSignature, decodedSignature); if (signatureValid) { byte[] decodedPayload = OBase64Utils.decode(tokenBytes, firstDot + 1, secondDot, OBase64Utils.URL_SAFE); // Class<?> payloadClass = payloadClasses.get(header.getType()); // if (payloadClass == null) { // throw new Exception("Payload class not registered:" + header.getType()); token = new JsonWebToken(header, deserializeWebPayload(header.getType(), decodedPayload)); token.setIsVerified(true); return token; } } catch (Exception ex) { OLogManager.instance().warn(this, "Error parsing token", ex); // noop } finally { mac.reset(); } return token; } @Override public boolean validateToken(OToken token, String command, String database) { boolean valid = false; if (!(token instanceof JsonWebToken)) { return false; } OrientJwtPayload payload = (OrientJwtPayload) ((JsonWebToken) token).getPayload(); if (payload.getDbName().equalsIgnoreCase(database) && payload.getExpiry() > System.currentTimeMillis() && payload.getNotBefore() < System.currentTimeMillis()) { valid = true; } // TODO: Other validations... (e.g. check audience, etc.) token.setIsValid(valid); return valid; } protected JwtHeader deserializeWebHeader(byte[] decodedHeader) throws JsonParseException, JsonMappingException, IOException { return mapper.readValue(decodedHeader, JwtHeader.class); } protected OJwtPayload deserializeWebPayload(String type, byte[] decodedPayload) throws Exception { return mapper.readValue(decodedPayload, OrientJwtPayload.class); } public byte[] getSignedWebToken(ODatabaseDocumentInternal db, OSecurityUser user) { ByteArrayOutputStream tokenByteOS = new ByteArrayOutputStream(1024); JwtHeader header = new JwtHeader(); header.setAlgorithm("HS256"); header.setKeyId(""); OJwtPayload payload = createPayload(db, user); header.setType(getPayloadType(payload)); Mac mac = threadLocalMac.get(); try { byte[] bytes = serializeHeader(header); tokenByteOS.write(OBase64Utils.encodeBytesToBytes(bytes, 0, bytes.length, OBase64Utils.URL_SAFE)); tokenByteOS.write(JWT_DELIMITER); bytes = serializePayload(payload); tokenByteOS.write(OBase64Utils.encodeBytesToBytes(bytes, 0, bytes.length, OBase64Utils.URL_SAFE)); byte[] unsignedToken = tokenByteOS.toByteArray(); tokenByteOS.write(JWT_DELIMITER); mac.init(getKeyProvider().getKey(header)); bytes = mac.doFinal(unsignedToken); tokenByteOS.write(OBase64Utils.encodeBytesToBytes(bytes, 0, bytes.length, OBase64Utils.URL_SAFE)); } catch (Exception ex) { OLogManager.instance().error(this, "Error signing token", ex); } return tokenByteOS.toByteArray(); } protected byte[] serializeHeader(OJwtHeader header) throws JsonProcessingException { return mapper.writeValueAsBytes(header); } protected byte[] serializePayload(OJwtPayload payload) throws JsonProcessingException { return mapper.writeValueAsBytes(payload); } protected OJwtPayload createPayload(ODatabaseDocumentInternal db, OSecurityUser user) { OrientJwtPayload payload = new OrientJwtPayload(); payload.setAudience("OrientDb"); payload.setDbName(db.getName()); payload.setUserRid(user.getDocument().getIdentity().toString()); long expiryMinutes = 60000 * 10; long currTime = System.currentTimeMillis(); Date issueTime = new Date(currTime); Date expDate = new Date(currTime + expiryMinutes); payload.setIssuedAt(issueTime.getTime()); payload.setNotBefore(issueTime.getTime()); payload.setSubject(user.getName()); payload.setTokenId(UUID.randomUUID().toString()); payload.setExpiry(expDate.getTime()); return payload; } protected String getPayloadType(OJwtPayload payload) { return "OrientDB"; } @Override public String getName() { return JWT_TOKEN_HANDLER; } protected OJwtKeyProvider getKeyProvider() { return keyProvider; } }
package io.spine.tools.compiler.annotation; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.protobuf.Descriptors; import io.spine.code.java.ClassName; import io.spine.code.proto.TypeSet; import org.jboss.forge.roaster.model.Method; import org.jboss.forge.roaster.model.impl.AbstractJavaSource; import org.jboss.forge.roaster.model.source.JavaClassSource; import org.jboss.forge.roaster.model.source.MethodHolderSource; import org.jboss.forge.roaster.model.source.MethodSource; import java.nio.file.Path; import java.util.stream.Stream; final class MethodNameAnnotator extends Annotator { private final ImmutableSet<MethodPattern> patterns; MethodNameAnnotator(ClassName annotation, ImmutableSet<MethodPattern> patterns, ImmutableList<Descriptors.FileDescriptor> descriptors, Path genProtoDir) { super(annotation, descriptors, genProtoDir); this.patterns = patterns; } @Override public void annotate() { if (!patterns.isEmpty()) { SourceVisitor<?> visitor = new AnnotateMethods(); descriptors().stream() .map(TypeSet::messagesAndEnums) .flatMap(typeSet -> typeSet.types().stream()) .map(type -> type.javaClassName().resolveFile()) .forEach(file -> rewriteSource(file, visitor)); } } private final class AnnotateMethods implements ClassInDepthVisitor { @Override public void accept(AbstractJavaSource<JavaClassSource> source) { allClasses(source) .flatMap(classSource -> classSource instanceof MethodHolderSource ? ((MethodHolderSource<?>) classSource).getMethods() .stream() : Stream.<MethodSource<?>>of()) .filter(Method::isPublic) .filter(this::matching) .forEach(MethodNameAnnotator.this::addAnnotation); } private boolean matching(Method<?, ?> method) { String methodName = method.getName(); return patterns.stream() .anyMatch(pattern -> pattern.matches(methodName)); } } }
package com.redhat.ceylon.compiler.java; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import ceylon.language.Boolean; import ceylon.language.Iterable; import ceylon.language.Iterator; import ceylon.language.exhausted; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Class; import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes; public class Util { /** * Returns true if the given object satisfies ceylon.language.Identifiable */ public static boolean isIdentifiable(java.lang.Object o){ return satisfiesInterface(o, "ceylon.language.Identifiable"); } /** * Returns true if the given object extends the given class */ public static boolean extendsClass(java.lang.Object o, String className) { if(o == null) return false; if(className == null) throw new IllegalArgumentException("Type name cannot be null"); return classExtendsClass(o.getClass(), className); } private static boolean classExtendsClass(java.lang.Class<?> klass, String className) { if(klass == null) return false; if (klass.getName().equals(className)) return true; if ((className.equals("ceylon.language.IdentifiableObject")) && klass!=java.lang.Object.class //&& klass!=java.lang.String.class && !klass.isAnnotationPresent(Ceylon.class)) { //TODO: this is broken for a Java class that // extends a Ceylon class return true; } Class classAnnotation = klass.getAnnotation(Class.class); if (classAnnotation != null) { String superclassName = classAnnotation.extendsType(); int i = superclassName.indexOf('<'); if (i>0) { superclassName = superclassName.substring(0, i); } try { return classExtendsClass( java.lang.Class.forName(superclassName), className); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } return classExtendsClass(klass.getSuperclass(), className); } /** * Returns true if the given object satisfies the given interface */ public static boolean satisfiesInterface(java.lang.Object o, String className){ if(o == null) return false; if(className == null) throw new IllegalArgumentException("Type name cannot be null"); // we use a hash set to speed things up for interfaces, to avoid looking at them twice Set<java.lang.Class<?>> alreadyVisited = new HashSet<java.lang.Class<?>>(); return classSatisfiesInterface(o.getClass(), className, alreadyVisited); } private static boolean classSatisfiesInterface(java.lang.Class<?> klass, String className, Set<java.lang.Class<?>> alreadyVisited) { if(klass == null) return false; if ((className.equals("ceylon.language.Identifiable")) && klass!=java.lang.Object.class //&& klass!=java.lang.String.class && !klass.isAnnotationPresent(Ceylon.class)) { //TODO: this is broken for a Java class that // extends a Ceylon class return true; } // try the interfaces if(lookForInterface(klass, className, alreadyVisited)) return true; // try its superclass Class classAnnotation = klass.getAnnotation(Class.class); if (classAnnotation!=null) { String superclassName = classAnnotation.extendsType(); int i = superclassName.indexOf('<'); if (i>0) { superclassName = superclassName.substring(0, i); } if (!superclassName.isEmpty()) { try { return classSatisfiesInterface( java.lang.Class.forName(superclassName), className, alreadyVisited); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } return classSatisfiesInterface(klass.getSuperclass(), className, alreadyVisited); } private static boolean lookForInterface(java.lang.Class<?> klass, String className, Set<java.lang.Class<?>> alreadyVisited){ if (klass.getName().equals(className)) return true; // did we already visit this type? if(!alreadyVisited.add(klass)) return false; // first see if it satisfies it directly SatisfiedTypes satisfiesAnnotation = klass.getAnnotation(SatisfiedTypes.class); if (satisfiesAnnotation!=null){ for (String satisfiedType : satisfiesAnnotation.value()){ int i = satisfiedType.indexOf('<'); if (i>0) { satisfiedType = satisfiedType.substring(0, i); } try { if (lookForInterface( java.lang.Class.forName(satisfiedType), className, alreadyVisited)) { return true; } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } // now look at this class's interfaces for (java.lang.Class<?> intrface : klass.getInterfaces()){ if (lookForInterface(intrface, className, alreadyVisited)) return true; } // no luck return false; } // Java variadic conversions private static <T> List<T> collectIterable(Iterable<? extends T> sequence) { List<T> list = new LinkedList<T>(); Iterator<? extends T> iterator = sequence.getIterator(); Object o; while((o = iterator.next()) != exhausted.getExhausted()){ list.add((T)o); } return list; } public static boolean[] toBooleanArray(ceylon.language.Iterable<? extends ceylon.language.Boolean> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toBooleanArray((ceylon.language.FixedSized<? extends ceylon.language.Boolean>)sequence); List<ceylon.language.Boolean> list = collectIterable(sequence); boolean[] ret = new boolean[list.size()]; int i=0; for(ceylon.language.Boolean e : list){ ret[i++] = e.booleanValue(); } return ret; } private static boolean[] toBooleanArray(ceylon.language.FixedSized<? extends ceylon.language.Boolean> sequence){ boolean[] ret = new boolean[(int) sequence.getSize()]; int i=0; while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().booleanValue(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.Boolean>)sequence).getRest(); else break; } return ret; } public static byte[] toByteArray(ceylon.language.Iterable<? extends ceylon.language.Integer> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toByteArray((ceylon.language.FixedSized<? extends ceylon.language.Integer>)sequence); List<ceylon.language.Integer> list = collectIterable(sequence); byte[] ret = new byte[list.size()]; int i=0; for(ceylon.language.Integer e : list){ ret[i++] = (byte)e.longValue(); } return ret; } private static byte[] toByteArray(ceylon.language.FixedSized<? extends ceylon.language.Integer> sequence){ byte[] ret = new byte[(int) sequence.getSize()]; int i=0; while(!sequence.getEmpty()){ ret[i++] = (byte) sequence.getFirst().longValue(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.Integer>)sequence).getRest(); else break; } return ret; } public static short[] toShortArray(ceylon.language.Iterable<? extends ceylon.language.Integer> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toShortArray((ceylon.language.FixedSized<? extends ceylon.language.Integer>)sequence); List<ceylon.language.Integer> list = collectIterable(sequence); short[] ret = new short[list.size()]; int i=0; for(ceylon.language.Integer e : list){ ret[i++] = (short)e.longValue(); } return ret; } private static short[] toShortArray(ceylon.language.FixedSized<? extends ceylon.language.Integer> sequence){ short[] ret = new short[(int) sequence.getSize()]; int i=0; while(!sequence.getEmpty()){ ret[i++] = (short) sequence.getFirst().longValue(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.Integer>)sequence).getRest(); else break; } return ret; } public static int[] toIntArray(ceylon.language.Iterable<? extends ceylon.language.Integer> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toIntArray((ceylon.language.FixedSized<? extends ceylon.language.Integer>)sequence); List<ceylon.language.Integer> list = collectIterable(sequence); int[] ret = new int[list.size()]; int i=0; for(ceylon.language.Integer e : list){ ret[i++] = (int)e.longValue(); } return ret; } private static int[] toIntArray(ceylon.language.FixedSized<? extends ceylon.language.Integer> sequence){ int[] ret = new int[(int) sequence.getSize()]; int i=0; while(!sequence.getEmpty()){ ret[i++] = (int) sequence.getFirst().longValue(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.Integer>)sequence).getRest(); else break; } return ret; } public static long[] toLongArray(ceylon.language.Iterable<? extends ceylon.language.Integer> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toLongArray((ceylon.language.FixedSized<? extends ceylon.language.Integer>)sequence); List<ceylon.language.Integer> list = collectIterable(sequence); long[] ret = new long[list.size()]; int i=0; for(ceylon.language.Integer e : list){ ret[i++] = e.longValue(); } return ret; } private static long[] toLongArray(ceylon.language.FixedSized<? extends ceylon.language.Integer> sequence){ long[] ret = new long[(int) sequence.getSize()]; int i=0; while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().longValue(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.Integer>)sequence).getRest(); else break; } return ret; } public static float[] toFloatArray(ceylon.language.Iterable<? extends ceylon.language.Float> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toFloatArray((ceylon.language.FixedSized<? extends ceylon.language.Float>)sequence); List<ceylon.language.Float> list = collectIterable(sequence); float[] ret = new float[list.size()]; int i=0; for(ceylon.language.Float e : list){ ret[i++] = (float)e.doubleValue(); } return ret; } private static float[] toFloatArray(ceylon.language.FixedSized<? extends ceylon.language.Float> sequence){ float[] ret = new float[(int) sequence.getSize()]; int i=0; while(!sequence.getEmpty()){ ret[i++] = (float) sequence.getFirst().doubleValue(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.Float>)sequence).getRest(); else break; } return ret; } public static double[] toDoubleArray(ceylon.language.Iterable<? extends ceylon.language.Float> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toDoubleArray((ceylon.language.FixedSized<? extends ceylon.language.Float>)sequence); List<ceylon.language.Float> list = collectIterable(sequence); double[] ret = new double[list.size()]; int i=0; for(ceylon.language.Float e : list){ ret[i++] = e.doubleValue(); } return ret; } private static double[] toDoubleArray(ceylon.language.FixedSized<? extends ceylon.language.Float> sequence){ double[] ret = new double[(int) sequence.getSize()]; int i=0; while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().doubleValue(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.Float>)sequence).getRest(); else break; } return ret; } public static char[] toCharArray(ceylon.language.Iterable<? extends ceylon.language.Character> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toCharArray((ceylon.language.FixedSized<? extends ceylon.language.Character>)sequence); List<ceylon.language.Character> list = collectIterable(sequence); char[] ret = new char[list.size()]; int i=0; // FIXME: this is invalid and should yield a larger array by splitting chars > 16 bits in two for(ceylon.language.Character e : list){ ret[i++] = (char)e.intValue(); } return ret; } private static char[] toCharArray(ceylon.language.FixedSized<? extends ceylon.language.Character> sequence){ char[] ret = new char[(int) sequence.getSize()]; int i=0; // FIXME: this is invalid and should yield a larger array by splitting chars > 16 bits in two while(!sequence.getEmpty()){ ret[i++] = (char) sequence.getFirst().intValue(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.Character>)sequence).getRest(); else break; } return ret; } public static java.lang.String[] toJavaStringArray(ceylon.language.Iterable<? extends ceylon.language.String> sequence){ if(sequence instanceof ceylon.language.FixedSized) return toJavaStringArray((ceylon.language.FixedSized<? extends ceylon.language.String>)sequence); List<ceylon.language.String> list = collectIterable(sequence); java.lang.String[] ret = new java.lang.String[list.size()]; int i=0; for(ceylon.language.String e : list){ ret[i++] = e.toString(); } return ret; } private static java.lang.String[] toJavaStringArray(ceylon.language.FixedSized<? extends ceylon.language.String> sequence){ java.lang.String[] ret = new java.lang.String[(int) sequence.getSize()]; int i=0; while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst().toString(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends ceylon.language.String>)sequence).getRest(); else break; } return ret; } public static <T> T[] toArray(ceylon.language.FixedSized<? extends T> sequence, T[] ret){ int i=0; while(!sequence.getEmpty()){ ret[i++] = sequence.getFirst(); if(sequence instanceof ceylon.language.Some<?>) sequence = ((ceylon.language.Some<? extends T>)sequence).getRest(); else break; } return ret; } public static <T> T[] toArray(ceylon.language.Iterable<? extends T> iterable, java.lang.Class<T> klass){ List<T> list = collectIterable(iterable); @SuppressWarnings("unchecked") T[] ret = (T[]) java.lang.reflect.Array.newInstance(klass, list.size()); return list.toArray(ret); } }
package org.opendaylight.ovsdb.utils.mdsal.openflow; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Dscp; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Prefix; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType; import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4MatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv6MatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.MetadataBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TcpFlagMatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6MatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.SctpMatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatchBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg0; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg1; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg2; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg3; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg4; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg5; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmNxReg6; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.match.rev140421.NxmOfEthDst; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.ExtensionKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNodesNodeTableFlow; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchNodesNodeTableFlowBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.grouping.ExtensionBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.list.grouping.ExtensionList; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.general.extension.list.grouping.ExtensionListBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchNodesNodeTableFlow; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxAugMatchNodesNodeTableFlowBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxCtStateKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxCtZoneKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg0Key; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg1Key; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg2Key; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg3Key; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg4Key; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg5Key; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg6Key; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxReg7Key; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxTunIdKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmOfTcpDstKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmOfTcpSrcKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmOfUdpDstKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmOfUdpSrcKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.ct.state.grouping.NxmNxCtStateBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.ct.zone.grouping.NxmNxCtZoneBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.reg.grouping.NxmNxRegBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.tun.id.grouping.NxmNxTunIdBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxNspKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.nsp.grouping.NxmNxNspBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.NxmNxNsiKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.nx.nsi.grouping.NxmNxNsiBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.eth.dst.grouping.NxmOfEthDstBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.tcp.src.grouping.NxmOfTcpSrcBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.tcp.dst.grouping.NxmOfTcpDstBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.udp.dst.grouping.NxmOfUdpDstBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.nicira.match.rev140714.nxm.of.udp.src.grouping.NxmOfUdpSrcBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; public class MatchUtils { private static final Logger LOG = LoggerFactory.getLogger(MatchUtils.class); public static final short ICMP_SHORT = 1; public static final short TCP_SHORT = 6; public static final short UDP_SHORT = 17; public static final short SCTP_SHORT = 132; public static final String TCP = "tcp"; public static final String UDP = "udp"; private static final int TCP_SYN = 0x0002; public static final String ICMP = "icmp"; public static final String ICMPV6 = "icmpv6"; public static final short ALL_ICMP = -1; public static final long ETHERTYPE_IPV4 = 0x0800; public static final long ETHERTYPE_IPV6 = 0x86dd; public static final int UNTRACKED_CT_STATE = 0x00; public static final int UNTRACKED_CT_STATE_MASK = 0x20; public static final int TRACKED_EST_CT_STATE = 0x22; public static final int TRACKED_EST_CT_STATE_MASK = 0x22; public static final int TRACKED_NEW_CT_STATE = 0x21; public static final int TRACKED_NEW_CT_STATE_MASK = 0x21; public static final int NEW_CT_STATE = 0x01; public static final int NEW_CT_STATE_MASK = 0x01; /** * Create Ingress Port Match dpidLong, inPort * * @param matchBuilder Map matchBuilder MatchBuilder Object without a match * @param dpidLong Long the datapath ID of a switch/node * @param inPort Long ingress port on a switch * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createInPortMatch(MatchBuilder matchBuilder, Long dpidLong, Long inPort) { NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + inPort); LOG.debug("createInPortMatch() Node Connector ID is - Type=openflow: DPID={} inPort={} ", dpidLong, inPort); matchBuilder.setInPort(NodeConnectorId.getDefaultInstance(ncid.getValue())); matchBuilder.setInPort(ncid); return matchBuilder; } public static MatchBuilder createInPortReservedMatch(MatchBuilder matchBuilder, Long dpidLong, String inPort) { NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + inPort); LOG.debug("createInPortResrevedMatch() Node Connector ID is - Type=openflow: DPID={} inPort={} ", dpidLong, inPort); matchBuilder.setInPort(NodeConnectorId.getDefaultInstance(ncid.getValue())); matchBuilder.setInPort(ncid); return matchBuilder; } /** * Create EtherType Match * * @param matchBuilder Map matchBuilder MatchBuilder Object without a match * @param etherType Long EtherType * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createEtherTypeMatch(MatchBuilder matchBuilder, EtherType etherType) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(etherType)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); return matchBuilder; } public static MatchBuilder createEthSrcDstMatch(MatchBuilder matchBuilder, MacAddress srcMac, MacAddress dstMac) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); if (srcMac != null) { EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder(); ethSourceBuilder.setAddress(srcMac); ethernetMatch.setEthernetSource(ethSourceBuilder.build()); } if (dstMac != null) { EthernetDestinationBuilder ethDestinationBuild = new EthernetDestinationBuilder(); ethDestinationBuild.setAddress(dstMac); ethernetMatch.setEthernetDestination(ethDestinationBuild.build()); } if (matchBuilder.getEthernetMatch() != null && matchBuilder.getEthernetMatch().getEthernetType() != null) { ethernetMatch.setEthernetType(matchBuilder.getEthernetMatch().getEthernetType()); } matchBuilder.setEthernetMatch(ethernetMatch.build()); return matchBuilder; } /** * Create Ethernet Source Match * * @param matchBuilder MatchBuilder Object without a match yet * @param sMacAddr String representing a source MAC * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createEthSrcMatch(MatchBuilder matchBuilder, MacAddress sMacAddr) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder(); ethSourceBuilder.setAddress(sMacAddr); ethernetMatch.setEthernetSource(ethSourceBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); return matchBuilder; } /** * Create Ethernet Destination Match * * @param matchBuilder MatchBuilder Object without a match yet * @param vlanId Integer representing a VLAN ID Integer representing a VLAN ID * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createVlanIdMatch(MatchBuilder matchBuilder, VlanId vlanId, boolean present) { VlanMatchBuilder vlanMatchBuilder = new VlanMatchBuilder(); VlanIdBuilder vlanIdBuilder = new VlanIdBuilder(); vlanIdBuilder.setVlanId(new VlanId(vlanId)); vlanIdBuilder.setVlanIdPresent(present); vlanMatchBuilder.setVlanId(vlanIdBuilder.build()); matchBuilder.setVlanMatch(vlanMatchBuilder.build()); return matchBuilder; } /** * Create Ethernet Destination Match * * @param matchBuilder MatchBuilder Object without a match yet * @param dMacAddr String representing a destination MAC * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createDestEthMatch(MatchBuilder matchBuilder, MacAddress dMacAddr, MacAddress mask) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder(); ethDestinationBuilder.setAddress(dMacAddr); if (mask != null) { ethDestinationBuilder.setMask(mask); } ethernetMatch.setEthernetDestination(ethDestinationBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); return matchBuilder; } /** * Tunnel ID Match Builder * * @param matchBuilder MatchBuilder Object without a match yet * @param tunnelId BigInteger representing a tunnel ID * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createTunnelIDMatch(MatchBuilder matchBuilder, BigInteger tunnelId) { TunnelBuilder tunnelBuilder = new TunnelBuilder(); tunnelBuilder.setTunnelId(tunnelId); matchBuilder.setTunnel(tunnelBuilder.build()); return matchBuilder; } /** * Match ICMP code and type * * @param matchBuilder MatchBuilder Object * @param type short representing an ICMP type * @param code short representing an ICMP code * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createICMPv4Match(MatchBuilder matchBuilder, short type, short code) { // Build the IPv4 Match requied per OVS Syntax IpMatchBuilder ipmatch = new IpMatchBuilder(); ipmatch.setIpProtocol((short) 1); matchBuilder.setIpMatch(ipmatch.build()); // Build the ICMPv4 Match Icmpv4MatchBuilder icmpv4match = new Icmpv4MatchBuilder(); if (type != ALL_ICMP) { icmpv4match.setIcmpv4Type(type); } if (code != ALL_ICMP) { icmpv4match.setIcmpv4Code(code); } matchBuilder.setIcmpv4Match(icmpv4match.build()); return matchBuilder; } /** * Match ICMPv6 code and type * * @param matchBuilder MatchBuilder Object * @param type short representing an ICMP type * @param code short representing an ICMP code * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createICMPv6Match(MatchBuilder matchBuilder, short type, short code) { // Build the IPv6 Match required per OVS Syntax IpMatchBuilder ipmatch = new IpMatchBuilder(); ipmatch.setIpProtocol((short) 58); matchBuilder.setIpMatch(ipmatch.build()); // Build the ICMPv6 Match Icmpv6MatchBuilder icmpv6match = new Icmpv6MatchBuilder(); if (type != ALL_ICMP || code != ALL_ICMP) { icmpv6match.setIcmpv6Type(type); icmpv6match.setIcmpv6Code(code); } matchBuilder.setIcmpv6Match(icmpv6match.build()); return matchBuilder; } /** * @param matchBuilder MatchBuilder Object without a match yet * @param dstip String containing an IPv4 prefix * @return matchBuilder Map Object with a match */ public static MatchBuilder createDstL3IPv4Match(MatchBuilder matchBuilder, Ipv4Prefix dstip) { EthernetMatchBuilder eth = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); eth.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(eth.build()); Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); ipv4match.setIpv4Destination(dstip); matchBuilder.setLayer3Match(ipv4match.build()); return matchBuilder; } /** * @param matchBuilder MatchBuilder Object without a match yet * @param dstip String containing an IPv4 prefix * @return matchBuilder Map Object with a match */ public static MatchBuilder createArpDstIpv4Match(MatchBuilder matchBuilder, Ipv4Prefix dstip) { ArpMatchBuilder arpDstMatch = new ArpMatchBuilder(); arpDstMatch.setArpTargetTransportAddress(dstip) .setArpOp(FlowUtils.ARP_OP_REQUEST); matchBuilder.setLayer3Match(arpDstMatch.build()); return matchBuilder; } /** * @param matchBuilder MatchBuilder Object without a match yet * @param srcip String containing an IPv4 prefix * @return matchBuilder Map Object with a match */ public static MatchBuilder createSrcL3IPv4Match(MatchBuilder matchBuilder, Ipv4Prefix srcip) { EthernetMatchBuilder eth = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); eth.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(eth.build()); Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); ipv4match.setIpv4Source(srcip); matchBuilder.setLayer3Match(ipv4match.build()); return matchBuilder; } /** * Create Source TCP Port Match * * @param matchBuilder MatchBuilder Object without a match yet * @param tcpport Integer representing a source TCP port * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createSetSrcTcpMatch(MatchBuilder matchBuilder, PortNumber tcpport) { EthernetMatchBuilder ethType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethType.build()); IpMatchBuilder ipmatch = new IpMatchBuilder(); ipmatch.setIpProtocol((short) 6); matchBuilder.setIpMatch(ipmatch.build()); TcpMatchBuilder tcpmatch = new TcpMatchBuilder(); tcpmatch.setTcpSourcePort(tcpport); matchBuilder.setLayer4Match(tcpmatch.build()); return matchBuilder; } /** * Create Destination TCP Port Match * * @param matchBuilder MatchBuilder Object without a match yet * @param tcpDstPort Integer representing a destination TCP port * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createSetDstTcpMatch(MatchBuilder matchBuilder, PortNumber tcpDstPort) { EthernetMatchBuilder ethType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethType.build()); IpMatchBuilder ipmatch = new IpMatchBuilder(); ipmatch.setIpProtocol((short) 6); matchBuilder.setIpMatch(ipmatch.build()); TcpMatchBuilder tcpmatch = new TcpMatchBuilder(); tcpmatch.setTcpDestinationPort(tcpDstPort); matchBuilder.setLayer4Match(tcpmatch.build()); return matchBuilder; } /** * Test match for TCP_Flags * * @param matchBuilder MatchBuilder Object without a match yet * @param tcpPort PortNumber representing a destination TCP port * @param tcpFlag int representing a tcp_flag * @return match containing TCP_Flag (), IP Protocol (TCP), TCP_Flag (SYN) * <p> * Defined TCP Flag values in OVS v2.1+ * TCP_FIN 0x001 / TCP_SYN 0x002 / TCP_RST 0x004 * TCP_PSH 0x008 / TCP_ACK 0x010 / TCP_URG 0x020 * TCP_ECE 0x040 / TCP_CWR 0x080 / TCP_NS 0x100 */ public static MatchBuilder createTcpFlagMatch(MatchBuilder matchBuilder, PortNumber tcpPort, int tcpFlag) { // Ethertype match EthernetMatchBuilder ethernetType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetType.build()); // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol((short) 6); matchBuilder.setIpMatch(ipMatch.build()); // TCP Port Match PortNumber dstPort = new PortNumber(tcpPort); TcpMatchBuilder tcpMatch = new TcpMatchBuilder(); tcpMatch.setTcpDestinationPort(dstPort); matchBuilder.setLayer4Match(tcpMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(tcpFlag); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); return matchBuilder; } /** * @return MatchBuilder containing the metadata match values */ public static MatchBuilder createMetadataMatch(MatchBuilder matchBuilder, BigInteger metaData, BigInteger metaDataMask) { // metadata matchbuilder MetadataBuilder metadata = new MetadataBuilder(); metadata.setMetadata(metaData); // Optional metadata mask if (metaDataMask != null) { metadata.setMetadataMask(metaDataMask); } matchBuilder.setMetadata(metadata.build()); return matchBuilder; } /** * Create TCP Port Match * * @param matchBuilder MatchBuilder Object without a match yet * @param ipProtocol Integer representing the IP protocol * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createIpProtocolMatch(MatchBuilder matchBuilder, short ipProtocol) { EthernetMatchBuilder ethType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethType.build()); IpMatchBuilder ipMmatch = new IpMatchBuilder(); if (ipProtocol == TCP_SHORT) { ipMmatch.setIpProtocol(TCP_SHORT); } else if (ipProtocol == UDP_SHORT) { ipMmatch.setIpProtocol(UDP_SHORT); } else if (ipProtocol == ICMP_SHORT) { ipMmatch.setIpProtocol(ICMP_SHORT); } matchBuilder.setIpMatch(ipMmatch.build()); return matchBuilder; } /** * Create TCP Port Match * * @param matchBuilder MatchBuilder Object without a match yet * @param ipProtocol Integer representing the IP protocol * @return matchBuilder Map MatchBuilder Object with a match */ public static MatchBuilder createIpv6ProtocolMatch(MatchBuilder matchBuilder, short ipProtocol) { EthernetMatchBuilder ethType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x86DDL)); ethType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethType.build()); IpMatchBuilder ipMmatch = new IpMatchBuilder(); if (ipProtocol == TCP_SHORT) { ipMmatch.setIpProtocol(TCP_SHORT); } else if (ipProtocol == UDP_SHORT) { ipMmatch.setIpProtocol(UDP_SHORT); } else if (ipProtocol == ICMP_SHORT) { ipMmatch.setIpProtocol(ICMP_SHORT); } matchBuilder.setIpMatch(ipMmatch.build()); return matchBuilder; } /** * Create tcp syn with proto match. * * @param matchBuilder the match builder * @return matchBuilder match builder */ public static MatchBuilder createTcpSynWithProtoMatch(MatchBuilder matchBuilder) { // Ethertype match EthernetMatchBuilder ethernetType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetType.build()); // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol((short) 6); matchBuilder.setIpMatch(ipMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(TCP_SYN); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); return matchBuilder; } /** * Create tcp proto syn match. * * @param matchBuilder the match builder * @return matchBuilder match builder */ public static MatchBuilder createTcpProtoSynMatch(MatchBuilder matchBuilder) { // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol((short) 6); matchBuilder.setIpMatch(ipMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(TCP_SYN); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); return matchBuilder; } /** * Create dmac tcp port with flag match. * * @param matchBuilder the match builder * @param attachedMac the attached mac * @param tcpFlag the tcp flag * @param tunnelID the tunnel iD * @return match containing TCP_Flag (), IP Protocol (TCP), TCP_Flag (SYN) */ public static MatchBuilder createDmacTcpPortWithFlagMatch(MatchBuilder matchBuilder, String attachedMac, Integer tcpFlag, String tunnelID) { return createDmacTcpPortIpSaWithFlagMatch(matchBuilder, attachedMac, tcpFlag, null, tunnelID); } /** * Create dmac ipSa match. * * @param matchBuilder the match builder * @param attachedMac the attached mac * @param ipPrefix the src ipPrefix * @param tunnelID the tunnel iD * @return match containing TCP_Flag (), IP Protocol (TCP), TCP_Flag (SYN), Ip Source Address (IPsa) */ public static MatchBuilder createDmacIpSaMatch( MatchBuilder matchBuilder, String attachedMac, Ipv4Prefix ipPrefix, String tunnelID) { return createDmacTcpPortIpSaWithFlagMatch(matchBuilder, attachedMac, null, ipPrefix, tunnelID); } /** * Create dmac tcp port ipSa with flag match. * * @param matchBuilder the match builder * @param attachedMac the attached mac * @param tcpFlag the tcp flag * @param ipPrefix the src ipPrefix * @param tunnelID the tunnel iD * @return match containing TCP_Flag (), IP Protocol (TCP), TCP_Flag (SYN), Ip Source Address (IPsa) */ public static MatchBuilder createDmacTcpPortIpSaWithFlagMatch( MatchBuilder matchBuilder, String attachedMac, Integer tcpFlag, Ipv4Prefix ipPrefix, String tunnelID) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); if (attachedMac != null) { EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder(); ethDestinationBuilder.setAddress(new MacAddress(attachedMac)); ethernetMatch.setEthernetDestination(ethDestinationBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); } if (tcpFlag != null) { // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol(TCP_SHORT); matchBuilder.setIpMatch(ipMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(tcpFlag); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); } if (tunnelID != null) { TunnelBuilder tunnelBuilder = new TunnelBuilder(); tunnelBuilder.setTunnelId(new BigInteger(tunnelID)); matchBuilder.setTunnel(tunnelBuilder.build()); } if (ipPrefix != null) { Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); ipv4match.setIpv4Source(ipPrefix); matchBuilder.setLayer3Match(ipv4match.build()); } return matchBuilder; } /** * Create dmac tcp syn match. * * @param matchBuilder the match builder * @param attachedMac the attached mac * @param tcpPort the tcp port * @param tcpFlag the tcp flag * @param tunnelID the tunnel iD * @return the match builder */ public static MatchBuilder createDmacTcpSynMatch(MatchBuilder matchBuilder, String attachedMac, PortNumber tcpPort, Integer tcpFlag, String tunnelID) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder(); ethDestinationBuilder.setAddress(new MacAddress(attachedMac)); ethernetMatch.setEthernetDestination(ethDestinationBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol((short) 6); matchBuilder.setIpMatch(ipMatch.build()); // TCP Port Match PortNumber dstPort = new PortNumber(tcpPort); TcpMatchBuilder tcpMatch = new TcpMatchBuilder(); tcpMatch.setTcpDestinationPort(dstPort); matchBuilder.setLayer4Match(tcpMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(tcpFlag); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); TunnelBuilder tunnelBuilder = new TunnelBuilder(); tunnelBuilder.setTunnelId(new BigInteger(tunnelID)); matchBuilder.setTunnel(tunnelBuilder.build()); return matchBuilder; } /** * Create dmac tcp syn dst ip prefix tcp port. * * @param matchBuilder the match builder * @param attachedMac the attached mac * @param tcpPort the tcp port * @param tcpFlag the tcp flag * @param segmentationId the segmentation id * @param dstIp the dst ip * @return the match builder */ public static MatchBuilder createDmacTcpSynDstIpPrefixTcpPort(MatchBuilder matchBuilder, MacAddress attachedMac, PortNumber tcpPort, Integer tcpFlag, String segmentationId, Ipv4Prefix dstIp) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder(); ethDestinationBuilder.setAddress(attachedMac); ethernetMatch.setEthernetDestination(ethDestinationBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); ipv4match.setIpv4Destination(dstIp); matchBuilder.setLayer3Match(ipv4match.build()); // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol(TCP_SHORT); matchBuilder.setIpMatch(ipMatch.build()); // TCP Port Match PortNumber dstPort = new PortNumber(tcpPort); TcpMatchBuilder tcpMatch = new TcpMatchBuilder(); tcpMatch.setTcpDestinationPort(dstPort); matchBuilder.setLayer4Match(tcpMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(tcpFlag); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); TunnelBuilder tunnelBuilder = new TunnelBuilder(); tunnelBuilder.setTunnelId(new BigInteger(segmentationId)); matchBuilder.setTunnel(tunnelBuilder.build()); return matchBuilder; } /** * Create dmac ip tcp syn match. * * @param matchBuilder the match builder * @param dMacAddr the d mac addr * @param mask the mask * @param ipPrefix the ip prefix * @return MatchBuilder containing the metadata match values */ public static MatchBuilder createDmacIpTcpSynMatch(MatchBuilder matchBuilder, MacAddress dMacAddr, MacAddress mask, Ipv4Prefix ipPrefix) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetDestinationBuilder ethDestBuilder = new EthernetDestinationBuilder(); ethDestBuilder.setAddress(dMacAddr); if (mask != null) { ethDestBuilder.setMask(mask); } ethernetMatch.setEthernetDestination(ethDestBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); // Ethertype match EthernetMatchBuilder ethernetType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetType.build()); if (ipPrefix != null) { Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); ipv4match.setIpv4Destination(ipPrefix); matchBuilder.setLayer3Match(ipv4match.build()); } // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol(TCP_SHORT); matchBuilder.setIpMatch(ipMatch.build()); // TCP Flag Match TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(TCP_SYN); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); return matchBuilder; } /** * Create smac tcp syn dst ip prefix tcp port. * * @param matchBuilder the match builder * @param attachedMac the attached mac * @param tcpPort the tcp port * @param tcpFlag the tcp flag * @param segmentationId the segmentation id * @param dstIp the dst ip * @return the match builder */ public static MatchBuilder createSmacTcpSynDstIpPrefixTcpPort(MatchBuilder matchBuilder, MacAddress attachedMac, PortNumber tcpPort, Integer tcpFlag, String segmentationId, Ipv4Prefix dstIp) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder(); ethSourceBuilder.setAddress(attachedMac); ethernetMatch.setEthernetSource(ethSourceBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); ipv4match.setIpv4Destination(dstIp); matchBuilder.setLayer3Match(ipv4match.build()); // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol(TCP_SHORT); matchBuilder.setIpMatch(ipMatch.build()); // TCP Port Match PortNumber dstPort = new PortNumber(tcpPort); TcpMatchBuilder tcpMatch = new TcpMatchBuilder(); tcpMatch.setTcpDestinationPort(dstPort); matchBuilder.setLayer4Match(tcpMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(tcpFlag); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); TunnelBuilder tunnelBuilder = new TunnelBuilder(); tunnelBuilder.setTunnelId(new BigInteger(segmentationId)); matchBuilder.setTunnel(tunnelBuilder.build()); return matchBuilder; } /** * Create smac tcp port with flag match. * * @param matchBuilder the match builder * @param attachedMac the attached mac * @param tcpFlag the tcp flag * @param tunnelID the tunnel iD * @return matchBuilder */ public static MatchBuilder createSmacTcpPortWithFlagMatch(MatchBuilder matchBuilder, String attachedMac, Integer tcpFlag, String tunnelID) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); EthernetSourceBuilder ethSrcBuilder = new EthernetSourceBuilder(); ethSrcBuilder.setAddress(new MacAddress(attachedMac)); ethernetMatch.setEthernetSource(ethSrcBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol(TCP_SHORT); matchBuilder.setIpMatch(ipMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(tcpFlag); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); TunnelBuilder tunnelBuilder = new TunnelBuilder(); tunnelBuilder.setTunnelId(new BigInteger(tunnelID)); matchBuilder.setTunnel(tunnelBuilder.build()); return matchBuilder; } /** * Create smac ip tcp syn match. * * @param matchBuilder the match builder * @param dMacAddr the d mac addr * @param mask the mask * @param ipPrefix the ip prefix * @return MatchBuilder containing the metadata match values */ public static MatchBuilder createSmacIpTcpSynMatch(MatchBuilder matchBuilder, MacAddress dMacAddr, MacAddress mask, Ipv4Prefix ipPrefix) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetSourceBuilder ethSrcBuilder = new EthernetSourceBuilder(); ethSrcBuilder.setAddress(dMacAddr); if (mask != null) { ethSrcBuilder.setMask(mask); } ethernetMatch.setEthernetSource(ethSrcBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); // Ethertype match EthernetMatchBuilder ethernetType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetType.build()); if (ipPrefix != null) { Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); ipv4match.setIpv4Destination(ipPrefix); matchBuilder.setLayer3Match(ipv4match.build()); } // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol(TCP_SHORT); matchBuilder.setIpMatch(ipMatch.build()); // TCP Flag Match TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(TCP_SYN); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); return matchBuilder; } /** * Create smac tcp syn. * * @param matchBuilder the match builder * @param attachedMac the attached mac * @param tcpPort the tcp port * @param tcpFlag the tcp flag * @param tunnelID the tunnel iD * @return the match builder */ public static MatchBuilder createSmacTcpSyn(MatchBuilder matchBuilder, String attachedMac, PortNumber tcpPort, Integer tcpFlag, String tunnelID) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); EthernetSourceBuilder ethSrcBuilder = new EthernetSourceBuilder(); ethSrcBuilder.setAddress(new MacAddress(attachedMac)); ethernetMatch.setEthernetSource(ethSrcBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol((short) 6); matchBuilder.setIpMatch(ipMatch.build()); // TCP Port Match PortNumber dstPort = new PortNumber(tcpPort); TcpMatchBuilder tcpMatch = new TcpMatchBuilder(); tcpMatch.setTcpDestinationPort(dstPort); matchBuilder.setLayer4Match(tcpMatch.build()); TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(tcpFlag); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); TunnelBuilder tunnelBuilder = new TunnelBuilder(); tunnelBuilder.setTunnelId(new BigInteger(tunnelID)); matchBuilder.setTunnel(tunnelBuilder.build()); return matchBuilder; } /** * @return MatchBuilder containing the metadata match values */ public static MatchBuilder createMacSrcIpTcpSynMatch(MatchBuilder matchBuilder, MacAddress dMacAddr, MacAddress mask, Ipv4Prefix ipPrefix) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder(); ethDestinationBuilder.setAddress(dMacAddr); if (mask != null) { ethDestinationBuilder.setMask(mask); } ethernetMatch.setEthernetDestination(ethDestinationBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); // Ethertype match EthernetMatchBuilder ethernetType = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetType.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetType.build()); if (ipPrefix != null) { Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); ipv4match.setIpv4Source(ipPrefix); matchBuilder.setLayer3Match(ipv4match.build()); } // TCP Protocol Match IpMatchBuilder ipMatch = new IpMatchBuilder(); // ipv4 version ipMatch.setIpProtocol(TCP_SHORT); matchBuilder.setIpMatch(ipMatch.build()); // TCP Flag Match TcpFlagMatchBuilder tcpFlagMatch = new TcpFlagMatchBuilder(); tcpFlagMatch.setTcpFlag(TCP_SYN); matchBuilder.setTcpFlagMatch(tcpFlagMatch.build()); return matchBuilder; } /** * Create a DHCP match with port provided. * * @param matchBuilder the match builder * @param srcPort the source port * @param dstPort the destination port * @return the DHCP match */ public static MatchBuilder createDhcpMatch(MatchBuilder matchBuilder, int srcPort, int dstPort) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); IpMatchBuilder ipmatch = new IpMatchBuilder(); ipmatch.setIpProtocol(UDP_SHORT); matchBuilder.setIpMatch(ipmatch.build()); UdpMatchBuilder udpmatch = new UdpMatchBuilder(); udpmatch.setUdpSourcePort(new PortNumber(srcPort)); udpmatch.setUdpDestinationPort(new PortNumber(dstPort)); matchBuilder.setLayer4Match(udpmatch.build()); return matchBuilder; } /** * Create a DHCP match with port provided. * * @param matchBuilder the match builder * @param srcPort the source port * @param dstPort the destination port * @return the DHCP match */ public static MatchBuilder createDhcpv6Match(MatchBuilder matchBuilder, int srcPort, int dstPort) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x86DDL)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); IpMatchBuilder ipmatch = new IpMatchBuilder(); ipmatch.setIpProtocol(UDP_SHORT); matchBuilder.setIpMatch(ipmatch.build()); UdpMatchBuilder udpmatch = new UdpMatchBuilder(); udpmatch.setUdpSourcePort(new PortNumber(srcPort)); udpmatch.setUdpDestinationPort(new PortNumber(dstPort)); matchBuilder.setLayer4Match(udpmatch.build()); return matchBuilder; } /** * Creates DHCP server packet match with DHCP mac address and port. * * @param matchBuilder the matchbuilder * @param dhcpServerMac MAc address of the DHCP server of the subnet * @param srcPort the source port * @param dstPort the destination port * @return the DHCP server match */ public static MatchBuilder createDhcpServerMatch(MatchBuilder matchBuilder, String dhcpServerMac, int srcPort, int dstPort) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder(); ethSourceBuilder.setAddress(new MacAddress(dhcpServerMac)); ethernetMatch.setEthernetSource(ethSourceBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); IpMatchBuilder ipmatch = new IpMatchBuilder(); ipmatch.setIpProtocol(UDP_SHORT); matchBuilder.setIpMatch(ipmatch.build()); UdpMatchBuilder udpmatch = new UdpMatchBuilder(); udpmatch.setUdpSourcePort(new PortNumber(srcPort)); udpmatch.setUdpDestinationPort(new PortNumber(dstPort)); matchBuilder.setLayer4Match(udpmatch.build()); return matchBuilder; } /** * Creates DHCPv6 server packet match with DHCP mac address and port. * * @param matchBuilder the matchbuilder * @param dhcpServerMac MAc address of the DHCP server of the subnet * @param srcPort the source port * @param dstPort the destination port * @return the DHCP server match */ public static MatchBuilder createDhcpv6ServerMatch(MatchBuilder matchBuilder, String dhcpServerMac, int srcPort, int dstPort) { EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder(); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x86DDL)); ethernetMatch.setEthernetType(ethTypeBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder(); ethSourceBuilder.setAddress(new MacAddress(dhcpServerMac)); ethernetMatch.setEthernetSource(ethSourceBuilder.build()); matchBuilder.setEthernetMatch(ethernetMatch.build()); IpMatchBuilder ipmatch = new IpMatchBuilder(); ipmatch.setIpProtocol(UDP_SHORT); matchBuilder.setIpMatch(ipmatch.build()); UdpMatchBuilder udpmatch = new UdpMatchBuilder(); udpmatch.setUdpSourcePort(new PortNumber(srcPort)); udpmatch.setUdpDestinationPort(new PortNumber(dstPort)); matchBuilder.setLayer4Match(udpmatch.build()); return matchBuilder; } /** * Creates a Match with src ip address mac address set. * @param matchBuilder MatchBuilder Object * @param srcip String containing an IPv4 prefix * @param srcMac The source macAddress * @return matchBuilder Map Object with a match */ public static MatchBuilder createSrcL3Ipv4MatchWithMac(MatchBuilder matchBuilder, Ipv4Prefix srcip, MacAddress srcMac) { Ipv4MatchBuilder ipv4MatchBuilder = new Ipv4MatchBuilder(); ipv4MatchBuilder.setIpv4Source(srcip); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); EthernetMatchBuilder eth = new EthernetMatchBuilder(); eth.setEthernetType(ethTypeBuilder.build()); eth.setEthernetSource(new EthernetSourceBuilder() .setAddress(srcMac) .build()); matchBuilder.setLayer3Match(ipv4MatchBuilder.build()); matchBuilder.setEthernetMatch(eth.build()); return matchBuilder; } /** * Creates a Match with src ip address mac address set. * @param matchBuilder MatchBuilder Object * @param srcip String containing an IPv6 prefix * @param srcMac The source macAddress * @return matchBuilder Map Object with a match */ public static MatchBuilder createSrcL3Ipv6MatchWithMac(MatchBuilder matchBuilder, Ipv6Prefix srcip, MacAddress srcMac) { Ipv6MatchBuilder ipv6MatchBuilder = new Ipv6MatchBuilder(); ipv6MatchBuilder.setIpv6Source(srcip); EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x86DDL)); EthernetMatchBuilder eth = new EthernetMatchBuilder(); eth.setEthernetType(ethTypeBuilder.build()); eth.setEthernetSource(new EthernetSourceBuilder() .setAddress(srcMac) .build()); matchBuilder.setLayer3Match(ipv6MatchBuilder.build()); matchBuilder.setEthernetMatch(eth.build()); return matchBuilder; } /** * Creates a ether net match with ether type set to 0x0800L. * @param matchBuilder MatchBuilder Object * @param srcMac The source macAddress * @param dstMac The destination mac address * @return matchBuilder Map Object with a match */ public static MatchBuilder createV4EtherMatchWithType(MatchBuilder matchBuilder,String srcMac, String dstMac) { EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x0800L)); EthernetMatchBuilder eth = new EthernetMatchBuilder(); eth.setEthernetType(ethTypeBuilder.build()); if (null != srcMac) { eth.setEthernetSource(new EthernetSourceBuilder() .setAddress(new MacAddress(srcMac)).build()); } if (null != dstMac) { eth.setEthernetDestination(new EthernetDestinationBuilder() .setAddress(new MacAddress(dstMac)).build()); } matchBuilder.setEthernetMatch(eth.build()); return matchBuilder; } /** * Creates a ether net match with ether type set to 0x86DDL. * @param matchBuilder MatchBuilder Object * @param srcMac The source macAddress * @param dstMac The destination mac address * @return matchBuilder Map Object with a match */ public static MatchBuilder createV6EtherMatchWithType(MatchBuilder matchBuilder,String srcMac, String dstMac) { EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder(); ethTypeBuilder.setType(new EtherType(0x86DDL)); EthernetMatchBuilder eth = new EthernetMatchBuilder(); eth.setEthernetType(ethTypeBuilder.build()); if (null != srcMac) { eth.setEthernetSource(new EthernetSourceBuilder() .setAddress(new MacAddress(srcMac)).build()); } if (null != dstMac) { eth.setEthernetDestination(new EthernetDestinationBuilder() .setAddress(new MacAddress(dstMac)).build()); } matchBuilder.setEthernetMatch(eth.build()); return matchBuilder; } /** * Adds remote Ip prefix to existing match. * @param matchBuilder The match builder * @param sourceIpPrefix The source IP prefix * @param destIpPrefix The destination IP prefix * @return matchBuilder Map Object with a match */ public static MatchBuilder addRemoteIpPrefix(MatchBuilder matchBuilder, Ipv4Prefix sourceIpPrefix,Ipv4Prefix destIpPrefix) { Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder(); if (null != sourceIpPrefix) { ipv4match.setIpv4Source(sourceIpPrefix); } if (null != destIpPrefix) { ipv4match.setIpv4Destination(destIpPrefix); } matchBuilder.setLayer3Match(ipv4match.build()); return matchBuilder; } /** * Adds remote Ipv6 prefix to existing match. * @param matchBuilder The match builder * @param sourceIpPrefix The source IP prefix * @param destIpPrefix The destination IP prefix * @return matchBuilder Map Object with a match */ public static MatchBuilder addRemoteIpv6Prefix(MatchBuilder matchBuilder, Ipv6Prefix sourceIpPrefix,Ipv6Prefix destIpPrefix) { Ipv6MatchBuilder ipv6match = new Ipv6MatchBuilder(); if (null != sourceIpPrefix) { ipv6match.setIpv6Source(sourceIpPrefix); } if (null != destIpPrefix) { ipv6match.setIpv6Destination(destIpPrefix); } matchBuilder.setLayer3Match(ipv6match.build()); return matchBuilder; } /** * Add a DSCP match to an existing match * @param matchBuilder Map matchBuilder MatchBuilder Object with a match * @param dscpValue * @return {@link MatchBuilder} */ public static MatchBuilder addDscp(MatchBuilder matchBuilder, short dscpValue) { createEtherTypeMatch(matchBuilder, new EtherType(ETHERTYPE_IPV4)); return matchBuilder.setIpMatch( new IpMatchBuilder() .setIpDscp(new Dscp(dscpValue)) .build()); } /** * Add a layer4 match to an existing match * * @param matchBuilder Map matchBuilder MatchBuilder Object with a match * @param protocol The layer4 protocol * @param srcPort The src port * @param destPort The destination port * @return matchBuilder Map Object with a match */ public static MatchBuilder addLayer4Match(MatchBuilder matchBuilder, int protocol, int srcPort, int destPort) { IpMatchBuilder ipmatch = new IpMatchBuilder(); if (TCP_SHORT == protocol) { ipmatch.setIpProtocol(TCP_SHORT); TcpMatchBuilder tcpmatch = new TcpMatchBuilder(); if (0 != srcPort) { tcpmatch.setTcpSourcePort(new PortNumber(srcPort)); } if (0 != destPort) { tcpmatch.setTcpDestinationPort(new PortNumber(destPort)); } matchBuilder.setLayer4Match(tcpmatch.build()); } else if (UDP_SHORT == protocol) { ipmatch.setIpProtocol(UDP_SHORT); UdpMatchBuilder udpMatch = new UdpMatchBuilder(); if (0 != srcPort) { udpMatch.setUdpSourcePort(new PortNumber(srcPort)); } if (0 != destPort) { udpMatch.setUdpDestinationPort(new PortNumber(destPort)); } matchBuilder.setLayer4Match(udpMatch.build()); } else if (SCTP_SHORT == protocol) { ipmatch.setIpProtocol(SCTP_SHORT); SctpMatchBuilder sctpMatchBuilder = new SctpMatchBuilder(); if (0 != srcPort) { sctpMatchBuilder.setSctpSourcePort(new PortNumber(srcPort)); } if (0 != destPort) { sctpMatchBuilder.setSctpDestinationPort(new PortNumber(destPort)); } matchBuilder.setLayer4Match(sctpMatchBuilder.build()); } matchBuilder.setIpMatch(ipmatch.build()); return matchBuilder; } /** * Add a layer4 match to an existing match with mask * * @param matchBuilder Map matchBuilder MatchBuilder Object with a match. * @param protocol The layer4 protocol * @param srcPort The src port * @param destPort The destination port * @param mask the mask for the port * @return matchBuilder Map Object with a match */ public static MatchBuilder addLayer4MatchWithMask(MatchBuilder matchBuilder, int protocol, int srcPort, int destPort,int mask) { IpMatchBuilder ipmatch = new IpMatchBuilder(); NxAugMatchNodesNodeTableFlow nxAugMatch = null; GeneralAugMatchNodesNodeTableFlow genAugMatch = null; if (protocol == TCP_SHORT) { ipmatch.setIpProtocol(TCP_SHORT); if (0 != srcPort) { NxmOfTcpSrcBuilder tcpSrc = new NxmOfTcpSrcBuilder(); tcpSrc.setPort(new PortNumber(srcPort)); tcpSrc.setMask(mask); nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder().setNxmOfTcpSrc(tcpSrc.build()).build(); genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmOfTcpSrcKey.class) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch) .build()).build())).build(); } else if (0 != destPort) { NxmOfTcpDstBuilder tcpDst = new NxmOfTcpDstBuilder(); tcpDst.setPort(new PortNumber(destPort)); tcpDst.setMask(mask); nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder() .setNxmOfTcpDst(tcpDst.build()) .build(); genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmOfTcpDstKey.class) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch) .build()).build())).build(); } } else if (UDP_SHORT == protocol) { ipmatch.setIpProtocol(UDP_SHORT); UdpMatchBuilder udpMatch = new UdpMatchBuilder(); if (0 != srcPort) { NxmOfUdpSrcBuilder udpSrc = new NxmOfUdpSrcBuilder(); udpSrc.setPort(new PortNumber(srcPort)); udpSrc.setMask(mask); nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder().setNxmOfUdpSrc(udpSrc.build()).build(); genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmOfUdpSrcKey.class) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch) .build()).build())).build(); } else if (0 != destPort) { NxmOfUdpDstBuilder udpDst = new NxmOfUdpDstBuilder(); udpDst.setPort(new PortNumber(destPort)); udpDst.setMask(mask); nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder() .setNxmOfUdpDst(udpDst.build()) .build(); genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmOfUdpDstKey.class) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch) .build()).build())).build(); } } matchBuilder.setIpMatch(ipmatch.build()); matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, genAugMatch); return matchBuilder; } public static MatchBuilder addCtState(MatchBuilder matchBuilder,int ct_state, int mask) { NxmNxCtStateBuilder ctStateBuilder = new NxmNxCtStateBuilder(); ctStateBuilder.setCtState((long)ct_state); ctStateBuilder.setMask((long)mask); NxAugMatchNodesNodeTableFlow nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder() .setNxmNxCtState(ctStateBuilder.build()) .build(); GeneralAugMatchNodesNodeTableFlow genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmNxCtStateKey.class) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch) .build()).build())).build(); matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, genAugMatch); return matchBuilder; } public static MatchBuilder addCtZone(MatchBuilder matchBuilder,int ct_zone) { NxmNxCtZoneBuilder ctZoneBuilder = new NxmNxCtZoneBuilder(); ctZoneBuilder.setCtZone(ct_zone); NxAugMatchNodesNodeTableFlow nxAugMatch = new NxAugMatchNodesNodeTableFlowBuilder() .setNxmNxCtZone(ctZoneBuilder.build()) .build(); GeneralAugMatchNodesNodeTableFlow genAugMatch = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(ImmutableList.of(new ExtensionListBuilder().setExtensionKey(NxmNxCtZoneKey.class) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, nxAugMatch) .build()).build())).build(); matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, genAugMatch); return matchBuilder; } public static class RegMatch { final Class<? extends NxmNxReg> reg; final Long value; public RegMatch(Class<? extends NxmNxReg> reg, Long value) { super(); this.reg = reg; this.value = value; } public static RegMatch of(Class<? extends NxmNxReg> reg, Long value) { return new RegMatch(reg, value); } } public static MatchBuilder addNxRegMatch(MatchBuilder matchBuilder, RegMatch... matches) { List<ExtensionList> extensions = new ArrayList<>(); for (RegMatch rm : matches) { Class<? extends ExtensionKey> key; if (NxmNxReg0.class.equals(rm.reg)) { key = NxmNxReg0Key.class; } else if (NxmNxReg1.class.equals(rm.reg)) { key = NxmNxReg1Key.class; } else if (NxmNxReg2.class.equals(rm.reg)) { key = NxmNxReg2Key.class; } else if (NxmNxReg3.class.equals(rm.reg)) { key = NxmNxReg3Key.class; } else if (NxmNxReg4.class.equals(rm.reg)) { key = NxmNxReg4Key.class; } else if (NxmNxReg5.class.equals(rm.reg)) { key = NxmNxReg5Key.class; } else if (NxmNxReg6.class.equals(rm.reg)) { key = NxmNxReg6Key.class; } else { key = NxmNxReg7Key.class; } NxAugMatchNodesNodeTableFlow am = new NxAugMatchNodesNodeTableFlowBuilder() .setNxmNxReg(new NxmNxRegBuilder() .setReg(rm.reg) .setValue(rm.value) .build()) .build(); extensions.add(new ExtensionListBuilder() .setExtensionKey(key) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, am) .build()) .build()); } GeneralAugMatchNodesNodeTableFlow m = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(extensions) .build(); matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, m); return matchBuilder; } public static MatchBuilder addNxTunIdMatch(MatchBuilder matchBuilder, int tunId) { NxAugMatchNodesNodeTableFlow am = new NxAugMatchNodesNodeTableFlowBuilder() .setNxmNxTunId(new NxmNxTunIdBuilder() .setValue(BigInteger.valueOf(tunId)) .build()) .build(); GeneralAugMatchNodesNodeTableFlow m = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(ImmutableList.of(new ExtensionListBuilder() .setExtensionKey(NxmNxTunIdKey.class) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, am) .build()) .build())) .build(); matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, m); return matchBuilder; } public static MatchBuilder addNxNspMatch(MatchBuilder matchBuilder, long nsp) { NxAugMatchNodesNodeTableFlow am = new NxAugMatchNodesNodeTableFlowBuilder() .setNxmNxNsp(new NxmNxNspBuilder() .setValue(nsp) .build()) .build(); addExtension(matchBuilder, NxmNxNspKey.class, am); return matchBuilder; } public static MatchBuilder addNxNsiMatch(MatchBuilder matchBuilder, short nsi) { NxAugMatchNodesNodeTableFlow am = new NxAugMatchNodesNodeTableFlowBuilder() .setNxmNxNsi(new NxmNxNsiBuilder() .setNsi(nsi) .build()) .build(); addExtension(matchBuilder, NxmNxNsiKey.class, am); return matchBuilder; } private static void addExtension(MatchBuilder matchBuilder, Class<? extends ExtensionKey> extensionKey, NxAugMatchNodesNodeTableFlow am) { GeneralAugMatchNodesNodeTableFlow existingAugmentations = matchBuilder.getAugmentation(GeneralAugMatchNodesNodeTableFlow.class); List<ExtensionList> extensions = null; if (existingAugmentations != null ) { extensions = existingAugmentations.getExtensionList(); } if (extensions == null) { extensions = Lists.newArrayList(); } extensions.add(new ExtensionListBuilder() .setExtensionKey(extensionKey) .setExtension(new ExtensionBuilder() .addAugmentation(NxAugMatchNodesNodeTableFlow.class, am) .build()) .build()); GeneralAugMatchNodesNodeTableFlow m = new GeneralAugMatchNodesNodeTableFlowBuilder() .setExtensionList(extensions) .build(); matchBuilder.addAugmentation(GeneralAugMatchNodesNodeTableFlow.class, m); } public static EthernetMatch ethernetMatch(MacAddress srcMac, MacAddress dstMac, Long etherType) { EthernetMatchBuilder emb = new EthernetMatchBuilder(); if (srcMac != null) { emb.setEthernetSource(new EthernetSourceBuilder() .setAddress(srcMac) .build()); } if (dstMac != null) { emb.setEthernetDestination(new EthernetDestinationBuilder() .setAddress(dstMac) .build()); } if (etherType != null) { emb.setEthernetType(new EthernetTypeBuilder() .setType(new EtherType(etherType)) .build()); } return emb.build(); } /** * Create ipv4 prefix from ipv4 address, by appending /32 mask * * @param ipv4AddressString the ip address, in string format * @return Ipv4Prefix with ipv4Address and /32 mask */ public static Ipv4Prefix iPv4PrefixFromIPv4Address(String ipv4AddressString) { return new Ipv4Prefix(ipv4AddressString + "/32"); } /** * Create ipv6 prefix from ipv6 address, by appending /128 mask * * @param ipv6AddressString the ip address, in string format * @return Ipv6Prefix with ipv6Address and /128 mask */ public static Ipv6Prefix iPv6PrefixFromIPv6Address(String ipv6AddressString) { return new Ipv6Prefix(ipv6AddressString + "/128"); } /** * Converts port range into a set of masked port ranges. * * @param portMin the strating port of the range. * @param portMax the ending port of the range. * @return the map contianing the port no and their mask. * */ public static Map<Integer,Integer> getLayer4MaskForRange(int portMin, int portMax) { int [] offset = {32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1}; int[] mask = {0x8000,0xC000,0xE000,0xF000,0xF800,0xFC00,0xFE00,0xFF00, 0xFF80,0xFFC0,0xFFE0,0xFFF0,0xFFF8,0xFFFC,0xFFFE,0xFFFF}; int noOfPorts = portMax - portMin + 1; String binaryNoOfPorts = Integer.toBinaryString(noOfPorts); int medianOffset = 16 - binaryNoOfPorts.length(); int medianLength = offset[medianOffset]; int median = 0; for (int tempMedian = 0;tempMedian < portMax;) { tempMedian = medianLength + tempMedian; if (portMin < tempMedian) { median = tempMedian; break; } } Map<Integer,Integer> portMap = new HashMap<Integer,Integer>(); int tempMedian = 0; int currentMedain = median; for (int tempMedianOffset = medianOffset;16 > tempMedianOffset;tempMedianOffset++) { tempMedian = currentMedain - offset[tempMedianOffset]; if (portMin <= tempMedian) { for (;portMin <= tempMedian;) { portMap.put(tempMedian, mask[tempMedianOffset]); currentMedain = tempMedian; tempMedian = tempMedian - offset[tempMedianOffset]; } } } currentMedain = median; for (int tempMedianOffset = medianOffset;16 > tempMedianOffset;tempMedianOffset++) { tempMedian = currentMedain + offset[tempMedianOffset]; if (portMax >= tempMedian - 1) { for (;portMax >= tempMedian - 1;) { portMap.put(currentMedain, mask[tempMedianOffset]); currentMedain = tempMedian; tempMedian = tempMedian + offset[tempMedianOffset]; } } } return portMap; } /** * Return Long that represents OF port for strings where OF is explicitly provided * * @param ofPortIdentifier the string with encoded OF port (example format "OFPort|999") * @return the OFport or null */ public static Long parseExplicitOFPort(String ofPortIdentifier) { if (ofPortIdentifier != null) { String[] pair = ofPortIdentifier.split("\\|"); if ((pair.length > 1) && (pair[0].equalsIgnoreCase("OFPort"))) { return new Long(pair[1]); } } return null; } }
package nl.jpoint.vertx.mod.cluster.command; import io.netty.handler.codec.http.HttpResponseStatus; import nl.jpoint.vertx.mod.cluster.request.ModuleRequest; import nl.jpoint.vertx.mod.cluster.util.MetadataXPathUtil; import nl.jpoint.vertx.mod.cluster.util.PlatformUtils; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vertx.java.core.json.JsonObject; import java.io.IOException; import java.util.Iterator; import java.util.List; public class ResolveSnapshotVersion implements Command<ModuleRequest> { private static final Logger LOG = LoggerFactory.getLogger(ResolveSnapshotVersion.class); private final JsonObject config; private final String logId; public ResolveSnapshotVersion(JsonObject config, String logId) { this.config = config; this.logId = logId; } @Override public JsonObject execute(ModuleRequest request) { List<String> repoList = PlatformUtils.initializeRepoList(logId, config.getString("vertx.home")); CredentialsProvider credsProvider = new BasicCredentialsProvider(); boolean secure = true; if (config.containsField("http.authSecure")) { secure = config.getBoolean("http.authSecure"); LOG.warn("[{} - {}]: Unsecure request to artifact repository.", logId, request.getId()); } credsProvider.setCredentials( new AuthScope(config.getString("http.authUri"),-1), new UsernamePasswordCredentials(config.getString("http.authUser"), config.getString("http.authPass"))); boolean resolved = false; String realSnapshotVersion = null; Iterator<String> it = repoList.iterator(); try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build()) { while (it.hasNext() && !resolved) { String uri = it.next(); if (request.isSnapshot()) { LOG.info("[{} - {}]: Artifact is -SNAPSHOT, trying to parse metadata for last version {}.", logId, request.getId(), request.getModuleId()); realSnapshotVersion = this.retrieveAndParseMetadata(request, httpclient, uri); if (realSnapshotVersion != null) { LOG.info("[{} - {}]: Parsed metadata. Snapshot version is {} ", logId, request.getId(), realSnapshotVersion); resolved = true; } } } } catch (IOException e) { LOG.error("[{} - {}]: Error downloading artifact {}.", logId, request.getId(), request.getArtifactId()); } return new JsonObject().putBoolean("success", resolved).putString("version", realSnapshotVersion); } private String retrieveAndParseMetadata(ModuleRequest request, CloseableHttpClient httpclient, String repoUri) { LOG.error("{}/{}",repoUri, request.getMetadataLocation()); HttpGet getMetadata = new HttpGet(repoUri + "/" + request.getMetadataLocation()); try (CloseableHttpResponse response = httpclient.execute(getMetadata)) { if (response.getStatusLine().getStatusCode() != HttpResponseStatus.OK.code()) { LOG.error("[{} - {}]: No metadata found for module {} with error code {} with request {}", logId, request.getId(), request.getModuleId(), response.getStatusLine().getStatusCode(), getMetadata.getURI()); return null; } byte[] metadata = EntityUtils.toByteArray(response.getEntity()); response.close(); return MetadataXPathUtil.getRealSnapshotVersionFromMetadata(metadata, request); } catch (IOException e) { LOG.error("[{} - {}]: Error while downloading metadata for module {} : {}", logId, request.getId(), request.getModuleId(), e.getMessage()); return null; } } }
package br.eti.rslemos.ad; import static org.mockito.Mockito.*; import static org.testng.Assert.*; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; import java.nio.charset.Charset; import java.util.Iterator; import org.testng.annotations.Test; public class ADParserBehavior { @Test public void shouldParseExt1000() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); checkExtract1000(extracts); } @Test public void shouldParseExt1000Title() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Extract e_1000 = getNext(extracts); Iterator<SentenceSet> e_1000_p = getSentenceSets(e_1000); checkExtract1000Title(e_1000_p); } @Test public void shouldParseExt1000TitleSentence1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Title e_1000_t = getSentenceSet(extracts, 0, 0, Title.class); Iterator<Sentence> e_1000_t_sentences = getSentences(e_1000_t); checkExtract1000TitleSentence1(e_1000_t_sentences); } @Test public void shouldParseExt1000TitleSentence1AnalysisA1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_t_s1_A1 = getAnalysis(extracts, 0, 0, 0, 0); checkAnalysis(e_1000_t_s1_A1, 1); } @Test public void shouldParseExt1000TitleSentence1AnalysisA1RootNode() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_t_s1_A1 = getAnalysis(extracts, 0, 0, 0, 0); TerminalNode e_1000_t_s1_A1_root_t = (TerminalNode) getRootNode(e_1000_t_s1_A1, 0); check_e_1000_t_s1_A1_0(e_1000_t_s1_A1_root_t); } @Test public void shouldParseExt1000Paragraph1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Extract e_1000 = getNext(extracts); Iterator<SentenceSet> e_1000_p = getSentenceSets(e_1000); checkExtract1000Paragraph1(e_1000_p); } @Test public void shouldParseExt1000Paragraph1Sentence1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); SentenceSet e_1000_p1 = getSentenceSet(extracts, 0, 1); Iterator<Sentence> e_1000_p1_sentences = getSentences(e_1000_p1); checkExtract1000Paragraph1Sentence1(e_1000_p1_sentences); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 0, 0, 0); checkAnalysis(e_1000_p1_s2_A1, 1); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNode() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); NonTerminalNode e_1000_p1_s2_A1_root_nt = (NonTerminalNode) getRootNode(e_1000_p1_s2_A1, 0); check_e_1000_p1_s2_A1_0(e_1000_p1_s2_A1_root_nt); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); NonTerminalNode e_1000_p1_s2_A1_root_c1_nt = getNonTerminalChild(e_1000_p1_s2_A1, 0); check_e_1000_p1_s2_A1_0_0(e_1000_p1_s2_A1_root_c1_nt); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); TerminalNode e_1000_p1_s2_A1_root_c1_c1_t = getTerminalChild(e_1000_p1_s2_A1, 0, 0); check_e_1000_p1_s2_A1_0_0_0(e_1000_p1_s2_A1_root_c1_c1_t); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child2() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); TerminalNode e_1000_p1_s2_A1_root_c1_c2_t = getTerminalChild(e_1000_p1_s2_A1, 0, 1); check_e_1000_p1_s2_A1_0_0_1(e_1000_p1_s2_A1_root_c1_c2_t); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child3() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_nt = getNonTerminalChild(e_1000_p1_s2_A1, 0, 2); check_e_1000_p1_s2_A1_0_0_2(e_1000_p1_s2_A1_root_c1_c3_nt); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child3Child1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); TerminalNode e_1000_p1_s2_A1_root_c1_c3_c1_t = getTerminalChild(e_1000_p1_s2_A1, 0, 2, 0); check_e_1000_p1_s2_A1_0_0_2_0(e_1000_p1_s2_A1_root_c1_c3_c1_t); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child3Child2() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_nt = getNonTerminalChild(e_1000_p1_s2_A1, 0, 2, 1); check_e_1000_p1_s2_A1_0_0_2_1(e_1000_p1_s2_A1_root_c1_c3_c2_nt); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child3Child2Child1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_nt = getNonTerminalChild(e_1000_p1_s2_A1, 0, 2, 1, 0); check_e_1000_p1_s2_A1_0_0_2_1_0(e_1000_p1_s2_A1_root_c1_c3_c2_c1_nt); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child3Child2Child1Child1() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_c1_t = getTerminalChild(e_1000_p1_s2_A1, 0, 2, 1, 0, 0); check_e_1000_p1_s2_A1_0_0_2_1_0_0(e_1000_p1_s2_A1_root_c1_c3_c2_c1_c1_t); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child3Child2Child1Child2() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_c2_t = getTerminalChild(e_1000_p1_s2_A1, 0, 2, 1, 0, 1); check_e_1000_p1_s2_A1_0_0_2_1_0_1(e_1000_p1_s2_A1_root_c1_c3_c2_c1_c2_t); } @Test public void shouldParseExt1000Paragraph1Sentence1AnalysisA1RootNodeChild1Child3Child2Child2() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c2_t = getTerminalChild(e_1000_p1_s2_A1, 0, 2, 1, 1); check_e_1000_p1_s2_A1_0_0_2_1_1(e_1000_p1_s2_A1_root_c1_c3_c2_c2_t); } @Test public void shouldParseTitleIntermingledInParagraphs() { Iterator<Extract> extracts = getExtracts("/pt_BR/FlorestaVirgem_CF.txt"); Title e_7_t1 = getSentenceSet(extracts, 6, 1, Title.class); Iterator<Sentence> e_7_t1_sentences = getSentences(e_7_t1); Sentence e_7_t1_s1 = getNext(e_7_t1_sentences); assertEquals(e_7_t1_s1.getText(), "Mais frangos"); } @Test public void shouldParseAnonymousSentenceSet() { Iterator<Extract> extracts = getExtracts("/pt_BR/Amazonia_CF.txt"); Sentence e_0_0_0 = getSentence(extracts, 0, 0, 0); assertEquals(e_0_0_0.getText(), "depois se encontram com a dissidência do grupo, os Bacamarteiros de Pinga Fogo, e a festa continua por muito tempo..."); } @Test public void shouldParseSentenceWithNonNumericRef() { Iterator<Extract> extracts = getExtracts("/pt_BR/Amazonia_CF.txt"); Sentence e_0_0_0 = getSentence(extracts, 0, 0, 0); assertEquals(e_0_0_0.getRef(), "1001.porto-poesia=removeme=-2 a poesia toma porto-alegre=removeme=-1"); } @Test public void shouldIgnoreSFragTag() { Iterator<Extract> extracts = getExtracts("/pt_BR/FlorestaVirgem_CF.txt"); Sentence sentence = getSentence(extracts, 8, 1, 0); assertEquals(sentence.getText(), "«Fatos e Relatos»"); } @Test public void shouldIgnoreLixoTag() { Iterator<Extract> extracts = getExtracts("/pt_BR/Amazonia_CF.txt"); Sentence sentence = getSentence(extracts, 13, 0, 13); assertEquals(sentence.getRef(), "1012.morangos nervososfragmentos de caio f-no-secxxi=removeme=-14"); } @Test public void shouldAllowColonNode() { Iterator<Extract> extracts = getExtracts("/pt_BR/Amazonia_CF.txt"); Analysis e_0_0_5_A1 = getAnalysis(extracts, 0, 0, 5, 0); TerminalNode e_0_0_5_A1_c2 = (TerminalNode) getRootNode(e_0_0_5_A1, 2); assertEquals(e_0_0_5_A1_c2.getText(), ":"); } @Test public void shouldIgnoreRemarksWithSharps() { Iterator<Extract> extracts = getExtracts("/pt_BR/Amazonia_CF.txt"); Sentence e_1_0_4 = getSentence(extracts, 1, 0, 4); assertEquals(e_1_0_4.getRef(), "1002.pesquisa da usp mapeia cultura livre em são paulo-5"); } @Test public void shouldNotRelyOnEmptyLineAtEndOfAnalysis() { Iterator<Extract> extracts = getExtracts("/pt_BR/Amazonia_CF.txt"); Sentence e_3_0_14 = getSentence(extracts, 3, 0, 14); assertEquals(e_3_0_14.getRef(), "1004.heroi exilado e estrangeiro em-seu-proprio=removeme=-pais-15"); } @Test public void shouldAllowEqualsSignOnSentence() { Iterator<Extract> extracts = getExtracts("/pt_BR/Amazonia_CF.txt"); Sentence e_10_0_75 = getSentence(extracts, 10, 0, 75); assertEquals(e_10_0_75.getRef(), "1011.a nova decadência da cultura-pernambucana=removeme=-76"); Iterator<Analysis> e_10_0_75_analyses = getAnalyses(e_10_0_75); Analysis e_10_0_75_A1 = getNext(e_10_0_75_analyses); TerminalNode e_10_0_75_A1_c2 = (TerminalNode) getRootNode(e_10_0_75_A1, 1); assertEquals(e_10_0_75_A1_c2.getText(), "="); } @Test public void shouldSkipRootNodes() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s2_A1 = getAnalysis(extracts, 0, 1, 0, 0); TerminalNode e_1000_p1_s2_A1_2ndroot_t = (TerminalNode) getRootNode(e_1000_p1_s2_A1, 1); check_e_1000_p1_s2_A1_1(e_1000_p1_s2_A1_2ndroot_t); } @Test public void shouldSkipAnalyses() { // actually we don't have more than 1 analysis per sentence // but hasNext should know how to tell this Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Sentence sentence = getSentence(extracts, 0, 0, 0); Iterator<Analysis> analyses = getAnalyses(sentence); getNext(analyses); assertEquals(analyses.hasNext(), false); } @Test public void shouldSkipSentences() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p1_s3_A1 = getAnalysis(extracts, 0, 1, 1, 0); TerminalNode e_1000_p1_s3_A1_root_t = (TerminalNode) getRootNode(e_1000_p1_s3_A1, 0); check_e_1000_p1_s3_A1_0(e_1000_p1_s3_A1_root_t); } @Test public void shouldSkipParagraphs() { Iterator<Extract> extracts = getExtracts("ext_1000.ad"); Analysis e_1000_p2_s4_A1 = getAnalysis(extracts, 0, 2, 0, 0); TerminalNode e_1000_p2_s4_A1_root_c5_c2_c2_c1_t = getTerminalChild(e_1000_p2_s4_A1, 4, 1, 1, 0); check_e_1000_p1_s2_A1_0_4_1_1_0(e_1000_p2_s4_A1_root_c5_c2_c2_c1_t); } @Test public void shouldSkipExtracts () { Iterator<Extract> extracts = getExtracts("ext_1001-1003.ad"); Analysis e_1003_p2_s17_A1 = getAnalysis(extracts, 2, 1, 0, 0); TerminalNode e_1000_p2_s17_A1_root_c3_c2_c7_c2_c3_c2_c2_c3_c3_t = getTerminalChild(e_1003_p2_s17_A1, 2, 1, 6, 1, 2, 1, 1, 2, 2); check_e_1003_p2_s17_A1_2_1_6_1_2_1_1_2_2(e_1000_p2_s17_A1_root_c3_c2_c7_c2_c3_c2_c2_c3_c3_t); } @Test public void shouldPartiallyParseExt1000() { ADCorpus corpus = getCorpus("ext_1000.ad"); ReferenceQueue<ADCorpus> refQueue = new ReferenceQueue<ADCorpus>(); PhantomReference<ADCorpus> ref = new PhantomReference<ADCorpus>(corpus, refQueue); Iterator<Extract> extracts = corpus.extracts(); assertNotNull(extracts); Extract e_1000 = checkExtract1000(extracts); Iterator<SentenceSet> e_1000_p = getSentenceSets(e_1000); Title e_1000_t = checkExtract1000Title(e_1000_p); Iterator<Sentence> e_1000_t_sentences = getSentences(e_1000_t); Sentence e_1000_t_s1 = checkExtract1000TitleSentence1(e_1000_t_sentences); Iterator<Analysis> e_1000_t_s1_analyses = getAnalyses(e_1000_t_s1); Analysis e_1000_t_s1_A1 = getNext(e_1000_t_s1_analyses); checkAnalysis(e_1000_t_s1_A1, 1); TerminalNode e_1000_t_s1_A1_root_t = (TerminalNode) getRootNode(e_1000_t_s1_A1, 0); check_e_1000_t_s1_A1_0(e_1000_t_s1_A1_root_t); assertEquals(e_1000_t_s1_analyses.hasNext(), false); assertEquals(e_1000_t_sentences.hasNext(), false); SentenceSet e_1000_p1 = checkExtract1000Paragraph1(e_1000_p); Iterator<Sentence> e_1000_p1_sentences = getSentences(e_1000_p1); Sentence e_1000_p1_s2 = checkExtract1000Paragraph1Sentence1(e_1000_p1_sentences); Iterator<Analysis> e_1000_p1_s2_analyses = getAnalyses(e_1000_p1_s2); Analysis e_1000_p1_s2_A11 = getNext(e_1000_p1_s2_analyses); checkAnalysis(e_1000_p1_s2_A11, 1); Analysis e_1000_p1_s2_A1 = e_1000_p1_s2_A11; NonTerminalNode e_1000_p1_s2_A1_root_nt = (NonTerminalNode) getRootNode(e_1000_p1_s2_A1, 0); check_e_1000_p1_s2_A1_0(e_1000_p1_s2_A1_root_nt); NonTerminalNode e_1000_p1_s2_A1_root_c1_nt = getNonTerminalChild(e_1000_p1_s2_A1_root_nt, 0); check_e_1000_p1_s2_A1_0_0(e_1000_p1_s2_A1_root_c1_nt); Iterator<Node> e_1000_p1_s2_A1_root_c1_children = getChildren(e_1000_p1_s2_A1_root_c1_nt); TerminalNode e_1000_p1_s2_A1_root_c1_c1_t = getNextChild(e_1000_p1_s2_A1_root_c1_children, TerminalNode.class); check_e_1000_p1_s2_A1_0_0_0(e_1000_p1_s2_A1_root_c1_c1_t); TerminalNode e_1000_p1_s2_A1_root_c1_c2_t = getNextChild(e_1000_p1_s2_A1_root_c1_children, TerminalNode.class); check_e_1000_p1_s2_A1_0_0_1(e_1000_p1_s2_A1_root_c1_c2_t); NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_nt = getNextChild(e_1000_p1_s2_A1_root_c1_children, NonTerminalNode.class); check_e_1000_p1_s2_A1_0_0_2(e_1000_p1_s2_A1_root_c1_c3_nt); Iterator<Node> e_1000_p1_s2_A1_root_c1_c3_children = getChildren(e_1000_p1_s2_A1_root_c1_c3_nt); TerminalNode e_1000_p1_s2_A1_root_c1_c3_c1_t = getNextChild(e_1000_p1_s2_A1_root_c1_c3_children, TerminalNode.class); check_e_1000_p1_s2_A1_0_0_2_0(e_1000_p1_s2_A1_root_c1_c3_c1_t); NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_nt = getNextChild(e_1000_p1_s2_A1_root_c1_c3_children, NonTerminalNode.class); check_e_1000_p1_s2_A1_0_0_2_1(e_1000_p1_s2_A1_root_c1_c3_c2_nt); Iterator<Node> e_1000_p1_s2_A1_root_c1_c3_c2_children = getChildren(e_1000_p1_s2_A1_root_c1_c3_c2_nt); NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_nt = getNextChild(e_1000_p1_s2_A1_root_c1_c3_c2_children, NonTerminalNode.class); check_e_1000_p1_s2_A1_0_0_2_1_0(e_1000_p1_s2_A1_root_c1_c3_c2_c1_nt); Iterator<Node> e_1000_p1_s2_A1_root_c1_c3_c2_c1_children = getChildren(e_1000_p1_s2_A1_root_c1_c3_c2_c1_nt); TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_c1_t = getNextChild(e_1000_p1_s2_A1_root_c1_c3_c2_c1_children, TerminalNode.class); check_e_1000_p1_s2_A1_0_0_2_1_0_0(e_1000_p1_s2_A1_root_c1_c3_c2_c1_c1_t); TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_c2_t = getNextChild(e_1000_p1_s2_A1_root_c1_c3_c2_c1_children, TerminalNode.class); check_e_1000_p1_s2_A1_0_0_2_1_0_1(e_1000_p1_s2_A1_root_c1_c3_c2_c1_c2_t); assertEquals(e_1000_p1_s2_A1_root_c1_c3_c2_c1_children.hasNext(), false); TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c2_t = getNextChild(e_1000_p1_s2_A1_root_c1_c3_c2_children, TerminalNode.class); check_e_1000_p1_s2_A1_0_0_2_1_1(e_1000_p1_s2_A1_root_c1_c3_c2_c2_t); while(extracts.hasNext()) extracts.next(); corpus = null; extracts = null; System.gc(); System.gc(); System.gc(); try { Thread.sleep(2000); } catch (InterruptedException e) { } assertSame(refQueue.poll(), ref); } @Test public void shouldFullyParseExt1000() { ADCorpus corpus = getCorpus("ext_1000.ad"); fullyParse(corpus); } @Test public void shouldFullyParseExt1001() { ADCorpus corpus = getCorpus("ext_1001.ad"); fullyParse(corpus); } @Test public void shouldFullyParseExt1001_1003() { ADCorpus corpus = getCorpus("ext_1001-1003.ad"); fullyParse(corpus); } @Test public void shouldCloseInputReader() throws Throwable { InputStream ext_1000 = ADParserBehavior.class.getResourceAsStream("ext_1000.ad"); Reader ext_1000r = new InputStreamReader(ext_1000, Charset.forName("UTF-8")); Reader ext_1000r_spy = spy(ext_1000r); ADCorpus corpus = new ADCorpus(ext_1000r_spy); fullyParse(corpus); verify(ext_1000r_spy, times(1)).close(); } @Test(enabled = false) public void shouldParseFlorestaVirgem() { ADCorpus corpus = getCorpus("/pt_BR/FlorestaVirgem_CF.txt"); assertEquals(fullyParse(corpus), 12408); } @Test(enabled = false) public void shouldParseAmazonia() { ADCorpus corpus = getCorpus("/pt_BR/Amazonia_CF.txt"); assertEquals(fullyParse(corpus), 4838); } private int fullyParse(ADCorpus corpus) { int f_extracts = 0; for (Extract extract : corpus) { f_extracts++; fullyParse(extract); } return f_extracts; } private void fullyParse(Extract extract) { for (SentenceSet sentenceSet : extract) { fullyParse(sentenceSet); } } private void fullyParse(SentenceSet sentenceSet) { for (Sentence sentence : sentenceSet) { fullyParse(sentence); } } private void fullyParse(Sentence sentence) { for (Analysis analysis : sentence) { fullyParse(analysis); } } private void fullyParse(Analysis analysis) { for (Node node : analysis) { fullyParse(node); } } private void fullyParse(Node node) { for (Node child : node) { fullyParse(child); } } private void check_e_1000_t_s1_A1_0(TerminalNode e_1000_t_s1_A1_root_t) { checkTerminalNode(e_1000_t_s1_A1_root_t, 0, "X", "n", "Consolação", "\"consolação\"", "<act>", "F", "S"); } private void check_e_1000_p1_s2_A1_0(NonTerminalNode e_1000_p1_s2_A1_root_nt) { // STA:fcl checkNonTerminalNode(e_1000_p1_s2_A1_root_nt, 0, "STA", "fcl"); } private void check_e_1000_p1_s2_A1_0_0(NonTerminalNode e_1000_p1_s2_A1_root_c1_nt) { // =S:np checkNonTerminalNode(e_1000_p1_s2_A1_root_c1_nt, 1, "S", "np"); } private void check_e_1000_p1_s2_A1_0_0_0(TerminalNode e_1000_p1_s2_A1_root_c1_c1_t) { // ==DN:pron-indef("o" <artd> DET F P) As checkTerminalNode(e_1000_p1_s2_A1_root_c1_c1_t, 2, "DN", "pron-indef", "As", "\"o\"", "<artd>", "DET", "F", "P"); } private void check_e_1000_p1_s2_A1_0_0_1(TerminalNode e_1000_p1_s2_A1_root_c1_c2_t) { checkTerminalNode(e_1000_p1_s2_A1_root_c1_c2_t, 2, "H", "n", "seleções", "\"seleção\"", "<HH>", "F", "P"); } private void check_e_1000_p1_s2_A1_0_0_2(NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_nt) { // ==DN:pp checkNonTerminalNode(e_1000_p1_s2_A1_root_c1_c3_nt, 2, "DN", "pp"); } private void check_e_1000_p1_s2_A1_0_0_2_0(TerminalNode e_1000_p1_s2_A1_root_c1_c3_c1_t) { checkTerminalNode(e_1000_p1_s2_A1_root_c1_c3_c1_t, 3, "H", "prp", "de", "\"de\"", "<sam->", "<np-close>"); } private void check_e_1000_p1_s2_A1_0_0_2_1(NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_nt) { checkNonTerminalNode(e_1000_p1_s2_A1_root_c1_c3_c2_nt, 3, "DP", "par"); } private void check_e_1000_p1_s2_A1_0_0_2_1_0(NonTerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_nt) { checkNonTerminalNode(e_1000_p1_s2_A1_root_c1_c3_c2_c1_nt, 4, "CJT", "np"); } private void check_e_1000_p1_s2_A1_0_0_2_1_0_0(TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_c1_t) { checkTerminalNode(e_1000_p1_s2_A1_root_c1_c3_c2_c1_c1_t, 5, "DN", "pron-indef", "o", "\"o\"", "<artd>", "<-sam>", "DET", "M", "S"); } private void check_e_1000_p1_s2_A1_0_0_2_1_0_1(TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c1_c2_t) { checkTerminalNode(e_1000_p1_s2_A1_root_c1_c3_c2_c1_c2_t, 5, "H", "prop", "Brasil", "\"Brasil\"", "<cjt-head>", "<civ>", "M", "S"); } private void check_e_1000_p1_s2_A1_0_0_2_1_1(TerminalNode e_1000_p1_s2_A1_root_c1_c3_c2_c2_t) { checkTerminalNodeNoInfo(e_1000_p1_s2_A1_root_c1_c3_c2_c2_t, 4, null, null, ","); } private void check_e_1000_p1_s2_A1_1(TerminalNode e_1000_p1_s2_A1_2ndroot_t) { checkTerminalNodeNoInfo(e_1000_p1_s2_A1_2ndroot_t, 0, null, null, "."); } private void check_e_1000_p1_s3_A1_0(TerminalNode e_1000_p1_s3_A1_root_c1_t) { // X:n("lugar" <L> M P) lugares checkTerminalNode(e_1000_p1_s3_A1_root_c1_t, 0, "X", "n", "lugares", "\"lugar\"", "<L>", "M", "P"); } private void check_e_1000_p1_s2_A1_0_4_1_1_0(TerminalNode e_1000_p2_s4_A1_root_c1_c4_c2_c1_t) { checkTerminalNode(e_1000_p2_s4_A1_root_c1_c4_c2_c1_t, 4, "DN", "pron-indef", "as", "\"o\"", "<artd>", "DET", "F", "P"); } private void check_e_1003_p2_s17_A1_2_1_6_1_2_1_1_2_2(TerminalNode e_1000_p2_s17_A1_root_c3_c2_c7_c2_c3_c2_c2_c3_c3_t) { checkTerminalNode(e_1000_p2_s17_A1_root_c3_c2_c7_c2_c3_c2_c2_c3_c3_t, 9, "DN", "adj", "brasileiro", "\"brasileiro\"", "<nat>", "<np-close>", "M", "S"); } private Sentence checkExtract1000Paragraph1Sentence1(Iterator<Sentence> e_1000_p1_sentences) { // <s id="2" ref="CF1000-2" source="CETENFolha id=1000 cad=Esporte sec=des sem=94a"> // SOURCE: ref="CF1000-2" source="CETENFolha id=1000 cad=Esporte sec=des sem=94a" Sentence e_1000_p1_s2 = getNext(e_1000_p1_sentences); assertNotNull(e_1000_p1_s2); assertEquals(e_1000_p1_s2.getId(), "2"); assertEquals(e_1000_p1_s2.getRef(), "CF1000-2"); assertEquals(e_1000_p1_s2.getSource(), "CETENFolha id=1000 cad=Esporte sec=des sem=94a"); assertEquals(e_1000_p1_s2.getText(), "As seleções do Brasil, Cuba, Coréia do Sul, Angola, Argentina e Egito, eliminadas na primeira fase, participarão do torneio de consolação, em Hamilton, que definirá as colocações do nono ao 16o."); return e_1000_p1_s2; } private SentenceSet checkExtract1000Paragraph1(Iterator<SentenceSet> e_1000_p) { SentenceSet e_1000_p1 = getNext(e_1000_p); assertNotNull(e_1000_p1); return e_1000_p1; } private void checkAnalysis(Analysis A1, int index) { assertNotNull(A1); assertEquals(A1.getIndex(), index); } private Sentence checkExtract1000TitleSentence1(Iterator<Sentence> e_1000_t_sentences) { // <s id="1" ref="CF1000-1" source="CETENFolha id=1000 cad=Esporte sec=des sem=94a"> // SOURCE: ref="CF1000-1" source="CETENFolha id=1000 cad=Esporte sec=des sem=94a" Sentence e_1000_t_s1 = getNext(e_1000_t_sentences); assertNotNull(e_1000_t_s1); assertEquals(e_1000_t_s1.getId(), "1"); assertEquals(e_1000_t_s1.getRef(), "CF1000-1"); assertEquals(e_1000_t_s1.getSource(), "CETENFolha id=1000 cad=Esporte sec=des sem=94a"); assertEquals(e_1000_t_s1.getText(), "Consolação"); return e_1000_t_s1; } private Title checkExtract1000Title(Iterator<SentenceSet> e_1000_p) { Title e_1000_t = getNext(e_1000_p, Title.class); assertNotNull(e_1000_t); return e_1000_t; } private Extract checkExtract1000(Iterator<Extract> extracts) { // <ext id=1000 cad="Esporte" sec="des" sem="94a"> Extract e_1000 = getNext(extracts); assertNotNull(e_1000); assertEquals(e_1000.getAttributes().get("id"), "1000"); assertEquals(e_1000.getAttributes().get("cad"), "Esporte"); assertEquals(e_1000.getAttributes().get("sec"), "des"); assertEquals(e_1000.getAttributes().get("sem"), "94a"); return e_1000; } private ADCorpus getCorpus(String name) { InputStream ext_1000 = ADParserBehavior.class.getResourceAsStream(name); InputStreamReader ext_1000r = new InputStreamReader(ext_1000, Charset.forName("UTF-8")); return new ADCorpus(ext_1000r); } private Iterator<Extract> getExtracts(String name) { ADCorpus corpus = getCorpus(name); Iterator<Extract> extracts = corpus.extracts(); assertNotNull(extracts); return extracts; } private Iterator<Analysis> getAnalyses(Sentence sentence) { Iterator<Analysis> analyses = sentence.analyses(); assertNotNull(analyses); return analyses; } private Iterator<Node> getChildren(Node node) { Iterator<Node> children = node.children(); assertNotNull(children); return children; } private Iterator<SentenceSet> getSentenceSets(Extract extract) { Iterator<SentenceSet> sentenceSets = extract.sentenceSets(); assertNotNull(sentenceSets); return sentenceSets; } private <T> T getNext(Iterator<T> iterator) { assertEquals(iterator.hasNext(), true); return iterator.next(); } private <T> T getNext(Iterator<? super T> iterator, Class<T> clazz) { return cast(clazz, getNext(iterator)); } private Iterator<Sentence> getSentences(SentenceSet sentenceSet) { Iterator<Sentence> sentences = sentenceSet.sentences(); assertNotNull(sentences); return sentences; } private <T extends Node> T getNextChild(Iterator<Node> children, Class<T> clazz) { Node child = getNext(children); assertTrue(clazz.isInstance(child)); return clazz.cast(child); } private void checkTerminalNode(TerminalNode node, int depth, String function, String form, String text, String... info) { checkTerminalNode0(node, depth, function, form, text); String[] node_info = node.getInfo(); assertNotNull(node_info); assertEquals(node_info, info); checkNoChildren(node); } private void checkTerminalNodeNoInfo(TerminalNode node, int depth, String function, String form, String text) { checkTerminalNode0(node, depth, function, form, text); String[] node_info = node.getInfo(); assertNull(node_info); checkNoChildren(node); } private void checkTerminalNode0(TerminalNode node, int depth, String function, String form, String text) { checkNode(node, depth, function, form); assertTrue(node instanceof TerminalNode); TerminalNode node_t = (TerminalNode) node; assertEquals(node_t.getText(), text); } private NonTerminalNode checkNonTerminalNode(Node node, int depth, String function, String form) { checkNode(node, depth, function, form); assertNull(node.getInfo()); assertTrue(node instanceof NonTerminalNode); return (NonTerminalNode) node; } private void checkNode(Node node, int depth, String function, String form) { assertNotNull(node); assertEquals(node.getDepth(), depth); assertEquals(node.getFunction(), function); assertEquals(node.getForm(), form); } private void checkNoChildren(Node node) { Iterator<Node> children = getChildren(node); assertEquals(children.hasNext(), false); } private NonTerminalNode getNonTerminalChild(Node node, int... n) { Node child = getChild(node, n); assertTrue(child instanceof NonTerminalNode); return (NonTerminalNode) child; } private TerminalNode getTerminalChild(Node node, int... n) { Node child = getChild(node, n); assertTrue(child instanceof TerminalNode); return (TerminalNode) child; } private Node getChild(Node node, int... n) { for (int j = 0; j < n.length; j++) { Iterator<Node> children = getChildren(node); for (int i = 0; i < n[j]; i++) getNextChild(children, Node.class); node = getNextChild(children, Node.class); } return node; } private Node getRootNode(Analysis analysis, int n) { Iterator<Node> children = analysis.children(); assertNotNull(children); for (int i = 0; i < n; i++) getNextChild(children, Node.class); return getNextChild(children, Node.class); } private NonTerminalNode getNonTerminalChild(Analysis analysis, int... n) { Node rootNode = getRootNode(analysis, 0); NonTerminalNode e_1000_p1_s2_A1_root_nt = (NonTerminalNode) rootNode; return getNonTerminalChild(e_1000_p1_s2_A1_root_nt, n); } private TerminalNode getTerminalChild(Analysis analysis, int... n) { Node rootNode = getRootNode(analysis, 0); NonTerminalNode e_1000_p1_s2_A1_root_nt = (NonTerminalNode) rootNode; return getTerminalChild(e_1000_p1_s2_A1_root_nt, n); } private Analysis getAnalysis(Iterator<Extract> extracts, int n_extract, int n_paragraph, int n_sentence, int n_analysis) { Sentence sentence = getSentence(extracts, n_extract, n_paragraph, n_sentence); Iterator<Analysis> analyses = getAnalyses(sentence); for (int i = 0; i < n_analysis; i++) getNext(analyses); Analysis analysis = getNext(analyses); return analysis; } private Sentence getSentence(Iterator<Extract> extracts, int n_extract, int n_set, int n_sentence) { SentenceSet sentenceSet = getSentenceSet(extracts, n_extract, n_set); Iterator<Sentence> sentences = getSentences(sentenceSet); for (int i = 0; i < n_sentence; i++) getNext(sentences); Sentence sentence = getNext(sentences); return sentence; } private SentenceSet getSentenceSet(Iterator<Extract> extracts, int n_extract, int n_set) { for (int i = 0; i < n_extract; i++) getNext(extracts); Extract extract = getNext(extracts); Iterator<SentenceSet> sentenceSets = getSentenceSets(extract); for (int i = 0; i < n_set; i++) getNext(sentenceSets); SentenceSet sentenceSet = getNext(sentenceSets); return sentenceSet; } private <T extends SentenceSet> T getSentenceSet(Iterator<Extract> extracts, int n_extract, int n_set, Class<T> clazz) { SentenceSet sentenceSet = getSentenceSet(extracts, n_extract, n_set); return cast(clazz, sentenceSet); } private <T> T cast(Class<T> clazz, Object obj) { assertTrue(clazz.isInstance(obj)); return clazz.cast(obj); } }
package io.spine.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotates a program element (class, method, package etc.) which is internal to Spine, * not part of the public API, and should not be used by users of the framework. * * <p>If you plan to implement an extension of the framework, which is going to be * wired into the framework, you may use the internal parts. Please consult with the Spine * team, as the internal APIs do not have the same stability API guarantee as public ones. * * <p>See {@link SPI} annotation if you plan to write an extension of the framework. * * @author Alexander Yevsyukov * @author Alexander Litus * @see SPI */ @Internal @Retention(RetentionPolicy.SOURCE) @Target({ ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE}) @Documented @Inherited public @interface Internal { }
package org.baderlab.autoannotate.internal.model.io; import java.awt.Color; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.Consumer; import java.util.stream.Collectors; import org.baderlab.autoannotate.internal.BuildProperties; import org.baderlab.autoannotate.internal.labels.LabelMakerFactory; import org.baderlab.autoannotate.internal.labels.LabelMakerManager; import org.baderlab.autoannotate.internal.model.AnnotationSet; import org.baderlab.autoannotate.internal.model.AnnotationSetBuilder; import org.baderlab.autoannotate.internal.model.Cluster; import org.baderlab.autoannotate.internal.model.DisplayOptions; import org.baderlab.autoannotate.internal.model.ModelManager; import org.baderlab.autoannotate.internal.model.NetworkViewSet; import org.baderlab.autoannotate.internal.ui.PanelManager; import org.baderlab.autoannotate.internal.ui.render.AnnotationPersistor; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.model.CyNetworkTableManager; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyRow; import org.cytoscape.model.CyTable; import org.cytoscape.model.CyTableFactory; import org.cytoscape.model.CyTableManager; import org.cytoscape.session.events.SessionAboutToBeSavedEvent; import org.cytoscape.session.events.SessionAboutToBeSavedListener; import org.cytoscape.session.events.SessionLoadedEvent; import org.cytoscape.session.events.SessionLoadedListener; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.model.CyNetworkViewManager; import org.cytoscape.view.presentation.annotations.ShapeAnnotation.ShapeType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; @Singleton public class ModelTablePersistor implements SessionAboutToBeSavedListener, SessionLoadedListener { private static final String CLUSTER_TABLE = BuildProperties.APP_ID + ".cluster"; private static final String ANNOTATION_SET_TABLE = BuildProperties.APP_ID + ".annotationSet"; // AnnotationSet and DisplayOptions properties private static final String ANNOTATION_SET_ID = "annotationSetID", NETWORK_VIEW_SUID = "networkView.SUID", NAME = "name", ACTIVE = "active", LABEL_COLUMN = "labelColumn", BORDER_WIDTH = "borderWidth", OPACITY = "opacity", FONT_SCALE = "fontScale", FONT_SIZE = "fontSize", MIN_FONT_SIZE = "minFontSize", USE_CONSTANT_FONT_SIZE = "useConstantFontSize", SHOW_LABELS = "showLabels", SHOW_CLUSTERS = "showClusters", SHAPE_TYPE = "shapeType", FILL_COLOR = "fillColor", BORDER_COLOR = "borderColor", FONT_COLOR = "fontColor", WORD_WRAP = "wordWrap", WORD_WRAP_LENGTH = "wordWrapLength", LABEL_MAKER_ID = "labelMakerID", LABEL_MAKER_CONTEXT = "labelMakerContext", CREATION_PARAMS = "creationParams"; // Cluster properties private static final String CLUSTER_ID = "clusterID", LABEL = "label", COLLAPSED = "collapsed", NODES_SUID = "nodes.SUID", // .SUID suffix has special meaning to Cytoscape SHAPE_ID = "shapeID", TEXT_ID = "textID", // Added word wrap which means multiple text IDs, but need separate column for backwards compatibility TEXT_ID_ADDITIONAL = "textID_additional", MANUAL = "manual"; @Inject private Provider<AnnotationPersistor> annotationPersistorProvider; @Inject private Provider<ModelManager> modelManagerProvider; @Inject private Provider<PanelManager> panelManagerProvider; @Inject private Provider<LabelMakerManager> labelManagerProvider; @Inject private CyNetworkTableManager networkTableManager; @Inject private CyNetworkManager networkManager; @Inject private CyNetworkViewManager networkViewManager; @Inject private CyTableManager tableManager; @Inject private CyTableFactory tableFactory; private final Logger logger = LoggerFactory.getLogger(ModelTablePersistor.class); @Override public void handleEvent(SessionLoadedEvent e) { importModel(); } @Override public void handleEvent(SessionAboutToBeSavedEvent e) { if(sessionIsActuallySaving()) { // Note, when a new session is loaded the NetworkViewAboutToBeDestroyedListener will clear out the model. exportModel(); } } private boolean sessionIsActuallySaving() { // Hackey fix for bug with STRING app installed StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for(StackTraceElement frame : stack) { String className = frame.getClassName(); if(className.equals("org.cytoscape.task.internal.session.SaveSessionTask") || className.equals("org.cytoscape.task.internal.session.SaveSessionAsTask")) { return true; } } return false; } public void importModel() { boolean imported = false; AnnotationPersistor annotationPersistor = annotationPersistorProvider.get(); annotationPersistor.clearAnnotations(); List<AnnotationSet> activeAnnotationSets = new LinkedList<>(); for(CyNetwork network: networkManager.getNetworkSet()) { Collection<CyNetworkView> networkViews = networkViewManager.getNetworkViews(network); Map<Long,CyNetworkView> networkViewIDs = Maps.uniqueIndex(networkViews, CyNetworkView::getSUID); if(!networkViews.isEmpty()) { // CyNetworkView networkView = networkViews.iterator().next(); // MKTODO what to do about multiple network views? CyTable asTable = networkTableManager.getTable(network, CyNetwork.class, ANNOTATION_SET_TABLE); CyTable clusterTable = networkTableManager.getTable(network, CyNetwork.class, CLUSTER_TABLE); if(asTable != null && clusterTable != null) { try { Collection<AnnotationSet> active = importModel(network, networkViewIDs, asTable, clusterTable); activeAnnotationSets.addAll(active); imported = true; } catch(Exception ex) { ex.printStackTrace(); } } } } for(AnnotationSet as : activeAnnotationSets) { NetworkViewSet nvs = as.getParent(); nvs.select(as); } if(imported) { PanelManager panelManager = panelManagerProvider.get(); panelManager.show(); } } private Collection<AnnotationSet> importModel(CyNetwork network, Map<Long,CyNetworkView> networkViewIDs, CyTable asTable, CyTable clusterTable) { Map<Long,AnnotationSetBuilder> builders = new HashMap<>(); ModelManager modelManager = modelManagerProvider.get(); Set<AnnotationSetBuilder> activeBuilders = new HashSet<>(); // Load AnnotationSets for(CyRow asRow : asTable.getAllRows()) { Long id = asRow.get(ANNOTATION_SET_ID, Long.class); String name = asRow.get(NAME, String.class); List<String> labels = asRow.getList(LABEL_COLUMN, String.class); if(id == null || name == null || labels == null || labels.isEmpty()) { logger.error(String.format("AutoAnnotate.importModel - Missing AnnotationSet attribute: %s:%s, %s:%s, %s:%s\n", ANNOTATION_SET_ID, id, NAME, name, LABEL_COLUMN, labels)); continue; } // This will be null in 3.3 because of #3473, its ok because 3.3 only supports one network view per network Long networkViewID = asRow.get(NETWORK_VIEW_SUID, Long.class); CyNetworkView networkView; if(networkViewID == null && networkViewIDs.size() == 1) { // importing from an older version of AutoAnnotation that didn't support multiple network views networkView = networkViewIDs.values().iterator().next(); logger.warn("AutoAnnotation.importModel - networkViewID not found, assuming " + networkView.getSUID()); } else { networkView = networkViewIDs.get(networkViewID); } if(networkView == null) { logger.error("AutoAnnotate.importModel - Missing Network View ID: " + networkViewID); continue; } NetworkViewSet nvs = modelManager.getNetworkViewSet(networkView); String label = labels.get(0); AnnotationSetBuilder builder = nvs.getAnnotationSetBuilder(name, label); // DisplayOptions safeGet(asRow, BORDER_WIDTH, Integer.class, builder::setBorderWidth); safeGet(asRow, OPACITY, Integer.class, builder::setOpacity); safeGet(asRow, FONT_SCALE, Integer.class, builder::setFontScale); safeGet(asRow, FONT_SIZE, Integer.class, builder::setFontSize); safeGet(asRow, MIN_FONT_SIZE, Integer.class, builder::setMinFontSize); safeGet(asRow, SHAPE_TYPE, String.class, s -> builder.setShapeType(ShapeType.valueOf(s))); safeGet(asRow, SHOW_CLUSTERS, Boolean.class, builder::setShowClusters); safeGet(asRow, SHOW_LABELS, Boolean.class, builder::setShowLabels); safeGet(asRow, USE_CONSTANT_FONT_SIZE, Boolean.class, builder::setUseConstantFontSize); safeGet(asRow, FILL_COLOR, Integer.class, rgb -> builder.setFillColor(new Color(rgb))); safeGet(asRow, BORDER_COLOR, Integer.class, rgb -> builder.setBorderColor(new Color(rgb))); safeGet(asRow, FONT_COLOR, Integer.class, rgb -> builder.setFontColor(new Color(rgb))); safeGet(asRow, WORD_WRAP, Boolean.class, builder::setUseWordWrap); safeGet(asRow, WORD_WRAP_LENGTH, Integer.class, builder::setWordWrapLength); String labelMakerID = asRow.get(LABEL_MAKER_ID, String.class); String serializedContext = asRow.get(LABEL_MAKER_CONTEXT, String.class); builder.onCreate(as -> { LabelMakerManager labelMakerManager = labelManagerProvider.get(); LabelMakerFactory factory = labelMakerManager.getFactory(labelMakerID); if(factory != null) { Object context = factory.deserializeContext(serializedContext); if(context != null) { labelMakerManager.register(as, factory, context); } } }); String cpJson = asRow.get(CREATION_PARAMS, String.class); if(cpJson != null) { Gson gson = new Gson(); Type type = new TypeToken<List<CreationParameter>>(){}.getType(); try { List<CreationParameter> creationParams = gson.fromJson(cpJson, type); creationParams.forEach(builder::addCreationParam); } catch (Exception e) { logger.error(e.getMessage(), e); } } Boolean active = asRow.get(ACTIVE, Boolean.class); if(Boolean.TRUE.equals(active)) // null safe activeBuilders.add(builder); builders.put(id, builder); } // Load Clusters for(CyRow clusterRow : clusterTable.getAllRows()) { Long asId = clusterRow.get(ANNOTATION_SET_ID, Long.class); if(asId == null || !builders.containsKey(asId)) { logger.error(String.format("AutoAnnotate.importModel - Cluster can't be imported because AnnotationSet ID is invalid: " + asId)); continue; } String label = clusterRow.get(LABEL, String.class); Boolean collapsed = clusterRow.get(COLLAPSED, Boolean.class); List<Long> nodeSUIDS = clusterRow.getList(NODES_SUID, Long.class); if(label == null || collapsed == null || nodeSUIDS == null) { logger.error(String.format("AutoAnnotate.importModel - Cluster attribute not found: %s:%s, %s:%s, %s:%s\n", LABEL, label, COLLAPSED, collapsed, NODES_SUID, nodeSUIDS)); continue; } // This column is optional Boolean manual = clusterRow.get(MANUAL, Boolean.class); if(manual == null) { manual = false; } Optional<UUID> shapeID = safeUUID(clusterRow.get(SHAPE_ID, String.class)); Optional<UUID> textID = safeUUID(clusterRow.get(TEXT_ID, String.class)); Optional<List<UUID>> textIDAdditional = safeUUID(clusterRow.getList(TEXT_ID_ADDITIONAL, String.class)); List<CyNode> nodes = nodeSUIDS.stream().map(network::getNode).collect(Collectors.toList()); AnnotationPersistor annotationPersistor = annotationPersistorProvider.get(); AnnotationSetBuilder builder = builders.get(asId); builder.addCluster(nodes, label, collapsed, manual, cluster -> { annotationPersistor.restoreCluster(cluster, shapeID, textID, textIDAdditional); }); } List<AnnotationSet> activeSets = new ArrayList<>(activeBuilders.size()); // Build Model for(AnnotationSetBuilder builder : builders.values()) { AnnotationSet as = builder.build(); // create the AnnotationSet in the model if(activeBuilders.contains(builder)) { activeSets.add(as); } } return activeSets; } private class Ids { long asId = 0; long clusterId = 0; } public void exportModel() { for(CyNetwork network: networkManager.getNetworkSet()) { CyTable asTable = createAnnotationSetTable(network); CyTable clusterTable = createClusterTable(network); Ids ids = new Ids(); Collection<CyNetworkView> networkViews = networkViewManager.getNetworkViews(network); for(CyNetworkView networkView : networkViews) { Optional<NetworkViewSet> nvs = modelManagerProvider.get().getExistingNetworkViewSet(networkView); if(nvs.isPresent()) { try { exportModel(nvs.get(), asTable, clusterTable, ids); }catch(Exception ex) { ex.printStackTrace(); } continue; } } } } private void exportModel(NetworkViewSet nvs, CyTable asTable, CyTable clusterTable, Ids ids) { AnnotationPersistor annotationPersistor = annotationPersistorProvider.get(); for(AnnotationSet as : nvs.getAnnotationSets()) { CyRow asRow = asTable.getRow(ids.asId); asRow.set(NAME, as.getName()); asRow.set(NETWORK_VIEW_SUID, as.getParent().getNetworkView().getSUID()); asRow.set(LABEL_COLUMN, Arrays.asList(as.getLabelColumn())); // may want to support multiple label columns in the future asRow.set(ACTIVE, as.isActive()); DisplayOptions disp = as.getDisplayOptions(); asRow.set(SHAPE_TYPE, disp.getShapeType().name()); asRow.set(SHOW_CLUSTERS, disp.isShowClusters()); asRow.set(SHOW_LABELS, disp.isShowLabels()); asRow.set(USE_CONSTANT_FONT_SIZE, disp.isUseConstantFontSize()); asRow.set(FONT_SCALE, disp.getFontScale()); asRow.set(FONT_SIZE, disp.getFontSize()); asRow.set(MIN_FONT_SIZE, disp.getMinFontSizeForScale()); asRow.set(OPACITY, disp.getOpacity()); asRow.set(BORDER_WIDTH, disp.getBorderWidth()); asRow.set(FILL_COLOR, disp.getFillColor().getRGB()); asRow.set(BORDER_COLOR, disp.getBorderColor().getRGB()); asRow.set(FONT_COLOR, disp.getFontColor().getRGB()); asRow.set(WORD_WRAP, disp.isUseWordWrap()); asRow.set(WORD_WRAP_LENGTH, disp.getWordWrapLength()); LabelMakerManager labelMakerManager = labelManagerProvider.get(); LabelMakerFactory labelFactory = labelMakerManager.getFactory(as); Object context = labelMakerManager.getContext(as, labelFactory); if(labelFactory != null && context != null) { String serializedContext = labelFactory.serializeContext(context); asRow.set(LABEL_MAKER_ID, labelFactory.getID()); asRow.set(LABEL_MAKER_CONTEXT, serializedContext); } Gson gson = new Gson(); String cpJson = gson.toJson(as.getCreationParameters()); asRow.set(CREATION_PARAMS, cpJson); for(Cluster cluster : as.getClusters()) { CyRow clusterRow = clusterTable.getRow(ids.clusterId); clusterRow.set(LABEL, cluster.getLabel()); clusterRow.set(COLLAPSED, cluster.isCollapsed()); clusterRow.set(MANUAL, cluster.isManual()); clusterRow.set(NODES_SUID, cluster.getNodes().stream().map(CyNode::getSUID).collect(Collectors.toList())); clusterRow.set(ANNOTATION_SET_ID, ids.asId); Optional<UUID> shapeID = annotationPersistor.getShapeID(cluster); clusterRow.set(SHAPE_ID, shapeID.map(UUID::toString).orElse(null)); Optional<List<UUID>> optTextIDs = annotationPersistor.getTextIDs(cluster); if(optTextIDs.map(List::size).orElse(0) > 0) { List<UUID> textIds = optTextIDs.get(); String firstId = textIds.get(0).toString(); List<String> rest = textIds.subList(1, textIds.size()).stream().map(UUID::toString).collect(Collectors.toList()); clusterRow.set(TEXT_ID, firstId); clusterRow.set(TEXT_ID_ADDITIONAL, rest); } ids.clusterId++; } ids.asId++; } } private CyTable createTable(CyNetwork network, String namespace, String id) { CyTable existingTable = networkTableManager.getTable(network, CyNetwork.class, namespace); if(existingTable != null) { tableManager.deleteTable(existingTable.getSUID()); networkTableManager.removeTable(network, CyNetwork.class, namespace); } CyTable table = tableFactory.createTable(namespace, id, Long.class, false, false); networkTableManager.setTable(network, CyNetwork.class, namespace, table); tableManager.addTable(table); return table; } private CyTable createAnnotationSetTable(CyNetwork network) { CyTable table = createTable(network, ANNOTATION_SET_TABLE, ANNOTATION_SET_ID); createColumn(table, NAME, String.class); createColumn(table, NETWORK_VIEW_SUID, Long.class); createListColumn(table, LABEL_COLUMN, String.class); createColumn(table, ACTIVE, Boolean.class); createColumn(table, SHAPE_TYPE, String.class); createColumn(table, SHOW_CLUSTERS, Boolean.class); createColumn(table, SHOW_LABELS, Boolean.class); createColumn(table, USE_CONSTANT_FONT_SIZE, Boolean.class); createColumn(table, FONT_SCALE, Integer.class); createColumn(table, FONT_SIZE, Integer.class); createColumn(table, MIN_FONT_SIZE, Integer.class); createColumn(table, OPACITY, Integer.class); createColumn(table, BORDER_WIDTH, Integer.class); createColumn(table, FILL_COLOR, Integer.class); // store as RGB int value createColumn(table, BORDER_COLOR, Integer.class); createColumn(table, FONT_COLOR, Integer.class); createColumn(table, WORD_WRAP, Boolean.class); createColumn(table, WORD_WRAP_LENGTH, Integer.class); createColumn(table, LABEL_MAKER_ID, String.class); createColumn(table, LABEL_MAKER_CONTEXT, String.class); createColumn(table, CREATION_PARAMS, String.class); return table; } private CyTable createClusterTable(CyNetwork network) { CyTable table = createTable(network, CLUSTER_TABLE, CLUSTER_ID); createColumn(table, LABEL, String.class); createColumn(table, COLLAPSED, Boolean.class); createColumn(table, MANUAL, Boolean.class); createListColumn(table, NODES_SUID, Long.class); createColumn(table, ANNOTATION_SET_ID, Long.class); createColumn(table, SHAPE_ID, String.class); createColumn(table, TEXT_ID, String.class); createListColumn(table, TEXT_ID_ADDITIONAL, String.class); return table; } private static void createColumn(CyTable table, String name, Class<?> type) { if(table.getColumn(name) == null) table.createColumn(name, type, true); } private static void createListColumn(CyTable table, String name, Class<?> type) { if(table.getColumn(name) == null) table.createListColumn(name, type, true); } private static Optional<UUID> safeUUID(String s) { if(s == null) return Optional.empty(); try { return Optional.of(UUID.fromString(s)); } catch(IllegalArgumentException e) { return Optional.empty(); } } private static Optional<List<UUID>> safeUUID(List<String> ss) { if(ss == null || ss.isEmpty()) return Optional.empty(); try { List<UUID> uuids = new ArrayList<>(ss.size()); for(String s : ss) { uuids.add(UUID.fromString(s)); } return Optional.of(uuids); } catch(IllegalArgumentException e) { return Optional.empty(); } } private static <T> void safeGet(CyRow row, String column, Class<T> type, Consumer<T> consumer) { try { T value = row.get(column, type); if(value == null) { System.err.println("AutoAnnotate.importModel - Can't find display option for " + column); } else { consumer.accept(value); } } catch(ClassCastException e) { System.err.println("AutoAnnotate.importModel - Error loading display options for " + column); e.printStackTrace(); } } }
package com.censoredsoftware.demigods.engine.command; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.censoredsoftware.censoredlib.helper.WrappedCommand; import com.censoredsoftware.censoredlib.language.Symbol; import com.censoredsoftware.censoredlib.util.Maps2; import com.censoredsoftware.censoredlib.util.Strings; import com.censoredsoftware.censoredlib.util.Titles; import com.censoredsoftware.demigods.engine.Demigods; import com.censoredsoftware.demigods.engine.battle.Battle; import com.censoredsoftware.demigods.engine.data.TributeManager; import com.censoredsoftware.demigods.engine.deity.Alliance; import com.censoredsoftware.demigods.engine.language.Translation; import com.censoredsoftware.demigods.engine.player.DCharacter; import com.censoredsoftware.demigods.engine.player.DPlayer; import com.censoredsoftware.demigods.engine.util.Messages; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class GeneralCommands extends WrappedCommand { public GeneralCommands() { super(Demigods.PLUGIN, false); } @Override public Set<String> getCommands() { return Sets.newHashSet("check", "owner", "binds", "leaderboard", "alliance", "values", "names"); } @Override public boolean processCommand(CommandSender sender, Command command, String[] args) { if(command.getName().equalsIgnoreCase("check")) return check(sender); else if(command.getName().equalsIgnoreCase("owner")) return owner(sender, args); else if(command.getName().equalsIgnoreCase("alliance")) return alliance(sender, args); else if(command.getName().equalsIgnoreCase("binds")) return binds(sender); else if(command.getName().equalsIgnoreCase("leaderboard")) return leaderboard(sender); else if(command.getName().equalsIgnoreCase("values")) return values(sender); else if(command.getName().equalsIgnoreCase("names")) return names(sender); return false; } private boolean check(CommandSender sender) { Player player = (Player) sender; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character == null) { player.sendMessage(ChatColor.RED + "You are nothing but a mortal. You have no worthy statistics."); return true; } // Define variables int kills = character.getKillCount(); int deaths = character.getDeathCount(); String charName = character.getName(); String deity = character.getDeity().getName(); Alliance alliance = character.getAlliance(); int favor = character.getMeta().getFavor(); int maxFavor = character.getMeta().getMaxFavor(); int ascensions = character.getMeta().getAscensions(); int skillPoints = character.getMeta().getSkillPoints(); ChatColor deityColor = character.getDeity().getColor(); ChatColor favorColor = Strings.getColor(character.getMeta().getFavor(), character.getMeta().getMaxFavor()); // Set player status String status = ChatColor.YELLOW + "Ready."; if(!character.canPvp()) status = ChatColor.DARK_AQUA + "Safe."; else if(Battle.Util.isInBattle(character)) status = ChatColor.GOLD + "In battle."; // Send the user their info via chat Messages.tagged(sender, "Player Check"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Character: " + deityColor + charName); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Deity: " + deityColor + deity + ChatColor.WHITE + " of the " + ChatColor.GOLD + alliance.getName() + "s"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Favor: " + favorColor + favor + ChatColor.GRAY + " (of " + ChatColor.GREEN + maxFavor + ChatColor.GRAY + ")"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Ascensions: " + ChatColor.GREEN + ascensions); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Available Skill Points: " + ChatColor.GREEN + skillPoints); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Kills: " + ChatColor.GREEN + kills + ChatColor.WHITE + " / Deaths: " + ChatColor.RED + deaths); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Status: " + status); return true; } private boolean owner(CommandSender sender, String[] args) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); Player player = (Player) sender; if(args.length < 1) { player.sendMessage(ChatColor.RED + "You must select a character."); player.sendMessage(ChatColor.RED + "/owner <character>"); return true; } DCharacter charToCheck = DCharacter.Util.getCharacterByName(args[0]); if(charToCheck == null) player.sendMessage(ChatColor.RED + "That character doesn't exist."); else player.sendMessage(charToCheck.getDeity().getColor() + charToCheck.getName() + ChatColor.YELLOW + " belongs to " + charToCheck.getOfflinePlayer().getName() + "."); return true; } private boolean alliance(CommandSender sender, String[] args) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); Player player = (Player) sender; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character == null) { player.sendMessage(Demigods.LANGUAGE.getText(Translation.Text.DISABLED_MORTAL)); return true; } if(args.length < 1) { character.chatWithAlliance("..."); return true; } else character.chatWithAlliance(Joiner.on(" ").join(args)); return true; } private boolean binds(CommandSender sender) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); // Define variables Player player = (Player) sender; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character != null && !character.getMeta().getBinds().isEmpty()) { player.sendMessage(ChatColor.YELLOW + Titles.chatTitle("Currently Bound Abilities")); player.sendMessage(" "); // Get the binds and display info for(Map.Entry<String, Object> entry : character.getMeta().getBinds().entrySet()) player.sendMessage(ChatColor.GREEN + " " + StringUtils.capitalize(entry.getKey().toLowerCase()) + ChatColor.GRAY + " is bound to " + (Strings.beginsWithVowel(entry.getValue().toString()) ? "an " : "a ") + ChatColor.ITALIC + Strings.beautify(entry.getValue().toString()).toLowerCase() + ChatColor.GRAY + "."); player.sendMessage(" "); } else player.sendMessage(ChatColor.RED + "You currently have no ability binds."); return true; } private boolean leaderboard(CommandSender sender) { // Define variables List<DCharacter> characters = Lists.newArrayList(DCharacter.Util.getAllUsable()); Map<UUID, Double> scores = Maps.newLinkedHashMap(); for(int i = 0; i < characters.size(); i++) { DCharacter character = characters.get(i); double score = character.getKillCount() - character.getDeathCount(); if(score > 0) scores.put(character.getId(), score); } // Sort rankings scores = Maps2.sortByValue(scores, false); // Print info Messages.tagged(sender, "Leaderboard"); sender.sendMessage(" "); sender.sendMessage(ChatColor.GRAY + " Rankings are determined by kills and deaths."); sender.sendMessage(" "); int length = characters.size() > 15 ? 16 : characters.size() + 1; List<Map.Entry<UUID, Double>> list = Lists.newArrayList(scores.entrySet()); int count = 0; for(int i = list.size() - 1; i >= 0; i { count++; Map.Entry<UUID, Double> entry = list.get(i); if(count >= length) break; DCharacter character = DCharacter.Util.load(entry.getKey()); sender.sendMessage(ChatColor.GRAY + " " + ChatColor.RESET + count + ". " + character.getDeity().getColor() + character.getName() + ChatColor.RESET + ChatColor.GRAY + " (" + character.getPlayerName() + ") " + ChatColor.RESET + "Kills: " + ChatColor.GREEN + character.getKillCount() + ChatColor.WHITE + " / Deaths: " + ChatColor.RED + character.getDeathCount()); } sender.sendMessage(" "); return true; } private boolean values(CommandSender sender) { // Define variables Player player = (Player) sender; int count = 0; if(TributeManager.getTributeValuesMap().isEmpty()) { sender.sendMessage(ChatColor.RED + "There are currently no tributes on record."); return true; } // Send header Messages.tagged(sender, "Current High Value Tributes"); sender.sendMessage(" "); for(Map.Entry<Material, Integer> entry : Maps2.sortByValue(TributeManager.getTributeValuesMap(), true).entrySet()) { // Handle count if(count >= 10) break; count++; // Display value sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.YELLOW + Strings.beautify(entry.getKey().name()) + ChatColor.GRAY + " (currently worth " + ChatColor.GREEN + entry.getValue() + ChatColor.GRAY + " per item)"); } sender.sendMessage(" "); sender.sendMessage(ChatColor.ITALIC + "Values are constantly changing based on how players"); sender.sendMessage(ChatColor.ITALIC + "tribute, so check back often!"); if(player.getItemInHand() != null && !player.getItemInHand().getType().equals(Material.AIR)) { sender.sendMessage(" "); sender.sendMessage(ChatColor.GRAY + "The " + (player.getItemInHand().getAmount() == 1 ? "items in your hand are" : "item in your hand is") + " worth " + ChatColor.GREEN + TributeManager.getValue(player.getItemInHand()) + ChatColor.GRAY + " in total."); } return true; } private boolean names(CommandSender sender) { // Print info Messages.tagged(sender, "Online Player Names"); sender.sendMessage(" "); sender.sendMessage(ChatColor.GRAY + " " + ChatColor.UNDERLINE + "Immortals:"); sender.sendMessage(" "); // Characters for(DCharacter character : DCharacter.Util.getOnlineCharacters()) sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + character.getDeity().getColor() + character.getName() + ChatColor.GRAY + " is owned by " + ChatColor.WHITE + character.getPlayerName() + ChatColor.GRAY + "."); sender.sendMessage(" "); Set<Player> mortals = DPlayer.Util.getOnlineMortals(); if(mortals.isEmpty()) return true; sender.sendMessage(ChatColor.GRAY + " " + ChatColor.UNDERLINE + "Mortals:"); sender.sendMessage(" "); // Mortals for(Player mortal : mortals) sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.WHITE + mortal.getDisplayName() + "."); sender.sendMessage(" "); return true; } }
package com.tradle.react; import android.os.AsyncTask; import android.support.annotation.Nullable; import android.util.Base64; import android.util.Pair; import com.facebook.react.bridge.Callback; import java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.SocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static com.tradle.react.UdpSenderTask.OnDataSentListener; /** * Client class that wraps a sender and a receiver for UDP data. */ public final class UdpSocketClient implements UdpReceiverTask.OnDataReceivedListener, OnDataSentListener { private final OnDataReceivedListener mReceiverListener; private final OnRuntimeExceptionListener mExceptionListener; private final boolean mReuseAddress; private UdpReceiverTask mReceiverTask; private final Map<UdpSenderTask, Callback> mPendingSends; private DatagramSocket mSocket; private UdpSocketClient(Builder builder) { this.mReceiverListener = builder.receiverListener; this.mExceptionListener = builder.exceptionListener; this.mReuseAddress = builder.reuse; this.mPendingSends = new ConcurrentHashMap<UdpSenderTask, Callback>(); } /** * Checks to see if client part of a multi-cast group. * @return boolean true IF the socket is part of a multi-cast group. */ public boolean isMulticast() { return (mSocket != null && mSocket instanceof MulticastSocket); } public void bind(Integer port, @Nullable String address) throws IOException { mSocket = new DatagramSocket(null); mReceiverTask = new UdpReceiverTask(); SocketAddress socketAddress; if (address != null) { socketAddress = new InetSocketAddress(InetAddress.getByName(address), port); } else { socketAddress = new InetSocketAddress(port); } mSocket.setReuseAddress(mReuseAddress); mSocket.bind(socketAddress); // begin listening for data in the background mReceiverTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Pair<DatagramSocket, UdpReceiverTask.OnDataReceivedListener>(mSocket, this)); } public void addMembership(String address) throws UnknownHostException, IOException, IllegalStateException { if (null == mSocket || !mSocket.isBound()) { throw new IllegalStateException("Socket is not bound."); } if (!(mSocket instanceof MulticastSocket)) { // cancel the current receiver task if (mReceiverTask != null) { mReceiverTask.cancel(true); } mReceiverTask = new UdpReceiverTask(); // tear down the DatagramSocket, and rebuild as a MulticastSocket final int port = mSocket.getLocalPort(); mSocket.close(); mSocket = new MulticastSocket(port); // begin listening for data in the background mReceiverTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Pair<DatagramSocket, UdpReceiverTask.OnDataReceivedListener>(mSocket, this)); } ((MulticastSocket) mSocket).joinGroup(InetAddress.getByName(address)); } /** * Removes this socket from the specified multicast group. * * @param address the multicast group to leave * @throws UnknownHostException * @throws IOException */ public void dropMembership(String address) throws UnknownHostException, IOException { if (mSocket instanceof MulticastSocket) { ((MulticastSocket) mSocket).leaveGroup(InetAddress.getByName(address)); } } public void send(String base64String, Integer port, String address, @Nullable Callback callback) throws UnknownHostException, IllegalStateException, IOException { if (null == mSocket || !mSocket.isBound()) { throw new IllegalStateException("Socket is not bound."); } byte[] data = Base64.decode(base64String, Base64.NO_WRAP); UdpSenderTask task = new UdpSenderTask(mSocket, this); UdpSenderTask.SenderPacket packet = new UdpSenderTask.SenderPacket(); packet.data = data; packet.socketAddress = new InetSocketAddress(InetAddress.getByName(address), port); if (callback != null) { synchronized (mPendingSends) { mPendingSends.put(task, callback); } } task.execute(packet); } /** * Sets the socket to enable broadcasts. */ public void setBroadcast(boolean flag) throws SocketException { if (mSocket != null) { mSocket.setBroadcast(flag); } } /** * Shuts down the receiver task, closing the socket. */ public void close() throws IOException { if (mReceiverTask != null && !mReceiverTask.isCancelled()) { // stop the receiving task mReceiverTask.cancel(true); } // close the socket if (mSocket != null && !mSocket.isClosed()) { mSocket.close(); mSocket = null; } } /** * Retransmits the data back a level, attaching {@code this} */ @Override public void didReceiveData(String data, String host, int port) { mReceiverListener.didReceiveData(this, data, host, port); } /** * Retransmits the error back a level, attaching {@code this} */ @Override public void didReceiveError(String message) { mReceiverListener.didReceiveError(this, message); } /** * Retransmits the exception back a level, attaching {@code this} */ @Override public void didReceiveRuntimeException(RuntimeException exception) { mExceptionListener.didReceiveException(exception); } /** * Transmits success to the javascript layer, if a callback is present. */ @Override public void onDataSent(UdpSenderTask task) { Callback callback; synchronized (mPendingSends) { callback = mPendingSends.get(task); mPendingSends.remove(task); } if (callback != null) { callback.invoke(); } } /** * Transmits an error to the javascript layer, if a callback is present. */ @Override public void onDataSentError(UdpSenderTask task, String error) { Callback callback; synchronized (mPendingSends) { callback = mPendingSends.get(task); mPendingSends.remove(task); } if (callback != null) { callback.invoke(UdpErrorUtil.getError(null, error)); } } /** * Retransmits the exception back a level, attaching {@code this} */ @Override public void onDataSentRuntimeException(UdpSenderTask task, RuntimeException exception) { mExceptionListener.didReceiveException(exception); synchronized (mPendingSends) { mPendingSends.remove(task); } } public static class Builder { private OnDataReceivedListener receiverListener; private OnRuntimeExceptionListener exceptionListener; private boolean reuse = true; public Builder(OnDataReceivedListener receiverListener, OnRuntimeExceptionListener exceptionListener) { this.receiverListener = receiverListener; this.exceptionListener = exceptionListener; } public Builder reuseAddress(boolean reuse) { this.reuse = reuse; return this; } public UdpSocketClient build() { return new UdpSocketClient(this); } } /** * Callback interface for runtime exceptions. */ public interface OnRuntimeExceptionListener { void didReceiveException(RuntimeException exception); } /** * Callback interface data received events. */ public interface OnDataReceivedListener { void didReceiveData(UdpSocketClient client, String data, String host, int port); void didReceiveError(UdpSocketClient client, String message); } }
package ch.openech.test.persistence; import junit.framework.Assert; import org.junit.Test; import ch.openech.datagenerator.DataGenerator; import ch.openech.dm.person.Person; import ch.openech.dm.person.PersonExtendedInformation; import ch.openech.server.EchPersistence; import ch.openech.server.EchServer; public class PersonExtendedInformationPersistenceTest { private static EchPersistence persistence = EchServer.getInstance().getPersistence(); @Test public void insertInformationTest() throws Exception { Person person = DataGenerator.person(); person.personExtendedInformation = new PersonExtendedInformation(); person.personExtendedInformation.armedForcesLiability = "1"; int id = persistence.person().insert(person); Person readPerson = persistence.person().read(id); Assert.assertEquals("1", readPerson.personExtendedInformation.armedForcesLiability); persistence.commit(); } @Test public void updateInformationTest() throws Exception { Person person = DataGenerator.person(); person.personExtendedInformation = new PersonExtendedInformation(); person.personExtendedInformation.armedForcesLiability = "1"; int id = persistence.person().insert(person); Person readPerson = persistence.person().read(id); Assert.assertEquals("1", readPerson.personExtendedInformation.armedForcesLiability); readPerson.personExtendedInformation.armedForcesService = "0"; persistence.person().update(readPerson); Person readPerson2 = persistence.person().read(id); Assert.assertEquals("0", readPerson2.personExtendedInformation.armedForcesService); persistence.commit(); } }
package ca.ualberta.cs.cmput301t02project.test; import java.util.ArrayList; import java.util.Date; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.location.Location; import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.test.ViewAsserts; import android.widget.ArrayAdapter; import android.widget.ListView; import ca.ualberta.cs.cmput301t02project.R; import ca.ualberta.cs.cmput301t02project.activity.BrowseFavoritesActivity; import ca.ualberta.cs.cmput301t02project.activity.CreateCommentActivity; import ca.ualberta.cs.cmput301t02project.activity.LoginActivity; import ca.ualberta.cs.cmput301t02project.activity.MainMenuActivity; import ca.ualberta.cs.cmput301t02project.controller.TopLevelListController; import ca.ualberta.cs.cmput301t02project.model.CommentListModel; import ca.ualberta.cs.cmput301t02project.model.CommentModel; import ca.ualberta.cs.cmput301t02project.model.CommentServer; import ca.ualberta.cs.cmput301t02project.model.FavoritesListModel; import ca.ualberta.cs.cmput301t02project.model.Server; import ca.ualberta.cs.cmput301t02project.model.StoredCommentListAbstraction; import ca.ualberta.cs.cmput301t02project.model.TopLevelCommentList; import ca.ualberta.cs.cmput301t02project.model.User; import ca.ualberta.cs.cmput301t02project.view.CommentListAdapter; public class BrowseFavoritesActivityTest extends ActivityInstrumentationTestCase2<BrowseFavoritesActivity> { public BrowseFavoritesActivityTest() { super(BrowseFavoritesActivity.class); } private Context context; // for unique username Date date = new Date(); @Override public void setUp() { context = getInstrumentation().getTargetContext(); // unique username User.login(new Random(date.getSeconds()).toString(), context); } // not a test, used in test below -SB public CommentModel initializeComment() { String loc = "Location Intialization"; Location currentLocation; currentLocation = new Location(loc); //unique username CommentModel comment = new CommentModel("sasha", currentLocation, new Random(date.getSeconds()).toString()); comment.setId("for testing, no need to push"); return comment; } /* Test for Use Case 11 */ public void testVisibleListView(){ // Check if the ListView shows up on the BrowseFavoritesActivity page BrowseFavoritesActivity activity = getActivity(); ListView view = (ListView) activity.findViewById(R.id.commentListView); ViewAsserts.assertOnScreen(activity.getWindow().getDecorView(), view); } /* Test for Use Case 11 */ @UiThreadTest public void testAddFavorite(){ BrowseFavoritesActivity activity = getActivity(); CommentModel comment = initializeComment(); User.getUser().getFavorites().add(comment); ListView view = (ListView) activity.findViewById(R.id.commentListView); assertEquals("should be one comment in faves", User.getUser().getFavorites().getList().size(), 1); assertEquals("one fave should be displayed on the listview", view.getAdapter().getCount(), 1); assertEquals("displayed fave should match the saved fave", view.getAdapter().getItem(0).toString(), User.getUser().getFavorites().getList().get(0).toString()); } @UiThreadTest public void testSortByDate(){ CommentModel comment1 = new CommentModel("post 1", null, "schmoop"); comment1.setDate(new Date(1)); comment1.setId("1"); CommentModel comment2 = new CommentModel("post 2", null, "schmoop"); comment2.setDate(new Date(20000)); comment2.setId("2"); CommentModel comment3 = new CommentModel("post 3", null, "schmoop"); comment3.setDate(new Date(300000000)); comment3.setId("3"); FavoritesListModel outOfOrderComments = new FavoritesListModel(context); outOfOrderComments.add(comment1); outOfOrderComments.add(comment2); outOfOrderComments.add(comment3); FavoritesListModel inOrderComments = new FavoritesListModel(context); inOrderComments.add(comment3); inOrderComments.add(comment2); inOrderComments.add(comment1); CommentListAdapter adapter1; CommentListAdapter adapter2; adapter1 = new CommentListAdapter(context, 0, outOfOrderComments); adapter2 = new CommentListAdapter(context, 0, inOrderComments); adapter1.sortByDate(); adapter2.sortByDate(); assertEquals("First items should be in same place", adapter1.getItem(0), adapter2.getItem(0)); assertEquals("Second items should be in same place", adapter1.getItem(1), adapter2.getItem(1)); assertEquals("Third items should be in same place", adapter1.getItem(2), adapter2.getItem(2)); assertEquals("First item's dates should be equal", adapter1.getItem(0).getDate(), adapter2.getItem(0).getDate()); assertEquals("Second item's dates should be equal", adapter1.getItem(1).getDate(), adapter2.getItem(1).getDate()); assertEquals("Third item's dates should be equal", adapter1.getItem(2).getDate(), adapter2.getItem(2).getDate()); } /* * Use Case 8 */ @UiThreadTest public void testSortByPicture (){ // retrived April 6th 2014. Bitmap.Config conf = Bitmap.Config.ARGB_4444; Bitmap pic = Bitmap.createBitmap(10, 10, conf); // Has picture -SB CommentModel comment1 = new CommentModel("post 1", pic, null, "schmoop"); comment1.setId("1"); // Does not have picture -SB CommentModel comment2 = new CommentModel("post 2", null, "schmoop"); comment2.setId("2"); // Has picture -SB CommentModel comment3 = new CommentModel("post 3", pic, null, "schmoop"); comment3.setId("3"); // Does not have picture -SB CommentModel comment4 = new CommentModel("post 4", null, "schmoop"); comment4.setId("4"); FavoritesListModel outOfOrderComments = new FavoritesListModel(context); outOfOrderComments.add(comment1); outOfOrderComments.add(comment2); outOfOrderComments.add(comment3); outOfOrderComments.add(comment4); FavoritesListModel inOrderComments = new FavoritesListModel(context); inOrderComments.add(comment1); inOrderComments.add(comment3); inOrderComments.add(comment2); inOrderComments.add(comment4); CommentListAdapter adapter1; CommentListAdapter adapter2; adapter1 = new CommentListAdapter(context, 0, outOfOrderComments); adapter2 = new CommentListAdapter(context, 0, inOrderComments); adapter1.sortByPicture(); adapter2.sortByPicture(); // 2 comments with pictures, 2 without. top 2 should have pictures, bottom two should not. Don't have to be exactly the same order. assertTrue("First item should have a picture", adapter1.getItem(0).hasPicture()); assertEquals("First items should have pictures", adapter1.getItem(0).hasPicture(), adapter2.getItem(0).hasPicture()); assertTrue("Second item should have a picture", adapter1.getItem(1).hasPicture()); assertEquals("Second items should have pictures", adapter1.getItem(1).hasPicture(), adapter2.getItem(1).hasPicture()); assertFalse("Third item should not have a picture", adapter1.getItem(2).hasPicture()); assertEquals("Third items should not have pictures", adapter1.getItem(2).hasPicture(), adapter2.getItem(2).hasPicture()); assertFalse("Forth item should not have a picture", adapter1.getItem(3).hasPicture()); assertEquals("Forth items should not have pictures", adapter1.getItem(3).hasPicture(), adapter2.getItem(3).hasPicture()); } } /* * TESTS FOR SORTING */ /* * Use Case 1 */ /* * Use Case 2 */ /* * Use Case 9 */ /* * Use Case 15 */ /* * Use Case 16 */ /*public void testSortByDefault (){ Location currentLocation = new Location("Location Initialization"); currentLocation.setLatitude(0); currentLocation.setLongitude(0); Location l1 = new Location("Location Initialization"); l1.setLatitude(0.01); l1.setLongitude(0); Location l2 = new Location("Location Initialization"); l2.setLatitude(0.5); l2.setLongitude(0); Location l3 = new Location("Location Initialization"); l3.setLatitude(120); l3.setLongitude(0); ProjectApplication projectApplication = ProjectApplication.getInstance().getInstance(); ProjectApplication.getInstance().setCurrentLocation(currentLocation); CommentModel comment1 = new CommentModel("post 1", l1, "schmoop"); comment1.setDate(new Date(1)); CommentModel comment2 = new CommentModel("post 2", l1, "schmoop"); comment2.setDate(new Date(20000)); CommentModel comment3 = new CommentModel("post 3", l1, "schmoop"); comment3.setDate(new Date(300000000)); CommentModel comment4 = new CommentModel("post 4", l2, "schmoop"); comment4.setDate(new Date(1)); CommentModel comment5 = new CommentModel("post 5", l2, "schmoop"); comment5.setDate(new Date(20000)); CommentModel comment6 = new CommentModel("post 6", l2, "schmoop"); comment6.setDate(new Date(300000000)); CommentModel comment7 = new CommentModel("post 7", l3, "schmoop"); comment7.setDate(new Date(1)); CommentModel comment8 = new CommentModel("post 8", l3, "schmoop"); comment8.setDate(new Date(20000)); CommentModel comment9 = new CommentModel("post 9", l3, "schmoop"); comment9.setDate(new Date(300000000)); CommentListModel outOfOrderComments = new CommentListModel(); outOfOrderComments.add(comment9); outOfOrderComments.add(comment5); outOfOrderComments.add(comment4); outOfOrderComments.add(comment3); outOfOrderComments.add(comment8); outOfOrderComments.add(comment6); outOfOrderComments.add(comment1); outOfOrderComments.add(comment2); outOfOrderComments.add(comment7); CommentListModel inOrderComments = new CommentListModel(); inOrderComments.add(comment3); inOrderComments.add(comment2); inOrderComments.add(comment1); inOrderComments.add(comment6); inOrderComments.add(comment5); inOrderComments.add(comment4); inOrderComments.add(comment9); inOrderComments.add(comment8); inOrderComments.add(comment7); CommentListAdapter adapter1; CommentListAdapter adapter2; adapter1 = new CommentListAdapter(getActivity(), R.layout.list_item, outOfOrderComments.getList()); adapter2 = new CommentListAdapter(getActivity(), R.layout.list_item, inOrderComments.getList()); outOfOrderComments.setAdapter(adapter1); inOrderComments.setAdapter(adapter2); adapter1.setModel(outOfOrderComments); adapter2.setModel(inOrderComments); adapter1.sortByDefault(); assertEquals("First items should be in same place", adapter1.getItem(0), adapter2.getItem(0)); assertEquals("Second items should be in same place", adapter1.getItem(1), adapter2.getItem(1)); assertEquals("Third items should be in same place", adapter1.getItem(2), adapter2.getItem(2)); assertEquals("Fourth items should be in same place", adapter1.getItem(3), adapter2.getItem(3)); assertEquals("Fifth items should be in same place", adapter1.getItem(4), adapter2.getItem(4)); assertEquals("Sixth items should be in same place", adapter1.getItem(5), adapter2.getItem(5)); assertEquals("Seventh items should be in same place", adapter1.getItem(6), adapter2.getItem(6)); assertEquals("Eighth items should be in same place", adapter1.getItem(7), adapter2.getItem(7)); assertEquals("Ninth items should be in same place", adapter1.getItem(8), adapter2.getItem(8)); assertEquals("First items' dates should be equal", adapter1.getItem(0).getDate(), adapter2.getItem(0).getDate()); assertEquals("Second items' dates should be equal", adapter1.getItem(1).getDate(), adapter2.getItem(1).getDate()); assertEquals("Third items' dates should be equal", adapter1.getItem(2).getDate(), adapter2.getItem(2).getDate()); assertEquals("Fourth items' dates should be equal", adapter1.getItem(3).getDate(), adapter2.getItem(3).getDate()); assertEquals("Fifth items' dates should be equal", adapter1.getItem(4).getDate(), adapter2.getItem(4).getDate()); assertEquals("Sixth items' dates should be equal", adapter1.getItem(5).getDate(), adapter2.getItem(5).getDate()); assertEquals("Seventh items' dates should be equal", adapter1.getItem(6).getDate(), adapter2.getItem(6).getDate()); assertEquals("Eighth items' dates should be equal", adapter1.getItem(7).getDate(), adapter2.getItem(7).getDate()); assertEquals("Ninth items' dates should be equal", adapter1.getItem(8).getDate(), adapter2.getItem(8).getDate()); assertEquals("First items' locations should be equal", adapter1.getItem(0).getLocation(), adapter2.getItem(0).getLocation()); assertEquals("Second items' locations should be equal", adapter1.getItem(1).getLocation(), adapter2.getItem(1).getLocation()); assertEquals("Third items' locations should be equal", adapter1.getItem(2).getLocation(), adapter2.getItem(2).getLocation()); assertEquals("Fourth items' locations should be equal", adapter1.getItem(3).getLocation(), adapter2.getItem(3).getLocation()); assertEquals("Fifth items' locations should be equal", adapter1.getItem(4).getLocation(), adapter2.getItem(4).getLocation()); assertEquals("Sixth items' locations should be equal", adapter1.getItem(5).getLocation(), adapter2.getItem(5).getLocation()); assertEquals("Seventh items' locations should be equal", adapter1.getItem(6).getLocation(), adapter2.getItem(6).getLocation()); assertEquals("Eighth items' locations should be equal", adapter1.getItem(7).getLocation(), adapter2.getItem(7).getLocation()); assertEquals("Ninth items' locations should be equal", adapter1.getItem(8).getLocation(), adapter2.getItem(8).getLocation()); }*/
package qa.qcri.aidr.trainer.pybossa.service.impl; import org.apache.log4j.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import qa.qcri.aidr.trainer.pybossa.dao.ClientAppGroupDao; import qa.qcri.aidr.trainer.pybossa.entity.*; import qa.qcri.aidr.trainer.pybossa.format.impl.MicroMapperPybossaFormatter; import qa.qcri.aidr.trainer.pybossa.format.impl.PybossaFormatter; import qa.qcri.aidr.trainer.pybossa.service.*; import qa.qcri.aidr.trainer.pybossa.store.StatusCodeType; import qa.qcri.aidr.trainer.pybossa.store.URLPrefixCode; import qa.qcri.aidr.trainer.pybossa.store.UserAccount; import qa.qcri.aidr.trainer.pybossa.util.DataFormatValidator; import qa.qcri.aidr.trainer.pybossa.util.DateTimeConverter; import java.text.SimpleDateFormat; import java.util.*; @Service("pybossaWorker") @Transactional(readOnly = false) public class PybossaWorker implements ClientAppRunWorker { protected static Logger logger = Logger.getLogger(PybossaWorker.class); @Autowired private ClientAppService clientAppService; @Autowired private TaskQueueService taskQueueService; @Autowired private TaskLogService taskLogService; @Autowired private ClientAppResponseService clientAppResponseService; @Autowired private ReportTemplateService reportTemplateService; @Autowired private ClientAppGroupDao clientAppGroupDao; private Client client; private int MAX_PENDING_QUEUE_SIZE = StatusCodeType.MAX_PENDING_QUEUE_SIZE; private String PYBOSSA_API_TASK_PUBLSIH_URL; private String AIDR_API_URL; private String AIDR_TASK_ANSWER_URL; private String AIDR_NOMINAL_ATTRIBUTE_LABEL_URL; private String PYBOSSA_API_TASK_RUN_BASE_URL; private String PYBOSSA_API_TASK_BASE_URL; private String AIDR_ASSIGNED_TASK_CLEAN_UP_URL; private String PYBOSSA_API_APP_DELETE_URL; private String PYBOSSA_TASK_DELETE_URL; private PybossaCommunicator pybossaCommunicator = new PybossaCommunicator(); private JSONParser parser = new JSONParser(); private PybossaFormatter pybossaFormatter = new PybossaFormatter(); @Autowired private TranslationService translationService; public void setClassVariable(Client theClient) throws Exception{ boolean resetVariable = false; if(client != null){ if(!client.getClientID().equals(theClient.getClientID())){ client = theClient; resetVariable = true; } } else{ client = theClient; resetVariable = true; } if(resetVariable){ AIDR_API_URL = client.getAidrHostURL() + URLPrefixCode.ASSINGN_TASK + UserAccount.SYSTEM_USER_NAME + "/"; AIDR_ASSIGNED_TASK_CLEAN_UP_URL = client.getAidrHostURL() + URLPrefixCode.AIDR_TASKASSIGNMENT_REVERT + UserAccount.SYSTEM_USER_NAME + "/"; PYBOSSA_API_TASK_PUBLSIH_URL = client.getHostURL() + URLPrefixCode.TASK_PUBLISH + client.getHostAPIKey(); AIDR_TASK_ANSWER_URL = client.getAidrHostURL() + URLPrefixCode.TASK_ANSWER_SAVE; PYBOSSA_API_TASK_BASE_URL = client.getHostURL() + URLPrefixCode.TASK_INFO; PYBOSSA_API_TASK_RUN_BASE_URL = client.getHostURL() + URLPrefixCode.TASKRUN_INFO; MAX_PENDING_QUEUE_SIZE = client.getQueueSize(); PYBOSSA_API_APP_DELETE_URL = client.getHostURL() + URLPrefixCode.PYBOSAA_APP ; PYBOSSA_TASK_DELETE_URL = client.getHostURL() + URLPrefixCode.PYBOSSA_TASK_DELETE; AIDR_NOMINAL_ATTRIBUTE_LABEL_URL = client.getAidrHostURL() + URLPrefixCode.AIDR_NOMINAL_ATTRIBUTE_LABEL; } } @Override public void processTaskRunImport() throws Exception{ List<ClientApp> clientAppList = clientAppService.findClientAppByStatus(StatusCodeType.AIDR_ONLY); Iterator itr= clientAppList.iterator(); pybossaFormatter.setTranslationService(translationService); while(itr.hasNext()){ ClientApp clientApp = (ClientApp)itr.next(); setClassVariable(clientApp.getClient()); processTaskRunPerClientAppImport(clientApp); //added translation processing into the process processTranslations(clientApp); } } private void processTranslations(ClientApp clientApp) throws Exception { translationService.processTranslations(clientApp); } @Override public void processTaskPublish() throws Exception{ List<ClientApp> crisisID = clientAppService.getAllCrisis(); for (int i = 0; i < crisisID.size(); i++) { Object obj = crisisID.get(i); Long id = (Long)obj; if(id!=null){ // this.deactivateClientApp(id); List<ClientApp> appList = this.getInGroupClientApp(id); if(appList.size() > 0){ this.setClassVariable(appList.get(0).getClient()); boolean isGroupBasedClientApp = this.isInGroupClientApp(id); int pushTaskNumber = calculateMinNumber(appList); if(!isGroupBasedClientApp) { pushTaskNumber = pushTaskNumber * appList.size(); } if( pushTaskNumber > 0 ){ logger.debug(AIDR_API_URL + id + "/" + pushTaskNumber); String inputData = pybossaCommunicator.sendGet(AIDR_API_URL + id + "/" +pushTaskNumber); if(DataFormatValidator.isValidateJson(inputData)){ try { if(isGroupBasedClientApp || appList.size() < 2){ processGroupPushing(appList, inputData) ; } else{ processNonGroupPushing(appList, inputData, pushTaskNumber) ; } } catch (Exception e) { logger.error(e.getMessage()); } } } } appList.clear(); } } } public void processGroupPushing(List<ClientApp> appList, String inputData){ try{ for (int index = 0; index < appList.size() ; index++){ ClientApp currentClientApp = appList.get(index); List<String> aidr_data = pybossaFormatter.assemblePybossaTaskPublishForm(inputData, currentClientApp); for(String temp : aidr_data) { String response = pybossaCommunicator.sendPostGet(temp, PYBOSSA_API_TASK_PUBLSIH_URL) ; if(!response.startsWith("Exception") && !response.contains("exception_cls")){ addToTaskQueue(response, currentClientApp.getClientAppID(), StatusCodeType.TASK_PUBLISHED) ; } else{ addToTaskQueue(temp, currentClientApp.getClientAppID(), StatusCodeType.Task_NOT_PUBLISHED) ; } } } } catch(Exception e){ logger.error(e.getMessage()); } } public void processNonGroupPushing(List<ClientApp> appList, String inputData, int pushTaskNumber){ try{ JSONParser parser = new JSONParser(); Object obj = parser.parse(inputData); JSONArray jsonObject = (JSONArray) obj; int inputDataSize = jsonObject.size(); int itemsPerApp = (int)(inputDataSize / appList.size()); int itemIndexStart = 0; int itemIndexEnd = itemsPerApp; for (int index = 0; index < appList.size() ; index++){ ClientApp currentClientApp = appList.get(index); if(itemIndexEnd > inputDataSize){ itemIndexEnd = inputDataSize; } if((itemIndexStart < itemIndexEnd) && (itemIndexEnd <= inputDataSize)) { List<String> aidr_data = pybossaFormatter.assemblePybossaTaskPublishFormWithIndex(inputData, currentClientApp, itemIndexStart, itemIndexEnd); int itemLoopEnd = itemIndexEnd - itemIndexStart; for(int i = 0; i < itemLoopEnd; i++){ String temp = aidr_data.get(i); String response = pybossaCommunicator.sendPostGet(temp, PYBOSSA_API_TASK_PUBLSIH_URL) ; if(!response.startsWith("Exception") && !response.contains("exception_cls")){ addToTaskQueue(response, currentClientApp.getClientAppID(), StatusCodeType.TASK_PUBLISHED) ; } else{ addToTaskQueue(temp, currentClientApp.getClientAppID(), StatusCodeType.Task_NOT_PUBLISHED) ; } } itemIndexStart = itemIndexEnd; itemIndexEnd = itemIndexEnd + itemsPerApp; if(itemIndexEnd > inputDataSize && itemIndexStart < inputDataSize){ itemIndexEnd = itemIndexStart + (inputDataSize - itemIndexStart); } } } } catch(Exception e){ logger.error(e.getMessage()); } } public List<ClientApp> getInGroupClientApp(Long crisisID){ List<ClientApp> appList = clientAppService.getAllClientAppByCrisisIDAndStatus(crisisID , StatusCodeType.AIDR_ONLY); List<ClientAppGroup> appGroups = clientAppGroupDao.findGroupByCrisisID(crisisID); if(appGroups.size() == 0 || appList.size() == 0){ return appList; } List<ClientApp> tempAppList = new ArrayList<ClientApp>(); if(appGroups.size() > 0){ for (int index = 0; index < appList.size() ; index++){ if(appList.get(index).getGroupID().equals(appGroups.get(0).getGroupID())){ tempAppList.add(appList.get(index)); } } return tempAppList; } return appList; } public boolean isInGroupClientApp(Long crisisID){ List<ClientAppGroup> appGroups = clientAppGroupDao.findGroupByCrisisID(crisisID); if(appGroups.size() > 0){ return true; } return false; } public void processTaskRunPerClientAppImport(ClientApp clientApp){ List<TaskQueue> taskQueues = taskQueueService.getTaskQueueByClientAppStatus(clientApp.getClientAppID(),StatusCodeType.TASK_PUBLISHED); if(taskQueues != null ){ int max_loop_size = taskQueues.size(); if(max_loop_size > 100){ max_loop_size = 100; } for(int i=0; i < max_loop_size; i++){ TaskQueue taskQueue = taskQueues.get(i); if(!this.isExpiredTaskQueue(taskQueue)){ Long taskID = taskQueue.getTaskID(); logger.debug("taskID :" + taskID); String taskQueryURL = PYBOSSA_API_TASK_BASE_URL + clientApp.getPlatformAppID() + "&id=" + taskID; String inputData = pybossaCommunicator.sendGet(taskQueryURL); try { boolean isFound = pybossaFormatter.isTaskStatusCompleted(inputData); logger.debug("isFound :" + isFound); if(isFound){ logger.debug("processTaskRunPerClientAppImport"); processTaskQueueImport(clientApp, taskQueue, taskID); } } catch (Exception e) { logger.error("Error for clientApp: " + clientApp.getShortName()); } } } } } private boolean isExpiredTaskQueue(TaskQueue taskQueue){ boolean isExpired = false; try{ long diffHours = DateTimeConverter.getHourDifference(taskQueue.getCreated(), null); if(diffHours >= StatusCodeType.TASK_CLEANUP_CUT_OFF_HOUR){ String returnValue = this.removeAbandonedTask(taskQueue.getTaskID(), taskQueue.getTaskQueueID()); isExpired = true; if(returnValue.equalsIgnoreCase("Exception")){ taskQueue.setStatus(StatusCodeType.TASK_ABANDONED); taskQueueService.updateTaskQueue(taskQueue); } } } catch(Exception e){ logger.error(e.getMessage()); } return isExpired; } private void processTaskQueueImport(ClientApp clientApp, TaskQueue taskQueue, Long taskID) throws Exception { String PYBOSSA_API_TASK_RUN = PYBOSSA_API_TASK_RUN_BASE_URL + clientApp.getPlatformAppID() + "&task_id=" + taskID; String importResult = pybossaCommunicator.sendGet(PYBOSSA_API_TASK_RUN) ; JSONArray array = (JSONArray) parser.parse(importResult) ; ClientAppAnswer clientAppAnswer = clientAppResponseService.getClientAppAnswer(clientApp.getClientAppID()); System.out.println("clientAppAnswer : " + clientAppAnswer.getAnswer()); if(clientAppAnswer == null){ int cutOffValue = StatusCodeType.MAX_VOTE_CUT_OFF_VALUE; String AIDR_NOMINAL_ATTRIBUTE_LABEL_URL_PER_APP = AIDR_NOMINAL_ATTRIBUTE_LABEL_URL + clientApp.getCrisisID() + "/" + clientApp.getNominalAttributeID(); String answerSet = pybossaCommunicator.sendGet(AIDR_NOMINAL_ATTRIBUTE_LABEL_URL_PER_APP) ; if(clientApp.getTaskRunsPerTask() < StatusCodeType.MAX_VOTE_CUT_OFF_VALUE){ cutOffValue = StatusCodeType.MIN_VOTE_CUT_OFF_VALUE; } clientAppResponseService.saveClientAppAnswer(clientApp.getClientAppID(), answerSet, cutOffValue); clientAppAnswer = clientAppResponseService.getClientAppAnswer(clientApp.getClientAppID()); } String pybossaResult = importResult; if(DataFormatValidator.isValidateJson(importResult)){ List<TaskLog> taskLogList = taskLogService.getTaskLog(taskQueue.getTaskQueueID()); pybossaResult = pybossaFormatter.buildTaskOutputForAIDR(taskQueue.getTaskQueueID(), taskLogList, importResult, parser, clientApp, clientAppAnswer); System.out.println("*****************************************************************************************"); System.out.println("pybossaResult:******** " + pybossaResult); int responseCode = StatusCodeType.HTTP_OK; if(pybossaResult != null && !pybossaFormatter.getTranslateRequired()){ responseCode = pybossaCommunicator.sendPost(pybossaResult, AIDR_TASK_ANSWER_URL); System.out.println("sent : " + responseCode); System.out.println("pybossaResult:******** " + importResult); System.out.println("AIDR_TASK_ANSWER_URL:******** " + AIDR_TASK_ANSWER_URL); System.out.println("*****************************************************************************************"); } if(responseCode ==StatusCodeType.HTTP_OK ||responseCode ==StatusCodeType.HTTP_OK_NO_CONTENT || pybossaFormatter.getTranslateRequired() ){ //System.out.println("update taskQueue : " + responseCode); TaskQueueResponse taskQueueResponse = pybossaFormatter.getTaskQueueResponse(clientApp, importResult, parser, taskQueue.getTaskQueueID(), clientAppAnswer, reportTemplateService); if(pybossaFormatter.getTranslateRequired()){ pybossaFormatter.setTranslateRequired(false); taskQueueResponse.setTaskInfo(pybossaResult); } taskQueue.setStatus(StatusCodeType.TASK_LIFECYCLE_COMPLETED); updateTaskQueue(taskQueue); clientAppResponseService.processTaskQueueResponse(taskQueueResponse); } } } private void addToTaskQueue(String inputData, Long clientAppID, Integer status){ try { Object obj = parser.parse(inputData); JSONObject jsonObject = (JSONObject) obj; Long taskID = (Long)jsonObject.get("id"); JSONObject info = (JSONObject)jsonObject.get("info"); Long documentID = (Long)info.get("documentID"); if(status.equals(StatusCodeType.Task_NOT_PUBLISHED)){ pybossaCommunicator.sendGet(AIDR_ASSIGNED_TASK_CLEAN_UP_URL+ documentID) ; } else{ TaskQueue taskQueue = new TaskQueue(taskID, clientAppID, documentID, status); taskQueueService.createTaskQueue(taskQueue); TaskLog taskLog = new TaskLog(taskQueue.getTaskQueueID(), taskQueue.getStatus()); taskLogService.createTaskLog(taskLog); } } catch (ParseException e) { logger.error("Error parsing: " + inputData); logger.error(e.getMessage()); } } private void updateTaskQueue(TaskQueue taskQueue){ taskQueueService.updateTaskQueue(taskQueue); TaskLog taskLog = new TaskLog(taskQueue.getTaskQueueID(), taskQueue.getStatus()); taskLogService.createTaskLog(taskLog); } private int calculateMinNumber(List<ClientApp> clientAppList){ int min = MAX_PENDING_QUEUE_SIZE; for (int i = 0; i < clientAppList.size(); i++) { ClientApp obj = clientAppList.get(i); int currentPendingTask = taskQueueService.getCountTaskQeueByStatusAndClientApp(obj.getClientAppID(), StatusCodeType.AIDR_ONLY); // System.out.println("currentPendingTask : " + currentPendingTask); // System.out.println("MAX_PENDING_QUEUE_SIZE : " + MAX_PENDING_QUEUE_SIZE); int numQueue = MAX_PENDING_QUEUE_SIZE - currentPendingTask; if(numQueue < 0) { min = 0; } else{ min = numQueue; } } return min; } private void deactivateClientApp(Long crisisID) throws Exception { //List<ClientApp> clientAppList = clientAppService.getAllClientAppByCrisisIDAndStatus(crisisID , StatusCodeType.CLIENT_APP_INACTIVE_REQUEST); List<ClientApp> clientAppList = clientAppService.getAllClientAppByCrisisID(crisisID); for (int i = 0; i < clientAppList.size(); i++) { ClientApp currentClientApp = clientAppList.get(i); setClassVariable(currentClientApp.getClient()); if(isEligibleForDeactivationRule(currentClientApp)) { String deleteURL = PYBOSSA_API_APP_DELETE_URL + currentClientApp.getPlatformAppID()+ URLPrefixCode.PYBOSSA_APP_UPDATE_KEY + client.getHostAPIKey(); String returnValue = pybossaCommunicator.deleteGet(deleteURL); clientAppService.updateClientAppStatus(currentClientApp, StatusCodeType.CLIENT_APP_DISABLED); } } } private boolean isEligibleForDeactivationRule(ClientApp currentClientApp){ if(currentClientApp.getStatus().equals(StatusCodeType.CLIENT_APP_INACTIVE_REQUEST)){ return true; } if(isActiveClientApp(currentClientApp)){ List<TaskQueue> latestTaskQueue = taskQueueService.getLastActiveTaskQueue(currentClientApp.getClientAppID()); if(latestTaskQueue.size() > 0){ Date s1 = latestTaskQueue.get(0).getUpdated(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, StatusCodeType.MAX_APP_HOLD_PERIOD_DAY); if(s1.getTime() < calendar.getTime().getTime()){ return true; } } } return false; } public String removeAbandonedTask(long taskID, long taskQueueID) throws Exception { String deleteTaskURL = PYBOSSA_TASK_DELETE_URL + taskID + URLPrefixCode.PYBOSSA_APP_UPDATE_KEY + client.getHostAPIKey(); //System.out.println(deleteTaskURL); String returnValue = pybossaCommunicator.deleteGet(deleteTaskURL); if(!returnValue.equalsIgnoreCase("Exception")) { taskLogService.deleteAbandonedTaskLog(taskQueueID); taskQueueService.deleteAbandonedTaskQueue(taskQueueID); } return returnValue; } public void doCleanAbandonedTask() throws Exception{ List<TaskQueue> taskQueues = taskQueueService.getTaskQueueByStatus("status",StatusCodeType.TASK_ABANDONED); for(int i = 0; i < taskQueues.size(); i++){ String returnValue = removeAbandonedTask(taskQueues.get(i).getTaskID(), taskQueues.get(i).getTaskQueueID()); } } private TaskQueue getTaskQueue(Long clientAppID, Long documentID){ TaskQueue taskQueue = null; List<TaskQueue> queSet = taskQueueService.getTaskQueueByDocument(clientAppID, documentID); if(queSet!=null){ if(queSet.size() > 0){ taskQueue = queSet.get(0); } } return taskQueue; } private boolean isActiveClientApp(ClientApp currentClientApp){ if(currentClientApp.getStatus().equals(StatusCodeType.AIDR_MICROMAPPER_BOTH)){ return true; } if(currentClientApp.getStatus().equals(StatusCodeType.MICROMAPPER_ONLY)){ return true; } if(currentClientApp.getStatus().equals(StatusCodeType.AIDR_ONLY)){ return true; } return false; } }