answer
stringlengths
17
10.2M
package org.eclipse.birt.report.designer.internal.ui.views.property.widgets; import org.eclipse.birt.report.designer.util.NumberUtil; import org.eclipse.birt.report.model.api.metadata.DimensionValue; import org.eclipse.birt.report.model.api.metadata.PropertyValueException; import org.eclipse.birt.report.model.api.util.StringUtil; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Text; import com.ibm.icu.util.ULocale; /** * A cell editor that manages a dimension field. */ public class DimensionCellEditor extends CDialogCellEditor { private String[] units; private String unitName; private Text defaultLabel; private int style; private int inProcessing = 0; /** * Creates a new dialog cell editor parented under the given control. * * @param parent * the parent control * @param unitNames * the name list */ public DimensionCellEditor( Composite parent, String[] unitNames ) { super( parent ); this.units = unitNames; } /** * Creates a new dialog cell editor parented under the given control. * * @param parent * the parent control * @param unitNames * the name list * @param style * the style bits */ public DimensionCellEditor( Composite parent, String[] unitNames, int style ) { super( parent, style ); this.units = unitNames; this.style = style; } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.DialogCellEditor#openDialogBox(org.eclipse. * swt.widgets.Control) */ protected Object openDialogBox( Control cellEditorWindow ) { DimensionBuilderDialog dialog = new DimensionBuilderDialog( cellEditorWindow.getShell( ) ); DimensionValue value; try { value = StringUtil.parseInput( (String) this.getDefaultText( ) .getText( ), ULocale.getDefault( ) ); } catch ( PropertyValueException e ) { value = null; } dialog.setUnitNames( units ); dialog.setUnitName( unitName ); if ( value != null ) { dialog.setMeasureData( new Double( value.getMeasure( ) ) ); } inProcessing = 1; if ( dialog.open( ) == Window.OK ) { deactivate( ); inProcessing = 0; String newValue = null; Double doubleValue = 0.0; if ( dialog.getMeasureData( ) instanceof Double ) { doubleValue = (Double) dialog.getMeasureData( ); } else if ( dialog.getMeasureData( ) instanceof DimensionValue ) { doubleValue = ( (DimensionValue) dialog.getMeasureData( ) ).getMeasure( ); } DimensionValue dValue = new DimensionValue( doubleValue, dialog.getUnitName( ) ); if ( dValue != null ) { newValue = dValue.toDisplayString( ); } return newValue; } else { getDefaultText( ).setFocus( ); getDefaultText( ).selectAll( ); } inProcessing = 0; return null; } /** * Set current units * * @param units */ public void setUnits( String units ) { this.unitName = units; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.CellEditor#doSetFocus() */ protected void doSetFocus( ) { getDefaultText( ).setFocus( ); getDefaultText( ).selectAll( ); } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.designer.internal.ui.views.property.widgets. * CDialogCellEditor#doValueChanged() */ protected void doValueChanged( ) { Object oldValue = doGetValue( ); if ( oldValue != null && oldValue instanceof String ) { oldValue = parseInputString2dValue( (String) oldValue ); } String newValue = defaultLabel.getText( ); DimensionValue dValue = parseInputString2dValue( newValue ); if ( dValue != null ) { newValue = dValue.toDisplayString( ); } if ( dValue != null && ( !dValue.equals( oldValue ) ) ) { markDirty( ); doSetValue( newValue ); } else if ( ( dValue == null && oldValue != null ) ) { markDirty( ); doSetValue( null ); } } private DimensionValue parseString2dValue( String strValue ) { DimensionValue dValue = null; try { dValue = StringUtil.parse( (String) strValue ); } catch ( PropertyValueException e ) { dValue = null; } return dValue; } private DimensionValue parseInputString2dValue( String strValue ) { DimensionValue dValue = null; try { dValue = StringUtil.parseInput( (String) strValue, ULocale.getDefault( ) ); } catch ( PropertyValueException e ) { dValue = null; } return dValue; } /** * Creates the controls used to show the value of this cell editor. * <p> * The default implementation of this framework method creates a label * widget, using the same font and background color as the parent control. * </p> * <p> * Subclasses may reimplement. If you reimplement this method, you should * also reimplement <code>updateContents</code>. * </p> * * @param cell * the control for this cell editor */ protected Control createContents( Composite cell ) { defaultLabel = new Text( cell, SWT.LEFT | style ); defaultLabel.setFont( cell.getFont( ) ); defaultLabel.setBackground( cell.getBackground( ) ); defaultLabel.addKeyListener( new KeyAdapter( ) { // hook key pressed - see PR 14201 public void keyPressed( KeyEvent e ) { keyReleaseOccured( e ); } } ); defaultLabel.addTraverseListener( new TraverseListener( ) { public void keyTraversed( TraverseEvent e ) { if ( e.detail == SWT.TRAVERSE_ESCAPE || e.detail == SWT.TRAVERSE_RETURN ) { e.doit = false; } } } ); defaultLabel.addFocusListener( new FocusAdapter( ) { public void focusLost( FocusEvent e ) { DimensionCellEditor.this.focusLost( ); } } ); return defaultLabel; } /** * Updates the controls showing the value of this cell editor. * <p> * The default implementation of this framework method just converts the * passed object to a string using <code>toString</code> and sets this as * the text of the label widget. * </p> * <p> * Subclasses may reimplement. If you reimplement this method, you should * also reimplement <code>createContents</code>. * </p> * * @param value * the new value of this cell editor */ protected void updateContents( Object value ) { if ( defaultLabel == null ) return; String text = "";//$NON-NLS-1$ if ( value != null ) { if ( value instanceof String ) { DimensionValue dValue; try { dValue = StringUtil.parseInput( (String) value, ULocale.getDefault( ) ); } catch ( PropertyValueException e ) { dValue = null; } if ( dValue == null ) { return; } text = NumberUtil.double2LocaleNum( dValue.getMeasure( ) ) + dValue.getUnits( ); } else { text = value.toString( ); } } defaultLabel.setText( text ); } protected Text getDefaultText( ) { return defaultLabel; } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.CellEditor#keyReleaseOccured(org.eclipse.swt * .events.KeyEvent) */ protected void keyReleaseOccured( KeyEvent keyEvent ) { if ( keyEvent.character == '\u001b' ) { // Escape character fireCancelEditor( ); } else if ( keyEvent.character == '\t' ) { // tab key applyEditorValueAndDeactivate( ); } else if ( keyEvent.character == '\r' ) { // Return key applyEditorValueAndDeactivate( ); } } private void applyEditorValueAndDeactivate( ) { inProcessing = 1; doValueChanged( ); fireApplyEditorValue( ); deactivate( ); inProcessing = 0; } /** * Processes a focus lost event that occurred in this cell editor. * <p> * The default implementation of this framework method applies the current * value and deactivates the cell editor. Subclasses should call this method * at appropriate times. Subclasses may also extend or reimplement. * </p> */ protected void focusLost( ) { if ( inProcessing == 1 ) return; else { // if click button, ignore focuslost event. Rectangle rect = getButton( ).getBounds( ); Point location = getButton( ).toDisplay( 0, 0 ); rect.x = location.x; rect.y = location.y; Point cursorLocation = getButton( ).getDisplay( ) .getCursorLocation( ); if ( rect.contains( cursorLocation ) ) return; } super.focusLost( ); } }
package dr.evomodel.coalescent; import dr.evolution.coalescent.IntervalList; import dr.evolution.coalescent.Intervals; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.evolution.util.Units; import dr.evomodel.tree.TreeModel; import dr.inference.model.*; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Forms a base class for a number of coalescent likelihood calculators. * * @author Andrew Rambaut * @author Alexei Drummond * @version $Id: CoalescentLikelihood.java,v 1.43 2006/07/28 11:27:32 rambaut Exp $ */ public abstract class AbstractCoalescentLikelihood extends AbstractModelLikelihood implements Units { // PUBLIC STUFF public AbstractCoalescentLikelihood( String name, Tree tree, TaxonList includeSubtree, List<TaxonList> excludeSubtrees) throws Tree.MissingTaxonException { super(name); this.tree = tree; if (includeSubtree != null) { includedLeafSet = Tree.Utils.getLeavesForTaxa(tree, includeSubtree); } else { includedLeafSet = null; } if (excludeSubtrees != null) { excludedLeafSets = new Set[excludeSubtrees.size()]; for (int i = 0; i < excludeSubtrees.size(); i++) { excludedLeafSets[i] = Tree.Utils.getLeavesForTaxa(tree, excludeSubtrees.get(i)); } } else { excludedLeafSets = new Set[0]; } if (tree instanceof TreeModel) { addModel((TreeModel) tree); } intervals = new Intervals(tree.getNodeCount()); storedIntervals = new Intervals(tree.getNodeCount()); eventsKnown = false; addStatistic(new DeltaStatistic()); likelihoodKnown = false; } // ModelListener IMPLEMENTATION protected final void handleModelChangedEvent(Model model, Object object, int index) { if (model == tree) { // treeModel has changed so recalculate the intervals eventsKnown = false; } likelihoodKnown = false; } // VariableListener IMPLEMENTATION protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { } // No parameters to respond to // Model IMPLEMENTATION /** * Stores the precalculated state: in this case the intervals */ protected final void storeState() { // copy the intervals into the storedIntervals storedIntervals.copyIntervals(intervals); storedEventsKnown = eventsKnown; storedLikelihoodKnown = likelihoodKnown; storedLogLikelihood = logLikelihood; } /** * Restores the precalculated state: that is the intervals of the tree. */ protected final void restoreState() { // swap the intervals back Intervals tmp = storedIntervals; storedIntervals = intervals; intervals = tmp; eventsKnown = storedEventsKnown; likelihoodKnown = storedLikelihoodKnown; logLikelihood = storedLogLikelihood; } protected final void acceptState() { } // nothing to do // Likelihood IMPLEMENTATION public final Model getModel() { return this; } public final double getLogLikelihood() { if (!eventsKnown) { setupIntervals(); likelihoodKnown = false; } if (!likelihoodKnown) { logLikelihood = calculateLogLikelihood(); likelihoodKnown = true; } return logLikelihood; } public final void makeDirty() { likelihoodKnown = false; eventsKnown = false; } /** * Calculates the log likelihood of this set of coalescent intervals, * given a demographic model. */ public abstract double calculateLogLikelihood(); /** * @return the node ref of the MRCA of this coalescent prior in the given tree. */ protected NodeRef getIncludedMRCA(Tree tree) { if (includedLeafSet != null) { return Tree.Utils.getCommonAncestorNode(tree, includedLeafSet); } else { return tree.getRoot(); } } /** * @return an array of noderefs that represent the MRCAs of subtrees to exclude from coalescent prior. * May return null if no subtrees should be excluded. */ protected Set<NodeRef> getExcludedMRCAs(Tree tree) { if (excludedLeafSets.length == 0) return null; Set<NodeRef> excludeNodesBelow = new HashSet<NodeRef>(); for( Set<String> excludedLeafSet : excludedLeafSets ) { excludeNodesBelow.add(Tree.Utils.getCommonAncestorNode(tree, excludedLeafSet)); } return excludeNodesBelow; } public Tree getTree() { return tree; } public IntervalList getIntervals() { return intervals; } /** * Recalculates all the intervals from the tree model. */ protected final void setupIntervals() { intervals.resetEvents(); collectTimes(tree, getIncludedMRCA(tree), getExcludedMRCAs(tree), intervals); // force a calculation of the intervals... intervals.getIntervalCount(); eventsKnown = true; } /** * extract coalescent times and tip information into ArrayList times from tree. * * @param tree the tree * @param node the node to start from * @param intervals the intervals object to store the events */ private void collectTimes(Tree tree, NodeRef node, Set<NodeRef> excludeNodesBelow, Intervals intervals) { intervals.addCoalescentEvent(tree.getNodeHeight(node)); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef child = tree.getChild(node, i); // check if this subtree is included in the coalescent density boolean include = true; if (excludeNodesBelow != null && excludeNodesBelow.contains(child)) { include = false; } if (!include || tree.isExternal(child)) { intervals.addSampleEvent(tree.getNodeHeight(child)); } else { collectTimes(tree, child, excludeNodesBelow, intervals); } } } public double[] getCoalescentIntervalHeights() { if (!eventsKnown) { setupIntervals(); } double[] heights = new double[intervals.getIntervalCount()]; for (int i = 0; i < heights.length; i++) { heights[i] = intervals.getInterval(i); } return heights; } public String toString() { return Double.toString(logLikelihood); } // Inner classes public class DeltaStatistic extends Statistic.Abstract { public DeltaStatistic() { super("delta"); } public int getDimension() { return 1; } public double getStatisticValue(int i) { throw new RuntimeException("Not implemented"); // return IntervalList.Utils.getDelta(intervals); } } // Private and protected stuff /** * The tree. */ private Tree tree = null; private final Set<String> includedLeafSet; private final Set[] excludedLeafSets; /** * The intervals. */ private Intervals intervals = null; /** * The stored values for intervals. */ private Intervals storedIntervals = null; private boolean eventsKnown = false; private boolean storedEventsKnown = false; private double logLikelihood; private double storedLogLikelihood; protected boolean likelihoodKnown = false; private boolean storedLikelihoodKnown = false; }
package edu.ucla.cens.awserver.service; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import edu.ucla.cens.awserver.datatransfer.AwRequest; import edu.ucla.cens.awserver.util.JsonUtils; /** * Service for logging details about data uploads. * * @author selsky */ public class MessageLoggerService implements Service { private static Logger _uploadLogger = Logger.getLogger("uploadLogger"); private static Logger _logger = Logger.getLogger(MessageLoggerService.class); /** * Performs the following tasks: logs the user's upload to the filesystem, logs the failed response message to the filesystem * (if the request failed), and logs a statistic message to the upload logger. */ public void execute(AwRequest awRequest) { _logger.info("beginning to log files and stats about a device upload"); logUploadToFilesystem(awRequest); logUploadStats(awRequest); _logger.info("finished with logging files and stats about a device upload"); } private void logUploadStats(AwRequest awRequest) { Object data = awRequest.getAttribute("jsonData"); String totalNumberOfMessages = "unknown"; String numberOfDuplicates = "unknown"; if(data instanceof JSONArray) { totalNumberOfMessages = String.valueOf(((JSONArray) data).length()); List<Integer> duplicateIndexList = (List<Integer>) awRequest.getAttribute("duplicateIndexList"); if(null != duplicateIndexList && duplicateIndexList.size() > 0) { numberOfDuplicates = String.valueOf(duplicateIndexList.size()); } else { numberOfDuplicates = "0"; } } long processingTime = System.currentTimeMillis() - (Long) awRequest.getAttribute("startTime"); StringBuilder builder = new StringBuilder(); if(awRequest.isFailedRequest()) { builder.append("failed_upload"); } else { builder.append("successful_upload"); } String user = awRequest.getUser().getUserName(); if(null == user) { user = "unknown.user"; } builder.append(" user=" + user); builder.append(" requestType=" + (String) awRequest.getAttribute("requestType")); builder.append(" numberOfRecords=" + totalNumberOfMessages); builder.append(" numberOfDuplicates=" + numberOfDuplicates); builder.append(" proccessingTimeMillis=" + processingTime); _uploadLogger.info(builder.toString()); } private void logUploadToFilesystem(AwRequest awRequest) { // Persist the devices's upload to the filesystem SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String userName = null == awRequest.getUser().getUserName() ? "unknown.user" : awRequest.getUser().getUserName(); String fileName = userName + "-" + sdf.format(new Date()); String catalinaBase = System.getProperty("catalina.base"); // need a system prop called upload-logging-directory or something like that Object data = awRequest.getAttribute("jsonData"); // could either be a String or a JSONArray depending on where the main // application processing ended PrintWriter printWriter = null; try { String uploadFileName = catalinaBase + "/logs/uploads/" + fileName + "-upload.json"; printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(uploadFileName)))); if(null != data) { printWriter.write(data.toString()); } else { printWriter.write("no data"); } close(printWriter); if(awRequest.isFailedRequest()) { printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/logs/uploads/" + fileName + "-failed-upload-response.json")))); String failedMessage = awRequest.getFailedRequestErrorMessage(); if(null != failedMessage) { JSONObject jsonObject = null; try { jsonObject = new JSONObject(failedMessage); // Dump out the request params jsonObject.put("request_type", awRequest.getAttribute("requestType")); jsonObject.put("user", awRequest.getUser().getUserName()); jsonObject.put("phone_version", awRequest.getAttribute("phoneVersion")); jsonObject.put("protocol_version", awRequest.getAttribute("protocolVersion")); jsonObject.put("upload_file_name", uploadFileName); } catch (JSONException jsone) { throw new IllegalArgumentException("invalid JSON in failedRequestErrorMessage -- logical error! JSON: " + failedMessage); } printWriter.write(jsonObject.toString()); } else { printWriter.write("no failed upload message found"); } close(printWriter); } List<Integer> duplicateIndexList = (List<Integer>) awRequest.getAttribute("duplicateIndexList"); Map<Integer, List<Integer>> duplicatePromptResponseMap = (Map<Integer, List<Integer>>) awRequest.getAttribute("duplicatePromptResponseMap"); if(null != duplicateIndexList && duplicateIndexList.size() > 0) { int size = duplicateIndexList.size(); int lastDuplicateIndex = -1; printWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(catalinaBase + "/logs/uploads/" + fileName + "-upload-duplicates.json")))); for(int i = 0; i < size; i++) { int duplicateIndex = duplicateIndexList.get(i); if("prompt".equals((String)awRequest.getAttribute("requestType"))) { if(lastDuplicateIndex != duplicateIndex) { List<Integer> list = duplicatePromptResponseMap.get(duplicateIndex); JSONObject outputObject = new JSONObject(); JSONArray jsonArray = new JSONArray(list); JSONObject dataPacket = JsonUtils.getJsonObjectFromJsonArray((JSONArray) data, duplicateIndex); try { outputObject.put("duplicatePromptIds", jsonArray); outputObject.put("dataPacket", dataPacket); } catch (JSONException jsone) { throw new IllegalStateException("attempt to add duplicateConfigIds array to data JSON Object for" + " duplicate logging caused JSONException: " + jsone.getMessage()); } lastDuplicateIndex = duplicateIndex; printWriter.write(outputObject.toString()); } } else { printWriter.write(JsonUtils.getJsonObjectFromJsonArray((JSONArray) data, duplicateIndex).toString()); } printWriter.write("\n"); } close(printWriter); } } catch(IOException ioe) { _logger.warn("caught IOException when logging upload data to the filesystem. " + ioe.getMessage()); close(printWriter); throw new ServiceException(ioe); } } private void close(PrintWriter writer) { if(null != writer) { writer.flush(); writer.close(); writer = null; } } }
package edu.washington.escience.myria.parallel; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.slf4j.LoggerFactory; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import edu.washington.escience.myria.DbException; import edu.washington.escience.myria.MyriaConstants; import edu.washington.escience.myria.MyriaConstants.FTMODE; import edu.washington.escience.myria.RelationKey; import edu.washington.escience.myria.api.encoding.QueryConstruct; import edu.washington.escience.myria.api.encoding.QueryConstruct.ConstructArgs; import edu.washington.escience.myria.api.encoding.QueryEncoding; import edu.washington.escience.myria.api.encoding.QueryStatusEncoding; import edu.washington.escience.myria.coordinator.catalog.CatalogException; import edu.washington.escience.myria.coordinator.catalog.MasterCatalog; import edu.washington.escience.myria.util.DateTimeUtils; import edu.washington.escience.myria.util.IPCUtils; /** * This class manages the queries running on Myria. It encapsulates the state outside of the Server object and handles * concurrency issues w.r.t. issuing, enqueuing, advance queries. */ public class QueryManager { /** The logger for this class. */ private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(MasterCatalog.class); /** * Queries currently active (queued, executing, being killed, etc.). */ private final ConcurrentHashMap<Long, Query> activeQueries; /** * Subqueries currently in execution. */ private final ConcurrentHashMap<SubQueryId, MasterSubQuery> executingSubQueries; /** The Myria catalog. */ private final MasterCatalog catalog; /** The Server on which this manager runs. */ private final Server server; /** * This class encapsulates all the work of keeping track of queries. This includes dispatching query plans to workers, * starting the queries, killing queries, restarting queries, etc. * * @param catalog the master catalog. Gets updated when queries finish, for example. * @param server the server on which the queries are executed. */ public QueryManager(final MasterCatalog catalog, final Server server) { this.catalog = catalog; this.server = server; activeQueries = new ConcurrentHashMap<>(); executingSubQueries = new ConcurrentHashMap<>(); } /** * @return if a query is running. * @param queryId queryID. */ public boolean queryCompleted(final long queryId) { return !activeQueries.containsKey(queryId); } /** * @return whether this master can handle more queries or not. */ private boolean canSubmitQuery() { return (activeQueries.size() < MyriaConstants.MAX_ACTIVE_QUERIES); } /** * Finish the specified query by updating its status in the Catalog and then removing it from the active queries. * * @param queryState the query to be finished * @throws DbException if there is an error updating the Catalog */ private void finishQuery(final Query queryState) throws DbException { try { catalog.queryFinished(queryState); } catch (CatalogException e) { throw new DbException("Error finishing query " + queryState.getQueryId(), e); } finally { activeQueries.remove(queryState.getQueryId()); } } /** * Computes and returns the status of queries that have been submitted to Myria. * * @param limit the maximum number of results to return. Any value <= 0 is interpreted as all results. * @param maxId the largest query ID returned. If null or <= 0, all queries will be returned. * @throws CatalogException if there is an error in the catalog. * @return a list of the status of every query that has been submitted to Myria. */ public List<QueryStatusEncoding> getQueries(final long limit, final long maxId) throws CatalogException { List<QueryStatusEncoding> ret = new LinkedList<>(); /* Begin by adding the status for all the active queries. */ TreeSet<Long> activeQueryIds = new TreeSet<>(activeQueries.keySet()); final Iterator<Long> iter = activeQueryIds.descendingIterator(); while (iter.hasNext()) { long queryId = iter.next(); final QueryStatusEncoding status = getQueryStatus(queryId); if (status == null) { LOGGER.warn("Weird: query status for active query {} is null.", queryId); continue; } ret.add(status); } /* Now add in the status for all the inactive (finished, killed, etc.) queries. */ for (QueryStatusEncoding q : catalog.getQueries(limit, maxId)) { if (!activeQueryIds.contains(q.queryId)) { ret.add(q); } } return ret; } @Nonnull public Query getQuery(@Nonnull final Long queryId) { Query query = activeQueries.get(Preconditions.checkNotNull(queryId, "queryId")); Preconditions.checkArgument(query != null, "Query #%s is not active", queryId); return query; } /** * Computes and returns the status of the requested query, or null if the query does not exist. * * @param queryId the identifier of the query. * @throws CatalogException if there is an error in the catalog. * @return the status of this query. */ public QueryStatusEncoding getQueryStatus(final long queryId) throws CatalogException { /* Get the stored data for this query, e.g., the submitted program. */ QueryStatusEncoding queryStatus = catalog.getQuery(queryId); if (queryStatus == null) { return null; } Query state = activeQueries.get(queryId); if (state == null) { /* Not active, so the information from the Catalog is authoritative. */ return queryStatus; } /* Currently active, so fill in the latest information about the query. */ queryStatus.startTime = state.getStartTime(); queryStatus.finishTime = state.getEndTime(); queryStatus.elapsedNanos = state.getElapsedTime(); queryStatus.status = state.getStatus(); return queryStatus; } /** * Submit a query for execution. The workerPlans may be removed in the future if the query compiler and schedulers are * ready. Returns null if there are too many active queries. * * @param queryId the catalog's assigned ID for this query. * @param query contains the query options (profiling, fault tolerance) * @param plan the query to be executed * @throws DbException if any error in non-catalog data processing * @throws CatalogException if any error in processing catalog * @return the query future from which the query status can be looked up. */ private QueryFuture submitQuery(final long queryId, final QueryEncoding query, final QueryPlan plan) throws DbException, CatalogException { final Query queryState = new Query(queryId, query, plan, server); activeQueries.put(queryId, queryState); advanceQuery(queryState); return queryState.getFuture(); } /** * @param queryId the query to be killed. */ public void killQuery(final long queryId) { getQuery(queryId).kill(); } /** * Find the master's subquery execution controller for the specified id. * * @param subQueryId the subquery id. * @return the master's subquery execution controller for the specified id. */ @Nonnull private MasterSubQuery getMasterSubQuery(@Nonnull final SubQueryId subQueryId) { return Preconditions.checkNotNull(executingSubQueries.get(subQueryId), "MasterSubQuery for subquery {} not found", subQueryId); } /** * Inform the query manager that the specified worker has acknowledged receiving the specified subquery. Once all * workers have received the subquery, the subquery may be started. * * @param subQueryId the subquery. * @param workerId the worker. */ public void workerReady(@Nonnull final SubQueryId subQueryId, final int workerId) { getMasterSubQuery(subQueryId).queryReceivedByWorker(workerId); } /** * Inform the query manager that the specified worker has successfully completed the specified subquery. Once all * workers have completed the subquery, the subquery is considered successful. * * @param subQueryId the subquery. * @param workerId the worker. */ public void workerComplete(@Nonnull final SubQueryId subQueryId, final int workerId) { getMasterSubQuery(subQueryId).workerComplete(workerId); } /** * Inform the query manager that the specified worker has failed with the given cause. * * @param subQueryId the subquery. * @param workerId the worker. * @param cause the cause of the worker's failure. */ public void workerFailed(@Nonnull final SubQueryId subQueryId, final int workerId, final Throwable cause) { getMasterSubQuery(subQueryId).workerFail(workerId, cause); } /** * Advance the given query to the next {@link SubQuery}. If there is no next {@link SubQuery}, mark the entire query * as having succeeded. * * @param queryState the specified query * @return the future of the next {@Link SubQuery}, or <code>null</code> if this query has succeeded. * @throws DbException if there is an error */ private LocalSubQueryFuture advanceQuery(final Query queryState) throws DbException { Verify.verify(queryState.getCurrentSubQuery() == null, "expected queryState current task is null"); SubQuery task; try { task = queryState.nextSubQuery(); } catch (QueryKilledException qke) { queryState.markKilled(); finishQuery(queryState); return null; } catch (RuntimeException | DbException e) { queryState.markFailed(e); finishQuery(queryState); return null; } if (task == null) { queryState.markSuccess(); finishQuery(queryState); return null; } return submitSubQuery(queryState); } /** * Submit the next subquery in the query for execution, and return its future. * * @param queryState the query containing the subquery to be executed * @return the future of the subquery * @throws DbException if there is an error submitting the subquery for execution */ private LocalSubQueryFuture submitSubQuery(final Query queryState) throws DbException { final SubQuery subQuery = Verify.verifyNotNull(queryState.getCurrentSubQuery(), "query state should have a current subquery"); final SubQueryId subQueryId = subQuery.getSubQueryId(); try { final MasterSubQuery mqp = new MasterSubQuery(subQuery, server); executingSubQueries.put(subQueryId, mqp); final LocalSubQueryFuture queryExecutionFuture = mqp.getExecutionFuture(); /* Add the future to update the metadata about created relations, if there are any. */ queryState.addDatasetMetadataUpdater(catalog, queryExecutionFuture); queryExecutionFuture.addListener(new LocalSubQueryFutureListener() { @Override public void operationComplete(final LocalSubQueryFuture future) throws Exception { finishSubQuery(subQueryId); final Long elapsedNanos = mqp.getExecutionStatistics().getQueryExecutionElapse(); if (future.isSuccess()) { LOGGER.info("Subquery #{} succeeded. Time elapsed: {}.", subQueryId, DateTimeUtils .nanoElapseToHumanReadable(elapsedNanos)); // TODO success management. advanceQuery(queryState); } else { Throwable cause = future.getCause(); LOGGER.info("Subquery #{} failed. Time elapsed: {}. Failure cause is {}.", subQueryId, DateTimeUtils .nanoElapseToHumanReadable(elapsedNanos), cause); if (cause instanceof QueryKilledException) { queryState.markKilled(); } else { queryState.markFailed(cause); } finishQuery(queryState); } } }); dispatchWorkerQueryPlans(mqp).addListener(new LocalSubQueryFutureListener() { @Override public void operationComplete(final LocalSubQueryFuture future) throws Exception { mqp.init(); if (subQueryId.getSubqueryId() == 0) { getQuery(subQueryId.getQueryId()).markStart(); } mqp.startExecution(); startWorkerQuery(future.getLocalSubQuery().getSubQueryId()); } }); return mqp.getExecutionFuture(); } catch (DbException | RuntimeException e) { finishSubQuery(subQueryId); queryState.markFailed(e); finishQuery(queryState); throw e; } } /** * @param mqp the master query * @return the query dispatch {@link LocalSubQueryFuture}. * @throws DbException if any error occurs. */ private LocalSubQueryFuture dispatchWorkerQueryPlans(final MasterSubQuery mqp) throws DbException { if (!server.getAliveWorkers().containsAll(mqp.getWorkerPlans().keySet())) { throw new DbException("Not all requested workers are alive."); } // directly set the master part as already received. mqp.queryReceivedByWorker(MyriaConstants.MASTER_ID); for (final Map.Entry<Integer, SubQueryPlan> e : mqp.getWorkerPlans().entrySet()) { int workerId = e.getKey(); try { server.getIPCConnectionPool().sendShortMessage(workerId, IPCUtils.queryMessage(mqp.getSubQueryId(), e.getValue())); } catch (final IOException ee) { throw new DbException(ee); } } return mqp.getWorkerReceiveFuture(); } /** * Tells all the workers to begin executing the specified {@link SubQuery}. * * @param subQueryId the id of the subquery to be started. */ private void startWorkerQuery(final SubQueryId subQueryId) { final MasterSubQuery mqp = executingSubQueries.get(subQueryId); for (final Integer workerID : mqp.getWorkerAssigned()) { server.getIPCConnectionPool().sendShortMessage(workerID, IPCUtils.startQueryTM(subQueryId)); } } /** * Finish the subquery by removing it from the data structures. * * @param subQueryId the id of the subquery to finish. */ private void finishSubQuery(final SubQueryId subQueryId) { long queryId = subQueryId.getQueryId(); executingSubQueries.remove(subQueryId); getQuery(queryId).finishSubQuery(); } /** * Submit a query for execution. The workerPlans may be removed in the future if the query compiler and schedulers are * ready. Returns null if there are too many active queries. * * @param query the query encoding. * @param plan the query to be executed * @throws DbException if any error in non-catalog data processing * @throws CatalogException if any error in processing catalog * @return the query future from which the query status can be looked up. */ public QueryFuture submitQuery(final QueryEncoding query, final QueryPlan plan) throws DbException, CatalogException { if (!canSubmitQuery()) { throw new DbException("Cannot submit query"); } if (query.profilingMode) { if (!(plan instanceof SubQuery || plan instanceof JsonSubQuery)) { throw new DbException("Profiling mode is not supported for plans (" + plan.getClass().getSimpleName() + ") that may contain multiple subqueries."); } if (!server.getDBMS().equals(MyriaConstants.STORAGE_SYSTEM_POSTGRESQL)) { throw new DbException("Profiling mode is only supported when using Postgres as the storage system."); } } if (plan instanceof JsonSubQuery) { /* Hack to instantiate a single-fragment query for the visualization. */ QueryConstruct.instantiate(((JsonSubQuery) plan).getFragments(), new ConstructArgs(server, -1)); } final long queryID = catalog.newQuery(query); return submitQuery(queryID, query, plan); } /** * @param queryId the query that owns the desired temp relation. * @param relationKey the key of the desired temp relation. * @return the list of workers that store the specified relation. */ public Set<Integer> getWorkersForTempRelation(@Nonnull final Long queryId, @Nonnull final RelationKey relationKey) { return getQuery(queryId).getWorkersForTempRelation(relationKey); } /** * Kill a subquery. * * @param subQueryId the ID of the subquery to be killed */ protected void killSubQuery(final SubQueryId subQueryId) { Preconditions.checkNotNull(subQueryId, "subQueryId"); MasterSubQuery subQuery = executingSubQueries.get(subQueryId); if (subQuery != null) { subQuery.kill(); } else { LOGGER.warn("tried to kill subquery {} but it is not executing.", subQueryId); } } /** * Submit a query for execution. The workerPlans may be removed in the future if the query compiler and schedulers are * ready. Returns null if there are too many active queries. * * @param rawQuery the raw user-defined query. E.g., the source Datalog program. * @param logicalRa the logical relational algebra of the compiled plan. * @param physicalPlan the Myria physical plan for the query. * @param workerPlans the physical parallel plan fragments for each worker. * @param masterPlan the physical parallel plan fragment for the master. * @param profilingMode is the profiling mode of the query on. * @throws DbException if any error in non-catalog data processing * @throws CatalogException if any error in processing catalog * @return the query future from which the query status can be looked up. */ public QueryFuture submitQuery(final String rawQuery, final String logicalRa, final String physicalPlan, final SubQueryPlan masterPlan, final Map<Integer, SubQueryPlan> workerPlans, @Nullable final Boolean profilingMode) throws DbException, CatalogException { QueryEncoding query = new QueryEncoding(); query.rawQuery = rawQuery; query.logicalRa = rawQuery; query.fragments = ImmutableList.of(); query.profilingMode = Objects.firstNonNull(profilingMode, false); return submitQuery(query, new SubQuery(masterPlan, workerPlans)); } /** * Kill all queries currently executing. */ protected void killAll() { for (MasterSubQuery p : executingSubQueries.values()) { p.kill(); } } /** * Inform the query manager that the specified worker has died. Depending on their fault-tolerance mode, executing * queries may be killed or be told that the worker has died. * * @param workerId the worker that died. */ protected void workerDied(final int workerId) { for (MasterSubQuery mqp : executingSubQueries.values()) { /* for each alive query that the failed worker is assigned to, tell the query that the worker failed. */ if (mqp.getWorkerAssigned().contains(workerId)) { mqp.workerFail(workerId, new LostHeartbeatException()); } if (mqp.getFTMode().equals(FTMODE.abandon)) { mqp.getMissingWorkers().add(workerId); mqp.updateProducerChannels(workerId, false); mqp.triggerFragmentEosEoiChecks(); } else if (mqp.getFTMode().equals(FTMODE.rejoin)) { mqp.getMissingWorkers().add(workerId); mqp.updateProducerChannels(workerId, false); } } } /** * Inform the query manager that the specified worker has restarted. Executing queries in REJOIN mode may be informed * that the worker is alive, assuming that all workers have acknowledged its rebirth. * * @param workerId the worker that has restarted. * @param workersAcked the workers that have acknowledged its rebirth. */ protected void workerRestarted(final int workerId, final Set<Integer> workersAcked) { for (MasterSubQuery mqp : executingSubQueries.values()) { if (mqp.getFTMode().equals(FTMODE.rejoin) && mqp.getMissingWorkers().contains(workerId) && workersAcked.containsAll(mqp.getWorkerAssigned())) { /* so a following ADD_WORKER_ACK won't cause queryMessage to be sent again */ mqp.getMissingWorkers().remove(workerId); try { server.getIPCConnectionPool().sendShortMessage(workerId, IPCUtils.queryMessage(mqp.getSubQueryId(), mqp.getWorkerPlans().get(workerId))); } catch (final IOException e) { throw new RuntimeException(e); } } } } }
package nl.mpi.kinnate.svg; import java.awt.Point; import nl.mpi.kinnate.kindata.EntityData; import java.util.ArrayList; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.uniqueidentifiers.IdentifierException; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.svg.SVGDocument; public class RelationSvg { private void addUseNode(SVGDocument doc, String svgNameSpace, Element targetGroup, String targetDefId) { String useNodeId = targetDefId + "use"; Node useNodeOld = doc.getElementById(useNodeId); if (useNodeOld != null) { useNodeOld.getParentNode().removeChild(useNodeOld); } Element useNode = doc.createElementNS(svgNameSpace, "use"); useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + targetDefId); // the xlink: of "xlink:href" is required for some svg viewers to render correctly // useNode.setAttribute("href", "#" + lineIdString); useNode.setAttribute("id", useNodeId); targetGroup.appendChild(useNode); } private void updateLabelNode(SVGDocument doc, String svgNameSpace, String lineIdString, String targetRelationId) { // remove and readd the text on path label so that it updates with the new path String labelNodeId = targetRelationId + "label"; Node useNodeOld = doc.getElementById(labelNodeId); if (useNodeOld != null) { Node textParentNode = useNodeOld.getParentNode(); String labelText = useNodeOld.getTextContent(); useNodeOld.getParentNode().removeChild(useNodeOld); Element textPath = doc.createElementNS(svgNameSpace, "textPath"); textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly textPath.setAttribute("startOffset", "50%"); textPath.setAttribute("id", labelNodeId); Text textNode = doc.createTextNode(labelText); textPath.appendChild(textNode); textParentNode.appendChild(textPath); } } protected void setPolylinePointsAttribute(LineLookUpTable lineLookUpTable, String lineIdString, Element targetNode, DataTypes.RelationType relationType, float vSpacing, float egoX, float egoY, float alterX, float alterY, float[] averageParent) { //float midY = (egoY + alterY) / 2; // todo: Ticket #1064 when an entity is above one that it should be below the line should make a zigzag to indicate it ArrayList<Point> initialPointsList = new ArrayList<Point>(); float midSpacing = vSpacing / 2; // float parentSpacing = 10; float egoYmid; float alterYmid; float centerX = (egoX + alterX) / 2; switch (relationType) { case ancestor: egoYmid = egoY - midSpacing; alterYmid = averageParent[1] + 30; // alterYmid = alterY + midSpacing; // egoYmid = alterYmid + 30; centerX = (egoYmid < alterYmid) ? centerX : egoX; centerX = (egoY < alterY && egoX == alterX) ? centerX - midSpacing : centerX; break; // float tempX = egoX; // float tempY = egoY; // egoX = alterX; // egoY = alterY; // alterX = tempX; // alterY = tempY; case descendant: throw new UnsupportedOperationException("in order to simplify this ancestor relations should be swapped so that ego is the parent"); // egoYmid = egoY + midSpacing; // alterYmid = alterY - midSpacing; // centerX = (egoYmid < alterYmid) ? alterX : centerX; // centerX = (egoY > alterY && egoX == alterX) ? centerX - midSpacing : centerX; // break; case sibling: egoYmid = egoY - midSpacing; alterYmid = alterY - midSpacing; centerX = (egoY < alterY) ? alterX : egoX; centerX = (egoX == alterX) ? centerX - midSpacing : centerX; break; case union: egoYmid = egoY + midSpacing; alterYmid = alterY + midSpacing; centerX = (egoY < alterY) ? egoX : alterX; centerX = (egoX == alterX) ? centerX - midSpacing : centerX; break; case affiliation: case none: default: egoYmid = egoY; alterYmid = alterY; break; } // if (alterY == egoY) { // // make sure that union lines go below the entities and sibling lines go above // if (relationType == DataTypes.RelationType.sibling) { // midY = alterY - vSpacing / 2; // } else if (relationType == DataTypes.RelationType.union) { // midY = alterY + vSpacing / 2; initialPointsList.add(new Point((int) egoX, (int) egoY)); initialPointsList.add(new Point((int) egoX, (int) egoYmid)); if (averageParent != null) { float averageParentX = averageParent[0]; // float minParentY = averageParent[1]; initialPointsList.add(new Point((int) averageParentX, (int) egoYmid)); initialPointsList.add(new Point((int) averageParentX, (int) alterYmid)); } else { initialPointsList.add(new Point((int) centerX, (int) egoYmid)); initialPointsList.add(new Point((int) centerX, (int) alterYmid)); } initialPointsList.add(new Point((int) alterX, (int) alterYmid)); initialPointsList.add(new Point((int) alterX, (int) alterY)); Point[] adjustedPointsList; if (lineLookUpTable != null) { // this version is used when the relations are drawn on the diagram // or when an entity is dragged before the diagram is redrawn in the case of a reloaded from disk diagram (this case is sub optimal in that on first load the loops will not be drawn) adjustedPointsList = lineLookUpTable.adjustLineToObstructions(lineIdString, initialPointsList); } else { // this version is used when the relation drag handles are used adjustedPointsList = initialPointsList.toArray(new Point[]{}); } StringBuilder stringBuilder = new StringBuilder(); for (Point currentPoint : adjustedPointsList) { stringBuilder.append(currentPoint.x); stringBuilder.append(","); stringBuilder.append(currentPoint.y); stringBuilder.append(" "); } targetNode.setAttribute("points", stringBuilder.toString()); } protected void setPathPointsAttribute(Element targetNode, DataTypes.RelationType relationType, DataTypes.RelationLineType relationLineType, float hSpacing, float vSpacing, float egoX, float egoY, float alterX, float alterY) { float fromBezX; float fromBezY; float toBezX; float toBezY; if ((egoX > alterX && egoY < alterY) || (egoX > alterX && egoY > alterY)) { // prevent the label on the line from rendering upside down float tempX = alterX; float tempY = alterY; alterX = egoX; alterY = egoY; egoX = tempX; egoY = tempY; } if (relationLineType == DataTypes.RelationLineType.verticalCurve) { fromBezX = egoX; fromBezY = alterY; toBezX = alterX; toBezY = egoY; // todo: update the bezier positions similar to in the follwing else statement if (1 / (egoY - alterY) < vSpacing) { fromBezX = egoX; fromBezY = alterY - vSpacing / 2; toBezX = alterX; toBezY = egoY - vSpacing / 2; } } else { fromBezX = alterX; fromBezY = egoY; toBezX = egoX; toBezY = alterY; // todo: if the nodes are almost in align then this test fails and it should insted check for proximity not equality // System.out.println(1 / (egoX - alterX)); // if (1 / (egoX - alterX) < vSpacing) { if (egoX > alterX) { if (egoX - alterX < hSpacing / 4) { fromBezX = egoX - hSpacing / 4; toBezX = alterX - hSpacing / 4; } else { fromBezX = (egoX - alterX) / 2 + alterX; toBezX = (egoX - alterX) / 2 + alterX; } } else { if (alterX - egoX < hSpacing / 4) { fromBezX = egoX + hSpacing / 4; toBezX = alterX + hSpacing / 4; } else { fromBezX = (alterX - egoX) / 2 + egoX; toBezX = (alterX - egoX) / 2 + egoX; } } } targetNode.setAttribute("d", "M " + egoX + "," + egoY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + alterX + "," + alterY); } private boolean hasCommonParent(EntityData currentNode, EntityRelation graphLinkNode) { if (graphLinkNode.relationType == DataTypes.RelationType.sibling) { for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) { if (altersRelation.relationType == DataTypes.RelationType.ancestor) { for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) { if (egosRelation.relationType == DataTypes.RelationType.ancestor) { if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) { if (altersRelation.getAlterNode().isVisible) { return true; } } } } } } } return false; } // private Float getCommonParentMaxY(EntitySvg entitySvg, EntityData currentNode, EntityRelation graphLinkNode) { // if (graphLinkNode.relationType == DataTypes.RelationType.sibling) { // Float maxY = null; // ArrayList<Float> commonParentY = new ArrayList<Float>(); // for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) { // if (altersRelation.relationType == DataTypes.RelationType.ancestor) { // for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) { // if (egosRelation.relationType == DataTypes.RelationType.ancestor) { // if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) { // float parentY = entitySvg.getEntityLocation(egosRelation.alterUniqueIdentifier)[1]; // maxY = parentY > maxY ? parentY : maxY; // return maxY; // } else { // return null; protected void insertRelation(GraphPanel graphPanel, Element relationGroupNode, EntityData currentNode, EntityRelation graphLinkNode, int hSpacing, int vSpacing) { if (graphLinkNode.relationLineType == DataTypes.RelationLineType.sanguineLine) { if (hasCommonParent(currentNode, graphLinkNode)) { return; // do not draw lines for siblings if the common parent is visible because the ancestor lines will take the place of the sibling lines } } int relationLineIndex = relationGroupNode.getChildNodes().getLength(); Element groupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); groupNode.setAttribute("id", "relation" + relationLineIndex); Element defsNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "defs"); String lineIdString = "relation" + relationLineIndex + "Line"; new DataStoreSvg().storeRelationParameters(graphPanel.doc, groupNode, graphLinkNode.relationType, graphLinkNode.relationLineType, currentNode.getUniqueIdentifier(), graphLinkNode.getAlterNode().getUniqueIdentifier()); // set the line end points // int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(currentNode.getUniqueIdentifier()); // int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier()); float[] egoSymbolPoint; float[] alterSymbolPoint; float[] parentPoint; DataTypes.RelationType directedRelation = graphLinkNode.relationType; if (directedRelation == DataTypes.RelationType.descendant) { // make sure the ancestral relations are unidirectional egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier()); alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(currentNode.getUniqueIdentifier()); parentPoint = graphPanel.entitySvg.getAverageParentLocation(graphLinkNode.getAlterNode()); directedRelation = DataTypes.RelationType.ancestor; } else { egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(currentNode.getUniqueIdentifier()); alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier()); parentPoint = graphPanel.entitySvg.getAverageParentLocation(currentNode); } // float fromX = (currentNode.getxPos()); // * hSpacing + hSpacing // float fromY = (currentNode.getyPos()); // * vSpacing + vSpacing // float toX = (graphLinkNode.getAlterNode().getxPos()); // * hSpacing + hSpacing // float toY = (graphLinkNode.getAlterNode().getyPos()); // * vSpacing + vSpacing float fromX = (egoSymbolPoint[0]); // * hSpacing + hSpacing float fromY = (egoSymbolPoint[1]); // * vSpacing + vSpacing float toX = (alterSymbolPoint[0]); // * hSpacing + hSpacing float toY = (alterSymbolPoint[1]); // * vSpacing + vSpacing boolean addedRelationLine = false; switch (graphLinkNode.relationLineType) { case kinTermLine: // this case uses the following case case verticalCurve: // todo: groupNode.setAttribute("id", ); // System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos); //// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/> // Element linkLine = doc.createElementNS(svgNS, "line"); // linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing)); // linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing)); // linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing)); // linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing)); // linkLine.setAttribute("stroke", "black"); // linkLine.setAttribute("stroke-width", "1"); // // Attach the rectangle to the root 'svg' element. // svgRoot.appendChild(linkLine); //System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos); // <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/> Element linkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "path"); setPathPointsAttribute(linkLine, directedRelation, graphLinkNode.relationLineType, hSpacing, vSpacing, fromX, fromY, toX, toY); // linkLine.setAttribute("x1", ); // linkLine.setAttribute("y1", ); // linkLine.setAttribute("x2", ); linkLine.setAttribute("fill", "none"); if (graphLinkNode.lineColour != null) { linkLine.setAttribute("stroke", graphLinkNode.lineColour); } else { linkLine.setAttribute("stroke", "blue"); } linkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); linkLine.setAttribute("id", lineIdString); defsNode.appendChild(linkLine); addedRelationLine = true; break; case sanguineLine: // Element squareLinkLine = doc.createElement("line"); // squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing)); // squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing)); // squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing)); // squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing)); // squareLinkLine.setAttribute("stroke", "grey"); // squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth)); Element squareLinkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineIdString, squareLinkLine, directedRelation, vSpacing, fromX, fromY, toX, toY, parentPoint); squareLinkLine.setAttribute("fill", "none"); squareLinkLine.setAttribute("stroke", "grey"); squareLinkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); squareLinkLine.setAttribute("id", lineIdString); defsNode.appendChild(squareLinkLine); addedRelationLine = true; break; } groupNode.appendChild(defsNode); if (addedRelationLine) { // insert the node that uses the above definition addUseNode(graphPanel.doc, graphPanel.svgNameSpace, groupNode, lineIdString); // add the relation label if (graphLinkNode.labelString != null) { Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("text-anchor", "middle"); // labelText.setAttribute("x", Integer.toString(labelX)); // labelText.setAttribute("y", Integer.toString(labelY)); if (graphLinkNode.lineColour != null) { labelText.setAttribute("fill", graphLinkNode.lineColour); } else { labelText.setAttribute("fill", "blue"); } labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "14"); // labelText.setAttribute("transform", "rotate(45)"); // Element textPath = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "textPath"); // textPath.setAttributeNS("http://www.w3.rg/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly // textPath.setAttribute("startOffset", "50%"); // textPath.setAttribute("id", "relation" + relationLineIndex + "label"); // Text textNode = graphPanel.doc.createTextNode(graphLinkNode.labelString); // textPath.appendChild(textNode); // labelText.appendChild(textPath); groupNode.appendChild(labelText); } } relationGroupNode.appendChild(groupNode); } public void updateRelationLines(GraphPanel graphPanel, ArrayList<UniqueIdentifier> draggedNodeIds, int hSpacing, int vSpacing) { // todo: if an entity is above its ancestor then this must be corrected, if the ancestor data is stored in the relationLine attributes then this would be a good place to correct this Element relationGroup = graphPanel.doc.getElementById("RelationGroup"); for (Node currentChild = relationGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { if ("g".equals(currentChild.getLocalName())) { Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); //System.out.println("idAttrubite: " + idAttrubite.getNodeValue()); try { DataStoreSvg.GraphRelationData graphRelationData = new DataStoreSvg().getEntitiesForRelations(currentChild); if (graphRelationData != null) { if (draggedNodeIds.contains(graphRelationData.egoNodeId) || draggedNodeIds.contains(graphRelationData.alterNodeId)) { // todo: update the relation lines //System.out.println("needs update on: " + idAttrubite.getNodeValue()); String lineElementId = idAttrubite.getNodeValue() + "Line"; Element relationLineElement = graphPanel.doc.getElementById(lineElementId); //System.out.println("type: " + relationLineElement.getLocalName()); float[] egoSymbolPoint; float[] alterSymbolPoint; float[] parentPoint; // int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.egoNodeId); // int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.alterNodeId); DataTypes.RelationType directedRelation = graphRelationData.relationType; if (directedRelation == DataTypes.RelationType.descendant) { // make sure the ancestral relations are unidirectional egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.alterNodeId); alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.egoNodeId); parentPoint = graphPanel.entitySvg.getAverageParentLocation(graphRelationData.alterNodeId); directedRelation = DataTypes.RelationType.ancestor; } else { egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.egoNodeId); alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.alterNodeId); parentPoint = graphPanel.entitySvg.getAverageParentLocation(graphRelationData.egoNodeId); } float egoX = egoSymbolPoint[0]; float egoY = egoSymbolPoint[1]; float alterX = alterSymbolPoint[0]; float alterY = alterSymbolPoint[1]; // SVGRect egoSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.egoNodeId); // SVGRect alterSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.alterNodeId); // float egoX = egoSymbolRect.getX() + egoSymbolRect.getWidth() / 2; // float egoY = egoSymbolRect.getY() + egoSymbolRect.getHeight() / 2; // float alterX = alterSymbolRect.getX() + alterSymbolRect.getWidth() / 2; // float alterY = alterSymbolRect.getY() + alterSymbolRect.getHeight() / 2; if ("polyline".equals(relationLineElement.getLocalName())) { setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineElementId, relationLineElement, directedRelation, vSpacing, egoX, egoY, alterX, alterY, parentPoint); } if ("path".equals(relationLineElement.getLocalName())) { setPathPointsAttribute(relationLineElement, directedRelation, graphRelationData.relationLineType, hSpacing, vSpacing, egoX, egoY, alterX, alterY); } addUseNode(graphPanel.doc, graphPanel.svgNameSpace, (Element) currentChild, lineElementId); updateLabelNode(graphPanel.doc, graphPanel.svgNameSpace, lineElementId, idAttrubite.getNodeValue()); } } } catch (IdentifierException exception) { // GuiHelper.linorgBugCatcher.logError(exception); ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to read related entities, sanguine lines might be incorrect", "Update Sanguine Lines"); } } } } // new RelationSvg().addTestNode(doc, (Element) relationLineElement.getParentNode().getParentNode(), svgNameSpace); // public void addTestNode(SVGDocument doc, Element addTarget, String svgNameSpace) { // Element squareNode = doc.createElementNS(svgNameSpace, "rect"); // squareNode.setAttribute("x", "100"); // squareNode.setAttribute("y", "100"); // squareNode.setAttribute("width", "20"); // squareNode.setAttribute("height", "20"); // squareNode.setAttribute("fill", "green"); // squareNode.setAttribute("stroke", "black"); // squareNode.setAttribute("stroke-width", "2"); // addTarget.appendChild(squareNode); }
package org.hisp.dhis.android.testapp.organisationunit; import org.hisp.dhis.android.core.common.BaseIdentifiableObject; import org.hisp.dhis.android.core.data.database.SyncedDatabaseMockIntegrationShould; import org.hisp.dhis.android.core.organisationunit.OrganisationUnit; import org.junit.Test; import org.junit.runner.RunWith; import java.text.ParseException; import java.util.List; import androidx.test.runner.AndroidJUnit4; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @RunWith(AndroidJUnit4.class) public class OrganisationUnitCollectionRepositoryMockIntegrationShould extends SyncedDatabaseMockIntegrationShould { @Test public void find_all() { List<OrganisationUnit> organisationUnits = d2.organisationUnitModule().organisationUnits.get(); assertThat(organisationUnits.size(), is(1)); } @Test public void filter_by_parent_uid() { List<OrganisationUnit> organisationUnits = d2.organisationUnitModule().organisationUnits .byParentUid().eq("YuQRtpLP10I").get(); assertThat(organisationUnits.size(), is(1)); } @Test public void filter_by_path() { List<OrganisationUnit> organisationUnits = d2.organisationUnitModule().organisationUnits .byPath().eq("/ImspTQPwCqd/O6uvpzGd5pu/YuQRtpLP10I/DiszpKrYNg8").get(); assertThat(organisationUnits.size(), is(1)); } @Test public void filter_by_opening_date() throws ParseException { List<OrganisationUnit> organisationUnits = d2.organisationUnitModule().organisationUnits .byOpeningDate().eq(BaseIdentifiableObject.parseDate("1970-01-01T00:00:00.000")).get(); assertThat(organisationUnits.size(), is(1)); } @Test public void filter_by_closed_date() throws ParseException { List<OrganisationUnit> organisationUnits = d2.organisationUnitModule().organisationUnits .byClosedDate().eq(BaseIdentifiableObject.parseDate("2018-05-22T15:21:48.516")).get(); assertThat(organisationUnits.size(), is(1)); } @Test public void filter_by_level() { List<OrganisationUnit> organisationUnits = d2.organisationUnitModule().organisationUnits .byLevel().eq(4).get(); assertThat(organisationUnits.size(), is(1)); } @Test public void filter_by_display_name_path() { List<OrganisationUnit> organisationUnits = d2.organisationUnitModule().organisationUnits .byDisplayNamePath().eq("/Ngelehun CHC").get(); assertThat(organisationUnits.size(), is(1)); } @Test public void filter_by_organisation_unit_scope() { List<OrganisationUnit> captureOrganisationUnits = d2.organisationUnitModule().organisationUnits .byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE) .get(); assertThat(captureOrganisationUnits.size(), is(1)); List<OrganisationUnit> searchOrganisationUnits = d2.organisationUnitModule().organisationUnits .byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_TEI_SEARCH) .get(); assertThat(searchOrganisationUnits.size(), is(0)); } @Test public void filter_by_root_organisation_unit() { List<OrganisationUnit> rootOrganisationUnits = d2.organisationUnitModule().organisationUnits .byRootOrganisationUnit(Boolean.TRUE) .get(); assertThat(rootOrganisationUnits.size(), is(1)); List<OrganisationUnit> notRootOrganisationUnits = d2.organisationUnitModule().organisationUnits .byRootOrganisationUnit(Boolean.FALSE) .get(); assertThat(notRootOrganisationUnits.size(), is(0)); } @Test public void filter_by_root_capture_organisation_unit() { List<OrganisationUnit> rootOrganisationUnits = d2.organisationUnitModule().organisationUnits .byRootOrganisationUnit(Boolean.TRUE) .byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE) .get(); assertThat(rootOrganisationUnits.size(), is(1)); } @Test public void include_programs_as_children() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .withPrograms().one().get(); assertThat(organisationUnit.programs().get(0).name(), is("Antenatal care visit")); } @Test public void include_data_sets_as_children() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .withDataSets().one().get(); assertThat(organisationUnit.dataSets().get(0).name(), is("ART monthly summary")); } @Test public void include_organisation_unit_groups_as_children() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .withOrganisationUnitGroups().one().get(); assertThat(organisationUnit.organisationUnitGroups().get(0).name(), is("CHC")); } @Test public void include_programs_as_children_in_collection_repository_when_all_selected() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .withAllChildren().get().get(0); assertThat(organisationUnit.programs().get(0).name(), is("Antenatal care visit")); } @Test public void include_data_sets_as_children_in_collection_repository_when_all_selected() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .withAllChildren().get().get(0); assertThat(organisationUnit.dataSets().get(0).name(), is("ART monthly summary")); } @Test public void include_organisation_unit_groups_as_children_in_collection_repository_when_all_selected() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .withAllChildren().get().get(0); assertThat(organisationUnit.organisationUnitGroups().get(0).name(), is("CHC")); } @Test public void include_programs_as_children_in_object_repository_when_all_selected() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .one().withAllChildren().get(); assertThat(organisationUnit.programs().get(0).name(), is("Antenatal care visit")); } @Test public void include_data_sets_as_children_in_object_repository_when_all_selected() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .one().withAllChildren().get(); assertThat(organisationUnit.dataSets().get(0).name(), is("ART monthly summary")); } @Test public void include_organisation_unit_groups_as_children_in_object_repository_when_all_selected() { OrganisationUnit organisationUnit = d2.organisationUnitModule().organisationUnits .one().withAllChildren().get(); assertThat(organisationUnit.organisationUnitGroups().get(0).name(), is("CHC")); } }
package eu.neclab.iotplatform.iotbroker.restcontroller; import java.io.BufferedReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import eu.neclab.iotplatform.iotbroker.commons.GenerateMetadata; import eu.neclab.iotplatform.iotbroker.commons.HttpRequester; import eu.neclab.iotplatform.iotbroker.commons.JsonValidator; import eu.neclab.iotplatform.iotbroker.commons.XmlValidator; import eu.neclab.iotplatform.iotbroker.commons.interfaces.LeafengineInterface; import eu.neclab.iotplatform.iotbroker.restcontroller.sanitycheck.SanityCheck; import eu.neclab.iotplatform.ngsi.api.datamodel.AppendContextElementRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.AppendContextElementResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.Code; import eu.neclab.iotplatform.ngsi.api.datamodel.ContextAttribute; import eu.neclab.iotplatform.ngsi.api.datamodel.ContextAttributeResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.ContextElement; import eu.neclab.iotplatform.ngsi.api.datamodel.ContextElementResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.ContextMetadata; import eu.neclab.iotplatform.ngsi.api.datamodel.Converter; import eu.neclab.iotplatform.ngsi.api.datamodel.EntityId; import eu.neclab.iotplatform.ngsi.api.datamodel.NotifyContextAvailabilityRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.NotifyContextAvailabilityResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.NotifyContextRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.NotifyContextResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.QueryContextRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.QueryContextResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.ReasonPhrase; import eu.neclab.iotplatform.ngsi.api.datamodel.StatusCode; import eu.neclab.iotplatform.ngsi.api.datamodel.SubscribeContextRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.SubscribeContextResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.SubscribeError; import eu.neclab.iotplatform.ngsi.api.datamodel.UnsubscribeContextRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.UnsubscribeContextResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.UpdateActionType; import eu.neclab.iotplatform.ngsi.api.datamodel.UpdateContextAttributeRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.UpdateContextElementRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.UpdateContextElementResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.UpdateContextRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.UpdateContextResponse; import eu.neclab.iotplatform.ngsi.api.datamodel.UpdateContextSubscriptionRequest; import eu.neclab.iotplatform.ngsi.api.datamodel.UpdateContextSubscriptionResponse; import eu.neclab.iotplatform.ngsi.api.ngsi10.Ngsi10Interface; import eu.neclab.iotplatform.ngsi.api.ngsi9.Ngsi9Interface; /** * This class implements the RESTful binding of NGSI 10 defined by the FI-WARE * project. It maps operations on the RESTful interface to operations on an NGSI * java interface. * <p> * In addition, also the NGSI 9 method for receiving notifications is * implemented by this class. * */ @Controller public class RestProviderController { /** The logger. */ private static Logger logger = Logger .getLogger(RestProviderController.class); /** String representing json content type. */ private final String CONTENT_TYPE_JSON = "application/json"; /** String representing xml content type. */ private final String CONTENT_TYPE_XML = "application/xml"; /** The ngsi9url address of NGSI 9 component */ @Value("${ngsi9Uri}") private String ngsi9url; /** The component for receiving Leafengine requests. */ @Autowired private LeafengineInterface leafengine; public LeafengineInterface getLeafengine() { return leafengine; } public void setLeafengine(LeafengineInterface leafengine) { this.leafengine = leafengine; } /** The component for receiving NGSI9 requests. */ @Autowired private Ngsi9Interface ngsi9Core; /** The component for receiving NGSI 10 requests. */ private Ngsi10Interface ngsiCore; /** * Returns a pointer to the component which receives NGSI 10 requests * arriving at the controller. * * @return the ngsi core */ public Ngsi10Interface getNgsiCore() { return ngsiCore; } /** * Assigns a pointer to the component which will receive NGSI 10 requests * arriving at the controller. * * @param ngsiCore * the new ngsi core */ public void setNgsiCore(Ngsi10Interface ngsiCore) { this.ngsiCore = ngsiCore; } /** * Returns a pointer to the component which receives NGSI 9 requests * arriving at the controller. * * @return the ngsi9 core */ public Ngsi9Interface getNgsi9Core() { return ngsi9Core; } /** * Assigns a pointer to the component which will receive NGSI 9 requests * arriving at the controller. * * @param ngsi9Core * the new ngsi9 core */ public void setNgsi9Core(Ngsi9Interface ngsi9Core) { this.ngsi9Core = ngsi9Core; } /** String representing the xml schema for NGSI 10. */ private @Value("${schema_ngsi10_operation}") String sNgsi10schema; /** String representing the xml schema for NGSI 9. */ private @Value("${schema_ngsi9_operation}") String sNgsi9schema; /** * Instantiates a new controller object. */ public RestProviderController() { } /** * Redirector to the index.html web page. * */ @RequestMapping(value = "/", method = RequestMethod.GET) public String index() { return "redirect:index.html"; } /** * Redirector to the index.html web page. * */ @RequestMapping(value = "/index.html", method = RequestMethod.GET) public String operation() { return "index"; } /** * Monitoring. * * @return the string */ @RequestMapping(value = "/monitoring", method = RequestMethod.GET) public String monitoring() { return "redirect:admin"; } /** * Redirector to the administration web page. * */ @RequestMapping(value = "/admin", method = RequestMethod.GET) public String admin() { return "redirect:admin.html"; } @RequestMapping(value = "/restclient.html", method = RequestMethod.GET) public String restclient() { return "restclient"; } /** * Redirector to the administration web page. * */ @RequestMapping(value = "/admin.html", method = RequestMethod.GET) public String adminHtml() { return "admin"; } /** * Redirector to the "login failed" web page. */ @RequestMapping(value = "/loginfailed.html", method = RequestMethod.GET) public String logoutHtml() { return "loginfailed"; } /** * Executes the Sanity Check Procedure of the IoT Broker. * * @return the response entity */ @RequestMapping(value = "/ngsi10/sanityCheck", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<SanityCheck> sanityCheck() { BundleContext bc = FrameworkUtil .getBundle(RestProviderController.class).getBundleContext(); SanityCheck response = new SanityCheck("IoT Broker GE", "Sanity Check", "Version: " + bc.getBundle().getVersion()); return new ResponseEntity<SanityCheck>(response, HttpStatus.OK); } /** * Executes the test of the IoT Broker, which simply returns the request * message. * * @return the response entity */ @RequestMapping(value = "/ngsi10/test", method = RequestMethod.POST, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<QueryContextRequest> test( HttpServletRequest requester, @RequestBody QueryContextRequest request) { System.out.println(request); return new ResponseEntity<QueryContextRequest>(request, HttpStatus.OK); } /** * Executes a syntax check of incoming messages. Currently supported formats * are XML and JSON. */ private boolean validateMessageBody(HttpServletRequest request, Object objRequest, String schema) { boolean status = false; logger.info("ContentType: " + request.getContentType()); if (request.getContentType().contains("application/xml")) { XmlValidator validator = new XmlValidator(); status = validator.xmlValidation(objRequest, schema); } else if (request.getContentType().contains("application/json")) { JsonValidator validator = new JsonValidator(); StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { jb.append(line); } } catch (Exception e) { logger.info("Impossible to get the Json Request! Please check the error using debug mode."); if (logger.isDebugEnabled()) { logger.debug("Impossible to get the Json Request", e); } } status = validator.isValidJSON(jb.toString()); } logger.info("Incoming request Valid:" + status); return status; } /** * Executes the standard NGSI 10 QueryContext method. * * @param requester * Represents the request message body and header. * @param request * The request body. * @return The response body. * */ @RequestMapping(value = "/ngsi10/queryContext", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<QueryContextResponse> complexQuery( HttpServletRequest requester, @RequestBody QueryContextRequest request) { logger.info(" < // System.out.println(request); if (validateMessageBody(requester, request, sNgsi10schema)) { QueryContextResponse response = ngsiCore.queryContext(request); if (logger.isDebugEnabled()) { logger.debug("Entity TYPE = " + request.getEntityIdList().get(0).getType()); } return new ResponseEntity<QueryContextResponse>(response, HttpStatus.OK); } else { QueryContextResponse response = new QueryContextResponse(); StatusCode statusCode = new StatusCode( Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!"); response.setErrorCode(statusCode); return new ResponseEntity<QueryContextResponse>(response, HttpStatus.BAD_REQUEST); } } /** * Executes the standard NGSI 10 SubscribeContext method. * * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/subscribeContext", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<SubscribeContextResponse> subscription( HttpServletRequest requester, @RequestBody SubscribeContextRequest request) { logger.info(" < if (!validateMessageBody(requester, request, sNgsi10schema)) { SubscribeContextResponse response = new SubscribeContextResponse( null, new SubscribeError(null, new StatusCode( Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!"))); return new ResponseEntity<SubscribeContextResponse>(response, HttpStatus.BAD_REQUEST); } // TODO here it seems it got lost the traceOriginator in the code. SubscribeContextResponse response = ngsiCore.subscribeContext(request); return new ResponseEntity<SubscribeContextResponse>(response, HttpStatus.OK); } /** * Executes the standard NGSI 10 UpdateContextSubscription method. * * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/updateContextSubscription", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<UpdateContextSubscriptionResponse> updateContextSubscription( HttpServletRequest requester, @RequestBody UpdateContextSubscriptionRequest request) { logger.info(" < if (!validateMessageBody(requester, request, sNgsi10schema)) { UpdateContextSubscriptionResponse response = new UpdateContextSubscriptionResponse( null, new SubscribeError(null, new StatusCode( Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!"))); return new ResponseEntity<UpdateContextSubscriptionResponse>( response, HttpStatus.BAD_REQUEST); } UpdateContextSubscriptionResponse response = ngsiCore .updateContextSubscription(request); return new ResponseEntity<UpdateContextSubscriptionResponse>(response, HttpStatus.OK); } /** * Executes the standard NGSI 10 UnsubscribeContext method. * * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/unsubscribeContext", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<UnsubscribeContextResponse> unsubscribeContext( HttpServletRequest requester, @RequestBody UnsubscribeContextRequest request) { logger.info(" < if (validateMessageBody(requester, request, sNgsi10schema)) { logger.info("SubscriptionIDRequest: " + request.getSubscriptionId()); UnsubscribeContextResponse response = ngsiCore .unsubscribeContext(request); return new ResponseEntity<UnsubscribeContextResponse>(response, HttpStatus.OK); } else { UnsubscribeContextResponse response = new UnsubscribeContextResponse(); StatusCode statusCode = new StatusCode( Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML sintax Error!"); response.setStatusCode(statusCode); return new ResponseEntity<UnsubscribeContextResponse>(response, HttpStatus.BAD_REQUEST); } } /** * Executes the standard NGSI 10 UpdateContext method. * * @param requester * Represents the HTTP request message. * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/updateContext", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<UpdateContextResponse> updateContextResponse( HttpServletRequest requester, @RequestBody UpdateContextRequest request) { logger.info(" < if (validateMessageBody(requester, request, sNgsi10schema)) { for (int i = 0; i < request.getContextElement().size(); i++) { /* * Add metadata to each context element contained by the update. */ if (!requester.getContentType().contains("application/json")) { if (request.getContextElement().get(i).getDomainMetadata() != null) { request.getContextElement() .get(i) .setDomainMetadata( new ArrayList<ContextMetadata>()); } try { request.getContextElement() .get(i) .getDomainMetadata() .add(GenerateMetadata .createSourceIPMetadata(new URI( requester.getRequestURL() .toString()))); request.getContextElement() .get(i) .getDomainMetadata() .add(GenerateMetadata .createDomainTimestampMetadata()); } catch (URISyntaxException e) { logger.info(" URI Syntax Exception ", e); } } } UpdateContextResponse response = ngsiCore.updateContext(request); System.out.println(" + response); return new ResponseEntity<UpdateContextResponse>(response, HttpStatus.OK); } else { UpdateContextResponse response = new UpdateContextResponse( new StatusCode(Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!"), null); return new ResponseEntity<UpdateContextResponse>(response, HttpStatus.OK); } } /** * Executes the convenience method for querying an individual context * entity. * * * @param id * The id of the context entity to query. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<ContextElementResponse> simpleQueryIdGet( @PathVariable("entityID") String id) { logger.info("< List<EntityId> entityIdList = new ArrayList<EntityId>(); EntityId entity = new EntityId(id, null, false); entityIdList.add(entity); QueryContextRequest request = new QueryContextRequest(entityIdList, null, null); QueryContextResponse response = ngsiCore.queryContext(request); if (response.getErrorCode() != null) { if (response.getErrorCode().getCode() == Code.CONTEXTELEMENTNOTFOUND_404 .getCode()) { ContextElementResponse contextElementResp = new ContextElementResponse( new ContextElement(new EntityId(id, null, false), null, null, null), response.getErrorCode()); return new ResponseEntity<ContextElementResponse>( contextElementResp, HttpStatus.OK); } else if (response.getErrorCode().getCode() == Code.INTERNALERROR_500 .getCode()) { ContextElementResponse contextElementResp = new ContextElementResponse( new ContextElement(new EntityId(id, null, false), null, null, null), response.getErrorCode()); return new ResponseEntity<ContextElementResponse>( contextElementResp, HttpStatus.OK); } } ContextElementResponse contextElementResp = response .getListContextElementResponse().get(0); return new ResponseEntity<ContextElementResponse>(contextElementResp, HttpStatus.OK); } /** * Executes the convenience method for updating an individual context * entity. * * @param EntityID * The id of the Context Entity to update. * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}", method = RequestMethod.PUT, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<UpdateContextElementResponse> simpleQueryIdPut( @PathVariable("entityID") String EntityID, HttpServletRequest requester, @RequestBody UpdateContextElementRequest request) { logger.info(" < if (validateMessageBody(requester, request, sNgsi10schema)) { List<ContextElement> contextElementList = new ArrayList<ContextElement>(); ContextElement contextElement = new ContextElement(new EntityId( EntityID, null, false), request.getAttributeDomainName(), request.getContextAttributeList(), request.getDomainMetadata()); contextElementList.add(contextElement); UpdateContextRequest reqUpdate = new UpdateContextRequest( contextElementList, UpdateActionType.UPDATE); UpdateContextResponse response = ngsiCore.updateContext(reqUpdate); if (response != null) { ContextAttributeResponse contextAttributeResp = new ContextAttributeResponse( response.getContextElementResponse().get(0) .getContextElement().getContextAttributeList(), response.getContextElementResponse().get(0) .getStatusCode()); UpdateContextElementResponse respUpdate = new UpdateContextElementResponse( response.getErrorCode(), contextAttributeResp); return new ResponseEntity<UpdateContextElementResponse>( respUpdate, HttpStatus.OK); } } UpdateContextElementResponse response = new UpdateContextElementResponse( new StatusCode(Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!"), null); return new ResponseEntity<UpdateContextElementResponse>(response, HttpStatus.OK); } /** * * Executes the convenience method for appending attribute values to an * individual context entity. * * * @param EntityID * The id of the Context Entity where attribute values shall be * appended. * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<AppendContextElementResponse> simpleQueryIdPost( @PathVariable("entityID") String EntityID, HttpServletRequest requester, @RequestBody AppendContextElementRequest request) { logger.info(" < if (validateMessageBody(requester, request, sNgsi10schema)) { List<ContextElement> contextElementList = new ArrayList<ContextElement>(); ContextElement contextElement = new ContextElement(new EntityId( EntityID, null, false), request.getAttributeDomainName(), request.getContextAttributeList(), request.getDomainMetadata()); contextElementList.add(contextElement); UpdateContextRequest reqUpdate = new UpdateContextRequest( contextElementList, UpdateActionType.APPEND); UpdateContextResponse response = ngsiCore.updateContext(reqUpdate); // create the new context attribute response ArrayList<ContextAttributeResponse> ar = new ArrayList<ContextAttributeResponse>(); for (ContextElementResponse element : response .getContextElementResponse()) { ContextAttributeResponse attrib = new ContextAttributeResponse(); attrib.setContextAttribute(element.getContextElement() .getContextAttributeList()); attrib.setStatusCode(element.getStatusCode()); ar.add(attrib); } AppendContextElementResponse respAppend = new AppendContextElementResponse( response.getErrorCode(), ar); return new ResponseEntity<AppendContextElementResponse>(respAppend, HttpStatus.OK); } else { AppendContextElementResponse response = new AppendContextElementResponse( new StatusCode(Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!"), null); return new ResponseEntity<AppendContextElementResponse>(response, HttpStatus.OK); } } /** * * Executes the convenience method for removing all information about a * context entity. * * * @param EntityID * The id of the target context entity of the operation. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}", method = RequestMethod.DELETE, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<StatusCode> simpleQueryIdDelete( @PathVariable("entityID") String EntityID) { logger.info(" < List<ContextElement> contextElementList = new ArrayList<ContextElement>(); ContextElement contextElement = new ContextElement(new EntityId( EntityID, null, false), null, null, null); contextElementList.add(contextElement); UpdateContextRequest reqUpdate = new UpdateContextRequest( contextElementList, UpdateActionType.DELETE); UpdateContextResponse response = ngsiCore.updateContext(reqUpdate); StatusCode statusCode = null; if (response.getErrorCode() == null) { statusCode = new StatusCode(Code.OK_200.getCode(), ReasonPhrase.OK_200.toString(), null); } else { statusCode = new StatusCode(response.getErrorCode().getCode(), response.getErrorCode().getReasonPhrase(), response .getErrorCode().getDetails().toString()); } return new ResponseEntity<StatusCode>(statusCode, HttpStatus.OK); } /** * Executes the convenience method for querying an individual context * entity. * * @param id * The id of the target context entity. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<ContextElementResponse> simpleQueryAttributesContainerGet( @PathVariable("entityID") String id) { logger.info(" < return simpleQueryIdGet(id); } /** * Executes the convenience method for updating an individual context * entity. * * @param EntityID * The id of the Context Entity to update. * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes", method = RequestMethod.PUT, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<UpdateContextElementResponse> simpleQueryAttributesContainerPut( @PathVariable("entityID") String EntityID, HttpServletRequest requester, @RequestBody UpdateContextElementRequest request) { logger.info(" < return simpleQueryIdPut(EntityID, requester, request); } /** * * Executes the convenience method for appending attribute values to an * individual context entity. * * * @param EntityID * The id of the Context Entity where attribute values shall be * appended. * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<AppendContextElementResponse> simpleQueryAttributesContainerPost( @PathVariable("entityID") String EntityID, HttpServletRequest requester, @RequestBody AppendContextElementRequest request) { logger.info(" < return simpleQueryIdPost(EntityID, requester, request); } /** * Executes the convenience method for removing all information about a * context entity. * * @param EntityID * The id of the target context entity of the operation. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes", method = RequestMethod.DELETE, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<StatusCode> simpleQueryAttributesContainerDelete( @PathVariable("entityID") String EntityID) { logger.info(" < return simpleQueryIdDelete(EntityID); } /** * Executes the convenience method for querying an individual attribute of a * context entity. * * @param id * The id of the target context entity. * @param attr * The name of the target attribute. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes/{attributeName}", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<ContextAttributeResponse> simpleQueryAttributeGet( @PathVariable("entityID") String id, @PathVariable("attributeName") String attr) { logger.info(" < QueryContextRequest regReq = Converter.toQueryContextRequest(id, attr); QueryContextResponse normalResp = ngsiCore.queryContext(regReq); ContextAttributeResponse response = Converter .toContextAttributeResponse(normalResp); return new ResponseEntity<ContextAttributeResponse>(response, HttpStatus.OK); } /** * Executes the convenience method for appending a value to an individual * attribute of a context entity. * * @param EntityID * The id of the target context entity. * @param attributeName * The name of the target attribute. * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes/{attributeName}", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<StatusCode> simpleQueryAttributePost( HttpServletRequest requester, @PathVariable("entityID") String EntityID, @PathVariable("attributeName") String attributeName, @RequestBody UpdateContextAttributeRequest request) { logger.info(" < if (validateMessageBody(requester, request, sNgsi10schema)) { List<ContextElement> contextElementList = new ArrayList<ContextElement>(); List<ContextAttribute> contextAttributeList = new ArrayList<ContextAttribute>(); contextAttributeList.add(new ContextAttribute(attributeName, request.getType(), request.getContextValue().toString(), request.getContextMetadata())); ContextElement contextElement = new ContextElement(new EntityId( EntityID, null, false), null, contextAttributeList, null); contextElementList.add(contextElement); UpdateContextRequest reqUpdate = new UpdateContextRequest( contextElementList, UpdateActionType.APPEND); UpdateContextResponse response = ngsiCore.updateContext(reqUpdate); StatusCode statusCode = new StatusCode(response.getErrorCode() .getCode(), response.getErrorCode().getReasonPhrase(), response.getErrorCode().getDetails().toString()); return new ResponseEntity<StatusCode>(statusCode, HttpStatus.OK); } else { StatusCode response = new StatusCode(Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!"); return new ResponseEntity<StatusCode>(response, HttpStatus.OK); } } /** * Executes the convenience method for deleting all values of an individual * attribute of a context entity. * * @param EntityID * The id of the target context entity. * @param attributeName * The name of the target attribute. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes/{attributeName}", method = RequestMethod.DELETE, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<StatusCode> simpleQueryAttributeDelete( @PathVariable("entityID") String EntityID, @PathVariable("attributeName") String attributeName) { logger.info(" < List<ContextElement> contextElementList = new ArrayList<ContextElement>(); List<ContextAttribute> contextAttributeList = new ArrayList<ContextAttribute>(); contextAttributeList.add(new ContextAttribute(attributeName, null, null, null)); ContextElement contextElement = new ContextElement(new EntityId( EntityID, null, false), null, contextAttributeList, null); contextElementList.add(contextElement); UpdateContextRequest reqUpdate = new UpdateContextRequest( contextElementList, UpdateActionType.DELETE); UpdateContextResponse response = ngsiCore.updateContext(reqUpdate); StatusCode statusCode = new StatusCode(response.getErrorCode() .getCode(), response.getErrorCode().getReasonPhrase(), response .getErrorCode().getDetails().toString()); return new ResponseEntity<StatusCode>(statusCode, HttpStatus.OK); } /** * Executes the convenience method for retrieving a specific value instance * of an attribute of a context entity. * * @param id * The id of the target context entity. * @param attr * The name of the target attribute. * @param valueID * The target value id. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes/{attributeName}/{valueID}", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<ContextAttributeResponse> simpleQuerySpecialAttributeValueGet( @PathVariable("entityID") String id, @PathVariable("attributeName") String attr, @PathVariable("valueID") String valueID) { logger.info(" < QueryContextRequest regReq = Converter.toQueryContextRequest(id, attr, valueID); QueryContextResponse normalResp = ngsiCore.queryContext(regReq); ContextAttributeResponse response = Converter .toContextAttributeResponse(normalResp); return new ResponseEntity<ContextAttributeResponse>(response, HttpStatus.OK); } /** * Executes the convenience method for updating a specific value instance of * an attribute of a context entity. * * @param EntityID * The id of the target context entity. * @param attributeName * The name of the target attribute. * @param valueID * The target value id. * @param request * The request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes/{attributeName}/{valueID}", method = RequestMethod.PUT, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<StatusCode> simpleQuerySpecialAttributeValuePut( HttpServletRequest requester, @PathVariable("entityID") String EntityID, @PathVariable("attributeName") String attributeName, @PathVariable("valueID") String valueID, @RequestBody UpdateContextAttributeRequest request) { logger.info(" < ResponseEntity<StatusCode> response = simpleQueryAttributePost( requester, EntityID, attributeName, request); return response; } /** * Executes the convenience method for deleting a specific value instance of * an attribute of a context entity. * * @param EntityID * The id of the target context entity. * @param attributeName * The name of the target attribute. * @param valueID * The target value id. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributes/{attributeName}/{valueID}", method = RequestMethod.DELETE, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<StatusCode> simpleQuerySpecialAttributeValueDelete( @PathVariable("entityID") String EntityID, @PathVariable("attributeName") String attributeName, @PathVariable("valueID") String valueID) { logger.info(" < ResponseEntity<StatusCode> response = simpleQueryAttributeDelete( EntityID, attributeName); return response; } /** * Executes the convenience method for querying a specific attribute domain * of a context entity. * * @param id * The id of the target context entity. * @param attrDomainName * The name of the target attribute. * @param scopeType * The type of the query scope, if present. * @param scopeValue * The value of the query scope, if present. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntities/{entityID}/attributeDomains/{attributeDomainName}", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public @ResponseBody ResponseEntity<ContextAttributeResponse> simpleQueryAttributeDomainGet( @PathVariable("entityID") String id, @PathVariable("attributeDomainName") String attrDomainName, @RequestParam(required = false) String scopeType, @RequestParam(required = false) Object scopeValue) { logger.info(" < QueryContextRequest regReq = Converter.toQueryContextRequest(id, attrDomainName); QueryContextResponse normalResp = ngsiCore.queryContext(regReq); ContextAttributeResponse response = Converter .toContextAttributeResponse(normalResp); return new ResponseEntity<ContextAttributeResponse>(response, HttpStatus.OK); } /** * Executes the convenience method for querying all context entities having * a specified type. * * @param typeName * The target entity type of the query. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntityTypes/{typeName}", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<QueryContextResponse> simpleQueryEntityType( @PathVariable("typeName") URI typeName) { logger.info(" < List<EntityId> entityIdList = new ArrayList<EntityId>(); List<String> attributeList = new ArrayList<String>(); EntityId entity = new EntityId(".*", typeName, true); entityIdList.add(entity); QueryContextRequest request = new QueryContextRequest(entityIdList, attributeList, null); QueryContextResponse response = ngsiCore.queryContext(request); return new ResponseEntity<QueryContextResponse>(response, HttpStatus.OK); } /** * Executes the convenience method for querying all context entities having * a specified type. * * @param typeName * The target entity type of the query. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntityTypes/{typeName}/attributes", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<QueryContextResponse> simpleQueryEntityTypeAttributeCont( @PathVariable("typeName") URI typeName) { logger.info(" < return simpleQueryEntityType(typeName); } /** * Executes the convenience method for querying a specific attribute from * all context entities having a specified type. * * @param typeName * The target entity type of the query. * @param attributeName * The target attribute of the query. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntityTypes/{typeName}/attributes/{attributeName}", method = RequestMethod.GET, consumes = { "*/*" }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<QueryContextResponse> simpleQueryEntityTypeAttribute( @PathVariable("typeName") URI typeName, @PathVariable("attributeName") String attributeName) { logger.info(" < List<EntityId> entityIdList = new ArrayList<EntityId>(); List<String> attributeList = new ArrayList<String>(); attributeList.add(attributeName); EntityId entity = new EntityId(".*", typeName, false); entityIdList.add(entity); QueryContextRequest request = new QueryContextRequest(entityIdList, attributeList, null); QueryContextResponse response = ngsiCore.queryContext(request); if (response.getErrorCode() == null && response.getListContextElementResponse().size() != 0) { return new ResponseEntity<QueryContextResponse>(response, HttpStatus.OK); } else if (response.getErrorCode() != null && response.getErrorCode().getCode() == 500) { return new ResponseEntity<QueryContextResponse>(response, HttpStatus.GATEWAY_TIMEOUT); } QueryContextResponse n_response = new QueryContextResponse(null, new StatusCode(Code.CONTEXTELEMENTNOTFOUND_404.getCode(), ReasonPhrase.CONTEXTELEMENTNOTFOUND_404.toString(), null)); return new ResponseEntity<QueryContextResponse>(n_response, HttpStatus.NOT_FOUND); } /** * Executes the convenience method for querying an attribute domain from all * context entities having a specified type. * * @param typeName * The target entity type of the query. * @param attrDomain * The target attribute domain of the query. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextEntityTypes/{typeName}/attributeDomains/{attributeDomainName}", method = RequestMethod.GET, consumes = { "*/*", }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public @ResponseBody ResponseEntity<QueryContextResponse> simpleQueryEntityTypeAttributeDomain( @PathVariable("typeName") URI typeName, @PathVariable("attributeDomainName") String attrDomain) { logger.info(" < QueryContextRequest regReq = Converter.toQueryContextRequest_typeBased( typeName, attrDomain, null, null); QueryContextResponse response = ngsiCore.queryContext(regReq); return new ResponseEntity<QueryContextResponse>(response, HttpStatus.OK); } /** * Executes the convenience method for subscribing. * * @param request * The request body of the subscription. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextSubscriptions/{subscriptionId}", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<SubscribeContextResponse> simpleSubscription( HttpServletRequest requester, @RequestBody SubscribeContextRequest request) { logger.info(" < if (!validateMessageBody(requester, request, sNgsi10schema)) { SubscribeContextResponse response = new SubscribeContextResponse( null, new SubscribeError(null, new StatusCode( Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!"))); return new ResponseEntity<SubscribeContextResponse>(response, HttpStatus.BAD_REQUEST); } SubscribeContextResponse response = ngsiCore.subscribeContext(request); if (response.getSubscribeError() != null) { return new ResponseEntity<SubscribeContextResponse>(response, HttpStatus.OK); } return new ResponseEntity<SubscribeContextResponse>(response, HttpStatus.OK); } /** * Executes the convenience method for updating a subscription. * * @param request * The request body of the subscription update. * @param subscriptionId * The identifier of the subscription to update. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextSubscriptions/{subscriptionId}", method = RequestMethod.PUT, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<UpdateContextSubscriptionResponse> updateSubscription( HttpServletRequest requester, @RequestBody UpdateContextSubscriptionRequest request, @PathVariable("subscriptionId") String subscriptionId) { return updateContextSubscription(requester, request); } /** * Executes the convenience method for removing a subscription. * * @param subscriptionId * The identifier of the subscription to remove. * @return The response body. */ @RequestMapping(value = "/ngsi10/contextSubscriptions/{subscriptionId}", method = RequestMethod.DELETE, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<UnsubscribeContextResponse> unsubscribe( HttpServletRequest requester, @PathVariable("subscriptionId") String subscriptionId) { logger.info(" < return unsubscribeContext(requester, new UnsubscribeContextRequest( subscriptionId)); } /** * Executes the convenience method for processing a notification. * * @param requester * Represents the HTTP request message. * @param request * The notification request body. * @return The response body. */ @RequestMapping(value = "/ngsi10/notify", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<NotifyContextResponse> notifyContext( HttpServletRequest requester, @RequestBody NotifyContextRequest request) { logger.info(" < if (validateMessageBody(requester, request, sNgsi10schema)) { NotifyContextResponse response = ngsiCore.notifyContext(request); return new ResponseEntity<NotifyContextResponse>(response, HttpStatus.OK); } else { NotifyContextResponse response = new NotifyContextResponse( new StatusCode(Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!")); return new ResponseEntity<NotifyContextResponse>(response, HttpStatus.OK); } } /** * Executes the convenience method for processing an NGSI9 notification. * * @param request * The notification request body. * * @return The response body. */ @RequestMapping(value = "/ngsi9/notifyContextAvailability", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<NotifyContextAvailabilityResponse> notifyContextAvailability( HttpServletRequest requester, @RequestBody NotifyContextAvailabilityRequest request) { logger.info(" < + request); if (!validateMessageBody(requester, request, sNgsi9schema)) { NotifyContextAvailabilityResponse response = new NotifyContextAvailabilityResponse( new StatusCode(Code.BADREQUEST_400.getCode(), ReasonPhrase.BADREQUEST_400.toString(), "XML syntax Error!")); return new ResponseEntity<NotifyContextAvailabilityResponse>( response, HttpStatus.BAD_REQUEST); } NotifyContextAvailabilityResponse response = ngsi9Core .notifyContextAvailability(request); return new ResponseEntity<NotifyContextAvailabilityResponse>(response, HttpStatus.OK); } @RequestMapping(value = "/ngsi9/discoverContextAvailability", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<String> forwardDiscoverContextAvailability(HttpServletRequest requester, @RequestBody String request) { // logger.info("Forwarding a DiscoverContextAvailabilityRequest to the IoT Discovery" // + request); logger.info("Forwarding a DiscoverContextAvailabilityRequest to the IoT Discovery"); // model.addAttribute("attribute", "forwardWithForwardPrefix"); // return new // ModelAndView("forward://localhost:8061/ngsi9/discoverContextAvailability", // model); // return new // HttpStatus.OK); String response = ""; try { response = HttpRequester.sendGenericRequestwithResponse( new URL(ngsi9url+"/ngsi9/discoverContextAvailability"), "POST", request, requester.getHeader("Content-Type")); response = response.split("\\|")[1]; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ResponseEntity<String>(response, HttpStatus.OK); } @RequestMapping(value = "/ngsi9/registerContext", method = RequestMethod.POST, headers = "Accept=*/*") public ResponseEntity<String> forwardRegisterContext( HttpServletRequest requester, @RequestBody String request) { logger.info("Forwarding a RegisterRequest to the IoT Discovery"); String response = ""; try { response = HttpRequester.sendGenericRequestwithResponse( new URL(ngsi9url+"/ngsi9/registerContext"), "POST", request, requester.getHeader("Content-Type")); response = response.split("\\|")[1]; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ResponseEntity<String>(response, HttpStatus.OK); } @RequestMapping(value = "/ngsi9/subscribeContextAvailability", method = RequestMethod.POST, headers = "Accept=*/*") public ResponseEntity<String> forwardSubscribeContextAvailability( HttpServletRequest requester, @RequestBody String request) { logger.info("Forwarding a SubscribeContextAvailability to the IoT Discovery"); String response = ""; try { response = HttpRequester.sendGenericRequestwithResponse( new URL(ngsi9url+"/ngsi9/subscribeContextAvailability"), "POST", request, requester.getHeader("Content-Type")); response = response.split("\\|")[1]; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ResponseEntity<String>(response, HttpStatus.OK); } @RequestMapping(value = "/ngsi9/updateContextAvailabilitySubscription", method = RequestMethod.POST, headers = "Accept=*/*") public @ResponseBody ResponseEntity<String> forwardUpdateContextAvailabilitySubscription(HttpServletRequest requester, @RequestBody String request) { logger.info("Forwarding a UpdateContextAvailabilitySubscription to the IoT Discovery"); String response = ""; try { response = HttpRequester.sendGenericRequestwithResponse( new URL(ngsi9url+"/ngsi9/updateContextAvailabilitySubscription"), "POST", request, requester.getHeader("Content-Type")); response = response.split("\\|")[1]; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ResponseEntity<String>(response, HttpStatus.OK); } @RequestMapping(value = "/ngsi9/unsubscribeContextAvailability", method = RequestMethod.POST, headers = "Accept=*/*") public @ResponseBody ResponseEntity<String> forwardUnsubscribeContextAvailability(HttpServletRequest requester, @RequestBody String request) { logger.info("Forwarding a UnsubscribeContextAvailability to the IoT Discovery"); String response = ""; try { response = HttpRequester.sendGenericRequestwithResponse( new URL(ngsi9url+"/ngsi9/unsubscribeContextAvailability"), "POST", request, requester.getHeader("Content-Type")); response = response.split("\\|")[1]; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ResponseEntity<String>(response, HttpStatus.OK); } /** * Executes the convenience method for processing a notification. * * @param requester * Represents the HTTP request message. * @param request * The notification request body. * @return The response body. */ @RequestMapping(value = "/leafengine/notify", method = RequestMethod.POST, consumes = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }, produces = { CONTENT_TYPE_XML, CONTENT_TYPE_JSON }) public ResponseEntity<String> notifyContext(HttpServletRequest requester, @RequestBody String notify) { logger.info(" < final String notification = notify; if (logger.isDebugEnabled()) { logger.debug("leafnegine Notification: " + notify); } if (leafengine != null) { new Thread() { @Override public void run() { UpdateContextRequest request = leafengine .convertSubscriptionToUpdate(notification); // TODO: check the request ngsiCore.updateContext(request); // TODO: check the response and create an response // System.out.println(request.toString()); } }.start(); } return new ResponseEntity<String>("", HttpStatus.OK); } }
package org.to2mbn.jmccc.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public final class FileUtils { public static void mkdirs(File dir) throws IOException { if (!dir.mkdirs()) { throw new IOException("Cannot mkdirs: " + dir); } } public static void prepareWrite(File file) throws IOException { File parent = file.getParentFile(); if (parent != null && !parent.exists()) { mkdirs(parent); } } public static void copyFile(File src, File target) throws IOException { prepareWrite(target); try (FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(target)) { FileChannel chin = in.getChannel(); FileChannel chout = out.getChannel(); chin.transferTo(0, chin.size(), chout); } } private FileUtils() { } }
package fi.mikuz.boarder.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.util.DisplayMetrics; import android.util.Log; /** * * @author Jan Mikael Lindlf */ public class IconUtils { public static Bitmap resizeIcon(Context context, Bitmap bitmap, float pixelsPerInch) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); float density = metrics.densityDpi; float imageSize = density/pixelsPerInch; int width = bitmap.getWidth(); int height = bitmap.getHeight(); float scaleWidth = ((float) imageSize) / width; float scaleHeight = ((float) imageSize) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); } }
package io.github.dead_i.bungeerelay.listeners; import io.github.dead_i.bungeerelay.IRC; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.ChatEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.event.EventHandler; public class ChatListener implements Listener { Plugin plugin; public ChatListener(Plugin plugin) { this.plugin = plugin; } @EventHandler public void onChat(ChatEvent event) { if (!IRC.sock.isConnected()) return; ProxiedPlayer player = (ProxiedPlayer) event.getSender(); String msg = event.getMessage(); if (!msg.startsWith("/") || (msg.startsWith("/me "))) { if (msg.startsWith("/me ")) msg = "\001ACTION " + msg.substring(4) + "\001"; IRC.out.println(":" + IRC.uids.get(player) + " PRIVMSG " + IRC.channel + " :" + msg); for (ProxiedPlayer o : plugin.getProxy().getPlayers()) { if (!player.getServer().getInfo().getName().equals(o.getServer().getInfo().getName())) o.sendMessage(new TextComponent(ChatColor.translateAlternateColorCodes('&', IRC.config.getString("formats.msg")) .replace("{SENDER}", player.getName()) .replace("{MESSAGE}", msg))); } } } }
// $Id: EntryUpdatedEvent.java,v 1.12 2003/05/01 02:11:22 ray Exp $ package com.threerings.presents.dobj; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; /** * An entry updated event is dispatched when an entry of a {@link DSet} is * updated. It can also be constructed to request the update of an entry * and posted to the dobjmgr. * * @see DObjectManager#postEvent */ public class EntryUpdatedEvent extends NamedEvent { /** * Constructs a new entry updated event on the specified target object * for the specified set name and with the supplied updated entry. * * @param targetOid the object id of the object to whose set we will * add an entry. * @param name the name of the attribute in which to update the * specified entry. * @param entry the entry to update. * @param oldEntry the previous value of the entry. */ public EntryUpdatedEvent (int targetOid, String name, DSet.Entry entry, DSet.Entry oldEntry) { super(targetOid, name); _entry = entry; _oldEntry = oldEntry; } /** * Constructs a blank instance of this event in preparation for * unserialization from the network. */ public EntryUpdatedEvent () { } /** * Returns the entry that has been updated. */ public DSet.Entry getEntry () { return _entry; } /** * Returns the entry that was in the set prior to being updated. */ public DSet.Entry getOldEntry () { return _oldEntry; } /** * Applies this event to the object. */ public boolean applyToObject (DObject target) throws ObjectAccessException { // only apply the change if we haven't already if (_oldEntry == UNSET_OLD_ENTRY) { DSet set = (DSet)target.getAttribute(_name); // fetch the previous value for interested callers _oldEntry = set.get(_entry.getKey()); // update the entry if (!set.update(_entry)) { // complain if we didn't update anything Log.warning("No matching entry to update [entry=" + this + ", set=" + set + "]."); return false; } } return true; } // documentation inherited protected void notifyListener (Object listener) { if (listener instanceof SetListener) { ((SetListener)listener).entryUpdated(this); } } // documentation inherited protected void toString (StringBuffer buf) { buf.append("ELUPD:"); super.toString(buf); buf.append(", entry="); StringUtil.toString(buf, _entry); } protected DSet.Entry _entry; protected transient DSet.Entry _oldEntry = UNSET_OLD_ENTRY; }
package com.twitter.mesos.scheduler; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.inject.BindingAnnotation; import com.google.inject.Inject; import com.google.protobuf.ByteString; import org.apache.mesos.Protos.ExecutorID; import org.apache.mesos.Protos.ExecutorInfo; import org.apache.mesos.Protos.FrameworkID; import org.apache.mesos.Protos.OfferID; import org.apache.mesos.Protos.SlaveID; import org.apache.mesos.Protos.SlaveOffer; import org.apache.mesos.Protos.TaskDescription; import org.apache.mesos.Protos.TaskID; import org.apache.mesos.Protos.TaskStatus; import org.apache.mesos.Scheduler; import org.apache.mesos.SchedulerDriver; import com.twitter.common.application.Lifecycle; import com.twitter.common.base.Closure; import com.twitter.common.quantity.Amount; import com.twitter.common.quantity.Time; import com.twitter.common.stats.Stats; import com.twitter.mesos.StateTranslator; import com.twitter.mesos.codec.ThriftBinaryCodec; import com.twitter.mesos.codec.ThriftBinaryCodec.CodingException; import com.twitter.mesos.gen.ExecutorMessage; import com.twitter.mesos.gen.RegisteredTaskUpdate; import com.twitter.mesos.gen.RestartExecutor; import com.twitter.mesos.gen.ScheduleStatus; import com.twitter.mesos.gen.SchedulerMessage; import static com.google.common.base.Preconditions.checkNotNull; import static com.twitter.common.base.MorePreconditions.checkNotBlank; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Location for communication with the mesos core. * * @author William Farner */ class MesosSchedulerImpl implements Scheduler { private static final Logger LOG = Logger.getLogger(MesosSchedulerImpl.class.getName()); private static final String TWITTER_EXECUTOR_ID = "twitter"; private static final Amount<Long, Time> MAX_REGISTRATION_DELAY = Amount.of(10L, Time.SECONDS); /** * Binding annotation for the path to the executor binary. */ @BindingAnnotation @Target({FIELD, PARAMETER, METHOD}) @Retention(RUNTIME) public @interface ExecutorPath {} // Stores scheduler state and handles actual scheduling decisions. private final SchedulerCore schedulerCore; private final ExecutorTracker executorTracker; private volatile FrameworkID frameworkID = null; private final String executorPath; @Inject public MesosSchedulerImpl(SchedulerCore schedulerCore, ExecutorTracker executorTracker, @ExecutorPath String executorPath, final Lifecycle lifecycle) { this.schedulerCore = checkNotNull(schedulerCore); this.executorTracker = checkNotNull(executorTracker); this.executorPath = checkNotBlank(executorPath); // TODO(William Farner): Clean this up. Thread registrationChecker = new Thread() { @Override public void run() { try { Thread.currentThread().sleep(MAX_REGISTRATION_DELAY.as(Time.MILLISECONDS)); } catch (InterruptedException e) { LOG.log(Level.WARNING, "Delayed registration check interrupted.", e); Thread.currentThread().interrupt(); } if (frameworkID == null) { LOG.severe("Framework has not been registered within the tolerated delay, quitting."); lifecycle.shutdown(); } } }; registrationChecker.setDaemon(true); registrationChecker.start(); } @Override public String getFrameworkName(SchedulerDriver driver) { return "TwitterScheduler"; } @Override public void slaveLost(SchedulerDriver schedulerDriver, SlaveID slaveId) { LOG.info("Received notification of lost slave: " + slaveId); } @Override public ExecutorInfo getExecutorInfo(SchedulerDriver driver) { return ExecutorInfo.newBuilder().setUri(executorPath) .setExecutorId(ExecutorID.newBuilder().setValue(TWITTER_EXECUTOR_ID)) .build(); } @Override public void registered(final SchedulerDriver driver, FrameworkID frameworkID) { LOG.info("Registered with ID " + frameworkID); this.frameworkID = frameworkID; schedulerCore.registered(frameworkID.getValue()); executorTracker.start(new Closure<String>() { @Override public void execute(String slaveId) { LOG.info("Sending restart request to executor " + slaveId); ExecutorMessage message = new ExecutorMessage(); message.setRestartExecutor(new RestartExecutor()); byte[] data; try { data = ThriftBinaryCodec.encode(message); } catch (CodingException e) { LOG.log(Level.SEVERE, "Failed to send restart request.", e); return; } LOG.info("Attempting to send message from scheduler to " + slaveId + " - " + message); int result = driver.sendFrameworkMessage(SlaveID.newBuilder().setValue(slaveId).build(), ExecutorID.newBuilder().setValue(TWITTER_EXECUTOR_ID).build(), data); if (result != 0) { LOG.severe(String.format("Attempt to send message failed with code %d [%s]", result, message)); } else { LOG.info("Message successfully sent"); } } }); } @Override public void resourceOffer(SchedulerDriver driver, OfferID offerId, List<SlaveOffer> slaveOffers) { Preconditions.checkState(frameworkID != null, "Must be registered before receiving offers."); List<TaskDescription> scheduledTasks = Lists.newLinkedList(); try { for (SlaveOffer offer : slaveOffers) { SchedulerCore.TwitterTask task = schedulerCore.offer(offer); if (task != null) { byte[] taskInBytes; try { taskInBytes = ThriftBinaryCodec.encode(task.task); } catch (ThriftBinaryCodec.CodingException e) { LOG.log(Level.SEVERE, "Unable to serialize task.", e); throw new ScheduleException("Internal error.", e); } scheduledTasks.add(TaskDescription.newBuilder() .setName(task.taskName) .setTaskId(TaskID.newBuilder().setValue(task.taskId)) .setSlaveId(SlaveID.newBuilder().setValue(task.slaveId)) .addAllResources(task.resources) .setData(ByteString.copyFrom(taskInBytes)) .build()); } } } catch (ScheduleException e) { LOG.log(Level.SEVERE, "Failed to schedule offer.", e); return; } if (!scheduledTasks.isEmpty()) { LOG.info(String.format("Accepting offer %s, to launch tasks %s", offerId.getValue(), ImmutableSet.copyOf(Iterables.transform(scheduledTasks, TASK_TO_ID)))); } driver.replyToOffer(offerId, scheduledTasks); } private static final Function<TaskDescription, String> TASK_TO_ID = new Function<TaskDescription, String>() { @Override public String apply(TaskDescription task) { return task.getTaskId().getValue(); } }; @Override public void offerRescinded(SchedulerDriver schedulerDriver, OfferID offerID) { LOG.info("Offer rescinded but we don't care " + offerID); } @Override public void statusUpdate(SchedulerDriver driver, TaskStatus status) { String info = status.hasData() ? status.getData().toStringUtf8() : null; String infoMsg = info != null ? " with info " + info : ""; LOG.info("Received status update for task " + status.getTaskId() + " in state " + status.getState() + infoMsg); Query query = Query.byId(status.getTaskId().getValue()); if (schedulerCore.getTasks(query).isEmpty()) { LOG.severe("Failed to find task id " + status.getTaskId()); } else { ScheduleStatus translatedState = StateTranslator.get(status.getState()); if (translatedState == null) { LOG.log(Level.SEVERE, "Failed to look up task state translation for: " + status.getState()); return; } schedulerCore.setTaskStatus(query, translatedState, info); } } @Override public void error(SchedulerDriver driver, int code, String message) { LOG.severe("Received error message: " + message + " with code " + code); // TODO(William Farner): Exit cleanly. System.exit(1); } @Override public void frameworkMessage(SchedulerDriver driver, SlaveID slave, ExecutorID executor, byte[] data) { if (data == null) { LOG.info("Received empty framework message."); return; } try { SchedulerMessage schedulerMsg = ThriftBinaryCodec.decode(SchedulerMessage.class, data); if (schedulerMsg == null || !schedulerMsg.isSet()) { LOG.warning("Received empty scheduler message."); return; } switch (schedulerMsg.getSetField()) { case TASK_UPDATE: RegisteredTaskUpdate update = schedulerMsg.getTaskUpdate(); vars.registeredTaskUpdates.incrementAndGet(); schedulerCore.updateRegisteredTasks(update); break; case EXECUTOR_STATUS: vars.executorStatusUpdates.incrementAndGet(); executorTracker.addStatus(schedulerMsg.getExecutorStatus()); break; default: LOG.warning("Received unhandled scheduler message type: " + schedulerMsg.getSetField()); } } catch (ThriftBinaryCodec.CodingException e) { LOG.log(Level.SEVERE, "Failed to decode framework message.", e); } } private static class Vars { final AtomicLong executorStatusUpdates = Stats.exportLong("executor_status_updates"); final AtomicLong registeredTaskUpdates = Stats.exportLong("executor_registered_task_updates"); } private final Vars vars = new Vars(); }
package floobits.actions; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import floobits.common.Constants; import floobits.common.PersistentJson; import floobits.common.Settings; import floobits.common.Utils; import floobits.utilities.Flog; import java.awt.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; public class CompleteSignup extends AnAction { public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); if (project == null) { return; } if (!Settings.canFloobits()) { Utils.errorMessage("Error, no account details detected. You will have to sign up manually.", project); return; } if(!Desktop.isDesktopSupported()) { Utils.errorMessage("Can't use a browser on this system.", project); return; } HashMap<String, HashMap<String, String>> auth = null; try { auth = Settings.get().auth; } catch (Throwable e1) { Utils.errorMessage("Invalid JSON in ~/.floorc.json", project); return; } if (auth.size() < 1) { Flog.warn("No auth."); return; } String host; if (auth.size() >= 1) { host = Constants.floobitsDomain; } else { host = (String) auth.keySet().toArray()[0]; } HashMap<String, String> hostAuth = auth.get(host); if (hostAuth == null) { Flog.warn("This probably shouldn't happen, but there is no auth."); return; } String username = hostAuth.get("username"); if (username == null) { Flog.warn("This probably shouldn't happen, but there is no username."); return; } String secret = hostAuth.get("secret"); String url = String.format("https://%s/%s/pinocchio/%s", host, username, secret); try { URI uri = new URI(url); Desktop.getDesktop().browse(uri); } catch (IOException error) { Flog.warn(error); } catch (URISyntaxException error) { Flog.warn(error); } } public void update (AnActionEvent e) { PersistentJson p = PersistentJson.getInstance(); e.getPresentation().setEnabledAndVisible(p.auto_generated_account); } }
public class BinaryOperator extends Expression { static enum Kind { OP_FUNCTION_CALL, OP_FUNCTION_ARGS_SEPARATOR, OP_ARRAY, OP_MUL, OP_DIV, OP_MOD, OP_ADD, OP_SUB, OP_LEFT_SHIFT, OP_RIGHT_SHIFT_ARITIMETIC, OP_RIGHT_SHIFT_LOGICAL, OP_LEFT_ROTATE, OP_RIGHT_ROTATE, OP_BIT_AND, OP_BIT_OR, OP_BIT_XOR, OP_ASSIGN, OP_GT, OP_GTE, OP_LT, OP_LTE, OP_EQUAL, OP_NOT_EQUAL, OP_LOGICAL_AND, OP_LOGICAL_OR } private Kind kind; private Expression left, right; private DataType dataType; private DataType getAritimeticDataType(DataType left, DataType right) { if (!(left instanceof IntegerType) || !(right instanceof IntegerType)) { throw new SyntaxException("invalid operand for aritimetic"); } IntegerType pt1 = (IntegerType)this.left.getDataType(); IntegerType pt2 = (IntegerType)this.right.getDataType(); if (pt1.getWidth() > pt2.getWidth()) { return pt1; } else if (pt1.getWidth() < pt2.getWidth()) { return pt2; } else { return new IntegerType(pt1.getWidth(), pt1.isSigned() && pt2.isSigned()); } } public BinaryOperator(Kind kind, Expression left, Expression right) { this.kind = kind; this.left = left; this.right = right; if (this.left.getDataType() instanceof ArrayType) { this.left = new UnaryOperator(UnaryOperator.Kind.UNARY_AUTO_TO_POINTER, this.left); } if (this.right.getDataType() instanceof ArrayType) { this.right = new UnaryOperator(UnaryOperator.Kind.UNARY_AUTO_TO_POINTER, this.right); } switch(this.kind) { case OP_FUNCTION_CALL: if (!(this.left.getDataType() instanceof FunctionType)) { throw new SyntaxException("tried to call something not a function"); } this.dataType = ((FunctionType)this.left.getDataType()).getReturnType(); //break; case OP_FUNCTION_ARGS_SEPARATOR: this.dataType = null; break; case OP_ARRAY: if (!(this.left.getDataType() instanceof PointerType) || !(this.right.getDataType() instanceof IntegerType)) { throw new SyntaxException("invalid operand for array indexing"); } this.dataType = ((PointerType)this.left.getDataType()).getPointsAt(); break; case OP_MUL: case OP_DIV: case OP_MOD: case OP_BIT_AND: case OP_BIT_OR: case OP_BIT_XOR: this.dataType = getAritimeticDataType(this.left.getDataType(), this.right.getDataType()); break; case OP_ADD: if (this.left.getDataType() instanceof IntegerType && this.right.getDataType() instanceof IntegerType) { this.dataType = getAritimeticDataType(this.left.getDataType(), this.right.getDataType()); } else if (this.left.getDataType() instanceof PointerType && this.right.getDataType() instanceof IntegerType) { this.dataType = this.left.getDataType(); } else if (this.left.getDataType() instanceof IntegerType && this.right.getDataType() instanceof PointerType) { this.dataType = this.right.getDataType(); } else { throw new SyntaxException("invalid operand for addition"); } break; case OP_SUB: if (this.left.getDataType() instanceof IntegerType && this.right.getDataType() instanceof IntegerType) { this.dataType = getAritimeticDataType(this.left.getDataType(), this.right.getDataType()); } else if (this.left.getDataType() instanceof PointerType && this.right.getDataType() instanceof PointerType) { if (!this.left.getDataType().equals(this.right.getDataType())) { throw new SyntaxException("subtraction between different pointers isn't allowed"); } this.dataType = new IntegerType(DataType.getPointerSize(), true); } else { throw new SyntaxException("invalid operand for subtraction"); } break; case OP_LEFT_SHIFT: case OP_RIGHT_SHIFT_ARITIMETIC: case OP_RIGHT_SHIFT_LOGICAL: case OP_LEFT_ROTATE: case OP_RIGHT_ROTATE: this.dataType = this.left.getDataType(); break; case OP_ASSIGN: this.dataType = this.left.getDataType(); break; case OP_GT: case OP_GTE: case OP_LT: case OP_LTE: if (this.left.getDataType() instanceof IntegerType && this.right.getDataType() instanceof IntegerType) { IntegerType pt1 = (IntegerType)this.left.getDataType(); IntegerType pt2 = (IntegerType)this.right.getDataType(); if (pt1.getWidth() == pt2.getWidth() && pt1.isSigned() != pt2.isSigned()) { throw new SyntaxException("comparing primitives with same width and different signedness isn't allowed"); } } else if (!(this.left.getDataType() instanceof PointerType && this.left.getDataType() instanceof PointerType)) { throw new SyntaxException("invaild operands for comparision"); } this.dataType = new IntegerType(DataType.getSystemIntSize(), true); break; case OP_EQUAL: case OP_NOT_EQUAL: if (this.left.getDataType() instanceof IntegerType && this.right.getDataType() instanceof IntegerType) { IntegerType pt1 = (IntegerType)this.left.getDataType(); IntegerType pt2 = (IntegerType)this.right.getDataType(); if (pt1.getWidth() == pt2.getWidth() && pt1.isSigned() != pt2.isSigned()) { throw new SyntaxException("checking equality of primitives with same width and different signedness isn't allowed"); } } else if (!(this.left.getDataType() instanceof PointerType && this.left.getDataType() instanceof PointerType) && !(this.left.getDataType() instanceof FunctionType && this.left.getDataType() instanceof FunctionType)) { throw new SyntaxException("invaild operands for equality check"); } this.dataType = new IntegerType(DataType.getSystemIntSize(), true); break; case OP_LOGICAL_AND: case OP_LOGICAL_OR: this.dataType = new IntegerType(DataType.getSystemIntSize(), true); break; } } public Kind getKind() { return kind; } public Expression getLeft() { return left; } public Expression getRight() { return right; } public DataType getDataType() { return dataType; } public Expression evaluate() { Expression left = this.left.evaluate(); Expression right = this.right.evaluate(); if ((!(left instanceof IntegerLiteral) || !(right instanceof IntegerLiteral)) && kind != Kind.OP_LOGICAL_AND && kind != Kind.OP_LOGICAL_OR) { return this; } IntegerLiteral lop = left instanceof IntegerLiteral ? (IntegerLiteral)left : null; IntegerLiteral rop = right instanceof IntegerLiteral ? (IntegerLiteral)right : null; int width = 0; boolean isSigned = true; if (lop != null && rop != null) { if (lop.getWidth() > rop.getWidth()) { width = lop.getWidth(); isSigned = lop.isSigned(); } else if (lop.getWidth() < rop.getWidth()) { width = rop.getWidth(); isSigned = rop.isSigned(); } else { width = lop.getWidth(); isSigned = lop.isSigned() && rop.isSigned(); } } switch (kind) { case OP_MUL: return new IntegerLiteral(lop.getValue() * rop.getValue(), width, isSigned); case OP_DIV: return new IntegerLiteral(lop.getValue() / rop.getValue(), width, isSigned); case OP_MOD: return new IntegerLiteral(lop.getValue() % rop.getValue(), width, isSigned); case OP_ADD: return new IntegerLiteral(lop.getValue() + rop.getValue(), width, isSigned); case OP_SUB: return new IntegerLiteral(lop.getValue() - rop.getValue(), width, isSigned); case OP_LEFT_SHIFT: return new IntegerLiteral(lop.getValue() << rop.getValue(), width, isSigned); case OP_RIGHT_SHIFT_ARITIMETIC: return this; // not implemented yet case OP_RIGHT_SHIFT_LOGICAL: return this; // not implemented yet case OP_LEFT_ROTATE: return this; // not implemented yet case OP_RIGHT_ROTATE: return this; // not implemented yet case OP_BIT_AND: return new IntegerLiteral(lop.getValue() & rop.getValue(), width, isSigned); case OP_BIT_OR: return new IntegerLiteral(lop.getValue() | rop.getValue(), width, isSigned); case OP_BIT_XOR: return new IntegerLiteral(lop.getValue() ^ rop.getValue(), width, isSigned); case OP_GT: return new IntegerLiteral(lop.getValue() > rop.getValue() ? 1 : 0, DataType.getSystemIntSize(), true); case OP_GTE: return new IntegerLiteral(lop.getValue() >= rop.getValue() ? 1 : 0, DataType.getSystemIntSize(), true); case OP_LT: return new IntegerLiteral(lop.getValue() < rop.getValue() ? 1 : 0, DataType.getSystemIntSize(), true); case OP_LTE: return new IntegerLiteral(lop.getValue() <= rop.getValue() ? 1 : 0, DataType.getSystemIntSize(), true); case OP_EQUAL: return new IntegerLiteral(lop.getValue() == rop.getValue() ? 1 : 0, DataType.getSystemIntSize(), true); case OP_NOT_EQUAL: return new IntegerLiteral(lop.getValue() != rop.getValue() ? 1 : 0, DataType.getSystemIntSize(), true); case OP_LOGICAL_AND: if (!(left instanceof IntegerLiteral)) return this; if (((IntegerLiteral)left).getValue() == 0) { return new IntegerLiteral(0, DataType.getSystemIntSize(), true); } else { if (!(right instanceof IntegerLiteral)) return this; return new IntegerLiteral(((IntegerLiteral)right).getValue() == 0 ? 0 : 1, DataType.getSystemIntSize(), true); } case OP_LOGICAL_OR: if (!(left instanceof IntegerLiteral)) return this; if (((IntegerLiteral)left).getValue() != 0) { return new IntegerLiteral(1, DataType.getSystemIntSize(), true); } else { if (!(right instanceof IntegerLiteral)) return this; return new IntegerLiteral(((IntegerLiteral)right).getValue() == 0 ? 0 : 1, DataType.getSystemIntSize(), true); } case OP_FUNCTION_CALL: case OP_FUNCTION_ARGS_SEPARATOR: case OP_ARRAY: case OP_ASSIGN: default: return this; } } }
package org.orbeon.oxf.processor.test; import org.orbeon.errorified.Exceptions; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.pipeline.api.XMLReceiver; import org.orbeon.oxf.processor.*; import org.orbeon.oxf.processor.generator.ExceptionGenerator; import org.orbeon.oxf.xml.ContentHandlerHelper; import org.orbeon.oxf.xml.SAXStore; /** * This processor has a data input and data output and behaves like the identity processor except if an exception is * thrown while reading its input, in which case it outputs the exception like the ExceptionGenerator does. */ public class ExceptionCatcher extends ProcessorImpl { public ExceptionCatcher() { addInputInfo(new ProcessorInputOutputInfo(INPUT_DATA)); addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA)); } @Override public ProcessorOutput createOutput(String name) { final ProcessorOutput output = new ProcessorOutputImpl(ExceptionCatcher.this, name) { public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) { try { // Try to read input in SAX store final SAXStore dataInput = new SAXStore(); readInputAsSAX(context, getInputByName(INPUT_DATA), dataInput); // No exception: output what was read dataInput.replay(xmlReceiver); } catch (Throwable e) { // Exception was thrown while reading input: generate a document with that exception final ContentHandlerHelper helper = new ContentHandlerHelper(xmlReceiver); helper.startDocument(); final String rootElementName = "exceptions"; helper.startElement(rootElementName); // Find the root throwable final Throwable innerMostThrowable = Exceptions.getRootThrowable(e); ExceptionGenerator.addThrowable(helper, innerMostThrowable); helper.endElement(); helper.endDocument(); } } }; addOutput(name, output); return output; } }
package bisq.desktop.main.dao.wallet.tx; import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.FxmlView; import bisq.desktop.components.AddressWithIconAndDirection; import bisq.desktop.components.AutoTooltipLabel; import bisq.desktop.components.AutoTooltipTableColumn; import bisq.desktop.components.HyperlinkWithIcon; import bisq.desktop.main.dao.wallet.BsqBalanceUtil; import bisq.desktop.util.BsqFormatter; import bisq.desktop.util.FormBuilder; import bisq.desktop.util.GUIUtil; import bisq.core.app.BisqEnvironment; import bisq.core.btc.wallet.BsqBalanceListener; import bisq.core.btc.wallet.BsqWalletService; import bisq.core.btc.wallet.BtcWalletService; import bisq.core.dao.DaoPeriodService; import bisq.core.dao.blockchain.ReadableBsqBlockChain; import bisq.core.dao.blockchain.vo.Tx; import bisq.core.dao.blockchain.vo.TxOutput; import bisq.core.dao.blockchain.vo.TxOutputType; import bisq.core.dao.blockchain.vo.TxType; import bisq.core.dao.node.BsqNode; import bisq.core.dao.node.BsqNodeProvider; import bisq.core.locale.Res; import bisq.core.user.Preferences; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Transaction; import javax.inject.Inject; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.Tooltip; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.geometry.Insets; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.transformation.SortedList; import javafx.util.Callback; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @FxmlView public class BsqTxView extends ActivatableView<GridPane, Void> implements BsqBalanceListener { TableView<BsqTxListItem> tableView; private Pane rootParent; private final BsqFormatter bsqFormatter; private final BsqWalletService bsqWalletService; private final ReadableBsqBlockChain readableBsqBlockChain; private final DaoPeriodService daoPeriodService; private final BtcWalletService btcWalletService; private final BsqBalanceUtil bsqBalanceUtil; private final BsqNode bsqNode; private final Preferences preferences; private final ObservableList<BsqTxListItem> observableList = FXCollections.observableArrayList(); // Need to be DoubleProperty as we pass it as reference private final DoubleProperty initialOccupiedHeight = new SimpleDoubleProperty(-1); private final SortedList<BsqTxListItem> sortedList = new SortedList<>(observableList); private ChangeListener<Number> parentHeightListener; private ListChangeListener<Transaction> walletBsqTransactionsListener; private int gridRow = 0; private Label chainHeightLabel; private BsqNode.BsqBlockChainListener bsqBlockChainListener; private ProgressBar chainSyncIndicator; private ChangeListener<Number> chainHeightChangedListener; // Constructor, lifecycle @Inject private BsqTxView(BsqFormatter bsqFormatter, BsqWalletService bsqWalletService, BsqNodeProvider bsqNodeProvider, Preferences preferences, ReadableBsqBlockChain readableBsqBlockChain, DaoPeriodService daoPeriodService, BtcWalletService btcWalletService, BsqBalanceUtil bsqBalanceUtil) { this.bsqFormatter = bsqFormatter; this.bsqWalletService = bsqWalletService; this.bsqNode = bsqNodeProvider.getBsqNode(); this.preferences = preferences; this.readableBsqBlockChain = readableBsqBlockChain; this.daoPeriodService = daoPeriodService; this.btcWalletService = btcWalletService; this.bsqBalanceUtil = bsqBalanceUtil; } @Override public void initialize() { gridRow = bsqBalanceUtil.addGroup(root, gridRow); tableView = new TableView<>(); tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); addDateColumn(); addTxIdColumn(); addAddressColumn(); addAmountColumn(); addConfidenceColumn(); addTxTypeColumn(); chainSyncIndicator = new ProgressBar(); chainSyncIndicator.setPrefWidth(120); if (BisqEnvironment.isDAOActivatedAndBaseCurrencySupportingBsq()) chainSyncIndicator.setProgress(-1); else chainSyncIndicator.setProgress(0); chainSyncIndicator.setPadding(new Insets(-6, 0, -10, 5)); chainHeightLabel = FormBuilder.addLabel(root, ++gridRow, ""); chainHeightLabel.setId("num-offers"); chainHeightLabel.setPadding(new Insets(-5, 0, -10, 5)); HBox hBox = new HBox(); hBox.setSpacing(10); hBox.getChildren().addAll(chainHeightLabel, chainSyncIndicator); VBox vBox = new VBox(); vBox.setSpacing(10); GridPane.setRowIndex(vBox, ++gridRow); GridPane.setColumnSpan(vBox, 2); GridPane.setMargin(vBox, new Insets(40, -10, 5, -10)); vBox.getChildren().addAll(tableView, hBox); root.getChildren().add(vBox); walletBsqTransactionsListener = change -> updateList(); parentHeightListener = (observable, oldValue, newValue) -> layout(); bsqBlockChainListener = this::onChainHeightChanged; chainHeightChangedListener = (observable, oldValue, newValue) -> onChainHeightChanged(); } @Override protected void activate() { bsqBalanceUtil.activate(); bsqWalletService.getWalletTransactions().addListener(walletBsqTransactionsListener); bsqWalletService.addBsqBalanceListener(this); btcWalletService.getChainHeightProperty().addListener(chainHeightChangedListener); sortedList.comparatorProperty().bind(tableView.comparatorProperty()); tableView.setItems(sortedList); bsqNode.addBsqBlockChainListener(bsqBlockChainListener); if (root.getParent() instanceof Pane) { rootParent = (Pane) root.getParent(); rootParent.heightProperty().addListener(parentHeightListener); } updateList(); onChainHeightChanged(); layout(); } @Override protected void deactivate() { bsqBalanceUtil.deactivate(); sortedList.comparatorProperty().unbind(); bsqWalletService.getWalletTransactions().removeListener(walletBsqTransactionsListener); bsqWalletService.removeBsqBalanceListener(this); btcWalletService.getChainHeightProperty().removeListener(chainHeightChangedListener); bsqNode.removeBsqBlockChainListener(bsqBlockChainListener); observableList.forEach(BsqTxListItem::cleanup); if (rootParent != null) rootParent.heightProperty().removeListener(parentHeightListener); } @Override public void onUpdateBalances(Coin confirmedBalance, Coin pendingBalance, Coin lockedForVotingBalance, Coin lockedInBondsBalance) { updateList(); } private void onChainHeightChanged() { final int bsqWalletChainHeight = bsqWalletService.getChainHeightProperty().get(); final int bsqBlockChainHeight = readableBsqBlockChain.getChainHeadHeight(); if (bsqWalletChainHeight > 0) { final boolean synced = bsqWalletChainHeight == bsqBlockChainHeight; chainSyncIndicator.setVisible(!synced); chainSyncIndicator.setManaged(!synced); if (bsqBlockChainHeight > 0) chainSyncIndicator.setProgress((double) bsqBlockChainHeight / (double) bsqWalletService.getBestChainHeight()); if (synced) chainHeightLabel.setText(Res.get("dao.wallet.chainHeightSynced", bsqBlockChainHeight, bsqWalletService.getBestChainHeight())); else chainHeightLabel.setText(Res.get("dao.wallet.chainHeightSyncing", bsqBlockChainHeight, bsqWalletService.getBestChainHeight())); } else { chainHeightLabel.setText(Res.get("dao.wallet.chainHeightSyncing", bsqBlockChainHeight, bsqWalletService.getBestChainHeight())); } updateList(); } private void updateList() { observableList.forEach(BsqTxListItem::cleanup); // copy list to avoid ConcurrentModificationException final List<Transaction> walletTransactions = new ArrayList<>(bsqWalletService.getWalletTransactions()); List<BsqTxListItem> items = walletTransactions.stream() .map(transaction -> new BsqTxListItem(transaction, bsqWalletService, btcWalletService, readableBsqBlockChain.getTxType(transaction.getHashAsString()), readableBsqBlockChain.hasTxBurntFee(transaction.getHashAsString()), transaction.getUpdateTime(), bsqFormatter) ) .collect(Collectors.toList()); List<BsqTxListItem> issuanceTxList = new ArrayList<>(); items.stream() .filter(item -> item.getTxType() == TxType.COMPENSATION_REQUEST) .peek(item -> { final Tx tx = readableBsqBlockChain.getTx(item.getTxId()).get(); long changeValue = tx.getOutputs().get(0).getValue(); long inputValue = tx.getInputs().stream() .filter(input -> input.getConnectedTxOutput() != null) .mapToLong(input -> input.getConnectedTxOutput().getValue()) .sum(); long fee = inputValue - changeValue; item.setAmount(Coin.valueOf(fee)); }) .filter(item -> { final Optional<Tx> optionalTx = readableBsqBlockChain.getTx(item.getTxId()); if (optionalTx.isPresent()) { final List<TxOutput> outputs = optionalTx.get().getOutputs(); if (!outputs.isEmpty()) { return outputs.get(0).getTxOutputType() == TxOutputType.BSQ_OUTPUT; } } return false; }) .forEach(item -> { final Tx tx = readableBsqBlockChain.getTx(item.getTxId()).get(); final int blockHeight = tx.getBlockHeight(); final int issuanceBlockHeight = daoPeriodService.getAbsoluteStartBlockOfPhase(blockHeight, DaoPeriodService.Phase.ISSUANCE); final long blockTimeInSec = readableBsqBlockChain.getBlockTime(issuanceBlockHeight); long inputValue = tx.getInputs().stream() .filter(input -> input.getConnectedTxOutput() != null) .mapToLong(input -> input.getConnectedTxOutput().getValue()) .sum(); long issuanceValue = tx.getOutputs().get(1).getValue(); final BsqTxListItem issuanceItem = new BsqTxListItem(item.getTransaction(), bsqWalletService, btcWalletService, Optional.of(TxType.ISSUANCE), item.isBurnedBsqTx(), new Date(blockTimeInSec * 1000), bsqFormatter); issuanceItem.setAmount(Coin.valueOf(issuanceValue)); issuanceTxList.add(issuanceItem); }); items.addAll(issuanceTxList); observableList.setAll(items); } private void layout() { GUIUtil.fillAvailableHeight(root, tableView, initialOccupiedHeight); } private void addDateColumn() { TableColumn<BsqTxListItem, BsqTxListItem> column = new AutoTooltipTableColumn(Res.get("shared.dateTime")); column.setCellValueFactory(item -> new ReadOnlyObjectWrapper<>(item.getValue())); column.setMinWidth(180); column.setMaxWidth(column.getMinWidth() + 20); column.setCellFactory( new Callback<TableColumn<BsqTxListItem, BsqTxListItem>, TableCell<BsqTxListItem, BsqTxListItem>>() { @Override public TableCell<BsqTxListItem, BsqTxListItem> call(TableColumn<BsqTxListItem, BsqTxListItem> column) { return new TableCell<BsqTxListItem, BsqTxListItem>() { @Override public void updateItem(final BsqTxListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { setText(bsqFormatter.formatDateTime(item.getDate())); } else { setText(""); } } }; } }); tableView.getColumns().add(column); column.setComparator((o1, o2) -> o1.getDate().compareTo(o2.getDate())); column.setSortType(TableColumn.SortType.DESCENDING); tableView.getSortOrder().add(column); } private void addTxIdColumn() { TableColumn<BsqTxListItem, BsqTxListItem> column = new AutoTooltipTableColumn(Res.get("shared.txId")); column.setCellValueFactory(item -> new ReadOnlyObjectWrapper<>(item.getValue())); column.setMinWidth(60); column.setCellFactory( new Callback<TableColumn<BsqTxListItem, BsqTxListItem>, TableCell<BsqTxListItem, BsqTxListItem>>() { @Override public TableCell<BsqTxListItem, BsqTxListItem> call(TableColumn<BsqTxListItem, BsqTxListItem> column) { return new TableCell<BsqTxListItem, BsqTxListItem>() { private HyperlinkWithIcon hyperlinkWithIcon; @Override public void updateItem(final BsqTxListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { String transactionId = item.getTxId(); hyperlinkWithIcon = new HyperlinkWithIcon(transactionId, AwesomeIcon.EXTERNAL_LINK); hyperlinkWithIcon.setOnAction(event -> openTxInBlockExplorer(item)); hyperlinkWithIcon.setTooltip(new Tooltip(Res.get("tooltip.openBlockchainForTx", transactionId))); setGraphic(hyperlinkWithIcon); } else { setGraphic(null); if (hyperlinkWithIcon != null) hyperlinkWithIcon.setOnAction(null); } } }; } }); tableView.getColumns().add(column); } private void addAddressColumn() { TableColumn<BsqTxListItem, BsqTxListItem> column = new AutoTooltipTableColumn<>(Res.get("shared.address")); column.setCellValueFactory(item -> new ReadOnlyObjectWrapper<>(item.getValue())); column.setMinWidth(160); column.setCellFactory( new Callback<TableColumn<BsqTxListItem, BsqTxListItem>, TableCell<BsqTxListItem, BsqTxListItem>>() { @Override public TableCell<BsqTxListItem, BsqTxListItem> call(TableColumn<BsqTxListItem, BsqTxListItem> column) { return new TableCell<BsqTxListItem, BsqTxListItem>() { private AddressWithIconAndDirection field; @Override public void updateItem(final BsqTxListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { TxType txType = item.getTxType(); String labelString = Res.get("dao.tx.type.enum." + txType.name()); Label label; if (item.getConfirmations() > 0 && txType.ordinal() > TxType.INVALID.ordinal()) { if (item.isBurnedBsqTx() || item.getAmount().isZero()) { if (field != null) field.setOnAction(null); switch (txType) { case UNDEFINED_TX_TYPE: case UNVERIFIED: break; case INVALID: break; case GENESIS: break; case TRANSFER_BSQ: if (item.getAmount().isZero()) labelString = Res.get("funds.tx.direction.self"); break; case PAY_TRADE_FEE: case COMPENSATION_REQUEST: case VOTE: break; case ISSUANCE: break; default: break; } label = new AutoTooltipLabel(labelString); setGraphic(label); } else { String addressString = item.getAddress(); field = new AddressWithIconAndDirection(item.getDirection(), addressString, AwesomeIcon.EXTERNAL_LINK, item.isReceived()); field.setOnAction(event -> openAddressInBlockExplorer(item)); field.setTooltip(new Tooltip(Res.get("tooltip.openBlockchainForAddress", addressString))); setGraphic(field); } } else { label = new AutoTooltipLabel(labelString); setGraphic(label); } } else { setGraphic(null); if (field != null) field.setOnAction(null); } } }; } }); tableView.getColumns().add(column); } private void addAmountColumn() { TableColumn<BsqTxListItem, BsqTxListItem> column = new AutoTooltipTableColumn<>(Res.get("shared.amountWithCur", "BSQ")); column.setMinWidth(120); column.setMaxWidth(column.getMinWidth()); column.setCellValueFactory((item) -> new ReadOnlyObjectWrapper<>(item.getValue())); column.setCellFactory(new Callback<TableColumn<BsqTxListItem, BsqTxListItem>, TableCell<BsqTxListItem, BsqTxListItem>>() { @Override public TableCell<BsqTxListItem, BsqTxListItem> call(TableColumn<BsqTxListItem, BsqTxListItem> column) { return new TableCell<BsqTxListItem, BsqTxListItem>() { @Override public void updateItem(final BsqTxListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) setText(item.getConfirmations() > 0 && item.getTxType().ordinal() > TxType.INVALID.ordinal() ? bsqFormatter.formatCoin(item.getAmount()) : Res.get("shared.na")); else setText(""); } }; } }); tableView.getColumns().add(column); } private void addConfidenceColumn() { TableColumn<BsqTxListItem, BsqTxListItem> column = new AutoTooltipTableColumn<>(Res.get("shared.confirmations")); column.setMinWidth(130); column.setMaxWidth(column.getMinWidth()); column.setCellValueFactory((item) -> new ReadOnlyObjectWrapper<>(item.getValue())); column.setCellFactory(new Callback<TableColumn<BsqTxListItem, BsqTxListItem>, TableCell<BsqTxListItem, BsqTxListItem>>() { @Override public TableCell<BsqTxListItem, BsqTxListItem> call(TableColumn<BsqTxListItem, BsqTxListItem> column) { return new TableCell<BsqTxListItem, BsqTxListItem>() { @Override public void updateItem(final BsqTxListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { setGraphic(item.getTxConfidenceIndicator()); } else { setGraphic(null); } } }; } }); tableView.getColumns().add(column); } private void addTxTypeColumn() { TableColumn<BsqTxListItem, BsqTxListItem> column = new AutoTooltipTableColumn<>(Res.get("dao.wallet.tx.type")); column.setCellValueFactory(item -> new ReadOnlyObjectWrapper<>(item.getValue())); column.setMinWidth(70); column.setMaxWidth(column.getMinWidth()); column.setCellFactory( new Callback<TableColumn<BsqTxListItem, BsqTxListItem>, TableCell<BsqTxListItem, BsqTxListItem>>() { @Override public TableCell<BsqTxListItem, BsqTxListItem> call(TableColumn<BsqTxListItem, BsqTxListItem> column) { return new TableCell<BsqTxListItem, BsqTxListItem>() { @Override public void updateItem(final BsqTxListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) { String style; AwesomeIcon awesomeIcon; TxType txType = item.getTxType(); String toolTipText = Res.get("dao.tx.type.enum." + txType.name()); boolean doRotate = false; switch (txType) { case UNDEFINED_TX_TYPE: case UNVERIFIED: awesomeIcon = AwesomeIcon.QUESTION_SIGN; style = "dao-tx-type-unverified-icon"; break; case INVALID: awesomeIcon = AwesomeIcon.WARNING_SIGN; style = "dao-tx-type-invalid-icon"; break; case GENESIS: awesomeIcon = AwesomeIcon.ROCKET; style = "dao-tx-type-genesis-icon"; break; case TRANSFER_BSQ: if (item.getAmount().isZero()) { awesomeIcon = AwesomeIcon.EXCHANGE; style = "dao-tx-type-default-icon"; } else { awesomeIcon = item.isReceived() ? AwesomeIcon.SIGNIN : AwesomeIcon.SIGNOUT; doRotate = item.isReceived(); style = item.isReceived() ? "dao-tx-type-received-funds-icon" : "dao-tx-type-sent-funds-icon"; toolTipText = item.isReceived() ? Res.get("dao.tx.type.enum.received." + txType.name()) : Res.get("dao.tx.type.enum.sent." + txType.name()); } break; case PAY_TRADE_FEE: awesomeIcon = AwesomeIcon.TICKET; style = "dao-tx-type-default-icon"; break; case COMPENSATION_REQUEST: awesomeIcon = AwesomeIcon.FILE; style = "dao-tx-type-fee-icon"; break; case VOTE: awesomeIcon = AwesomeIcon.THUMBS_UP; style = "dao-tx-type-vote-icon"; break; case VOTE_REVEAL: awesomeIcon = AwesomeIcon.LIGHTBULB; style = "dao-tx-type-vote-reveal-icon"; break; case ISSUANCE: awesomeIcon = AwesomeIcon.MONEY; style = "dao-tx-type-issuance-icon"; break; default: awesomeIcon = AwesomeIcon.QUESTION_SIGN; style = "dao-tx-type-unverified-icon"; break; } Label label = AwesomeDude.createIconLabel(awesomeIcon); label.getStyleClass().addAll("icon", style); label.setTooltip(new Tooltip(toolTipText)); if (doRotate) label.setRotate(180); setGraphic(label); } else { setGraphic(null); } } }; } }); tableView.getColumns().add(column); } private void openTxInBlockExplorer(BsqTxListItem item) { if (item.getTxId() != null) GUIUtil.openWebPage(preferences.getBsqBlockChainExplorer().txUrl + item.getTxId()); } private void openAddressInBlockExplorer(BsqTxListItem item) { if (item.getAddress() != null) { GUIUtil.openWebPage(preferences.getBsqBlockChainExplorer().addressUrl + item.getAddress()); } } }
package ca.blarg.gdx.graphics; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.Vector3; /** * Various additional {@link SpriteBatch#draw} methods mostly for convenience. Most of these additional overloads * are to make drawing sprites at projected screen coordinates easier. * * Projected screen coordinate sprite rendering requires a perspective camera to project the 3D coordinates correctly. * A camera _must_ be set via {@link #begin(Camera)} (instead of using {@link #begin()}) before any of these draw * methods are called. */ public class ExtendedSpriteBatch extends SpriteBatch { static final float DEFAULT_COLOR = Color.WHITE.toFloatBits(); static final Vector3 tmp1 = new Vector3(); Camera projectionCamera; int pixelScale = 1; public ExtendedSpriteBatch() { super(); } public ExtendedSpriteBatch(int size) { super(size); } public ExtendedSpriteBatch(int size, ShaderProgram defaultShader) { super(size, defaultShader); } public ExtendedSpriteBatch(int size, int buffers) { super(size, buffers); } public ExtendedSpriteBatch(int size, int buffers, ShaderProgram defaultShader) { super(size, buffers, defaultShader); } public void setPixelScale(int pixelScale) { if (pixelScale <= 0) throw new IllegalArgumentException(); this.pixelScale = pixelScale; } @Override public void begin() { super.begin(); setColor(DEFAULT_COLOR); } public void begin(Camera projectionCamera) { begin(); this.projectionCamera = projectionCamera; } @Override public void end() { super.end(); this.projectionCamera = null; } public void draw(Texture texture, float x, float y, float z) { draw(texture, x, y, z, texture.getWidth(), texture.getHeight(), 0.0f, 1.0f, 1.0f, 0.0f); } public void draw(Texture texture, float x, float y, float z, float width, float height) { draw(texture, x, y, z, width, height, 0.0f, 1.0f, 1.0f, 0.0f); } public void draw(Texture texture, float x, float y, float z, float width, float height, float u, float v, float u2, float v2) { getProjectedCenteredPosition(x, y, z, width, height, tmp1); draw(texture, tmp1.x, tmp1.y, width, height, u, v, u2, v2); } public void draw(Texture texture, float x, float y, float z, int srcX, int srcY, int srcWidth, int srcHeight) { draw(texture, x, y, z, Math.abs(srcWidth), Math.abs(srcHeight), srcX, srcY, srcWidth, srcHeight); } public void draw(Texture texture, float x, float y, float z, float width, float height, int srcX, int srcY, int srcWidth, int srcHeight) { getProjectedCenteredPosition(x, y, z, width, height, tmp1); draw(texture, tmp1.x, tmp1.y, width, height, srcX, srcY, srcWidth, srcHeight, false, false); } public void draw(TextureRegion region, float x, float y, float z) { draw(region, x, y, z, region.getRegionWidth(), region.getRegionHeight()); } public void draw(TextureRegion region, float x, float y, float z, float width, float height) { getProjectedCenteredPosition(x, y, z, width, height, tmp1); draw(region, tmp1.x, tmp1.y, width, height); } // NOTE: these are not going to be as fast as BitmapFont's draw() method due to it's use of BitmapFontCache // probably don't need these ones with x,y only and just keep the x,y,z variants ... public void draw(BitmapFont font, float x, float y, CharSequence str) { draw(font, x, y, str, 1.0f); } public void draw(BitmapFont font, float x, float y, CharSequence str, float scale) { BitmapFont.BitmapFontData fontData = font.getData(); Texture fontTexture = font.getRegion().getTexture(); float currentX = x; float currentY = y; float lineHeight = fontData.lineHeight * scale; float spaceWidth = fontData.spaceWidth * scale; for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); // multiline support if (c == '\r') continue; // can't render this anyway, and likely a '\n' is right behind ... if (c == '\n') { currentY -= lineHeight; currentX = x; continue; } BitmapFont.Glyph glyph = fontData.getGlyph(c); if (glyph == null) { // TODO: maybe rendering some special char here instead would be better? currentX += spaceWidth; continue; } float glyphWidth = ((float)glyph.width * scale); float glyphHeight = ((float)glyph.height * scale); float glyphXoffset = ((float)glyph.xoffset * scale); float glyphYoffset = ((float)glyph.yoffset * scale); draw( fontTexture, currentX + glyphXoffset, currentY + glyphYoffset, glyphWidth, glyphHeight, glyph.u, glyph.v, glyph.u2, glyph.v2 ); currentX += ((float)glyph.xadvance * scale); } } public void draw(BitmapFont font, float x, float y, float z, CharSequence str) { draw(font, x, y, z, str, 1.0f); } public void draw(BitmapFont font, float x, float y, float z, CharSequence str, float scale) { BitmapFont.TextBounds bounds = font.getMultiLineBounds(str); float scaledBoundsWidth = bounds.width * scale; float scaledBoundsHeight = bounds.height * scale; getProjectedCenteredPosition(x, y, z, scaledBoundsWidth, scaledBoundsHeight, tmp1); // getProjectedCenteredPosition will actually center the Y coord incorrectly... we need to add // instead of subtract, but since that's already been done we need to add twice... (hence, *2) // TODO: this is the only place we need to do this right now, but if that changes, should // probably just move the centering calcs to each method tmp1.y += (scaledBoundsHeight / 2) * 2.0f; draw(font, tmp1.x, tmp1.y, str, scale); } public void getProjectedCenteredPosition(float x, float y, float z, float width, float height, Vector3 result) { if (projectionCamera == null) throw new IllegalStateException("Cannot project 3D coordinates to screen space when no projection camera is set."); result.set(x, y, z); projectionCamera.project(result); // screen coordinates will be unscaled, need to apply appropriate scaling result.x /= pixelScale; result.y /= pixelScale; // now center them on the bounds given result.x -= (width / 2.0f); result.y -= (height / 2.0f); } }
package ch.sbb.iib.plugin.mojos; import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId; import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration; import static org.twdata.maven.mojoexecutor.MojoExecutor.element; import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo; import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment; import static org.twdata.maven.mojoexecutor.MojoExecutor.goal; import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId; import static org.twdata.maven.mojoexecutor.MojoExecutor.name; import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin; import static org.twdata.maven.mojoexecutor.MojoExecutor.version; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; @Mojo(name="package-src") public class PackageIibSrcMojo extends AbstractMojo { /** * The Maven Project Object */ @Parameter(property = "project", required = true, readonly = true) protected MavenProject project; /** * The Maven Session Object */ @Parameter(property="session", required = true, readonly = true) protected MavenSession session; /** * The Maven PluginManager Object */ @Component protected BuildPluginManager buildPluginManager; /** * The path to write the assemblies/iib-src-project.xml file to before invoking the maven-assembly-plugin. */ @Parameter(defaultValue="${project.build.directory}/assemblies/iib-src-project.xml", readonly=true) private File buildAssemblyFile; public void execute() throws MojoExecutionException, MojoFailureException { InputStream is = this.getClass().getResourceAsStream("/assemblies/iib-src-project.xml"); FileOutputStream fos; buildAssemblyFile.getParentFile().mkdirs(); try { fos = new FileOutputStream(buildAssemblyFile); } catch (FileNotFoundException e) { // should never happen, as the file is packaged in this plugin's jar throw new MojoFailureException("Error creating the build assembly file: " + buildAssemblyFile, e); } try { IOUtil.copy(is, fos); } catch (IOException e) { // should never happen throw new MojoFailureException("Error creating the assembly file: " + buildAssemblyFile.getAbsolutePath(), e); } // mvn org.apache.maven.plugins:maven-assembly-plugin:2.4:single -Ddescriptor=target\assemblies\iib-src-project.xml -Dassembly.appendAssemblyId=false executeMojo(plugin(groupId("org.apache.maven.plugins"), artifactId("maven-assembly-plugin"), version("2.4")), goal("single"), configuration(element(name("descriptor"), "${project.build.directory}/assemblies/iib-src-project.xml"), element(name("appendAssemblyId"), "false")), executionEnvironment(project, session, buildPluginManager)); // delete the archive-tmp directory try { FileUtils.deleteDirectory(new File(project.getBuild().getDirectory(), "archive-tmp")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
// -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; -*- // vim: et ts=4 sts=4 sw=4 syntax=java package com.aragaer.jtt.resources; import java.text.DateFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.aragaer.jtt.Settings; import com.aragaer.jtt.R; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.preference.PreferenceManager; public class StringResources implements SharedPreferences.OnSharedPreferenceChangeListener { public static final int TYPE_HOUR_NAME = 0x1; public static final int TYPE_TIME_FORMAT = 0x2; private int change_pending; private final BroadcastReceiver TZChangeReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) { df = android.text.format.DateFormat.getTimeFormat(c); change_pending |= TYPE_TIME_FORMAT; notifyChange(); } } }; private static final IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED); private final Context c; private final Resources r; private String Hours[], HrOf[], Quarters[]; private DateFormat df; private int hour_name_option; protected StringResources(final Context context) { c = context; r = new Resources(c.getAssets(), null, null); final SharedPreferences pref = PreferenceManager .getDefaultSharedPreferences(c); hour_name_option = Integer.parseInt(pref.getString(Settings.PREF_HNAME, "0")); setLocale(pref.getString(Settings.PREF_LOCALE, "")); pref.registerOnSharedPreferenceChangeListener(this); } private static void setLocaleToResources(final String l, final Resources r) { final Locale locale = l.length() == 0 ? Resources.getSystem().getConfiguration().locale : new Locale(l); final Configuration config = r.getConfiguration(); config.locale = locale; r.updateConfiguration(config, null); } public static void setLocaleToContext(Context context) { final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final String lang = pref.getString(Settings.PREF_LOCALE, ""); setLocaleToResources(lang, context.getResources()); } private synchronized void setLocale(final String l) { setLocaleToResources(l, c.getApplicationContext().getResources()); load_hour_names(); df = android.text.format.DateFormat.getTimeFormat(c); change_pending |= TYPE_TIME_FORMAT; } public void onSharedPreferenceChanged(SharedPreferences pref, String key) { if (key.equals(Settings.PREF_LOCALE)) setLocale(pref.getString(key, "")); else if (key.equals(Settings.PREF_HNAME)) { hour_name_option = Integer.parseInt(pref.getString(key, "0")); load_hour_names(); } notifyChange(); } public String getHour(final int num) { return Hours[num]; } public String getHrOf(final int num) { return HrOf[num]; } public String getQuarter(final int q) { return Quarters[q]; } public interface StringResourceChangeListener { public void onStringResourcesChanged(final int changes); } private final Map<StringResourceChangeListener, Integer> listeners = new HashMap<StringResources.StringResourceChangeListener, Integer>(); public synchronized void registerStringResourceChangeListener( final StringResourceChangeListener listener, final int changeMask) { if (listeners.size() == 0) c.registerReceiver(TZChangeReceiver, filter); listeners.put(listener, changeMask); } public synchronized void unregisterStringResourceChangeListener( final StringResourceChangeListener listener) { listeners.remove(listener); if (listeners.size() == 0) c.unregisterReceiver(TZChangeReceiver); } private synchronized void notifyChange() { for (StringResourceChangeListener listener : listeners.keySet()) if ((listeners.get(listener) & change_pending) != 0) listener.onStringResourcesChanged(change_pending); change_pending = 0; } private static final int hnh[] = { R.array.hour, R.array.romaji_hour, R.array.hiragana_hour }; private static final int hnhof[] = { R.array.hour_of, R.array.romaji_hour_of, R.array.hiragana_hour_of }; private static final int q[] = { R.array.quarter, R.array.romaji_quarter, R.array.hiragana_quarter }; private void load_hour_names() { HrOf = r.getStringArray(hnhof[hour_name_option]); Hours = r.getStringArray(hnh[hour_name_option]); Quarters = r.getStringArray(q[hour_name_option]); change_pending |= TYPE_HOUR_NAME; } public String format_time(final long timestamp) { return df.format(timestamp); } }
package com.carlosefonseca.common.utils; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.location.LocationManager; import android.os.*; import android.provider.Settings; import android.text.InputType; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.*; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.carlosefonseca.common.CFApp; import android.support.annotation.Nullable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; import java.util.regex.Pattern; import static java.lang.Runtime.getRuntime; public final class CodeUtils { // public static final Pattern packageNameRegex = Pattern.compile(".+\\.([^.]+\\.).+"); public static final Pattern packageNameRegex = Pattern.compile("\\."); public static Pattern NIF_PATTERN; private static final String TAG = CodeUtils.getTag(CodeUtils.class); public static final String SIDE_T = ""; public static final String LONG_L = ""; private static Pattern sMacAddressPattern; private CodeUtils() {} public static boolean isMacAddress(CharSequence macAddress) { if (macAddress == null) return false; if (sMacAddressPattern == null) { sMacAddressPattern = Pattern.compile("([0-9a-fA-F]{12})|(([0-9a-fA-F]{2}[-:]){5}[0-9a-fA-F]{2})"); } return sMacAddressPattern.matcher(macAddress).matches(); } public static void hideKeyboard(View input) { //noinspection ConstantConditions InputMethodManager imm = (InputMethodManager) input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(input.getWindowToken(), 0); } public static void recreateActivity(Activity a) { Log.d(TAG, "Recreating Activity."); if (Build.VERSION.SDK_INT >= 11) { a.recreate(); } else { Intent intent = a.getIntent(); a.finish(); a.startActivity(intent); } } public static String getTag(Class clazz) { return packageNameRegex.split(clazz.getName(), 3)[1] + "." + clazz.getSimpleName(); } public static boolean isMainThread() { return Looper.getMainLooper() == Looper.myLooper(); } public static String separator(final String text) {return " " + text + " ";} public static void sleep(int i) { try { Thread.sleep(i); } catch (InterruptedException e) { Log.e(TAG, "" + e.getMessage(), e); } } public static int hashCode(int seed, Object... objects) { if (objects == null) return seed; int hashCode = seed; for (Object element : objects) { hashCode = 31 * hashCode + (element == null ? 0 : element.hashCode()); } return hashCode; } @SuppressLint("SetJavaScriptEnabled") public static void setupWebView(WebView webView) { final Context context = webView.getContext(); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setDatabaseEnabled(true); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { webSettings.setDatabasePath(context.getFilesDir() + "/databases/"); } webSettings.setAppCacheEnabled(true); webSettings.setUseWideViewPort(true); webSettings.setGeolocationEnabled(true); webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) webSettings.setDisplayZoomControls(false); webView.zoomOut(); webSettings.setGeolocationDatabasePath(context.getFilesDir() + "/databases/"); // Force links and redirects to open in the WebView instead of in a browser webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("http")) { view.loadUrl(url); } else { UrlUtils.tryStartIntentForUrl(context, url); } return true; } }); webView.setWebChromeClient(new WebChromeClient() { @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } }); } static DecimalFormat formatter; static { formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US); DecimalFormatSymbols decimalFormatSymbols = formatter.getDecimalFormatSymbols(); decimalFormatSymbols.setGroupingSeparator(' '); formatter.setDecimalFormatSymbols(decimalFormatSymbols); } public static String getKB(long bytes) { return formatter.format(bytes / 1024); } protected static long getFreeMem() { Runtime r = getRuntime(); long freeMem = r.maxMemory() - r.totalMemory() + r.freeMemory(); long freeMemLess = Math.max(0, freeMem - (2 * 1024 * 1024)); Log.d(TAG, "getFreeMem: Memory usage: %s ( %s / %s ) kB. Reporting only: %s kB", getKB(freeMem), getKB(r.totalMemory() - r.freeMemory()), getKB(r.maxMemory()), getKB(freeMemLess)); return freeMemLess; } public static String getTimespan(long uptimeMillisOnStart) { double secs = (SystemClock.uptimeMillis() - uptimeMillisOnStart) / 1000d; if (secs < 10) { return String.format("%.03fs", secs); } else if (secs < 60) { return String.valueOf((int) secs) + "s"; } else { return "" + (secs / 60) + "m " + (secs % 60) + "s"; } } /** * Checks if the given String is a valid NIF. * <p/> * Must be numbers only, must start with 1,2,5,6,7,8 or 9, check digit must be valid. * * @param nif String containing the number to validate. * @return true if is valid, false otherwise. */ public static boolean isNifValid(String nif) { if (NIF_PATTERN == null) NIF_PATTERN = Pattern.compile("[125689]\\d{8}"); if (!NIF_PATTERN.matcher(nif).matches()) return false; int sum = 0; int ii = 0; for (int i = 9; i >= 2; i sum += i * getDigitFromChar(nif.charAt(ii++)); } int expected = 11 - sum % 11; expected = (expected > 9) ? 0 : expected; return expected == getDigitFromChar(nif.charAt(8)); } /** * Converts a char into an int. Throws a RuntimeException if it is not a digit. */ public static int getDigitFromChar(char c) { if (c >= '0' && c <= '9') return c - '0'; throw new RuntimeException("Char '" + c + "' is not a number."); } public interface RunnableWithView<T extends View> { void run(T view); } public static <T extends View> void runOnGlobalLayout(final T view, final RunnableWithView<T> runnable) { try { assert view.getViewTreeObserver() != null; if (view.getViewTreeObserver().isAlive()) { view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") // We check which build version we are using. @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { view.getViewTreeObserver().removeOnGlobalLayoutListener(this); } runnable.run(view); } }); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } } public static void runOnGlobalLayout(final View view, final Runnable runnable) { try { assert view.getViewTreeObserver() != null; if (view.getViewTreeObserver().isAlive()) { view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") // We check which build version we are using. @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { view.getViewTreeObserver().removeOnGlobalLayoutListener(this); } runnable.run(); } }); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } } public static void setupNumericEditText(final AlertDialog dialog, final EditText editText, @Nullable final DialogInterface.OnClickListener onDone) { editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setInputType(InputType.TYPE_CLASS_PHONE | InputType.TYPE_NUMBER_VARIATION_PASSWORD); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (onDone != null && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { // the user is done typing. onDone.onClick(dialog, 0); return true; // consume. } return false; // pass on to other listeners. } }); } @SuppressLint("InlinedApi") public static void setupNumericEditText(final EditText editText, @Nullable final DialogInterface.OnClickListener onDone) { editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setInputType(InputType.TYPE_CLASS_PHONE | InputType.TYPE_NUMBER_VARIATION_PASSWORD); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (onDone != null && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { // the user is done typing. onDone.onClick(null, 0); return true; // consume. } return false; // pass on to other listeners. } }); } @SuppressLint("InlinedApi") public static void setupNumericEditText(final EditText editText, @Nullable final View.OnClickListener onDone) { editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setInputType(InputType.TYPE_CLASS_PHONE | InputType.TYPE_NUMBER_VARIATION_PASSWORD); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (onDone != null && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { // the user is done typing. onDone.onClick(editText); return true; // consume. } return false; // pass on to other listeners. } }); } @SuppressLint("InlinedApi") public static void setupNumericEditText(final EditText editText, @Nullable final Runnable runnable) { editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setInputType(InputType.TYPE_CLASS_PHONE | InputType.TYPE_NUMBER_VARIATION_PASSWORD); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (runnable != null && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { // the user is done typing. runnable.run(); return true; // consume. } return false; // pass on to other listeners. } }); } public static boolean isGpsOn() { return Settings.Secure.isLocationProviderEnabled(CFApp.getContext().getContentResolver(), LocationManager.GPS_PROVIDER); } /** * Creates a TouchListener that repeats a specified action as long as the view is being pressed. * * @param runnable The code to be repeated. * @param delayMillis The interval between repetitions. * @return A new OnTouchListener setup to handle long press to repeat. */ public static View.OnTouchListener getRepeatActionListener(final Runnable runnable, final int delayMillis) { return getRepeatActionListener(runnable, delayMillis, null); } /** * Creates a TouchListener that repeats a specified action as long as the view is being pressed. * * @param runnable The code to be repeated. * @param delayMillis The interval between repetitions. * @param onUpRunnable Code to run when the button is no longer being pressed. * @return A new OnTouchListener setup to handle long press to repeat. */ public static View.OnTouchListener getRepeatActionListener(final Runnable runnable, final int delayMillis, @Nullable final Runnable onUpRunnable) { final Handler mHandler = new Handler(); final Runnable repeatRunnable = new Runnable() { @Override public void run() { runnable.run(); mHandler.postDelayed(this, delayMillis); } }; return new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { int action = motionEvent.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: mHandler.removeCallbacks(repeatRunnable); runnable.run(); mHandler.postDelayed(repeatRunnable, 200); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mHandler.removeCallbacks(repeatRunnable); if (onUpRunnable != null) onUpRunnable.run(); break; } return false; } }; } /** * Computes the md5 hex hash for the specified string * * @param s The string to hash. * @return The hexadecimal hash. */ public static String md5(final String s) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuilder hexString = new StringBuilder(); for (byte aMessageDigest : messageDigest) { String h = Integer.toHexString(0xFF & aMessageDigest); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { Log.e(TAG, e); } return ""; } private static String versionName; public static String getAppVersionName() { if (versionName == null) { versionName = ""; try { //noinspection ConstantConditions PackageInfo pInfo = CFApp.getContext() .getPackageManager() .getPackageInfo(CFApp.getContext().getPackageName(), 0); versionName = pInfo.versionName; } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception", e); } } return versionName; } private static int versionCode = -1; public static int getAppVersionCode() { if (versionCode == -1) { try { //noinspection ConstantConditions PackageInfo pInfo = CFApp.getContext() .getPackageManager() .getPackageInfo(CFApp.getContext().getPackageName(), 0); versionCode = pInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception", e); } } return versionCode; } public static void runOnBackground(final Runnable runnable) { new AsyncTask<Void, Void, Void>() { @Nullable @Override protected Void doInBackground(Void... params) { runnable.run(); return null; } }.execute(); } public static void pauseRunningAppForDebugPurposesDontLeaveThisHangingAround() { if (CFApp.isTestDevice()) { Log.w(TAG, " try { boolean block = true; //noinspection ConstantConditions while (block) { Thread.sleep(1000); } } catch (InterruptedException e) { Log.e(TAG, "" + e.getMessage(), e); } } } public static void toast(final String message) { runOnUIThread(new Runnable() { @Override public void run() { Toast.makeText(CFApp.getContext(), message, Toast.LENGTH_SHORT).show(); } }); } public static void ltoast(final String message) { runOnUIThread(new Runnable() { @Override public void run() { Toast.makeText(CFApp.getContext(), message, Toast.LENGTH_LONG).show(); } }); } /** * Null-safe equivalent of {@code a.equals(b)}. */ public static boolean equals(@Nullable Object a, @Nullable Object b) { return (a == null) ? (b == null) : a.equals(b); } public static void runOnUIThread(Runnable runnable) { if (isMainThread()) { runnable.run(); } else { new Handler(Looper.getMainLooper()).post(runnable); } } public static void setVisibility(int visibility, View...views) { for (View view : views) { view.setVisibility(visibility); } } }
package com.evolvedbinary.jni.consbench; /** * A small JNI Benchmark to show the difference * in cost between various models of Object Construction * for a Java API that wraps a C++ API using JNI * * @author <a href="mailto:adam@evolvedbinary.com">Adam Retter</a> */ public class Benchmark { private final static int DEFAULT_ITERATIONS = 1_000_000; public static final void main(final String args[]) { int iterations = DEFAULT_ITERATIONS; boolean outputAsCSV = false; boolean inNs = false; boolean close = false; if (args != null && args.length > 0) { for (String arg : args) { if (arg.startsWith("--iterations=")) { arg = arg.substring("--iterations=".length()); iterations = Integer.parseInt(arg); } else if (arg.equals("--csv")) { outputAsCSV = true; } else if (arg.equals("--ns")) { inNs = true; } else if (arg.equals("--close")) { close = true; } else if (arg.equals("--help") || arg.equals("-h") || arg.equals("/?")) { System.out.println(); System.out.println("Benchmark"); System.out.println("--iterations=n set the number of iterations"); System.out.println("--csv output results in CSV format"); System.out.println("--ns compute times in ns as opposed to ms"); System.out.println("--close native objects should be closed (disposed) after use"); System.out.println(); } } } NarSystem.loadLibrary(); if (close) { testWithClose(iterations, outputAsCSV, inNs); } else { testWithoutClose(iterations, outputAsCSV, inNs); } } private static final void testWithClose(final int iterations, final boolean outputAsCSV, final boolean inNs) { //TEST1 - Foo By Call final long start1 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCall fooByCall = new FooByCall(); fooByCall.close(); } final long end1 = time(inNs); //TEST2 - Foo By Call Static final long start2 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallStatic fooByCallStatic = new FooByCallStatic(); fooByCallStatic.close(); } final long end2 = time(inNs); //TEST3 - Foo By Call Invoke final long start3 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallInvoke fooByCallStatic = new FooByCallInvoke(); fooByCallStatic.close(); } final long end3 = time(inNs); //TEST4 - Foo By Call Final final long start4 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallFinal fooByCallFinal = new FooByCallFinal(); fooByCallFinal.close(); } final long end4 = time(inNs); //TEST5 - Foo By Call Static Final final long start5 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallStaticFinal fooByCallStaticFinal = new FooByCallStaticFinal(); fooByCallStaticFinal.close(); } final long end5 = time(inNs); //TEST6 - Foo By Call Invoke Final final long start6 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallInvokeFinal fooByCallInvokeFinal = new FooByCallInvokeFinal(); fooByCallInvokeFinal.close(); } final long end6 = time(inNs); outputResults(outputAsCSV, inNs, end1 - start1, end2 - start2, end3 - start3, end4 - start4, end5 - start5, end6 - start6 ); } private static final void testWithoutClose(final int iterations, final boolean outputAsCSV, final boolean inNs) { //TEST1 - Foo By Call final long start1 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCall fooByCall = new FooByCall(); } final long end1 = time(inNs); //TEST2 - Foo By Call Static final long start2 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallStatic fooByCallStatic = new FooByCallStatic(); } final long end2 = time(inNs); //TEST3 - Foo By Call Invoke final long start3 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallInvoke fooByCallInvoke = new FooByCallInvoke(); } final long end3 = time(inNs); //TEST4 - Foo By Call Final final long start4 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallFinal fooByCallFinal = new FooByCallFinal(); } final long end4 = time(inNs); //TEST5 - Foo By Call Static Final final long start5 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallStaticFinal fooByCallStaticFinal = new FooByCallStaticFinal(); } final long end5 = time(inNs); //TEST6 - Foo By Call Invoke Final final long start6 = time(inNs); for(int i = 0; i < iterations; i++) { final FooByCallInvokeFinal fooByCallInvokeFinal = new FooByCallInvokeFinal(); } final long end6 = time(inNs); outputResults(outputAsCSV, inNs, end1 - start1, end2 - start2, end3 - start3, end4 - start4, end5 - start5, end6 - start6 ); } private static final void outputResults(final boolean outputAsCSV, final boolean inNs, final long res1, final long res2, final long res3, final long res4, final long res5, final long res6) { if (outputAsCSV) { System.out.println(String.format("%d,%d,%d,%d,%d,%d", res1, res2, res3, res4, res5, res6)); } else { final String timeUnits = timeUnits(inNs); System.out.println("FooByCall: " + res1 + timeUnits); System.out.println("FooByCallStatic: " + res2 + timeUnits); System.out.println("FooByCallInvoke: " + res3 + timeUnits); System.out.println("FooByCallFinal: " + res4 + timeUnits); System.out.println("FooByCallStaticFinal: " + res5 + timeUnits); System.out.println("FooByCallInvokeFinal: " + res6 + timeUnits); } } private static final long time(final boolean inNs) { if (inNs) { return System.nanoTime(); } else { return System.currentTimeMillis(); } } private static final String timeUnits(final boolean inNs) { if (inNs) { return "ns"; } else { return "ms"; } } }
package com.github.davidcanboni.jenkins; import com.github.davidcanboni.jenkins.xml.Xml; import com.github.davidcarboni.ResourceUtils; import com.github.onsdigital.http.Endpoint; import com.github.onsdigital.http.Http; import com.github.onsdigital.http.Response; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.WordUtils; import org.w3c.dom.Document; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; /** * Handles jobs in the Maven Build category. */ public class MavenJobs { public static Document forRepo(URL gitUrl) throws IOException { Document document = getTemplate(); setGitUrl(gitUrl, document); return document; } public static Document forRepo(URL gitUrl, String branch) throws IOException { Document document = getTemplate(); setGitUrl(gitUrl, document); setBranch(branch, document); return document; } private static Document getTemplate() throws IOException { return ResourceUtils.getXml(Templates.configMaven); } private static void setGitUrl(URL gitUrl, Document template) throws IOException { Xml.setTextValue(template, "//hudson.plugins.git.UserRemoteConfig/url", gitUrl.toString()); } private static void setBranch(String branch, Document template) throws IOException { Xml.setTextValue(template, "//hudson.plugins.git.BranchSpec/name", branch); } public static void create(String name, URL gitUrl, String branch) throws IOException, URISyntaxException { if (StringUtils.isNotBlank(name)) { try (Http http = new Http()) { http.addHeader("Content-Type", "application/xml"); String jobName = "Maven " + WordUtils.capitalize(branch) + " " + WordUtils.capitalize(name); Document config = forRepo(gitUrl, branch); if (!Jobs.exists(jobName)) { System.out.println("Creating Maven job " + jobName); // Set the URL and create: //create(jobName, config, http); } else { System.out.println("Updating Maven job " + jobName); Endpoint endpoint = new Endpoint(Jobs.jenkins, "/job/" + jobName + "/config.xml"); //update(jobName, config, http, endpoint); } } } } private static void create(String jobName, Document config, Http http) throws IOException { // Post the config XML to create the job Endpoint endpoint = Jobs.createItem.setParameter("name", jobName); Response<String> create = http.post(endpoint, config, String.class); if (create.statusLine.getStatusCode() != 200) { System.out.println(create.body); throw new RuntimeException("Error setting configuration for job " + jobName + ": " + create.statusLine.getReasonPhrase()); } } private static void update(String jobName, Document config, Http http, Endpoint endpoint) throws IOException { // Post the config XML to update the job Response<String> create = http.post(endpoint, config, String.class); if (create.statusLine.getStatusCode() != 200) { System.out.println(create.body); throw new RuntimeException("Error setting configuration for job " + jobName + ": " + create.statusLine.getReasonPhrase()); } } public static void main(String[] args) throws IOException, URISyntaxException { // Loop through the matrix of combinations and set up the jobs: for (Environment branch : Environment.values()) { for (GitRepo gitRepo : GitRepo.values()) { String name = gitRepo.name(); URL githubUrl = gitRepo.url; create(name, githubUrl, branch.name()); } } } }
package be.ibridge.kettle.core.values; import java.math.BigDecimal; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import junit.framework.TestCase; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.exception.KettleValueException; import be.ibridge.kettle.core.value.Value; /** * Test class for the basic functionality of Value. * * @author Sven Boden */ public class ValueTest extends TestCase { /** * Constructor test 1. */ public void testConstructor1() { Value vs = new Value(); // Set by clearValue() assertFalse(vs.isNull()); // historical probably assertTrue(vs.isEmpty()); // historical probably assertEquals(null, vs.getName()); assertEquals(null, vs.getOrigin()); assertEquals(Value.VALUE_TYPE_NONE, vs.getType()); assertFalse(vs.isString()); assertFalse(vs.isDate()); assertFalse(vs.isNumeric()); assertFalse(vs.isInteger()); assertFalse(vs.isBigNumber()); assertFalse(vs.isNumber()); assertFalse(vs.isBoolean()); Value vs1 = new Value("Name"); // Set by clearValue() assertFalse(vs1.isNull()); // historical probably assertTrue(vs1.isEmpty()); // historical probably assertEquals("Name", vs1.getName()); assertEquals(null, vs1.getOrigin()); assertEquals(Value.VALUE_TYPE_NONE, vs1.getType()); } /** * Constructor test 2. */ public void testConstructor2() { Value vs = new Value("Name", Value.VALUE_TYPE_NUMBER); assertFalse(vs.isNull()); assertFalse(vs.isEmpty()); assertEquals("Name", vs.getName()); assertEquals(Value.VALUE_TYPE_NUMBER, vs.getType()); assertTrue(vs.isNumber()); assertTrue(vs.isNumeric()); Value vs1= new Value("Name", Value.VALUE_TYPE_STRING); assertFalse(vs1.isNull()); assertFalse(vs1.isEmpty()); assertEquals("Name", vs1.getName()); assertEquals(Value.VALUE_TYPE_STRING, vs1.getType()); assertTrue(vs1.isString()); Value vs2= new Value("Name", Value.VALUE_TYPE_DATE); assertFalse(vs2.isNull()); assertFalse(vs2.isEmpty()); assertEquals("Name", vs2.getName()); assertEquals(Value.VALUE_TYPE_DATE, vs2.getType()); assertTrue(vs2.isDate()); Value vs3= new Value("Name", Value.VALUE_TYPE_BOOLEAN); assertFalse(vs3.isNull()); assertFalse(vs3.isEmpty()); assertEquals("Name", vs3.getName()); assertEquals(Value.VALUE_TYPE_BOOLEAN, vs3.getType()); assertTrue(vs3.isBoolean()); Value vs4= new Value("Name", Value.VALUE_TYPE_INTEGER); assertFalse(vs4.isNull()); assertFalse(vs4.isEmpty()); assertEquals("Name", vs4.getName()); assertEquals(Value.VALUE_TYPE_INTEGER, vs4.getType()); assertTrue(vs4.isInteger()); assertTrue(vs4.isNumeric()); Value vs5= new Value("Name", Value.VALUE_TYPE_BIGNUMBER); assertFalse(vs5.isNull()); assertFalse(vs5.isEmpty()); assertEquals("Name", vs5.getName()); assertEquals(Value.VALUE_TYPE_BIGNUMBER, vs5.getType()); assertTrue(vs5.isBigNumber()); assertTrue(vs5.isNumeric()); Value vs6= new Value("Name", 1000000); assertEquals(Value.VALUE_TYPE_NONE, vs6.getType()); } /** * Constructors using Values */ public void testConstructor3() { Value vs = new Value("Name", Value.VALUE_TYPE_NUMBER); vs.setValue(10.0D); vs.setOrigin("origin"); vs.setLength(4, 2); Value copy = new Value(vs); assertEquals(vs.getType(), copy.getType()); assertEquals(vs.getNumber(), copy.getNumber(), 0.1D); assertEquals(vs.getLength(), copy.getLength()); assertEquals(vs.getPrecision(), copy.getPrecision()); assertEquals(vs.isNull(), copy.isNull()); assertEquals(vs.getOrigin(), copy.getOrigin()); assertEquals(vs.getName(), copy.getName()); // Show it's a deep copy copy.setName("newName"); assertEquals("Name", vs.getName()); assertEquals("newName", copy.getName()); copy.setOrigin("newOrigin"); assertEquals("origin", vs.getOrigin()); assertEquals("newOrigin", copy.getOrigin()); copy.setValue(11.0D); assertEquals(10.0D, vs.getNumber(), 0.1D); assertEquals(11.0D, copy.getNumber(), 0.1D); Value vs1 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs1.setName(null); // name and origin are null Value copy1 = new Value(vs1); assertEquals(vs1.getType(), copy1.getType()); assertEquals(vs1.getNumber(), copy1.getNumber(), 0.1D); assertEquals(vs1.getLength(), copy1.getLength()); assertEquals(vs1.getPrecision(), copy1.getPrecision()); assertEquals(vs1.isNull(), copy1.isNull()); assertEquals(vs1.getOrigin(), copy1.getOrigin()); assertEquals(vs1.getName(), copy1.getName()); Value vs2 = new Value((Value)null); assertTrue(vs2.isNull()); assertNull(vs2.getName()); assertNull(vs2.getOrigin()); } /** * Constructors using Values */ public void testConstructor4() { Value vs = new Value("Name", new StringBuffer("buffer")); assertEquals(Value.VALUE_TYPE_STRING, vs.getType()); assertEquals("buffer", vs.getString()); } /** * Constructors using Values */ public void testConstructor5() { Value vs = new Value("Name", 10.0D); assertEquals(Value.VALUE_TYPE_NUMBER, vs.getType()); assertEquals("Name", vs.getName()); Value copy = new Value("newName", vs); assertEquals("newName", copy.getName()); assertFalse(!vs.equals(copy)); copy.setName("Name"); assertTrue(vs.equals(copy)); } /** * Test of string representation of String Value. */ public void testToStringString() { String result = null; Value vs = new Value("Name", Value.VALUE_TYPE_STRING); vs.setValue("test string"); result = vs.toString(true); assertEquals("test string", result); vs.setLength(20); result = vs.toString(true); // padding assertEquals("test string ", result); vs.setLength(4); result = vs.toString(true); // truncate assertEquals("test", result); vs.setLength(0); result = vs.toString(true); // on 0 => full string assertEquals("test string", result); // no padding result = vs.toString(false); assertEquals("test string", result); vs.setLength(20); result = vs.toString(false); assertEquals("test string", result); vs.setLength(4); result = vs.toString(false); assertEquals("test string", result); vs.setLength(0); result = vs.toString(false); assertEquals("test string", result); vs.setLength(4); vs.setNull(); result = vs.toString(false); assertEquals("", result); Value vs1 = new Value("Name", Value.VALUE_TYPE_STRING); assertEquals("", vs1.toString()); // Just to get 100% coverage Value vs2 = new Value("Name", Value.VALUE_TYPE_NONE); assertEquals("", vs2.toString()); } /** * Test of string representation of Number Value. */ public void testToStringNumber() { Value vs1 = new Value("Name", Value.VALUE_TYPE_NUMBER); assertEquals(" 0"+Const.DEFAULT_DECIMAL_SEPARATOR+"0", vs1.toString(true)); Value vs2 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs2.setNull(); assertEquals("", vs2.toString(true)); Value vs3 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs3.setValue(100.0D); vs3.setLength(6); vs3.setNull(); assertEquals(" ", vs3.toString(true)); Value vs4 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs4.setValue(100.0D); vs4.setLength(6); assertEquals(" 000100"+Const.DEFAULT_DECIMAL_SEPARATOR+"00", vs4.toString(true)); Value vs5 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs5.setValue(100.5D); vs5.setLength(-1); vs5.setPrecision(-1); assertEquals(" 100"+Const.DEFAULT_DECIMAL_SEPARATOR+"5", vs5.toString(true)); Value vs6 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs6.setValue(100.5D); vs6.setLength(8); vs6.setPrecision(-1); assertEquals(" 00000100"+Const.DEFAULT_DECIMAL_SEPARATOR+"50", vs6.toString(true)); Value vs7 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs7.setValue(100.5D); vs7.setLength(0); vs7.setPrecision(3); assertEquals(" 100"+Const.DEFAULT_DECIMAL_SEPARATOR+"5", vs7.toString(true)); Value vs8 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs8.setValue(100.5D); vs8.setLength(5); vs8.setPrecision(3); assertEquals("100.5", vs8.toString(false)); Value vs9 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs9.setValue(100.0D); vs9.setLength(6); assertEquals("100.0", vs9.toString(false)); Value vs10 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs10.setValue(100.5D); vs10.setLength(-1); vs10.setPrecision(-1); assertEquals("100.5", vs10.toString(false)); Value vs11 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs11.setValue(100.5D); vs11.setLength(8); vs11.setPrecision(-1); assertEquals("100.5", vs11.toString(false)); Value vs12 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs12.setValue(100.5D); vs12.setLength(0); vs12.setPrecision(3); assertEquals("100.5", vs12.toString(false)); Value vs13 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs13.setValue(100.5D); vs13.setLength(5); vs13.setPrecision(3); assertEquals("100.5", vs13.toString(false)); Value vs14 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs14.setValue(100.5D); vs14.setLength(5); vs14.setPrecision(3); assertEquals(" 100"+Const.DEFAULT_DECIMAL_SEPARATOR+"500", vs14.toString(true)); } /** * Test of string representation of Integer Value. */ public void testToIntegerNumber() { Value vs1 = new Value("Name", Value.VALUE_TYPE_INTEGER); assertEquals(" 0", vs1.toString(true)); Value vs2 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs2.setNull(); assertEquals("", vs2.toString(true)); Value vs3 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs3.setValue(100); vs3.setLength(6); vs3.setNull(); assertEquals(" ", vs3.toString(true)); Value vs4 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs4.setValue(100); vs4.setLength(6); assertEquals(" 000100", vs4.toString(true)); Value vs5 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs5.setValue(100); vs5.setLength(-1); vs5.setPrecision(-1); assertEquals(" 100", vs5.toString(true)); Value vs6 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs6.setValue(105); vs6.setLength(8); vs6.setPrecision(-1); assertEquals(" 00000105", vs6.toString(true)); Value vs7 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs7.setValue(100); vs7.setLength(0); vs7.setPrecision(3); assertEquals(" 100", vs7.toString(true)); Value vs8 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs8.setValue(100); vs8.setLength(5); vs8.setPrecision(3); assertEquals("100", vs8.toString(false)); Value vs9 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs9.setValue(100); vs9.setLength(6); assertEquals("100", vs9.toString(false)); Value vs10 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs10.setValue(100); vs10.setLength(-1); vs10.setPrecision(-1); assertEquals(" 100", vs10.toString(false)); Value vs11 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs11.setValue(100); vs11.setLength(8); vs11.setPrecision(-1); assertEquals("100", vs11.toString(false)); Value vs12 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs12.setValue(100); vs12.setLength(0); vs12.setPrecision(3); assertEquals(" 100", vs12.toString(false)); Value vs13 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs13.setValue(100); vs13.setLength(5); vs13.setPrecision(3); assertEquals("100", vs13.toString(false)); Value vs14 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs14.setValue(100); vs14.setLength(5); vs14.setPrecision(3); assertEquals(" 00100", vs14.toString(true)); } /** * Test of boolean representation of Value. */ public void testToStringBoolean() { String result = null; Value vs = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs.setValue(true); result = vs.toString(true); assertEquals("true", result); Value vs1 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs1.setValue(false); result = vs1.toString(true); assertEquals("false", result); // set to "null" Value vs2 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs2.setValue(true); vs2.setNull(); result = vs2.toString(true); assertEquals("", result); // set to "null" Value vs3 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs3.setValue(false); vs3.setNull(); result = vs3.toString(true); assertEquals("", result); // set to length = 1 => get Y/N Value vs4 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs4.setValue(true); vs4.setLength(1); result = vs4.toString(true); assertEquals("true", result); // set to length = 1 => get Y/N Value vs5 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs5.setValue(false); vs5.setLength(1); result = vs5.toString(true); assertEquals("false", result); // set to length > 1 => get true/false Value vs6 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs6.setValue(true); vs6.setLength(3); result = vs6.toString(true); assertEquals("true", result); // set to length > 1 => get true/false (+ truncation) Value vs7 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs7.setValue(false); vs7.setLength(3); result = vs7.toString(true); assertEquals("false", result); } /** * Test of boolean representation of Value. */ public void testToStringDate() { String result = null; Value vs1 = new Value("Name", Value.VALUE_TYPE_DATE); result = vs1.toString(true); assertEquals("", result); Value vs2 = new Value("Name", Value.VALUE_TYPE_DATE); vs2.setNull(true); result = vs2.toString(true); assertEquals("", result); SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); Date dt = df.parse("2006/03/01 17:01:02.005", new ParsePosition(0)); Value vs3 = new Value("Name", Value.VALUE_TYPE_DATE); vs3.setValue(dt); result = vs3.toString(true); assertEquals("2006/03/01 17:01:02.005", result); Value vs4 = new Value("Name", Value.VALUE_TYPE_DATE); vs4.setNull(true); vs4.setLength(2); result = vs4.toString(true); assertEquals("", result); Value vs5 = new Value("Name", Value.VALUE_TYPE_DATE); vs3.setValue(dt); vs5.setLength(10); result = vs5.toString(true); assertEquals("", result); } public void testToStringMeta() { String result = null; // Strings Value vs = new Value("Name", Value.VALUE_TYPE_STRING); vs.setValue("test"); result = vs.toStringMeta(); assertEquals("String", result); Value vs1= new Value("Name", Value.VALUE_TYPE_STRING); vs1.setValue("test"); vs1.setLength(0); result = vs1.toStringMeta(); assertEquals("String", result); Value vs2= new Value("Name", Value.VALUE_TYPE_STRING); vs2.setValue("test"); vs2.setLength(4); result = vs2.toStringMeta(); assertEquals("String(4)", result); // Booleans: not affected by length on output Value vs3 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs3.setValue(false); result = vs3.toStringMeta(); assertEquals("Boolean", result); Value vs4= new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs4.setValue(false); vs4.setLength(0); result = vs4.toStringMeta(); assertEquals("Boolean", result); Value vs5= new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs5.setValue(false); vs5.setLength(4); result = vs5.toStringMeta(); assertEquals("Boolean", result); // Integers Value vs6 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs6.setValue(10); result = vs6.toStringMeta(); assertEquals("Integer", result); Value vs7= new Value("Name", Value.VALUE_TYPE_INTEGER); vs7.setValue(10); vs7.setLength(0); result = vs7.toStringMeta(); assertEquals("Integer", result); Value vs8= new Value("Name", Value.VALUE_TYPE_INTEGER); vs8.setValue(10); vs8.setLength(4); result = vs8.toStringMeta(); assertEquals("Integer(4)", result); // Numbers Value vs9 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs9.setValue(10.0D); result = vs9.toStringMeta(); assertEquals("Number", result); Value vs10 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs10.setValue(10.0D); vs10.setLength(0); result = vs10.toStringMeta(); assertEquals("Number", result); Value vs11 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs11.setValue(10.0D); vs11.setLength(4); result = vs11.toStringMeta(); assertEquals("Number(4)", result); Value vs12 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs12.setValue(10.0D); vs12.setLength(4); vs12.setPrecision(2); result = vs12.toStringMeta(); assertEquals("Number(4, 2)", result); // BigNumber Value vs13 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs13.setValue(new BigDecimal(10)); result = vs13.toStringMeta(); assertEquals("BigNumber", result); Value vs14 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs14.setValue(new BigDecimal(10)); vs14.setLength(0); result = vs14.toStringMeta(); assertEquals("BigNumber", result); Value vs15 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs15.setValue(new BigDecimal(10)); vs15.setLength(4); result = vs15.toStringMeta(); assertEquals("BigNumber(4)", result); Value vs16 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs16.setValue(new BigDecimal(10)); vs16.setLength(4); vs16.setPrecision(2); result = vs16.toStringMeta(); assertEquals("BigNumber(4, 2)", result); // Date Value vs17 = new Value("Name", Value.VALUE_TYPE_DATE); vs17.setValue(new Date()); result = vs17.toStringMeta(); assertEquals("Date", result); Value vs18 = new Value("Name", Value.VALUE_TYPE_DATE); vs18.setValue(new Date()); vs18.setLength(0); result = vs18.toStringMeta(); assertEquals("Date", result); Value vs19 = new Value("Name", Value.VALUE_TYPE_DATE); vs19.setValue(new Date()); vs19.setLength(4); result = vs19.toStringMeta(); assertEquals("Date", result); Value vs20 = new Value("Name", Value.VALUE_TYPE_DATE); vs20.setValue(new Date()); vs20.setLength(4); vs20.setPrecision(2); result = vs20.toStringMeta(); assertEquals("Date", result); } /** * Constructors using Values. */ public void testClone1() { Value vs = new Value("Name", Value.VALUE_TYPE_NUMBER); vs.setValue(10.0D); vs.setOrigin("origin"); vs.setLength(4, 2); Value copy = (Value)vs.Clone(); assertEquals(vs.getType(), copy.getType()); assertEquals(vs.getNumber(), copy.getNumber(), 0.1D); assertEquals(vs.getLength(), copy.getLength()); assertEquals(vs.getPrecision(), copy.getPrecision()); assertEquals(vs.isNull(), copy.isNull()); assertEquals(vs.getOrigin(), copy.getOrigin()); assertEquals(vs.getName(), copy.getName()); // Show it's a deep copy copy.setName("newName"); assertEquals("Name", vs.getName()); assertEquals("newName", copy.getName()); copy.setOrigin("newOrigin"); assertEquals("origin", vs.getOrigin()); assertEquals("newOrigin", copy.getOrigin()); copy.setValue(11.0D); assertEquals(10.0D, vs.getNumber(), 0.1D); assertEquals(11.0D, copy.getNumber(), 0.1D); Value vs1 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs1.setName(null); // name and origin are null Value copy1 = new Value(vs1); assertEquals(vs1.getType(), copy1.getType()); assertEquals(vs1.getNumber(), copy1.getNumber(), 0.1D); assertEquals(vs1.getLength(), copy1.getLength()); assertEquals(vs1.getPrecision(), copy1.getPrecision()); assertEquals(vs1.isNull(), copy1.isNull()); assertEquals(vs1.getOrigin(), copy1.getOrigin()); assertEquals(vs1.getName(), copy1.getName()); Value vs2 = new Value((Value)null); assertTrue(vs2.isNull()); assertNull(vs2.getName()); assertNull(vs2.getOrigin()); } /** * Test of getStringLength(). * */ public void testGetStringLength() { int result = 0; Value vs1 = new Value("Name", Value.VALUE_TYPE_STRING); result = vs1.getStringLength(); assertEquals(0, result); Value vs2 = new Value("Name", Value.VALUE_TYPE_STRING); vs2.setNull(); result = vs2.getStringLength(); assertEquals(0, result); Value vs3 = new Value("Name", Value.VALUE_TYPE_STRING); vs3.setValue("stringlength"); result = vs3.getStringLength(); assertEquals(12, result); } public void testGetXML() { String result = null; Value vs1= new Value("Name", Value.VALUE_TYPE_STRING); vs1.setValue("test"); vs1.setLength(4); vs1.setPrecision(2); result = vs1.getXML(); assertEquals("<name>Name</name><type>String</type><text>test</text><length>4</length><precision>-1</precision><isnull>N</isnull>", result); Value vs2= new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs2.setValue(false); vs2.setLength(4); vs2.setPrecision(2); result = vs2.getXML(); assertEquals("<name>Name</name><type>Boolean</type><text>false</text><length>-1</length><precision>-1</precision><isnull>N</isnull>", result); Value vs3= new Value("Name", Value.VALUE_TYPE_INTEGER); vs3.setValue(10); vs3.setLength(4); vs3.setPrecision(2); result = vs3.getXML(); assertEquals("<name>Name</name><type>Integer</type><text>10</text><length>4</length><precision>0</precision><isnull>N</isnull>", result); Value vs4 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs4.setValue(10.0D); vs4.setLength(4); vs4.setPrecision(2); result = vs4.getXML(); assertEquals("<name>Name</name><type>Number</type><text>10.0</text><length>4</length><precision>2</precision><isnull>N</isnull>", result); Value vs5 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs5.setValue(new BigDecimal(10)); vs5.setLength(4); vs5.setPrecision(2); result = vs5.getXML(); assertEquals("<name>Name</name><type>BigNumber</type><text>10</text><length>4</length><precision>2</precision><isnull>N</isnull>", result); SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); Date dt = df.parse("2006/03/01 17:01:02.005", new ParsePosition(0)); Value vs6 = new Value("Name", Value.VALUE_TYPE_DATE); vs6.setValue(dt); vs6.setLength(4); vs6.setPrecision(2); result = vs6.getXML(); assertEquals("<name>Name</name><type>Date</type><text>2006&#47;03&#47;01 17:01:02.005</text><length>-1</length><precision>2</precision><isnull>N</isnull>", result); } /** * Test of setValue() */ public void testSetValue() { Value vs = new Value("Name", Value.VALUE_TYPE_INTEGER); vs.setValue(100L); vs.setOrigin("origin"); Value vs1 = new Value((Value)null); assertTrue(vs1.isNull()); assertTrue(vs1.isEmpty()); assertNull(vs1.getName()); assertNull(vs1.getOrigin()); assertEquals(Value.VALUE_TYPE_NONE, vs1.getType()); Value vs2 = new Value("newName", Value.VALUE_TYPE_INTEGER); vs2.setOrigin("origin1"); vs2.setValue(vs); assertEquals("origin", vs2.getOrigin()); assertEquals(vs.getInteger(), vs2.getInteger()); Value vs3 = new Value("newName", Value.VALUE_TYPE_INTEGER); vs3.setValue(new StringBuffer("Sven")); assertEquals(Value.VALUE_TYPE_STRING, vs3.getType()); assertEquals("Sven", vs3.getString()); Value vs4 = new Value("newName", Value.VALUE_TYPE_STRING); vs4.setValue(new StringBuffer("Test")); vs4.setValue(new StringBuffer("Sven")); assertEquals(Value.VALUE_TYPE_STRING, vs4.getType()); assertEquals("Sven", vs4.getString()); Value vs5 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs5.setValue((byte)4); assertEquals(4L, vs5.getInteger()); Value vs6 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs6.setValue((Value)null); assertFalse(vs6.isNull()); assertNull(vs6.getName()); assertNull(vs6.getOrigin()); assertEquals(Value.VALUE_TYPE_NONE, vs6.getType()); } /** * Test for isNumeric(). */ public void testIsNumeric() { assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_NONE)); assertEquals(true, Value.isNumeric(Value.VALUE_TYPE_NUMBER)); assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_STRING)); assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_DATE)); assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_BOOLEAN)); assertEquals(true, Value.isNumeric(Value.VALUE_TYPE_INTEGER)); assertEquals(true, Value.isNumeric(Value.VALUE_TYPE_BIGNUMBER)); assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_SERIALIZABLE)); } public void testIsEqualTo() { Value vs1 = new Value("Name", Value.VALUE_TYPE_STRING); vs1.setValue("test"); assertTrue(vs1.isEqualTo("test")); assertFalse(vs1.isEqualTo("test1")); Value vs2 = new Value("Name", Value.VALUE_TYPE_STRING); vs2.setValue(new BigDecimal(1.0D)); assertTrue(vs2.isEqualTo(new BigDecimal(1.0D))); assertFalse(vs2.isEqualTo(new BigDecimal(2.0D))); Value vs3 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs3.setValue(10.0D); assertTrue(vs3.isEqualTo(10.0D)); assertFalse(vs3.isEqualTo(11.0D)); Value vs4 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs4.setValue(10L); assertTrue(vs4.isEqualTo(10L)); assertFalse(vs4.isEqualTo(11L)); Value vs5 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs5.setValue(10); assertTrue(vs5.isEqualTo(10)); assertFalse(vs5.isEqualTo(11)); Value vs6 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs6.setValue((byte)10); assertTrue(vs6.isEqualTo(10)); assertFalse(vs6.isEqualTo(11)); SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); Date dt = df.parse("2006/03/01 17:01:02.005", new ParsePosition(0)); Value vs7 = new Value("Name", Value.VALUE_TYPE_DATE); vs7.setValue(dt); assertTrue(vs7.isEqualTo(dt)); assertFalse(vs7.isEqualTo(new Date())); // assume it's not 2006/03/01 } /** * Test boolean operators. */ public void testBooleanOperators() { Value vs1 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); Value vs2 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs1.setValue(false); vs2.setValue(false); vs1.bool_and(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(true); vs1.bool_and(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(false); vs1.bool_and(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(true); vs1.bool_and(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(false); vs1.bool_or(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(true); vs1.bool_or(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(false); vs1.bool_or(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(true); vs1.bool_or(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(false); vs1.bool_xor(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(true); vs1.bool_xor(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(false); vs1.bool_xor(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(true); vs1.bool_xor(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(true); vs1.bool_not(); assertEquals(false, vs1.getBoolean()); vs1.setValue(false); vs1.bool_not(); assertEquals(true, vs1.getBoolean()); } /** * Test boolean operators. */ public void testBooleanOperators1() { Value vs1 = new Value("Name", Value.VALUE_TYPE_INTEGER); Value vs2 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs1.setValue(255L); vs2.setValue(255L); vs1.and(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(0L); vs1.and(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(255L); vs1.and(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(0L); vs1.and(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(255L); vs1.or(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(0L); vs1.or(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(255L); vs1.or(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(0L); vs1.or(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(255L); vs1.xor(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(0L); vs1.xor(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(255L); vs1.xor(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(0L); vs1.xor(vs2); assertEquals(0L, vs1.getInteger()); } /** * Test comparators. */ public void testComparators() { Value vs1 = new Value("Name", Value.VALUE_TYPE_INTEGER); Value vs2 = new Value("Name", Value.VALUE_TYPE_INTEGER); Value vs3 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs1.setValue(128L); vs2.setValue(100L); vs3.setValue(128L); assertEquals(true, (vs1.Clone().greater_equal(vs2)).getBoolean()); assertEquals(true, (vs1.Clone().greater_equal(vs3)).getBoolean()); assertEquals(false, (vs2.Clone().greater_equal(vs1)).getBoolean()); assertEquals(false, (vs1.Clone().smaller_equal(vs2)).getBoolean()); assertEquals(true, (vs1.Clone().smaller_equal(vs3)).getBoolean()); assertEquals(true, (vs2.Clone().smaller_equal(vs1)).getBoolean()); assertEquals(true, (vs1.Clone().different(vs2)).getBoolean()); assertEquals(false, (vs1.Clone().different(vs3)).getBoolean()); assertEquals(false, (vs1.Clone().equal(vs2)).getBoolean()); assertEquals(true, (vs1.Clone().equal(vs3)).getBoolean()); assertEquals(true, (vs1.Clone().greater(vs2)).getBoolean()); assertEquals(false, (vs1.Clone().greater(vs3)).getBoolean()); assertEquals(false, (vs2.Clone().greater(vs1)).getBoolean()); assertEquals(false, (vs1.Clone().smaller(vs2)).getBoolean()); assertEquals(false, (vs1.Clone().smaller(vs3)).getBoolean()); assertEquals(true, (vs2.Clone().smaller(vs1)).getBoolean()); } /** * Test trim, ltrim, rtrim. */ public void testTrim() { Value vs1 = new Value("Name1", Value.VALUE_TYPE_INTEGER); Value vs2 = new Value("Name2", Value.VALUE_TYPE_STRING); vs1.setValue(128L); vs1.setNull(); assertNull(vs1.Clone().ltrim().getString()); assertNull(vs1.Clone().rtrim().getString()); assertNull(vs1.Clone().trim().getString()); vs1.setValue(128L); assertEquals("128", vs1.Clone().ltrim().getString()); assertEquals(" 128", vs1.Clone().rtrim().getString()); assertEquals("128", vs1.Clone().trim().getString()); vs2.setValue(" Sven Boden trim test "); assertEquals("Sven Boden trim test ", vs2.Clone().ltrim().getString()); assertEquals(" Sven Boden trim test", vs2.Clone().rtrim().getString()); assertEquals("Sven Boden trim test", vs2.Clone().trim().getString()); vs2.setValue(""); assertEquals("", vs2.Clone().ltrim().getString()); assertEquals("", vs2.Clone().rtrim().getString()); assertEquals("", vs2.Clone().trim().getString()); vs2.setValue(" "); assertEquals("", vs2.Clone().ltrim().getString()); assertEquals("", vs2.Clone().rtrim().getString()); assertEquals("", vs2.Clone().trim().getString()); } /** * Test hexToByteDecode. */ public void testHexToByteDecode() throws KettleValueException { Value vs1 = new Value("Name1", Value.VALUE_TYPE_INTEGER); vs1.setValue("6120622063"); vs1.hexToByteDecode(); assertEquals("a b c", vs1.getString()); vs1.setValue("4161426243643039207A5A2E3F2F"); vs1.hexToByteDecode(); assertEquals("AaBbCd09 zZ.?/", vs1.getString()); vs1.setValue("4161426243643039207a5a2e3f2f"); vs1.hexToByteDecode(); assertEquals("AaBbCd09 zZ.?/", vs1.getString()); // leading 0 if odd. vs1.setValue("F6120622063"); vs1.hexToByteDecode(); assertEquals("\u000fa b c", vs1.getString()); try { vs1.setValue("g"); vs1.hexToByteDecode(); fail("Expected KettleValueException"); } catch (KettleValueException ex) { } } /** * Test hexEncode. */ public void testByteToHexEncode() throws KettleValueException { Value vs1 = new Value("Name1", Value.VALUE_TYPE_INTEGER); vs1.setValue("AaBbCd09 zZ.?/"); vs1.byteToHexEncode(); assertEquals("4161426243643039207A5A2E3F2F", vs1.getString()); vs1.setValue("1234567890"); vs1.byteToHexEncode(); assertEquals("31323334353637383930", vs1.getString()); vs1.setNull(); vs1.byteToHexEncode(); assertNull(vs1.getString()); } /** * Regression test for bug: hexdecode/encode would not * work for some UTF8 strings. */ public void testHexByteRegression() throws KettleValueException { Value vs1 = new Value("Name1", Value.VALUE_TYPE_INTEGER); vs1.setValue("9B"); vs1.hexToByteDecode(); vs1.byteToHexEncode(); assertEquals("9B", vs1.getString()); vs1.setValue("A7"); vs1.hexToByteDecode(); vs1.byteToHexEncode(); assertEquals("A7", vs1.getString()); vs1.setValue("74792121212121212121212121C2A7"); vs1.hexToByteDecode(); vs1.byteToHexEncode(); assertEquals("74792121212121212121212121C2A7", vs1.getString()); vs1.setValue("70616E2D6C656FC5A1"); vs1.hexToByteDecode(); vs1.byteToHexEncode(); assertEquals("70616E2D6C656FC5A1", vs1.getString()); vs1.setValue("736B76C49B6C6520"); vs1.hexToByteDecode(); vs1.byteToHexEncode(); assertEquals("736B76C49B6C6520", vs1.getString()); } /** * Test for Hex to Char decoding and vica versa. */ public void testHexCharTest() throws KettleValueException { Value vs1 = new Value("Name1", Value.VALUE_TYPE_INTEGER); vs1.setValue("009B"); vs1.hexToCharDecode(); vs1.charToHexEncode(); assertEquals("009B", vs1.getString()); vs1.setValue("007400790021002100C200A7"); vs1.hexToCharDecode(); vs1.charToHexEncode(); assertEquals("007400790021002100C200A7", vs1.getString()); vs1.setValue("FFFF00FFFF000F0FF0F0"); vs1.hexToCharDecode(); vs1.charToHexEncode(); assertEquals("FFFF00FFFF000F0FF0F0", vs1.getString()); } /** * Test like. */ public void testLike() { Value vs1 = new Value("Name1", Value.VALUE_TYPE_STRING); Value vs2 = new Value("Name2", Value.VALUE_TYPE_STRING); Value vs3 = new Value("Name3", Value.VALUE_TYPE_STRING); vs1.setValue("This is a test"); vs2.setValue("is a"); vs3.setValue("not"); assertEquals(true, (vs1.Clone().like(vs2)).getBoolean()); assertEquals(true, (vs1.Clone().like(vs1)).getBoolean()); assertEquals(false, (vs1.Clone().like(vs3)).getBoolean()); assertEquals(false, (vs3.Clone().like(vs1)).getBoolean()); } /** * Stuff which we didn't get in other checks. */ public void testLooseEnds() { assertEquals(Value.VALUE_TYPE_NONE, Value.getType("INVALID_TYPE")); assertEquals("String", Value.getTypeDesc(Value.VALUE_TYPE_STRING)); } /** * Constructors using Values. */ public void testClone2() { Value vs = new Value("Name", Value.VALUE_TYPE_NUMBER); vs.setValue(10.0D); vs.setOrigin("origin"); vs.setLength(4, 2); Value copy = (Value)vs.clone(); assertEquals(vs.getType(), copy.getType()); assertEquals(vs.getNumber(), copy.getNumber(), 0.1D); assertEquals(vs.getLength(), copy.getLength()); assertEquals(vs.getPrecision(), copy.getPrecision()); assertEquals(vs.isNull(), copy.isNull()); assertEquals(vs.getOrigin(), copy.getOrigin()); assertEquals(vs.getName(), copy.getName()); // Show it's a deep copy copy.setName("newName"); assertEquals("Name", vs.getName()); assertEquals("newName", copy.getName()); copy.setOrigin("newOrigin"); assertEquals("origin", vs.getOrigin()); assertEquals("newOrigin", copy.getOrigin()); copy.setValue(11.0D); assertEquals(10.0D, vs.getNumber(), 0.1D); assertEquals(11.0D, copy.getNumber(), 0.1D); Value vs1 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs1.setName(null); // name and origin are null Value copy1 = new Value(vs1); assertEquals(vs1.getType(), copy1.getType()); assertEquals(vs1.getNumber(), copy1.getNumber(), 0.1D); assertEquals(vs1.getLength(), copy1.getLength()); assertEquals(vs1.getPrecision(), copy1.getPrecision()); assertEquals(vs1.isNull(), copy1.isNull()); assertEquals(vs1.getOrigin(), copy1.getOrigin()); assertEquals(vs1.getName(), copy1.getName()); Value vs2 = new Value((Value)null); assertTrue(vs2.isNull()); assertNull(vs2.getName()); assertNull(vs2.getOrigin()); } }
package com.github.daytron.twaattin.ui; import javax.servlet.annotation.WebServlet; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.annotations.Widgetset; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinServlet; import com.vaadin.ui.UI; @Theme("mytheme") @Widgetset("com.github.daytron.twaattin.MyAppWidgetset") public class TwaattinUI extends UI { private static final long serialVersionUID = 1L; @Override protected void init(VaadinRequest vaadinRequest) { setContent(new LoginScreen()); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package kg.apc.jmeter.config; import kg.apc.emulators.TestJMeterUtils; import org.apache.jmeter.testelement.TestElement; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author z000205 */ public class VariablesFromCSVGuiTest { public VariablesFromCSVGuiTest() { } @BeforeClass public static void setUpClass() throws Exception { TestJMeterUtils.createJmeterEnv(); } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getStaticLabel method, of class VariablesFromCSVGui. */ @Test public void testGetStaticLabel() { System.out.println("getStaticLabel"); VariablesFromCSVGui instance = new VariablesFromCSVGui(); String result = instance.getStaticLabel(); assertTrue(result.length()>0); } /** * Test of getLabelResource method, of class VariablesFromCSVGui. */ @Test public void testGetLabelResource() { System.out.println("getLabelResource"); VariablesFromCSVGui instance = new VariablesFromCSVGui(); String result = instance.getLabelResource(); assertTrue(result.length()>0); } /** * Test of configure method, of class VariablesFromCSVGui. */ @Test public void testConfigure() { System.out.println("configure"); TestElement element = new VariablesFromCSV(); VariablesFromCSVGui instance = new VariablesFromCSVGui(); instance.configure(element); } /** * Test of createTestElement method, of class VariablesFromCSVGui. */ @Test public void testCreateTestElement() { System.out.println("createTestElement"); VariablesFromCSVGui instance = new VariablesFromCSVGui(); TestElement result = instance.createTestElement(); assertTrue(result instanceof VariablesFromCSV); } /** * Test of modifyTestElement method, of class VariablesFromCSVGui. */ @Test public void testModifyTestElement() { System.out.println("modifyTestElement"); TestElement te = new VariablesFromCSV(); VariablesFromCSVGui instance = new VariablesFromCSVGui(); instance.modifyTestElement(te); } /** * Test configure() with skipLines property not present in test element, simulating the scenario where * a test plan is loaded and the serialized state of the plugin is missing the skipLines property. */ @Test public void testConfigureSkipLinesMissing() { VariablesFromCSV te = new VariablesFromCSV(); VariablesFromCSVGui gui = new VariablesFromCSVGui(); // Given skipLines property is missing from TestElement te.removeProperty(VariablesFromCSV.SKIP_LINES); // When configure() is called followed by modifyTestElement() gui.configure(te); gui.modifyTestElement(te); // Then skipLines should have default value assertEquals("skipLines not set to default", VariablesFromCSV.SKIP_LINES_DEFAULT, te.getSkipLines()); } /** * Test of clearGui method, of class VariablesFromCSVGui. */ @Test public void testClearGui() { System.out.println("clearGui"); VariablesFromCSVGui instance = new VariablesFromCSVGui(); instance.clearGui(); } }
package com.github.nkzawa.socketio.client; import com.github.nkzawa.backo.Backoff; import com.github.nkzawa.emitter.Emitter; import com.github.nkzawa.socketio.parser.Packet; import com.github.nkzawa.socketio.parser.Parser; import com.github.nkzawa.thread.EventThread; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import java.net.URI; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Manager class represents a connection to a given Socket.IO server. */ public class Manager extends Emitter { private static final Logger logger = Logger.getLogger(Manager.class.getName()); /*package*/ enum ReadyState { CLOSED, OPENING, OPEN } /** * Called on a successful connection. */ public static final String EVENT_OPEN = "open"; /** * Called on a disconnection. */ public static final String EVENT_CLOSE = "close"; public static final String EVENT_PACKET = "packet"; public static final String EVENT_ERROR = "error"; /** * Called on a connection error. */ public static final String EVENT_CONNECT_ERROR = "connect_error"; /** * Called on a connection timeout. */ public static final String EVENT_CONNECT_TIMEOUT = "connect_timeout"; /** * Called on a successful reconnection. */ public static final String EVENT_RECONNECT = "reconnect"; /** * Called on a reconnection attempt error. */ public static final String EVENT_RECONNECT_ERROR = "reconnect_error"; public static final String EVENT_RECONNECT_FAILED = "reconnect_failed"; public static final String EVENT_RECONNECT_ATTEMPT = "reconnect_attempt"; public static final String EVENT_RECONNECTING = "reconnecting"; /** * Called when a new transport is created. (experimental) */ public static final String EVENT_TRANSPORT = Engine.EVENT_TRANSPORT; /*package*/ static SSLContext defaultSSLContext; /*package*/ static HostnameVerifier defaultHostnameVerifier; /*package*/ ReadyState readyState = null; private boolean _reconnection; private boolean skipReconnect; private boolean reconnecting; private boolean encoding; private int _reconnectionAttempts; private long _reconnectionDelay; private long _reconnectionDelayMax; private double _randomizationFactor; private Backoff backoff; private long _timeout; private Set<Socket> connected; private URI uri; private List<Packet> packetBuffer; private Queue<On.Handle> subs; private Options opts; /*package*/ com.github.nkzawa.engineio.client.Socket engine; private Parser.Encoder encoder; private Parser.Decoder decoder; /** * This HashMap can be accessed from outside of EventThread. */ private ConcurrentHashMap<String, Socket> nsps; public Manager() { this(null, null); } public Manager(URI uri) { this(uri, null); } public Manager(Options opts) { this(null, opts); } public Manager(URI uri, Options opts) { if (opts == null) { opts = new Options(); } if (opts.path == null) { opts.path = "/socket.io"; } if (opts.sslContext == null) { opts.sslContext = defaultSSLContext; } if (opts.hostnameVerifier == null) { opts.hostnameVerifier = defaultHostnameVerifier; } this.opts = opts; this.nsps = new ConcurrentHashMap<String, Socket>(); this.subs = new LinkedList<On.Handle>(); this.reconnection(opts.reconnection); this.reconnectionAttempts(opts.reconnectionAttempts != 0 ? opts.reconnectionAttempts : Integer.MAX_VALUE); this.reconnectionDelay(opts.reconnectionDelay != 0 ? opts.reconnectionDelay : 1000); this.reconnectionDelayMax(opts.reconnectionDelayMax != 0 ? opts.reconnectionDelayMax : 5000); this.randomizationFactor(opts.randomizationFactor != 0.0 ? opts.randomizationFactor : 0.5); this.backoff = new Backoff() .setMin(this.reconnectionDelay()) .setMax(this.reconnectionDelayMax()) .setJitter(this.randomizationFactor()); this.timeout(opts.timeout); this.readyState = ReadyState.CLOSED; this.uri = uri; this.connected = new HashSet<Socket>(); this.encoding = false; this.packetBuffer = new ArrayList<Packet>(); this.encoder = new Parser.Encoder(); this.decoder = new Parser.Decoder(); } private void emitAll(String event, Object... args) { this.emit(event, args); for (Socket socket : this.nsps.values()) { socket.emit(event, args); } } /** * Update `socket.id` of all sockets */ private void updateSocketIds() { for (Socket socket : this.nsps.values()) { socket.id = this.engine.id(); } } public boolean reconnection() { return this._reconnection; } public Manager reconnection(boolean v) { this._reconnection = v; return this; } public int reconnectionAttempts() { return this._reconnectionAttempts; } public Manager reconnectionAttempts(int v) { this._reconnectionAttempts = v; return this; } public long reconnectionDelay() { return this._reconnectionDelay; } public Manager reconnectionDelay(long v) { this._reconnectionDelay = v; if (this.backoff != null) { this.backoff.setMin(v); } return this; } public double randomizationFactor() { return this._randomizationFactor; } public Manager randomizationFactor(double v) { this._randomizationFactor = v; if (this.backoff != null) { this.backoff.setJitter(v); } return this; } public long reconnectionDelayMax() { return this._reconnectionDelayMax; } public Manager reconnectionDelayMax(long v) { this._reconnectionDelayMax = v; if (this.backoff != null) { this.backoff.setMax(v); } return this; } public long timeout() { return this._timeout; } public Manager timeout(long v) { this._timeout = v; return this; } private void maybeReconnectOnOpen() { // Only try to reconnect if it's the first time we're connecting if (!this.reconnecting && this._reconnection && this.backoff.getAttempts() == 0) { this.reconnect(); } } public Manager open(){ return open(null); } /** * Connects the client. * * @param fn callback. * @return a reference to this object. */ public Manager open(final OpenCallback fn) { EventThread.exec(new Runnable() { @Override public void run() { logger.fine(String.format("readyState %s", Manager.this.readyState)); if (Manager.this.readyState == ReadyState.OPEN || Manager.this.readyState == ReadyState.OPENING) return; logger.fine(String.format("opening %s", Manager.this.uri)); Manager.this.engine = new Engine(Manager.this.uri, Manager.this.opts); final com.github.nkzawa.engineio.client.Socket socket = Manager.this.engine; final Manager self = Manager.this; Manager.this.readyState = ReadyState.OPENING; Manager.this.skipReconnect = false; // propagate transport event. socket.on(Engine.EVENT_TRANSPORT, new Listener() { @Override public void call(Object... args) { self.emit(Manager.EVENT_TRANSPORT, args); } }); final On.Handle openSub = On.on(socket, Engine.EVENT_OPEN, new Listener() { @Override public void call(Object... objects) { self.onopen(); if (fn != null) fn.call(null); } }); On.Handle errorSub = On.on(socket, Engine.EVENT_ERROR, new Listener() { @Override public void call(Object... objects) { Object data = objects.length > 0 ? objects[0] : null; logger.fine("connect_error"); self.cleanup(); self.readyState = ReadyState.CLOSED; self.emitAll(EVENT_CONNECT_ERROR, data); if (fn != null) { Exception err = new SocketIOException("Connection error", data instanceof Exception ? (Exception) data : null); fn.call(err); } else { // Only do this if there is no fn to handle the error self.maybeReconnectOnOpen(); } } }); if (Manager.this._timeout >= 0) { final long timeout = Manager.this._timeout; logger.fine(String.format("connection attempt will timeout after %d", timeout)); final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { EventThread.exec(new Runnable() { @Override public void run() { logger.fine(String.format("connect attempt timed out after %d", timeout)); openSub.destroy(); socket.close(); socket.emit(Engine.EVENT_ERROR, new SocketIOException("timeout")); self.emitAll(EVENT_CONNECT_TIMEOUT, timeout); } }); } }, timeout); Manager.this.subs.add(new On.Handle() { @Override public void destroy() { timer.cancel(); } }); } Manager.this.subs.add(openSub); Manager.this.subs.add(errorSub); Manager.this.engine.open(); } }); return this; } private void onopen() { logger.fine("open"); this.cleanup(); this.readyState = ReadyState.OPEN; this.emit(EVENT_OPEN); final com.github.nkzawa.engineio.client.Socket socket = this.engine; this.subs.add(On.on(socket, Engine.EVENT_DATA, new Listener() { @Override public void call(Object... objects) { Object data = objects[0]; if (data instanceof String) { Manager.this.ondata((String)data); } else if (data instanceof byte[]) { Manager.this.ondata((byte[])data); } } })); this.subs.add(On.on(this.decoder, Parser.Decoder.EVENT_DECODED, new Listener() { @Override public void call(Object... objects) { Manager.this.ondecoded((Packet) objects[0]); } })); this.subs.add(On.on(socket, Engine.EVENT_ERROR, new Listener() { @Override public void call(Object... objects) { Manager.this.onerror((Exception)objects[0]); } })); this.subs.add(On.on(socket, Engine.EVENT_CLOSE, new Listener() { @Override public void call(Object... objects) { Manager.this.onclose((String)objects[0]); } })); } private void ondata(String data) { this.decoder.add(data); } private void ondata(byte[] data) { this.decoder.add(data); } private void ondecoded(Packet packet) { this.emit(EVENT_PACKET, packet); } private void onerror(Exception err) { logger.log(Level.FINE, "error", err); this.emitAll(EVENT_ERROR, err); } /** * Initializes {@link Socket} instances for each namespaces. * * @param nsp namespace. * @return a socket instance for the namespace. */ public Socket socket(String nsp) { Socket socket = this.nsps.get(nsp); if (socket == null) { socket = new Socket(this, nsp); Socket _socket = this.nsps.putIfAbsent(nsp, socket); if (_socket != null) { socket = _socket; } else { final Manager self = this; final Socket s = socket; socket.on(Socket.EVENT_CONNECT, new Listener() { @Override public void call(Object... objects) { s.id = self.engine.id(); self.connected.add(s); } }); } } return socket; } /*package*/ void destroy(Socket socket) { this.connected.remove(socket); if (this.connected.size() > 0) return; this.close(); } /*package*/ void packet(Packet packet) { logger.fine(String.format("writing packet %s", packet)); final Manager self = this; if (!self.encoding) { self.encoding = true; this.encoder.encode(packet, new Parser.Encoder.Callback() { @Override public void call(Object[] encodedPackets) { for (Object packet : encodedPackets) { if (packet instanceof String) { self.engine.write((String)packet); } else if (packet instanceof byte[]) { self.engine.write((byte[])packet); } } self.encoding = false; self.processPacketQueue(); } }); } else { self.packetBuffer.add(packet); } } private void processPacketQueue() { if (this.packetBuffer.size() > 0 && !this.encoding) { Packet pack = this.packetBuffer.remove(0); this.packet(pack); } } private void cleanup() { On.Handle sub; while ((sub = this.subs.poll()) != null) sub.destroy(); } /*package*/ void close() { if (this.readyState != ReadyState.OPEN) { this.cleanup(); } this.skipReconnect = true; this.backoff.reset(); this.readyState = ReadyState.CLOSED; if (this.engine != null) { this.engine.close(); } } private void onclose(String reason) { logger.fine("close"); this.cleanup(); this.backoff.reset(); this.readyState = ReadyState.CLOSED; this.emit(EVENT_CLOSE, reason); if (this._reconnection && !this.skipReconnect) { this.reconnect(); } } private void reconnect() { if (this.reconnecting || this.skipReconnect) return; final Manager self = this; if (this.backoff.getAttempts() >= this._reconnectionAttempts) { logger.fine("reconnect failed"); this.backoff.reset(); this.emitAll(EVENT_RECONNECT_FAILED); this.reconnecting = false; } else { long delay = this.backoff.duration(); logger.fine(String.format("will wait %dms before reconnect attempt", delay)); this.reconnecting = true; final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { EventThread.exec(new Runnable() { @Override public void run() { if (self.skipReconnect) return; logger.fine("attempting reconnect"); int attempts = self.backoff.getAttempts(); self.emitAll(EVENT_RECONNECT_ATTEMPT, attempts); self.emitAll(EVENT_RECONNECTING, attempts); // check again for the case socket closed in above events if (self.skipReconnect) return; self.open(new OpenCallback() { @Override public void call(Exception err) { if (err != null) { logger.fine("reconnect attempt error"); self.reconnecting = false; self.reconnect(); self.emitAll(EVENT_RECONNECT_ERROR, err); } else { logger.fine("reconnect success"); self.onreconnect(); } } }); } }); } }, delay); this.subs.add(new On.Handle() { @Override public void destroy() { timer.cancel(); } }); } } private void onreconnect() { int attempts = this.backoff.getAttempts(); this.reconnecting = false; this.backoff.reset(); this.updateSocketIds(); this.emitAll(EVENT_RECONNECT, attempts); } public static interface OpenCallback { public void call(Exception err); } private static class Engine extends com.github.nkzawa.engineio.client.Socket { Engine(URI uri, Options opts) { super(uri, opts); } } public static class Options extends com.github.nkzawa.engineio.client.Socket.Options { public boolean reconnection = true; public int reconnectionAttempts; public long reconnectionDelay; public long reconnectionDelayMax; public double randomizationFactor; /** * Connection timeout (ms). Set -1 to disable. */ public long timeout = 20000; } }
package com.gmail.nossr50.util.skills; import org.bukkit.Material; import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.Animals; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.IronGolem; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Tameable; import org.bukkit.entity.Wolf; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.inventory.ItemStack; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent; import com.gmail.nossr50.events.fake.FakeEntityDamageEvent; import com.gmail.nossr50.events.fake.FakePlayerAnimationEvent; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.runnables.skills.AwardCombatXpTask; import com.gmail.nossr50.runnables.skills.BleedTimerTask; import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager; import com.gmail.nossr50.skills.archery.ArcheryManager; import com.gmail.nossr50.skills.axes.AxesManager; import com.gmail.nossr50.skills.swords.Swords; import com.gmail.nossr50.skills.swords.SwordsManager; import com.gmail.nossr50.skills.taming.TamingManager; import com.gmail.nossr50.skills.unarmed.UnarmedManager; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.MobHealthbarUtils; import com.gmail.nossr50.util.ModUtils; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; public final class CombatUtils { private CombatUtils() {} private static void processSwordCombat(LivingEntity target, Player player, double damage) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); SwordsManager swordsManager = mcMMOPlayer.getSwordsManager(); if (swordsManager.canActivateAbility()) { SkillUtils.abilityCheck(mcMMOPlayer, SkillType.SWORDS); } if (swordsManager.canUseBleed()) { swordsManager.bleedCheck(target); } if (swordsManager.canUseSerratedStrike()) { swordsManager.serratedStrikes(target, damage); } startGainXp(mcMMOPlayer, target, SkillType.SWORDS); } private static void processAxeCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); AxesManager axesManager = mcMMOPlayer.getAxesManager(); if (axesManager.canActivateAbility()) { SkillUtils.abilityCheck(mcMMOPlayer, SkillType.AXES); } if (axesManager.canUseAxeMastery()) { axesManager.axeMastery(target); } if (axesManager.canCriticalHit(target)) { axesManager.criticalHit(target, event.getDamage()); } if (axesManager.canImpact(target)) { axesManager.impactCheck(target); } else if (axesManager.canGreaterImpact(target)) { axesManager.greaterImpact(target); } if (axesManager.canUseSkullSplitter(target)) { axesManager.skullSplitterCheck(target, event.getDamage()); } startGainXp(mcMMOPlayer, target, SkillType.AXES); } private static void processUnarmedCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager(); if (unarmedManager.canActivateAbility()) { SkillUtils.abilityCheck(mcMMOPlayer, SkillType.UNARMED); } if (unarmedManager.canUseIronArm()) { unarmedManager.ironArm(target); } if (unarmedManager.canUseBerserk()) { unarmedManager.berserkDamage(target, event.getDamage()); } if (unarmedManager.canDisarm(target)) { unarmedManager.disarmCheck((Player) target); } startGainXp(mcMMOPlayer, target, SkillType.UNARMED); } private static void processTamingCombat(LivingEntity target, Player master, Wolf wolf, EntityDamageByEntityEvent event) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master); TamingManager tamingManager = mcMMOPlayer.getTamingManager(); if (tamingManager.canUseFastFoodService()) { tamingManager.fastFoodService(wolf, event.getDamage()); } if (tamingManager.canUseSharpenedClaws()) { tamingManager.sharpenedClaws(target, wolf); } if (tamingManager.canUseGore()) { tamingManager.gore(target, event.getDamage(), wolf); } startGainXp(mcMMOPlayer, target, SkillType.TAMING); } private static void processArcheryCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event, Arrow arrow) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); ArcheryManager archeryManager = mcMMOPlayer.getArcheryManager(); if (archeryManager.canSkillShot()) { archeryManager.skillShot(target, event.getDamage(), arrow); } if (target instanceof Player && SkillType.UNARMED.getPVPEnabled()) { UnarmedManager unarmedManager = UserManager.getPlayer((Player) target).getUnarmedManager(); if (unarmedManager.canDeflect()) { event.setCancelled(unarmedManager.deflectCheck()); if (event.isCancelled()) { return; } } } if (archeryManager.canDaze(target)) { archeryManager.daze((Player) target, arrow); } if (!arrow.hasMetadata(mcMMO.infiniteArrowKey) && archeryManager.canTrackArrows()) { archeryManager.trackArrows(target); } archeryManager.distanceXpBonus(target, arrow); startGainXp(mcMMOPlayer, target, SkillType.ARCHERY, arrow.getMetadata(mcMMO.bowForceKey).get(0).asDouble()); } /** * Apply combat modifiers and process and XP gain. * * @param event The event to run the combat checks on. */ public static void processCombatAttack(EntityDamageByEntityEvent event, Entity attacker, LivingEntity target) { Entity damager = event.getDamager(); if (attacker instanceof Player && damager.getType() == EntityType.PLAYER) { Player player = (Player) attacker; if (Misc.isNPCEntity(player)) { return; } ItemStack heldItem = player.getItemInHand(); if (target instanceof Tameable) { if (heldItem.getType() == Material.BONE) { TamingManager tamingManager = UserManager.getPlayer(player).getTamingManager(); if (tamingManager.canUseBeastLore()) { tamingManager.beastLore(target); event.setCancelled(true); return; } } if (isFriendlyPet(player, (Tameable) target)) { return; } } if (ItemUtils.isSword(heldItem)) { if (!shouldProcessSkill(target, SkillType.SWORDS)) { return; } if (Permissions.skillEnabled(player, SkillType.SWORDS)) { processSwordCombat(target, player, event.getDamage()); } } else if (ItemUtils.isAxe(heldItem)) { if (!shouldProcessSkill(target, SkillType.AXES)) { return; } if (Permissions.skillEnabled(player, SkillType.AXES)) { processAxeCombat(target, player, event); } } else if (heldItem.getType() == Material.AIR) { if (!shouldProcessSkill(target, SkillType.UNARMED)) { return; } if (Permissions.skillEnabled(player, SkillType.UNARMED)) { processUnarmedCombat(target, player, event); } } } /* Temporary fix for MCPC+ * * This will be reverted back to the switch statement once the fix is addressed on their end. */ else if (damager.getType() == EntityType.WOLF) { Wolf wolf = (Wolf) damager; AnimalTamer tamer = wolf.getOwner(); if (tamer != null && tamer instanceof Player && shouldProcessSkill(target, SkillType.TAMING)) { Player master = (Player) tamer; if (!Misc.isNPCEntity(master) && Permissions.skillEnabled(master, SkillType.TAMING)) { processTamingCombat(target, master, wolf, event); } } } else if (damager.getType() == EntityType.ARROW) { Arrow arrow = (Arrow) damager; LivingEntity shooter = arrow.getShooter(); if (shooter != null && shooter instanceof Player && shouldProcessSkill(target, SkillType.ARCHERY)) { Player player = (Player) shooter; if (!Misc.isNPCEntity(player) && Permissions.skillEnabled(player, SkillType.ARCHERY)) { processArcheryCombat(target, player, event, arrow); } } } // switch (damager.getType()) { // case WOLF: // Wolf wolf = (Wolf) damager; // AnimalTamer tamer = wolf.getOwner(); // if (tamer == null || !(tamer instanceof Player) || !shouldProcessSkill(target, SkillType.TAMING)) { // break; // Player master = (Player) tamer; // if (Misc.isNPCEntity(master)) { // break; // processTamingCombat(target, master, wolf, event); // break; // case ARROW: // LivingEntity shooter = ((Arrow) damager).getShooter(); // if (shooter == null || !(shooter instanceof Player) || !shouldProcessSkill(target, SkillType.ARCHERY)) { // break; // Player player = (Player) shooter; // if (Misc.isNPCEntity(player)) { // break; // processArcheryCombat(target, player, event, damager); // break; // default: // break; if (target instanceof Player) { if (Misc.isNPCEntity(target)) { return; } Player player = (Player) target; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); AcrobaticsManager acrobaticsManager = mcMMOPlayer.getAcrobaticsManager(); if (acrobaticsManager.canDodge(damager)) { event.setDamage(acrobaticsManager.dodgeCheck(event.getDamage())); } if (ItemUtils.isSword(player.getItemInHand())) { if (!shouldProcessSkill(target, SkillType.SWORDS)) { return; } SwordsManager swordsManager = mcMMOPlayer.getSwordsManager(); if (swordsManager.canUseCounterAttack(damager)) { swordsManager.counterAttackChecks((LivingEntity) damager, event.getDamage()); } } } else if (attacker instanceof Player) { Player player = (Player) attacker; if (Misc.isNPCEntity(player)) { return; } MobHealthbarUtils.handleMobHealthbars(player, target, event.getDamage()); } } /** * Attempt to damage target for value dmg with reason CUSTOM * * @param target LivingEntity which to attempt to damage * @param damage Amount of damage to attempt to do */ public static void dealDamage(LivingEntity target, double damage) { dealDamage(target, damage, DamageCause.CUSTOM, null); } /** * Attempt to damage target for value dmg with reason ENTITY_ATTACK with damager attacker * * @param target LivingEntity which to attempt to damage * @param damage Amount of damage to attempt to do * @param attacker Player to pass to event as damager */ public static void dealDamage(LivingEntity target, double damage, LivingEntity attacker) { dealDamage(target, damage, DamageCause.ENTITY_ATTACK, attacker); } /** * Attempt to damage target for value dmg with reason ENTITY_ATTACK with damager attacker * * @param target LivingEntity which to attempt to damage * @param damage Amount of damage to attempt to do * @param attacker Player to pass to event as damager */ public static void dealDamage(LivingEntity target, double damage, DamageCause cause, Entity attacker) { if (target.isDead()) { return; } if (Config.getInstance().getEventCallbackEnabled()) { EntityDamageEvent damageEvent = attacker == null ? new FakeEntityDamageEvent(target, cause, damage) : new FakeEntityDamageByEntityEvent(attacker, target, cause, damage); mcMMO.p.getServer().getPluginManager().callEvent(damageEvent); if (damageEvent.isCancelled()) { return; } damage = damageEvent.getDamage(); } target.damage(damage); } /** * Apply Area-of-Effect ability actions. * * @param attacker The attacking player * @param target The defending entity * @param damage The initial damage amount * @param type The type of skill being used */ public static void applyAbilityAoE(Player attacker, LivingEntity target, double damage, SkillType type) { int numberOfTargets = Misc.getTier(attacker.getItemInHand()); // The higher the weapon tier, the more targets you hit double damageAmount = Math.max(damage, 1); for (Entity entity : target.getNearbyEntities(2.5, 2.5, 2.5)) { if (numberOfTargets <= 0) { break; } if (Misc.isNPCEntity(entity) || !(entity instanceof LivingEntity) || !shouldBeAffected(attacker, entity)) { continue; } LivingEntity livingEntity = (LivingEntity) entity; mcMMO.p.getServer().getPluginManager().callEvent(new FakePlayerAnimationEvent(attacker)); switch (type) { case SWORDS: if (entity instanceof Player) { ((Player) entity).sendMessage(LocaleLoader.getString("Swords.Combat.SS.Struck")); } BleedTimerTask.add(livingEntity, Swords.serratedStrikesBleedTicks); break; case AXES: if (entity instanceof Player) { ((Player) entity).sendMessage(LocaleLoader.getString("Axes.Combat.SS.Struck")); } break; default: break; } dealDamage(livingEntity, damageAmount, attacker); numberOfTargets } } public static void startGainXp(McMMOPlayer mcMMOPlayer, LivingEntity target, SkillType skillType) { startGainXp(mcMMOPlayer, target, skillType, 1.0); } /** * Start the task that gives combat XP. * * @param mcMMOPlayer The attacking player * @param target The defending entity * @param skillType The skill being used */ public static void startGainXp(McMMOPlayer mcMMOPlayer, LivingEntity target, SkillType skillType, double multiplier) { double baseXP = 0; if (target instanceof Player) { if (!ExperienceConfig.getInstance().getExperienceGainsPlayerVersusPlayerEnabled()) { return; } Player defender = (Player) target; if (defender.isOnline() && System.currentTimeMillis() >= UserManager.getPlayer(defender).getRespawnATS() + 5) { baseXP = 20 * ExperienceConfig.getInstance().getPlayerVersusPlayerXP(); } } else { if (target instanceof Animals) { if (ModUtils.isCustomEntity(target)) { baseXP = ModUtils.getCustomEntity(target).getXpMultiplier(); } else { baseXP = ExperienceConfig.getInstance().getAnimalsXP(); } } else { EntityType type = target.getType(); switch (type) { case BAT: baseXP = ExperienceConfig.getInstance().getAnimalsXP(); break; case BLAZE: case CAVE_SPIDER: case CREEPER: case ENDERMAN: case GHAST: case GIANT: case MAGMA_CUBE: case PIG_ZOMBIE: case SILVERFISH: case SLIME: case SPIDER: case ZOMBIE: baseXP = ExperienceConfig.getInstance().getCombatXP(type); break; // Temporary workaround for custom entities case UNKNOWN: baseXP = 1.0; break; case SKELETON: switch (((Skeleton) target).getSkeletonType()) { case WITHER: baseXP = ExperienceConfig.getInstance().getWitherSkeletonXP(); break; default: baseXP = ExperienceConfig.getInstance().getCombatXP(type); break; } break; case IRON_GOLEM: if (!((IronGolem) target).isPlayerCreated()) { baseXP = ExperienceConfig.getInstance().getCombatXP(type); } break; default: if (ModUtils.isCustomEntity(target)) { baseXP = ModUtils.getCustomEntity(target).getXpMultiplier(); } break; } } if (target.hasMetadata(mcMMO.entityMetadataKey)) { baseXP *= ExperienceConfig.getInstance().getSpawnedMobXpMultiplier(); } baseXP *= 10; } baseXP *= multiplier; if (baseXP != 0) { new AwardCombatXpTask(mcMMOPlayer, skillType, baseXP, target).runTaskLater(mcMMO.p, 0); } } /** * Check to see if the given LivingEntity should be affected by a combat ability. * * @param player The attacking Player * @param entity The defending Entity * @return true if the Entity should be damaged, false otherwise. */ public static boolean shouldBeAffected(Player player, Entity entity) { if (entity instanceof Player) { Player defender = (Player) entity; if (!defender.getWorld().getPVP() || defender == player || UserManager.getPlayer(defender).getGodMode()) { return false; } if (PartyManager.inSameParty(player, defender) && !(Permissions.friendlyFire(player) && Permissions.friendlyFire(defender))) { return false; } // It may seem a bit redundant but we need a check here to prevent bleed from being applied in applyAbilityAoE() EntityDamageEvent ede = new FakeEntityDamageByEntityEvent(player, entity, EntityDamageEvent.DamageCause.ENTITY_ATTACK, 1); mcMMO.p.getServer().getPluginManager().callEvent(ede); if (ede.isCancelled()) { return false; } } else if (entity instanceof Tameable) { if (isFriendlyPet(player, (Tameable) entity)) { // isFriendlyPet ensures that the Tameable is: Tamed, owned by a player, and the owner is in the same party // So we can make some assumptions here, about our casting and our check Player owner = (Player) ((Tameable) entity).getOwner(); if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire(owner))) { return false; } } } return true; } /** * Checks to see if an entity is currently invincible. * * @param entity The {@link LivingEntity} to check * @param eventDamage The damage from the event the entity is involved in * @return true if the entity is invincible, false otherwise */ public static boolean isInvincible(LivingEntity entity, double eventDamage) { /* * So apparently if you do more damage to a LivingEntity than its last damage int you bypass the invincibility. * So yeah, this is for that. */ return (entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2.0F) && (eventDamage <= entity.getLastDamage()); } /** * Checks to see if an entity is currently friendly toward a given player. * * @param attacker The player to check. * @param pet The entity to check. * @return true if the entity is friendly, false otherwise */ public static boolean isFriendlyPet(Player attacker, Tameable pet) { if (pet.isTamed()) { AnimalTamer tamer = pet.getOwner(); if (tamer instanceof Player) { Player owner = (Player) tamer; return (owner == attacker || PartyManager.inSameParty(attacker, owner)); } } return false; } public static boolean shouldProcessSkill(Entity target, SkillType skill) { return (target instanceof Player || (target instanceof Tameable && ((Tameable) target).isTamed())) ? skill.getPVPEnabled() : skill.getPVEEnabled(); } }
package com.kasije.main; import java.util.*; /** * CLI. */ public class KasijeCli { private List<KasijeCliUtility> utilities = new LinkedList<>(); private void addUtility(KasijeCliUtility utility) { utilities.add(utility); } public void parseInput(String input) { String[] split = input.split(" "); if (split.length == 0) { System.out.println("Utility name missing."); System.out.println("Type help for help."); } else { processUtility(split); } } public static void main(String[] args) { KasijeCli kasijeCli = new KasijeCli(); KasijeCliUtility kuCreate = new KasijeCliUtility("create", "creates..."); kuCreate.addOption(new KasijeCliOption("engine", KasijeCliOptionStyle.WITH_ARGUMENT)); kuCreate.addOption(new KasijeCliOption("comp", KasijeCliOptionStyle.WITH_ARGUMENT)); kuCreate.setFirstMandatoryOptionName("siteName"); kuCreate.setKasijeCliExecutor(argumentValueMap -> { System.out.println("Creating site " + argumentValueMap.get("siteName")); System.out.println(" Using engine " + argumentValueMap.get("engine")); System.out.println(" Component type " + argumentValueMap.get("comp")); }); kasijeCli.addUtility(kuCreate); kasijeCli.processUtility(args); } private void processUtility(String[] args) { for (KasijeCliUtility utility : utilities) { if (utility.getName().equals(args[0])) { utility.process(Arrays.copyOfRange(args, 1, args.length)); break; } else { System.out.println("Ignoring unknown utility: " + args[0]); System.out.println(" Type in help for help"); } } } private static void processHelp(String[] args) { if (args.length == 0) { System.out.println("KasijeCli Utilities: "); System.out.println(" create - Creates a new site."); System.out.println(" generate - Generates page components."); System.out.println(" start - Start service."); System.out.println(" "); } else { switch (args[0]) { case "create": System.out.println("Uses of create:"); break; case "generate": System.out.println("Uses of generate:"); break; case "start": System.out.println("Uses of start"); break; case "help": System.out.println("Uses of start"); System.out.println(" Call 'help utility' to see the utility related help."); System.out.println(" "); break; } } } public static class KasijeCliUtility { private String name; private String firstMandatoryOptionName; private List<KasijeCliOption> kasijeCliOptions; private String help; private KasijeCliExecutor kasijeCliExecutor; public KasijeCliUtility(String name, String help) { this.name = name; this.help = help; kasijeCliOptions = new LinkedList<>(); } public String getFirstMandatoryOptionName() { return firstMandatoryOptionName; } public void setFirstMandatoryOptionName(String firstMandatoryOptionName) { this.firstMandatoryOptionName = firstMandatoryOptionName; } public void addOption(KasijeCliOption kasijeCliOption) { kasijeCliOptions.add(kasijeCliOption); } public void setKasijeCliExecutor(KasijeCliExecutor kasijeCliExecutor) { this.kasijeCliExecutor = kasijeCliExecutor; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHelp() { return help; } public void setHelp(String help) { this.help = help; } public void process(String[] args) { String mandatoryOptionValue = null; Map<String, String> map = new HashMap<>(); String[] arguments = Arrays.copyOfRange(args, 1, args.length); if (args.length == 0) { System.out.format("Missing options for the %s utility", getName()); return; } /* Obtaining mandatory option */ if (firstMandatoryOptionName != null) { map.put(firstMandatoryOptionName, args[0]); if (args.length > 1) { arguments = Arrays.copyOfRange(args, 1, args.length); } else { if (kasijeCliExecutor != null) { kasijeCliExecutor.execute(map); } return; } } int i = 1; ARGS: for (String arg : arguments) { String[] split = arg.split("="); if (split.length != 2) { System.out.println(String.format(" Bad option at argument %d, assignment expression required.", i)); } else { for (KasijeCliOption option : kasijeCliOptions) { if (split[0].equals(option.getName())) { map.put(option.getName(), split[1]); continue ARGS; } } System.out.println("Ignoring unrecognized option: " + split[0]); } } if (kasijeCliExecutor != null) { kasijeCliExecutor.execute(map); } } } public static class KasijeCliOption { private String name; private KasijeCliOptionStyle kasijeCliOptionStyle; public KasijeCliOption(String name, KasijeCliOptionStyle kasijeCliOptionStyle) { this.name = name; this.kasijeCliOptionStyle = kasijeCliOptionStyle; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public interface KasijeCliExecutor { void execute(Map<String, String> argumentValueMap); } enum KasijeCliOptionStyle { SIMPLE, WITH_ARGUMENT, SPACED } }
package org.peerbox; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; public class RegisterValidation { public static void checkUsername(TextField username){ //TODO } public static void checkPassword(PasswordField pwd_1, PasswordField pwd_2){ if (pwd_1.getLength() >= 6){ System.out.println("Password length okay"); if(pwd_1.getText().equals(pwd_2.getText())){ System.out.println("Passwords identical."); } else { System.err.println("Passwords not identical. Try again"); } } else { System.err.println("Password too short. Needs at least 6 characters!"); } } public static void checkPIN(PasswordField pin_1, PasswordField pin_2){ if (pin_1.getLength() >= 3){ System.out.println("PIN length okay"); if(pin_1.getText().equals(pin_2.getText())){ System.out.println("PINs identical."); } else { System.err.println("PINs not identical. Try again"); } } else { System.err.println("PIN too short. Needs at least 3 characters!"); } } }
package com.inari.firefly.libgdx; import com.inari.commons.event.EventDispatcher; import com.inari.firefly.animation.AnimationSystem; import com.inari.firefly.asset.AssetSystem; import com.inari.firefly.control.ComponentControllerSystem; import com.inari.firefly.entity.EntityPrefabSystem; import com.inari.firefly.entity.EntityProvider; import com.inari.firefly.entity.EntitySystem; import com.inari.firefly.movement.MovementSystem; import com.inari.firefly.renderer.sprite.SpriteViewRenderer; import com.inari.firefly.renderer.sprite.SpriteViewSystem; import com.inari.firefly.renderer.tile.TileGridRenderer; import com.inari.firefly.renderer.tile.TileGridSystem; import com.inari.firefly.sound.SoundSystem; import com.inari.firefly.state.StateSystem; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.FFContextImpl.InitMap; import com.inari.firefly.system.view.ViewSystem; public interface GDXConfiguration { public final static InitMap GDX_INIT_MAP = new InitMap() .put( FFContext.EVENT_DISPATCHER, EventDispatcher.class ) .put( FFContext.TIMER, GDXTimerImpl.class ) .put( FFContext.INPUT, GDXInputImpl.class ) .put( FFContext.LOWER_SYSTEM_FACADE, GDXLowerSystemImpl.class ) .put( FFContext.ENTITY_PROVIDER, EntityProvider.class ) .put( AssetSystem.CONTEXT_KEY, AssetSystem.class ) .put( StateSystem.CONTEXT_KEY, StateSystem.class ) .put( ViewSystem.CONTEXT_KEY, ViewSystem.class ) .put( EntitySystem.CONTEXT_KEY, EntitySystem.class ) .put( EntityPrefabSystem.CONTEXT_KEY, EntityPrefabSystem.class ) .put( SpriteViewSystem.CONTEXT_KEY, SpriteViewSystem.class ) .put( TileGridSystem.CONTEXT_KEY, TileGridSystem.class ) .put( MovementSystem.CONTEXT_KEY, MovementSystem.class ) .put( ComponentControllerSystem.CONTEXT_KEY, ComponentControllerSystem.class ) .put( AnimationSystem.CONTEXT_KEY, AnimationSystem.class ) .put( SoundSystem.CONTEXT_KEY, SoundSystem.class ) .put( SpriteViewRenderer.CONTEXT_KEY, SpriteViewRenderer.class ) .put( TileGridRenderer.CONTEXT_KEY, TileGridRenderer.class ); }
package algorithms.imageProcessing.matching; import algorithms.compGeometry.LinesAndAngles; import algorithms.util.PairInt; import algorithms.util.PairIntArray; import gnu.trove.list.TDoubleList; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntDoubleMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntDoubleHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import thirdparty.edu.princeton.cs.algs4.Interval; import thirdparty.edu.princeton.cs.algs4.IntervalRangeSearch; /** NOTE: NOT READY FOR USE YET... still testing. Adapted the chord descriptor difference matrix from PartialShapeMatcher.java which was made following the paper "Efficient Partial Shape Matching of Outer Contours" by Donoser The differences in chords of the implied second shape, a line is always 0, so edits are present specific to a one dimensional value instead of a closed curve. @author nichole */ public class LineFinder { /** * in sampling the boundaries of the shapes, one can * choose to use the same number for each (which can result * in very different spacings for different sized curves) * or one can choose a set distance between sampling * points. * dp is the set distance between sampling points. The authors of the paper use 3 as an example. */ protected int dp = 1; // 10 degrees is 0.1745 radians // for a fit to a line, consider 1E-9 private float thresh = (float)(1.e-7); protected Logger log = Logger.getLogger(this.getClass().getName()); private boolean debug = false; /** * override the threshhold for using a chord differernce value * to this. By default it is set to 1.e-7 radians. * @param t */ public void _overrideToThreshhold(float t) { this.thresh = t; } /** * override the sampling distance along the boundary which is by default * set to 1. If a larger value is used, the curve is sampled at * the given spacing, and the results are interpolated as filled in * between a sampled range. * @param d */ public void overrideSamplingDistance(int d) { this.dp = d; } public void setToDebug() { debug = true; log.setLevel(Level.FINE); } /** NOT READY FOR USE... still testing... A shape is defined as the clockwise ordered sequence of points P_1...P_N. The spacings used within this method are equidistant The default spacing is 1, so override that if a different number is needed. <em>NOTE: You may need to pre-process the shape points for example, smooth the boundary.</em> <pre> This method: PairIntArray p = imageProcessor .extractSmoothedOrderedBoundary() uses a Gaussian smoothing of 2 sigma, but a smaller sigma can be specified. </pre> @param p */ public LineResult match(PairIntArray p) { log.fine("p.n=" + p.getN()); if (p.getN() < 2) { throw new IllegalArgumentException("p must " + " have at least dp*2 points = " + (dp * 2)); } if (dp == 1) { return match0(p); } PairIntArray pSub = new PairIntArray(p.getN()/dp); for (int i = 0; i < p.getN(); i += dp) { pSub.add(p.getX(i), p.getY(i)); } log.fine("pSub.n=" + pSub.getN()); LineResult rSub = match0(pSub); if (rSub == null) { return null; } // -- put results back into frame of p -- LineResult r = new LineResult(); List<PairInt> lr = rSub.getLineIndexRanges(); for (int i = 0; i < lr.size(); ++i) { PairInt startStop = lr.get(i); int x = startStop.getX() * dp; int y = startStop.getY() * dp; r.addLineRange(new PairInt(x, y)); } return r; } private LineResult match0(PairIntArray p) { if (p == null || p.getN() < 2) { throw new IllegalArgumentException("p must have at " + "least 2 points"); } //md[0:n2-1][0:n1-1][0:n1-1] int n1 = p.getN(); float[][] md = createDifferenceMatrices(p); // find the intervals of contiguous 0s and assign curve indexes to the // largest segments. // (note that the 0s are the values below threshold, effectively // 0 by user request, and that the objective formula for the cost // is the Salukwzde distance). /* reading each row read start and stop cols of values < threshold and store each as an interval. if intersects with existing interval, compare cost and keep the one that is smallest cost in the interval tree */ // key = map size at put, value = interval TIntObjectMap<Interval<Integer>> intervalMap = new TIntObjectHashMap<Interval<Integer>>(); // key = key of intervalMap. item = chord diff sum TIntDoubleMap chordMap = new TIntDoubleHashMap(); // storing the interval of consecutive indexes, each below threshold, // and storing as the value, the key to entry in intervalMap IntervalRangeSearch<Integer, Integer> rangeSearch = new IntervalRangeSearch<Integer, Integer>(); Interval<Integer> interval = null; double maxChordSum = Double.MIN_VALUE; for (int i = 0; i < md.length; ++i) { int start = -1; double sum = 0; for (int j = 0; j < md[i].length; ++j) { float d = md[i][j]; boolean store = false; if (d < thresh) { if (start == -1) { // do not start if on diagonal // TODO: revisit this soon if (j == i) { continue; } start = j; } sum += d; if ((j == (md[i].length - 1)) && (start > -1)) { store = true; } } else if (start > -1) { store = true; } if (store) { // create an interval, int stop = j - 1; // to prevent two intersecting lines from being merged // into one, will use a start interval one // index higher, and correct for it later. // also, not storing single index matches start++; if (start > (md[i].length - 1)) { start = (md[i].length - 1); } if (stop < start) { // do not store single index matches start = -1; sum = 0; continue; } if (sum > maxChordSum) { maxChordSum = sum; } interval = new Interval<Integer>(start, stop); int sz = intervalMap.size(); // store it in range search Integer existing = rangeSearch.put(interval, Integer.valueOf(sz)); if (existing != null) { // clashes with existing, so make sure the lowest cost // remains in range tree Interval<Integer> comp = intervalMap.get(existing); double compChord = chordMap.get(existing.intValue()); int nc = comp.max().intValue() - comp.min().intValue() + 2; int ni = stop - start + 2; double compSD = calcSalukDist(compChord, maxChordSum, nc, md.length); double currentSD = calcSalukDist(sum, maxChordSum, ni, md.length); if (compSD < currentSD) { //re-insert existing interval Integer rmvd = rangeSearch.put(comp, existing); assert(rmvd != null); assert(rmvd.intValue() == sz); } else { //store current interval in associated maps intervalMap.put(Integer.valueOf(sz), interval); chordMap.put(sz, sum); } } else { // store current interval in associated maps intervalMap.put(Integer.valueOf(sz), interval); chordMap.put(sz, sum); } // reset vars start = -1; sum = 0; } } } // end loop j List<Interval<Integer>> list = rangeSearch.getAllIntrvals(); TIntSet existing = new TIntHashSet(); LineResult result = new LineResult(); for (Interval<Integer> interval2 : list) { // correct for the interval start being +1 int start = interval2.min() - 1; if (existing.contains(start)) { start++; } int stop = interval2.max(); if (existing.contains(stop)) { stop } PairInt s = new PairInt(start, stop); result.addLineRange(s); for (int i = start; i <= stop; ++i) { existing.add(i); } } //TODO: add the intersection of lines to LineResult as junctions // when a point is clearly part of two lines. such points are // currently usually seen as gaps between intervals return result; } /** * create the matrices of differences between p * and q. Note that the matrix differences are * absolute differences. returns a[0:p.n-1][0:p.n-1] */ protected float[][] createDifferenceMatrices( PairIntArray p) { /* | a_1_1...a_1_N | | a_2_1...a_2_N | | a_N_1...a_N_N | elements on the diagonal are zero to shift to different first point as reference, can shift down k-1 rows and left k-1 columns. */ //log.fine("a1:"); float[][] a1 = createDescriptorMatrix(p, p.getN()); //log.fine("a2:"); float[][] a2 = createLineDescriptorMatrix(p.getN()); /* MXM <XM 20 21 22 20 21 22 10 11 12 10 11 12 00 01 02 00 01 02 p_i_j - q_i_j */ int n1 = p.getN(); int n2 = n1; float[][] md = copy(a2); // NOTE: absolute values are stored. //M_D^n = A_1(1:M,1:M) - A_2(n:n+M-1,n:n+M-1) md = subtract(a1, md); if (debug) { print("a1", a1); print("a2", a2); print("diff matrix", md); } return md; } protected float[][] createLineDescriptorMatrix(int n) { float[][] a = new float[n][]; for (int i = 0; i < n; ++i) { a[i] = new float[n]; Arrays.fill(a[i], (float)Math.PI); // diagonal is zero a[i][i] = 0; } return a; } /** given the shape points for p and q, create a matrix of descriptors, describing the difference in chord angles. The chord descriptor is invariant to translation, rotation, and scale: - a chord is a line joining 2 region points - uses the relative orientation between 2 chords angle a_i_j is from chord P_i_P_j to reference point P_i to another sampled point and chord P_j_P_(j-d) and P_j d is the number of points before j in the sequence of points P. a_i_j is the angle between the 2 chords P_i_P_j and P_j_P_(j-d) */ protected float[][] createDescriptorMatrix(PairIntArray p, int n) { int dp1 = 1; float[][] a = new float[n][]; for (int i = 0; i < n; ++i) { a[i] = new float[n]; } /* P1 Pmid P2 */ log.fine("n=" + n); for (int i1 = 0; i1 < n; ++i1) { int start = i1 + 1 + dp1; for (int ii = start; ii < (start + n - 1 - dp1); ++ii) { int i2 = ii; int imid = i2 - dp1; // wrap around if (imid > (n - 1)) { imid -= n; } // wrap around if (i2 > (n - 1)) { i2 -= n; } //log.fine("i1=" + i1 + " imid=" + imid + " i2=" + i2); double angleA = LinesAndAngles .calcClockwiseAngle( p.getX(i1), p.getY(i1), p.getX(i2), p.getY(i2), p.getX(imid), p.getY(imid) ); //System.out.println("i1=" + i1 + " imid=" + imid + " i2=" + i2 + // " angleA=" + angleA); a[i1][i2] = (float)angleA; if (i2 == (i1 + 2)) { // fill in missing point, assume same value if (a[i1][i2] == a[i1][ii]) { a[i1][i1 + 1] = a[i1][i2]; } } } } return a; } protected int distanceSqEucl(int x1, int y1, int x2, int y2) { int diffX = x1 - x2; int diffY = y1 - y2; return (diffX * diffX + diffY * diffY); } private float[][] copy(float[][] a) { float[][] a2 = new float[a.length][]; for (int i = 0; i < a2.length; ++i) { a2[i] = Arrays.copyOf(a[i], a[i].length); } return a2; } /** * subtract the portion of a2 that is same size as * a1 from a1. * @param a1 * @param a2 * @return */ private float[][] subtract(float[][] a1, float[][] a2) { /* MXM NXN 20 21 22 10 11 10 11 12 00 01 00 01 02 01 02 00 10 11 21 22 20 00 01 11 12 10 12 10 11 10 11 02 00 01 00 01 22 20 21 subtracting only the MXM portion */ assert(a1.length == a1[0].length); assert(a2.length == a2[0].length); int n1 = a1.length; int n2 = a2.length; assert(n1 <= n2); float[][] output = new float[n1][]; for (int i = 0; i < n1; ++i) { output[i] = new float[n1]; for (int j = 0; j < n1; ++j) { float v = a1[i][j] - a2[i][j]; if (v < 0) { v *= -1; } output[i][j] = v; } } return output; } private void print(String label, float[][][] a) { for (int i = 0; i < a.length; ++i) { print(label + " off " + i, a[i]); } } private void print(String label, float[][] a) { StringBuilder sb = new StringBuilder(label); sb.append("\n"); for (int i = 0; i < a.length; ++i) { sb.append(String.format("row %3d: ", i)); for (int j = 0; j < a[i].length; ++j) { sb.append(String.format(" %.2f,", a[i][j])); } log.fine(sb.toString()); System.out.println(sb.toString()); sb.delete(0, sb.length()); } } private double calcSalukDist(double compChord, double maxChord, int length, int maxLength) { double d = compChord/maxChord; double f = 1. - ((double)length/(double)maxLength); return f*f + d*d; } public static class LineResult { List<PairInt> lineIndexRanges = new ArrayList<PairInt>(); public LineResult() { } /** * add start and stop index ranges for a found line segment * @param startStop */ public void addLineRange(PairInt startStop) { lineIndexRanges.add(startStop); } public List<PairInt> getLineIndexRanges() { return lineIndexRanges; } } }
package org.bouncycastle.cms.test; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.cms.CMSProcessable; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.cms.CMSSignedDataParser; import org.bouncycastle.cms.SignerId; import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.cms.SignerInformationStore; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.x509.X509AttributeCertificate; import org.bouncycastle.x509.X509CollectionStoreParameters; import org.bouncycastle.x509.X509Store; import java.io.ByteArrayInputStream; import java.security.KeyFactory; import java.security.KeyPair; import java.security.MessageDigest; import java.security.cert.CertStore; import java.security.cert.CollectionCertStoreParameters; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; public class SignedDataTest extends TestCase { boolean DEBUG = true; private static String _origDN; private static KeyPair _origKP; private static X509Certificate _origCert; private static String _signDN; private static KeyPair _signKP; private static X509Certificate _signCert; private static KeyPair _signGostKP; private static X509Certificate _signGostCert; private static KeyPair _signEcDsaKP; private static X509Certificate _signEcDsaCert; private static KeyPair _signEcGostKP; private static X509Certificate _signEcGostCert; private static KeyPair _signDsaKP; private static X509Certificate _signDsaCert; private static String _reciDN; private static KeyPair _reciKP; private static X509Certificate _reciCert; private static X509CRL _signCrl; private static boolean _initialised = false; private byte[] disorderedMessage = Base64.decode( "SU9fc3RkaW5fdXNlZABfX2xpYmNfc3RhcnRfbWFpbgBnZXRob3N0aWQAX19n" + "bW9uX3M="); private byte[] disorderedSet = Base64.decode( "MIIYXQYJKoZIhvcNAQcCoIIYTjCCGEoCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCFqswggJUMIIBwKADAgECAgMMg6wwCgYGKyQDAwECBQAwbzEL" + "MAkGA1UEBhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbI" + "dXIgVGVsZWtvbW11bmlrYXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwEx" + "MBEGA1UEAxQKNFItQ0EgMTpQTjAiGA8yMDAwMDMyMjA5NDM1MFoYDzIwMDQw" + "MTIxMTYwNDUzWjBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1" + "bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEh" + "MAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1DQSAxOlBOMIGhMA0GCSqGSIb3" + "DQEBAQUAA4GPADCBiwKBgQCKHkFTJx8GmoqFTxEOxpK9XkC3NZ5dBEKiUv0I" + "fe3QMqeGMoCUnyJxwW0k2/53duHxtv2yHSZpFKjrjvE/uGwdOMqBMTjMzkFg" + "19e9JPv061wyADOucOIaNAgha/zFt9XUyrHF21knKCvDNExv2MYIAagkTKaj" + "LMAw0bu1J0FadQIFAMAAAAEwCgYGKyQDAwECBQADgYEAgFauXpoTLh3Z3pT/" + "3bhgrxO/2gKGZopWGSWSJPNwq/U3x2EuctOJurj+y2inTcJjespThflpN+7Q" + "nvsUhXU+jL2MtPlObU0GmLvWbi47cBShJ7KElcZAaxgWMBzdRGqTOdtMv+ev" + "2t4igGF/q71xf6J2c3pTLWr6P8s6tzLfOCMwggJDMIIBr6ADAgECAgQAuzyu" + "MAoGBiskAwMBAgUAMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGll" + "cnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0" + "MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE4wIhgPMjAwMTA4" + "MjAwODA4MjBaGA8yMDA1MDgyMDA4MDgyMFowSzELMAkGA1UEBhMCREUxEjAQ" + "BgNVBAoUCVNpZ250cnVzdDEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFDQSBT" + "SUdOVFJVU1QgMTpQTjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAhV12" + "N2WhlR6f+3CXP57GrBM9la5Vnsu2b92zv5MZqQOPeEsYbZqDCFkYg1bSwsDE" + "XsGVQqXdQNAGUaapr/EUVVN+hNZ07GcmC1sPeQECgUkxDYjGi4ihbvzxlahj" + "L4nX+UTzJVBfJwXoIvJ+lMHOSpnOLIuEL3SRhBItvRECxN0CAwEAAaMSMBAw" + "DgYDVR0PAQH/BAQDAgEGMAoGBiskAwMBAgUAA4GBACDc9Pc6X8sK1cerphiV" + "LfFv4kpZb9ev4WPy/C6987Qw1SOTElhZAmxaJQBqmDHWlQ63wj1DEqswk7hG" + "LrvQk/iX6KXIn8e64uit7kx6DHGRKNvNGofPjr1WelGeGW/T2ZJKgmPDjCkf" + "sIKt2c3gwa2pDn4mmCz/DStUIqcPDbqLMIICVTCCAcGgAwIBAgIEAJ16STAK" + "BgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1" + "bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEh" + "MAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1DQSAxOlBOMCIYDzIwMDEwMjAx" + "MTM0NDI1WhgPMjAwNTAzMjIwODU1NTFaMG8xCzAJBgNVBAYTAkRFMT0wOwYD" + "VQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0" + "aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjZSLUNhIDE6" + "UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGLAoGBAIOiqxUkzVyqnvthihnl" + "tsE5m1Xn5TZKeR/2MQPStc5hJ+V4yptEtIx+Fn5rOoqT5VEVWhcE35wdbPvg" + "JyQFn5msmhPQT/6XSGOlrWRoFummXN9lQzAjCj1sgTcmoLCVQ5s5WpCAOXFw" + "VWu16qndz3sPItn3jJ0F3Kh3w79NglvPAgUAwAAAATAKBgYrJAMDAQIFAAOB" + "gQBpSRdnDb6AcNVaXSmGo6+kVPIBhot1LzJOGaPyDNpGXxd7LV4tMBF1U7gr" + "4k1g9BO6YiMWvw9uiTZmn0CfV8+k4fWEuG/nmafRoGIuay2f+ILuT+C0rnp1" + "4FgMsEhuVNJJAmb12QV0PZII+UneyhAneZuQQzVUkTcVgYxogxdSOzCCAlUw" + "ggHBoAMCAQICBACdekowCgYGKyQDAwECBQAwbzELMAkGA1UEBhMCREUxPTA7" + "BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbIdXIgVGVsZWtvbW11bmlr" + "YXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwExMBEGA1UEAxQKNlItQ2Eg" + "MTpQTjAiGA8yMDAxMDIwMTEzNDcwN1oYDzIwMDUwMzIyMDg1NTUxWjBvMQsw" + "CQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1" + "ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEhMAwGBwKCBgEKBxQTATEw" + "EQYDVQQDFAo1Ui1DQSAxOlBOMIGhMA0GCSqGSIb3DQEBAQUAA4GPADCBiwKB" + "gQCKHkFTJx8GmoqFTxEOxpK9XkC3NZ5dBEKiUv0Ife3QMqeGMoCUnyJxwW0k" + "2/53duHxtv2yHSZpFKjrjvE/uGwdOMqBMTjMzkFg19e9JPv061wyADOucOIa" + "NAgha/zFt9XUyrHF21knKCvDNExv2MYIAagkTKajLMAw0bu1J0FadQIFAMAA" + "AAEwCgYGKyQDAwECBQADgYEAV1yTi+2gyB7sUhn4PXmi/tmBxAfe5oBjDW8m" + "gxtfudxKGZ6l/FUPNcrSc5oqBYxKWtLmf3XX87LcblYsch617jtNTkMzhx9e" + "qxiD02ufcrxz2EVt0Akdqiz8mdVeqp3oLcNU/IttpSrcA91CAnoUXtDZYwb/" + "gdQ4FI9l3+qo/0UwggJVMIIBwaADAgECAgQAxIymMAoGBiskAwMBAgUAMG8x" + "CzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBm" + "yHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMB" + "MTARBgNVBAMUCjZSLUNhIDE6UE4wIhgPMjAwMTEwMTUxMzMxNThaGA8yMDA1" + "MDYwMTA5NTIxN1owbzELMAkGA1UEBhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVy" + "dW5nc2JlaMhvcmRlIGbIdXIgVGVsZWtvbW11bmlrYXRpb24gdW5kIFBvc3Qx" + "ITAMBgcCggYBCgcUEwExMBEGA1UEAxQKN1ItQ0EgMTpQTjCBoTANBgkqhkiG" + "9w0BAQEFAAOBjwAwgYsCgYEAiokD/j6lEP4FexF356OpU5teUpGGfUKjIrFX" + "BHc79G0TUzgVxqMoN1PWnWktQvKo8ETaugxLkP9/zfX3aAQzDW4Zki6x6GDq" + "fy09Agk+RJvhfbbIzRkV4sBBco0n73x7TfG/9NTgVr/96U+I+z/1j30aboM6" + "9OkLEhjxAr0/GbsCBQDAAAABMAoGBiskAwMBAgUAA4GBAHWRqRixt+EuqHhR" + "K1kIxKGZL2vZuakYV0R24Gv/0ZR52FE4ECr+I49o8FP1qiGSwnXB0SwjuH2S" + "iGiSJi+iH/MeY85IHwW1P5e+bOMvEOFhZhQXQixOD7totIoFtdyaj1XGYRef" + "0f2cPOjNJorXHGV8wuBk+/j++sxbd/Net3FtMIICVTCCAcGgAwIBAgIEAMSM" + "pzAKBgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxp" + "ZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9z" + "dDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAo3Ui1DQSAxOlBOMCIYDzIwMDEx" + "MDE1MTMzNDE0WhgPMjAwNTA2MDEwOTUyMTdaMG8xCzAJBgNVBAYTAkRFMT0w" + "OwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5p" + "a2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjZSLUNh" + "IDE6UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGLAoGBAIOiqxUkzVyqnvth" + "ihnltsE5m1Xn5TZKeR/2MQPStc5hJ+V4yptEtIx+Fn5rOoqT5VEVWhcE35wd" + "bPvgJyQFn5msmhPQT/6XSGOlrWRoFummXN9lQzAjCj1sgTcmoLCVQ5s5WpCA" + "OXFwVWu16qndz3sPItn3jJ0F3Kh3w79NglvPAgUAwAAAATAKBgYrJAMDAQIF" + "AAOBgQBi5W96UVDoNIRkCncqr1LLG9vF9SGBIkvFpLDIIbcvp+CXhlvsdCJl" + "0pt2QEPSDl4cmpOet+CxJTdTuMeBNXxhb7Dvualog69w/+K2JbPhZYxuVFZs" + "Zh5BkPn2FnbNu3YbJhE60aIkikr72J4XZsI5DxpZCGh6xyV/YPRdKSljFjCC" + "AlQwggHAoAMCAQICAwyDqzAKBgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9" + "MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVu" + "aWthdGlvbiB1bmQgUG9zdDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1D" + "QSAxOlBOMCIYDzIwMDAwMzIyMDk0MTI3WhgPMjAwNDAxMjExNjA0NTNaMG8x" + "CzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBm" + "yHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMB" + "MTARBgNVBAMUCjRSLUNBIDE6UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGL" + "AoGBAI8x26tmrFJanlm100B7KGlRemCD1R93PwdnG7svRyf5ZxOsdGrDszNg" + "xg6ouO8ZHQMT3NC2dH8TvO65Js+8bIyTm51azF6clEg0qeWNMKiiXbBXa+ph" + "hTkGbXiLYvACZ6/MTJMJ1lcrjpRF7BXtYeYMcEF6znD4pxOqrtbf9z5hAgUA" + "wAAAATAKBgYrJAMDAQIFAAOBgQB99BjSKlGPbMLQAgXlvA9jUsDNhpnVm3a1" + "YkfxSqS/dbQlYkbOKvCxkPGA9NBxisBM8l1zFynVjJoy++aysRmcnLY/sHaz" + "23BF2iU7WERy18H3lMBfYB6sXkfYiZtvQZcWaO48m73ZBySuiV3iXpb2wgs/" + "Cs20iqroAWxwq/W/9jCCAlMwggG/oAMCAQICBDsFZ9UwCgYGKyQDAwECBQAw" + "bzELMAkGA1UEBhMCREUxITAMBgcCggYBCgcUEwExMBEGA1UEAxQKNFItQ0Eg" + "MTpQTjE9MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxl" + "a29tbXVuaWthdGlvbiB1bmQgUG9zdDAiGA8xOTk5MDEyMTE3MzUzNFoYDzIw" + "MDQwMTIxMTYwMDAyWjBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxp" + "ZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9z" + "dDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAozUi1DQSAxOlBOMIGfMA0GCSqG" + "SIb3DQEBAQUAA4GNADCBiQKBgI4B557mbKQg/AqWBXNJhaT/6lwV93HUl4U8" + "u35udLq2+u9phns1WZkdM3gDfEpL002PeLfHr1ID/96dDYf04lAXQfombils" + "of1C1k32xOvxjlcrDOuPEMxz9/HDAQZA5MjmmYHAIulGI8Qg4Tc7ERRtg/hd" + "0QX0/zoOeXoDSEOBAgTAAAABMAoGBiskAwMBAgUAA4GBAIyzwfT3keHI/n2P" + "LrarRJv96mCohmDZNpUQdZTVjGu5VQjVJwk3hpagU0o/t/FkdzAjOdfEw8Ql" + "3WXhfIbNLv1YafMm2eWSdeYbLcbB5yJ1od+SYyf9+tm7cwfDAcr22jNRBqx8" + "wkWKtKDjWKkevaSdy99sAI8jebHtWz7jzydKMIID9TCCA16gAwIBAgICbMcw" + "DQYJKoZIhvcNAQEFBQAwSzELMAkGA1UEBhMCREUxEjAQBgNVBAoUCVNpZ250" + "cnVzdDEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFDQSBTSUdOVFJVU1QgMTpQ" + "TjAeFw0wNDA3MzAxMzAyNDZaFw0wNzA3MzAxMzAyNDZaMDwxETAPBgNVBAMM" + "CFlhY29tOlBOMQ4wDAYDVQRBDAVZYWNvbTELMAkGA1UEBhMCREUxCjAIBgNV" + "BAUTATEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIWzLlYLQApocXIp" + "pgCCpkkOUVLgcLYKeOd6/bXAnI2dTHQqT2bv7qzfUnYvOqiNgYdF13pOYtKg" + "XwXMTNFL4ZOI6GoBdNs9TQiZ7KEWnqnr2945HYx7UpgTBclbOK/wGHuCdcwO" + "x7juZs1ZQPFG0Lv8RoiV9s6HP7POqh1sO0P/AgMBAAGjggH1MIIB8TCBnAYD" + "VR0jBIGUMIGRgBQcZzNghfnXoXRm8h1+VITC5caNRqFzpHEwbzELMAkGA1UE" + "BhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbIdXIgVGVs" + "ZWtvbW11bmlrYXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwExMBEGA1UE" + "AxQKNVItQ0EgMTpQToIEALs8rjAdBgNVHQ4EFgQU2e5KAzkVuKaM9I5heXkz" + "bcAIuR8wDgYDVR0PAQH/BAQDAgZAMBIGA1UdIAQLMAkwBwYFKyQIAQEwfwYD" + "VR0fBHgwdjB0oCygKoYobGRhcDovL2Rpci5zaWdudHJ1c3QuZGUvbz1TaWdu" + "dHJ1c3QsYz1kZaJEpEIwQDEdMBsGA1UEAxMUQ1JMU2lnblNpZ250cnVzdDE6" + "UE4xEjAQBgNVBAoTCVNpZ250cnVzdDELMAkGA1UEBhMCREUwYgYIKwYBBQUH" + "AQEEVjBUMFIGCCsGAQUFBzABhkZodHRwOi8vZGlyLnNpZ250cnVzdC5kZS9T" + "aWdudHJ1c3QvT0NTUC9zZXJ2bGV0L2h0dHBHYXRld2F5LlBvc3RIYW5kbGVy" + "MBgGCCsGAQUFBwEDBAwwCjAIBgYEAI5GAQEwDgYHAoIGAQoMAAQDAQH/MA0G" + "CSqGSIb3DQEBBQUAA4GBAHn1m3GcoyD5GBkKUY/OdtD6Sj38LYqYCF+qDbJR" + "6pqUBjY2wsvXepUppEler+stH8mwpDDSJXrJyuzf7xroDs4dkLl+Rs2x+2tg" + "BjU+ABkBDMsym2WpwgA8LCdymmXmjdv9tULxY+ec2pjSEzql6nEZNEfrU8nt" + "ZCSCavgqW4TtMYIBejCCAXYCAQEwUTBLMQswCQYDVQQGEwJERTESMBAGA1UE" + "ChQJU2lnbnRydXN0MSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEUNBIFNJR05U" + "UlVTVCAxOlBOAgJsxzAJBgUrDgMCGgUAoIGAMBgGCSqGSIb3DQEJAzELBgkq" + "hkiG9w0BBwEwIwYJKoZIhvcNAQkEMRYEFIYfhPoyfGzkLWWSSLjaHb4HQmaK" + "MBwGCSqGSIb3DQEJBTEPFw0wNTAzMjQwNzM4MzVaMCEGBSskCAYFMRgWFi92" + "YXIvZmlsZXMvdG1wXzEvdGVzdDEwDQYJKoZIhvcNAQEFBQAEgYA2IvA8lhVz" + "VD5e/itUxbFboKxeKnqJ5n/KuO/uBCl1N14+7Z2vtw1sfkIG+bJdp3OY2Cmn" + "mrQcwsN99Vjal4cXVj8t+DJzFG9tK9dSLvD3q9zT/GQ0kJXfimLVwCa4NaSf" + "Qsu4xtG0Rav6bCcnzabAkKuNNvKtH8amSRzk870DBg=="); /* * * INFRASTRUCTURE * */ public SignedDataTest(String name) { super(name); } public static void main(String args[]) { junit.textui.TestRunner.run(SignedDataTest.class); } public static Test suite() throws Exception { init(); return new CMSTestSetup(new TestSuite(SignedDataTest.class)); } private static void init() throws Exception { if (!_initialised) { _initialised = true; _origDN = "O=Bouncy Castle, C=AU"; _origKP = CMSTestUtil.makeKeyPair(); _origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _origKP, _origDN); _signDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; _signKP = CMSTestUtil.makeKeyPair(); _signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _origKP, _origDN); _signGostKP = CMSTestUtil.makeGostKeyPair(); _signGostCert = CMSTestUtil.makeCertificate(_signGostKP, _signDN, _origKP, _origDN); _signDsaKP = CMSTestUtil.makeDsaKeyPair(); _signDsaCert = CMSTestUtil.makeCertificate(_signDsaKP, _signDN, _origKP, _origDN); _signEcDsaKP = CMSTestUtil.makeEcDsaKeyPair(); _signEcDsaCert = CMSTestUtil.makeCertificate(_signEcDsaKP, _signDN, _origKP, _origDN); _signEcGostKP = CMSTestUtil.makeEcGostKeyPair(); _signEcGostCert = CMSTestUtil.makeCertificate(_signEcGostKP, _signDN, _origKP, _origDN); _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; _reciKP = CMSTestUtil.makeKeyPair(); _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); _signCrl = CMSTestUtil.makeCrl(_signKP); } } private void verifySignatures(CMSSignedData s, byte[] contentDigest) throws Exception { CertStore certStore = s.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); assertEquals(true, signer.verify(cert, "BC")); if (contentDigest != null) { assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest())); } } Collection certColl = certStore.getCertificates(null); Collection crlColl = certStore.getCRLs(null); assertEquals(certColl.size(), s.getCertificates("Collection", "BC").getMatches(null).size()); assertEquals(crlColl.size(), s.getCRLs("Collection", "BC").getMatches(null).size()); } private void verifySignatures(CMSSignedData s) throws Exception { verifySignatures(s, null); } public void testSHA1AndMD5WithRSAEncapsulatedRepeated() throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_MD5); gen.addCertificatesAndCRLs(certs); CMSSignedData s = gen.generate(msg, true, "BC"); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = s.getSignerInfos(); assertEquals(2, signers.size()); Collection c = signers.getSigners(); Iterator it = c.iterator(); SignerId sid = null; while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); sid = signer.getSID(); assertEquals(true, signer.verify(cert, "BC")); // check content digest byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(signer.getDigestAlgOID()); AttributeTable table = signer.getSignedAttributes(); Attribute hash = table.get(CMSAttributes.messageDigest); assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); } c = signers.getSigners(sid); assertEquals(2, c.size()); // try using existing signer gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); gen.addCertificatesAndCRLs(s.getCertificatesAndCRLs("Collection", "BC")); s = gen.generate(msg, true, "BC"); bIn = new ByteArrayInputStream(s.getEncoded()); aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificatesAndCRLs("Collection", "BC"); signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); assertEquals(2, c.size()); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); assertEquals(true, signer.verify(cert, "BC")); } checkSignerStoreReplacement(s, signers); } public void testSHA1WithRSANoAttributes() throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); CMSSignedData s = gen.generate(CMSSignedDataGenerator.DATA, msg, false, "BC", false); // compute expected content digest MessageDigest md = MessageDigest.getInstance("SHA1", "BC"); verifySignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_SHA1); } public void testSHA224WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_SHA224); } public void testSHA256WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_SHA256); } public void testRIPEMD128WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_RIPEMD128); } public void testRIPEMD160WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_RIPEMD160); } public void testRIPEMD256WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_RIPEMD256); } public void testECDSAEncapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA1); } public void testECDSASHA224Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA224); } public void testECDSASHA256Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA256); } public void testECDSASHA384Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA384); } public void testECDSASHA512Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA512); } public void testECDSASHA512EncapsulatedWithKeyFactoryAsEC() throws Exception { X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(_signEcDsaKP.getPublic().getEncoded()); PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(_signEcDsaKP.getPrivate().getEncoded()); KeyFactory keyFact = KeyFactory.getInstance("EC", "BC"); KeyPair kp = new KeyPair(keyFact.generatePublic(pubSpec), keyFact.generatePrivate(privSpec)); encapsulatedTest(kp, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA512); } public void testDSAEncapsulated() throws Exception { encapsulatedTest(_signDsaKP, _signDsaCert, CMSSignedDataGenerator.DIGEST_SHA1); } public void testGOST3411WithGOST3410Encapsulated() throws Exception { encapsulatedTest(_signGostKP, _signGostCert, CMSSignedDataGenerator.DIGEST_GOST3411); } public void testGOST3411WithECGOST3410Encapsulated() throws Exception { encapsulatedTest(_signEcGostKP, _signEcGostCert, CMSSignedDataGenerator.DIGEST_GOST3411); } private void encapsulatedTest( KeyPair signaturePair, X509Certificate signatureCert, String digestAlgorithm) throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(signatureCert); certList.add(_origCert); certList.add(_signCrl); CertStore certsAndCrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(signaturePair.getPrivate(), signatureCert, digestAlgorithm); gen.addCertificatesAndCRLs(certsAndCrls); CMSSignedData s = gen.generate(msg, true, "BC"); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certsAndCrls = s.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certsAndCrls.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); assertEquals(true, signer.verify(cert, "BC")); } // check for CRLs Collection crls = certsAndCrls.getCRLs(null); assertEquals(1, crls.size()); assertTrue(crls.contains(_signCrl)); // try using existing signer gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); gen.addCertificatesAndCRLs(s.getCertificatesAndCRLs("Collection", "BC")); s = gen.generate(msg, true, "BC"); bIn = new ByteArrayInputStream(s.getEncoded()); aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certsAndCrls = s.getCertificatesAndCRLs("Collection", "BC"); signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certsAndCrls.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); assertEquals(true, signer.verify(cert, "BC")); } checkSignerStoreReplacement(s, signers); } // signerInformation store replacement test. private void checkSignerStoreReplacement( CMSSignedData orig, SignerInformationStore signers) throws Exception { CMSSignedData s = CMSSignedData.replaceSigners(orig, signers); CertStore certs = s.getCertificatesAndCRLs("Collection", "BC"); signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); assertEquals(true, signer.verify(cert, "BC")); } } public void testUnsortedAttributes() throws Exception { CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(disorderedMessage), disorderedSet); CertStore certs = s.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); assertEquals(true, signer.verify(cert, "BC")); } } public void testNullContentWithSigner() throws Exception { List certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); CMSSignedData s = gen.generate(null, false, "BC"); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); verifySignatures(s); } public void testWithAttributeCertificate() throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); X509AttributeCertificate attrCert = CMSTestUtil.getAttributeCertificate(); X509Store store = X509Store.getInstance("AttributeCertificate/Collection", new X509CollectionStoreParameters(Collections.singleton(attrCert)), "BC"); gen.addAttributeCertificates(store); CMSSignedData sd = gen.generate(msg, "BC"); assertEquals(4, sd.getVersion()); store = sd.getAttributeCertificates("Collection", "BC"); Collection coll = store.getMatches(null); assertEquals(1, coll.size()); assertTrue(coll.contains(attrCert)); // create new certstore certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); // replace certs sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs); verifySignatures(sd); } public void testCertStoreReplacement() throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); CMSSignedData sd = gen.generate(msg, "BC"); // create new certstore certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); // replace certs sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs); verifySignatures(sd); } public void testEncapsulatedCertStoreReplacement() throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); CMSSignedData sd = gen.generate(msg, true, "BC"); // create new certstore certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); // replace certs sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs); verifySignatures(sd); } public void testCertOrdering1() throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); certList.add(_signDsaCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); CMSSignedData sd = gen.generate(msg, true, "BC"); certs = sd.getCertificatesAndCRLs("Collection", "BC"); Iterator it = certs.getCertificates(null).iterator(); assertEquals(_origCert, it.next()); assertEquals(_signCert, it.next()); assertEquals(_signDsaCert, it.next()); } public void testCertOrdering2() throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signCert); certList.add(_signDsaCert); certList.add(_origCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); CMSSignedData sd = gen.generate(msg, true, "BC"); certs = sd.getCertificatesAndCRLs("Collection", "BC"); Iterator it = certs.getCertificates(null).iterator(); assertEquals(_signCert, it.next()); assertEquals(_signDsaCert, it.next()); assertEquals(_origCert, it.next()); } public void testSignerStoreReplacement() throws Exception { List certList = new ArrayList(); CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); gen.addCertificatesAndCRLs(certs); CMSSignedData original = gen.generate(msg, true, "BC"); // create new Signer gen = new CMSSignedDataGenerator(); gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA224); gen.addCertificatesAndCRLs(certs); CMSSignedData newSD = gen.generate(msg, true, "BC"); // replace signer CMSSignedData sd = CMSSignedData.replaceSigners(original, newSD.getSignerInfos()); SignerInformation signer = (SignerInformation)sd.getSignerInfos().getSigners().iterator().next(); assertEquals(CMSSignedDataGenerator.DIGEST_SHA224, signer.getDigestAlgOID()); // we use a parser here as it requires the digests to be correct in the digest set, if it // isn't we'll get a NullPointerException CMSSignedDataParser sp = new CMSSignedDataParser(sd.getEncoded()); sp.getSignedContent().drain(); verifySignatures(sp); } private void verifySignatures(CMSSignedDataParser sp) throws Exception { CertStore certs = sp.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = sp.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); assertEquals(true, signer.verify(cert, "BC")); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.sam; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.util.CloseableIterator; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.sam.reader.AlignmentReader; import org.broad.igv.sam.reader.AlignmentReaderFactory; import org.broad.igv.sam.reader.ReadGroupFilter; import org.broad.igv.util.ResourceLocator; import org.broad.igv.util.TestUtils; import org.junit.*; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author jrobinso */ public class CachingQueryReaderTest { String testFile = "http: String sequence = "chr1"; int start = 44680145; int end = 44789983; private boolean contained = false; ; public CachingQueryReaderTest() { } @BeforeClass public static void setUpClass() throws Exception { TestUtils.setUpHeadless(); } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getHeader method, of class CachingQueryReader. The test compares * the results of CachingQueryReader with a non-caching reader which * is assumed to be correct. */ @Test public void testGetHeader() throws IOException { ResourceLocator loc = new ResourceLocator(testFile); AlignmentReader reader = AlignmentReaderFactory.getReader(loc); SAMFileHeader expectedHeader = reader.getHeader(); reader.close(); reader = AlignmentReaderFactory.getReader(loc); CachingQueryReader cachingReader = new CachingQueryReader(reader); SAMFileHeader header = cachingReader.getHeader(); cachingReader.close(); assertTrue(header.equals(expectedHeader)); } @Test public void testQuery() throws IOException { tstQuery(testFile, sequence, start, end, contained); } /** * Test of query method, of class CachingQueryReader. The test compares * the results of CachingQueryReader non-caching reader which * is assumed to be correct. */ public void tstQuery(String testFile, String sequence, int start, int end, boolean contained) throws IOException { ResourceLocator loc = new ResourceLocator(testFile); AlignmentReader reader = AlignmentReaderFactory.getReader(loc); CloseableIterator<Alignment> iter = reader.query(sequence, start, end, contained); Map<String, Alignment> expectedResult = new HashMap(); while (iter.hasNext()) { Alignment rec = iter.next(); // the following filters are applied in the Caching reader, so we need to apply them here. boolean filterFailedReads = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS); ReadGroupFilter filter = ReadGroupFilter.getFilter(); boolean showDuplicates = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES); int qualityThreshold = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD); if (!rec.isMapped() || (!showDuplicates && rec.isDuplicate()) || (filterFailedReads && rec.isVendorFailedRead()) || rec.getMappingQuality() < qualityThreshold || (filter != null && filter.filterAlignment(rec))) { continue; } expectedResult.put(rec.getReadName(), rec); if(contained){ assertTrue(rec.getStart() >= start); }else{ //All we require is some overlap boolean overlap = rec.getStart() >= start && rec.getStart() <= end; overlap |= rec.getEnd() >= start && rec.getEnd() <= end; assertTrue(overlap); } assertEquals(sequence, rec.getChr()); } reader.close(); reader = AlignmentReaderFactory.getReader(loc); CachingQueryReader cachingReader = new CachingQueryReader(reader); CloseableIterator<Alignment> cachingIter = cachingReader.query(sequence, start, end, new ArrayList(), new ArrayList(), Integer.MAX_VALUE / 1000, null, null); List<Alignment> result = new ArrayList(); while (cachingIter.hasNext()) { result.add(cachingIter.next()); } cachingReader.close(); assertTrue(expectedResult.size() > 0); assertEquals(expectedResult.size(), result.size()); for (int i = 0; i < result.size(); i++) { Alignment rec = result.get(i); if(contained){ assertTrue(rec.getStart() >= start); }else{ //All we require is some overlap boolean overlap = rec.getStart() >= start && rec.getStart() <= end; overlap |= start >= rec.getStart() && start <= rec.getEnd(); assertTrue(overlap); } assertEquals(sequence, rec.getChr()); assertTrue(expectedResult.containsKey(rec.getReadName())); Alignment exp = expectedResult.get(rec.getReadName()); assertEquals(exp.getAlignmentStart(), rec.getAlignmentStart()); assertEquals(exp.getAlignmentEnd(), rec.getAlignmentEnd()); } } @Test public void testQueryLargeFile() throws Exception{ PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, "5"); String path = TestUtils.LARGE_DATA_DIR + "/ABCD_igvSample.bam"; String sequence = "chr12"; int start = 56815621; int end = start + 2; int expSize = 1066; //tstSize(cachingReader, sequence, start, end, Integer.MAX_VALUE / 100, expSize); sequence = "chr12"; start = 56815634; end = start + 2; expSize = 165; tstQuery(path, sequence, start, end, false); } public List<Alignment> tstSize(CachingQueryReader cachingReader, String sequence, int start, int end, int maxDepth, int expSize){ CloseableIterator<Alignment> cachingIter = cachingReader.query(sequence, start, end, new ArrayList(), new ArrayList(), maxDepth, null, null); List<Alignment> result = new ArrayList(); while (cachingIter.hasNext()) { result.add(cachingIter.next()); } assertEquals(expSize, result.size()); return result; } @Test public void testQueryLargeFile() throws Exception{ PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, "5"); String path = TestUtils.LARGE_DATA_DIR + "/ABCD_igvSample.bam"; String sequence = "chr12"; int start = 56815621; int end = start + 2; int expSize = 1066; //tstSize(cachingReader, sequence, start, end, Integer.MAX_VALUE / 100, expSize); sequence = "chr12"; start = 56815634; end = start + 2; expSize = 165; tstQuery(path, sequence, start, end, false); } public List<Alignment> tstSize(CachingQueryReader cachingReader, String sequence, int start, int end, int maxDepth, int expSize){ CloseableIterator<Alignment> cachingIter = cachingReader.query(sequence, start, end, new ArrayList(), new ArrayList(), maxDepth, null, null); List<Alignment> result = new ArrayList(); while (cachingIter.hasNext()) { result.add(cachingIter.next()); } assertEquals(expSize, result.size()); return result; } }
package com.lambdaworks.redis; import static com.google.common.base.Preconditions.checkArgument; import java.io.Closeable; import java.net.SocketAddress; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.lambdaworks.redis.protocol.CommandHandler; import com.lambdaworks.redis.pubsub.PubSubCommandHandler; import com.lambdaworks.redis.resource.ClientResources; import com.lambdaworks.redis.resource.DefaultClientResources; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.*; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.ChannelGroupFuture; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.HashedWheelTimer; import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; /** * Base Redis client. This class holds the netty infrastructure, {@link ClientOptions} and the basic connection procedure. This * class creates the netty {@link EventLoopGroup}s for NIO ({@link NioEventLoopGroup}) and EPoll ( * {@link io.netty.channel.epoll.EpollEventLoopGroup}) with a default of {@code Runtime.getRuntime().availableProcessors() * 4} * threads. Reuse the instance as much as possible since the {@link EventLoopGroup} instances are expensive and can consume a * huge part of your resources, if you create multiple instances. * <p> * You can set the number of threads per {@link NioEventLoopGroup} by setting the {@code io.netty.eventLoopThreads} system * property to a reasonable number of threads. * </p> * * @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a> * @since 3.0 */ public abstract class AbstractRedisClient { protected static final PooledByteBufAllocator BUF_ALLOCATOR = PooledByteBufAllocator.DEFAULT; protected static final InternalLogger logger = InternalLoggerFactory.getInstance(RedisClient.class); /** * @deprecated use map eventLoopGroups instead. */ @Deprecated protected EventLoopGroup eventLoopGroup; protected EventExecutorGroup genericWorkerPool; protected final Map<Class<? extends EventLoopGroup>, EventLoopGroup> eventLoopGroups = new ConcurrentHashMap<Class<? extends EventLoopGroup>, EventLoopGroup>();; protected final HashedWheelTimer timer; protected final ChannelGroup channels; protected final ClientResources clientResources; protected long timeout = 60; protected TimeUnit unit; protected ConnectionEvents connectionEvents = new ConnectionEvents(); protected Set<Closeable> closeableResources = Sets.newConcurrentHashSet(); protected volatile ClientOptions clientOptions = new ClientOptions.Builder().build(); private final boolean sharedResources; /** * @deprecated use {@link #AbstractRedisClient(ClientResources)} */ @Deprecated protected AbstractRedisClient() { this(null); } /** * Create a new instance with client resources. * * @param clientResources the client resources. If {@literal null}, the client will create a new dedicated instance of * client resources and keep track of them. */ protected AbstractRedisClient(ClientResources clientResources) { if (clientResources == null) { sharedResources = false; this.clientResources = DefaultClientResources.create(); } else { sharedResources = true; this.clientResources = clientResources; } unit = TimeUnit.SECONDS; genericWorkerPool = this.clientResources.eventExecutorGroup(); channels = new DefaultChannelGroup(genericWorkerPool.next()); timer = new HashedWheelTimer(); } public void setDefaultTimeout(long timeout, TimeUnit unit) { this.timeout = timeout; this.unit = unit; } @SuppressWarnings("unchecked") protected <K, V, T extends RedisChannelHandler<K, V>> T connectAsyncImpl(final CommandHandler<K, V> handler, final T connection, final Supplier<SocketAddress> socketAddressSupplier) { ConnectionBuilder connectionBuilder = ConnectionBuilder.connectionBuilder(); connectionBuilder.clientOptions(clientOptions); connectionBuilder.clientResources(clientResources); connectionBuilder(handler, connection, socketAddressSupplier, connectionBuilder, null); channelType(connectionBuilder, null); return (T) initializeChannel(connectionBuilder); } /** * Populate connection builder with necessary resources. * * @param handler instance of a CommandHandler for writing redis commands * @param connection implementation of a RedisConnection * @param socketAddressSupplier address supplier for initial connect and re-connect * @param connectionBuilder connection builder to configure the connection * @param redisURI URI of the redis instance */ protected void connectionBuilder(CommandHandler<?, ?> handler, RedisChannelHandler<?, ?> connection, Supplier<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder, RedisURI redisURI) { Bootstrap redisBootstrap = new Bootstrap(); redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR); if (redisURI == null) { redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) unit.toMillis(timeout)); connectionBuilder.timeout(timeout, unit); } else { redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) redisURI.getUnit() .toMillis(redisURI.getTimeout())); connectionBuilder.timeout(redisURI.getTimeout(), redisURI.getUnit()); connectionBuilder.password(redisURI.getPassword()); } connectionBuilder.bootstrap(redisBootstrap); connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer); connectionBuilder.commandHandler(handler).socketAddressSupplier(socketAddressSupplier).connection(connection); connectionBuilder.workerPool(genericWorkerPool); } protected void channelType(ConnectionBuilder connectionBuilder, ConnectionPoint connectionPoint) { connectionBuilder.bootstrap().group(getEventLoopGroup(connectionPoint)); if (connectionPoint != null && connectionPoint.getSocket() != null) { checkForEpollLibrary(); connectionBuilder.bootstrap().channel(EpollProvider.epollDomainSocketChannelClass); } else { connectionBuilder.bootstrap().channel(NioSocketChannel.class); } } private synchronized EventLoopGroup getEventLoopGroup(ConnectionPoint connectionPoint) { if ((connectionPoint == null || connectionPoint.getSocket() == null) && !eventLoopGroups.containsKey(NioEventLoopGroup.class)) { if (eventLoopGroup == null) { eventLoopGroup = clientResources.eventLoopGroupProvider().allocate(NioEventLoopGroup.class); } eventLoopGroups.put(NioEventLoopGroup.class, eventLoopGroup); } if (connectionPoint != null && connectionPoint.getSocket() != null) { checkForEpollLibrary(); if (!eventLoopGroups.containsKey(EpollProvider.epollEventLoopGroupClass)) { EventLoopGroup epl = clientResources.eventLoopGroupProvider().allocate(EpollProvider.epollEventLoopGroupClass); eventLoopGroups.put(EpollProvider.epollEventLoopGroupClass, epl); } } if (connectionPoint == null || connectionPoint.getSocket() == null) { return eventLoopGroups.get(NioEventLoopGroup.class); } if (connectionPoint != null && connectionPoint.getSocket() != null) { checkForEpollLibrary(); return eventLoopGroups.get(EpollProvider.epollEventLoopGroupClass); } throw new IllegalStateException("This should not have happened in a binary decision. Please file a bug."); } private void checkForEpollLibrary() { EpollProvider.checkForEpollLibrary(); } @SuppressWarnings("unchecked") protected <K, V, T extends RedisChannelHandler<K, V>> T initializeChannel(ConnectionBuilder connectionBuilder) { RedisChannelHandler<?, ?> connection = connectionBuilder.connection(); SocketAddress redisAddress = connectionBuilder.socketAddress(); try { logger.debug("Connecting to Redis, address: " + redisAddress); Bootstrap redisBootstrap = connectionBuilder.bootstrap(); RedisChannelInitializer initializer = connectionBuilder.build(); redisBootstrap.handler(initializer); ChannelFuture connectFuture = redisBootstrap.connect(redisAddress); connectFuture.await(); if (!connectFuture.isSuccess()) { if (connectFuture.cause() instanceof Exception) { throw (Exception) connectFuture.cause(); } connectFuture.get(); } try { initializer.channelInitialized().get(connectionBuilder.getTimeout(), connectionBuilder.getTimeUnit()); } catch (TimeoutException e) { throw new RedisConnectionException("Could not initialize channel within " + connectionBuilder.getTimeout() + " " + connectionBuilder.getTimeUnit(), e); } connection.registerCloseables(closeableResources, connection, connectionBuilder.commandHandler()); return (T) connection; } catch (RedisException e) { connectionBuilder.commandHandler().initialState(); throw e; } catch (Exception e) { connectionBuilder.commandHandler().initialState(); throw new RedisConnectionException("Unable to connect to " + redisAddress, e); } } /** * Shutdown this client and close all open connections. The client should be discarded after calling shutdown. The shutdown * has 2 secs quiet time and a timeout of 15 secs. */ public void shutdown() { shutdown(2, 15, TimeUnit.SECONDS); } /** * Shutdown this client and close all open connections. The client should be discarded after calling shutdown. * * @param quietPeriod the quiet period as described in the documentation * @param timeout the maximum amount of time to wait until the executor is shutdown regardless if a task was submitted * during the quiet period * @param timeUnit the unit of {@code quietPeriod} and {@code timeout} */ public void shutdown(long quietPeriod, long timeout, TimeUnit timeUnit) { timer.stop(); while (!closeableResources.isEmpty()) { Closeable closeableResource = closeableResources.iterator().next(); try { closeableResource.close(); } catch (Exception e) { logger.debug("Exception on Close: " + e.getMessage(), e); } closeableResources.remove(closeableResource); } List<Future<?>> closeFutures = Lists.newArrayList(); if (channels != null) { for (Channel c : channels) { ChannelPipeline pipeline = c.pipeline(); CommandHandler<?, ?> commandHandler = pipeline.get(CommandHandler.class); if (commandHandler != null && !commandHandler.isClosed()) { commandHandler.close(); } PubSubCommandHandler<?, ?> psCommandHandler = pipeline.get(PubSubCommandHandler.class); if (psCommandHandler != null && !psCommandHandler.isClosed()) { psCommandHandler.close(); } } ChannelGroupFuture closeFuture = channels.close(); closeFutures.add(closeFuture); } if (!sharedResources) { clientResources.shutdown(quietPeriod, timeout, timeUnit); } else { for (EventLoopGroup eventExecutors : eventLoopGroups.values()) { Future<?> groupCloseFuture = clientResources.eventLoopGroupProvider().release(eventExecutors, quietPeriod, timeout, timeUnit); closeFutures.add(groupCloseFuture); } } for (Future<?> future : closeFutures) { try { future.get(); } catch (Exception e) { throw new RedisException(e); } } } protected int getResourceCount() { return closeableResources.size(); } protected int getChannelCount() { return channels.size(); } /** * Add a listener for the RedisConnectionState. The listener is notified every time a connect/disconnect/IO exception * happens. The listeners are not bound to a specific connection, so every time a connection event happens on any * connection, the listener will be notified. The corresponding netty channel handler (async connection) is passed on the * event. * * @param listener must not be {@literal null} */ public void addListener(RedisConnectionStateListener listener) { checkArgument(listener != null, "RedisConnectionStateListener must not be null"); connectionEvents.addListener(listener); } /** * Removes a listener. * * @param listener must not be {@literal null} */ public void removeListener(RedisConnectionStateListener listener) { checkArgument(listener != null, "RedisConnectionStateListener must not be null"); connectionEvents.removeListener(listener); } /** * Returns the {@link ClientOptions} which are valid for that client. Connections inherit the current options at the moment * the connection is created. Changes to options will not affect existing connections. * * @return the {@link ClientOptions} for this client */ public ClientOptions getOptions() { return clientOptions; } /** * Set the {@link ClientOptions} for the client. * * @param clientOptions client options for the client and connections that are created after setting the options */ protected void setOptions(ClientOptions clientOptions) { checkArgument(clientOptions != null, "clientOptions must not be null"); this.clientOptions = clientOptions; } }
/* * $Id: TestStatusTable.java,v 1.17 2013-01-02 21:01:23 tlipkis Exp $ */ package org.lockss.daemon.status; import java.util.*; import org.lockss.test.*; import org.lockss.util.*; import org.lockss.protocol.*; import org.lockss.servlet.*; public class TestStatusTable extends LockssTestCase { StatusTable table; static ServletDescr srvDescr = new ServletDescr("name", LockssServlet.class, "name"); static Properties args = new Properties(); static { args.setProperty("foo", "bar"); } public void setUp() throws Exception { super.setUp(); table = new StatusTable("table1", "key1"); } public void testAccessors() { StatusTable tbl; tbl = new StatusTable("nom"); assertEquals("nom", tbl.getName()); assertNull(tbl.getKey()); tbl = new StatusTable("nom", "cle"); assertEquals("nom", tbl.getName()); assertEquals("cle", tbl.getKey()); tbl.setName("jacques"); assertEquals("jacques", tbl.getName()); assertNull(tbl.getTitle()); tbl.setTitle("titre"); assertEquals("titre", tbl.getTitle()); assertNull(tbl.getTitleFootnote()); tbl.setTitleFootnote("note"); assertEquals("note", tbl.getTitleFootnote()); assertTrue(tbl.isResortable()); tbl.setResortable(false); assertFalse(tbl.isResortable()); assertNull(tbl.getSummaryInfo()); List lst = new ArrayList(); tbl.setSummaryInfo(lst); assertSame(lst, tbl.getSummaryInfo()); assertEmpty(tbl.getDefaultSortRules()); tbl.setColumnDescriptors(Collections.EMPTY_LIST); assertEmpty(tbl.getDefaultSortRules()); List rules = new ArrayList(); tbl.setDefaultSortRules(rules); assertSame(rules, tbl.getDefaultSortRules()); assertNotNull(tbl.getOptions()); } public void testProperties() { StatusTable tbl = new StatusTable("tab"); assertNull(tbl.getProperties()); tbl.setProperty("k1", "v3"); assertEquals("v3", tbl.getProperty("k1")); assertEquals(PropUtil.fromArgs("k1", "v3"), tbl.getProperties()); tbl.setProperty("k3", "xxx"); assertEquals("xxx", tbl.getProperty("k3")); assertEquals(PropUtil.fromArgs("k1", "v3", "k3", "xxx"), tbl.getProperties()); } public void testColDescMap() { List cols = ListUtil.list ( new ColumnDescriptor("col1", "Column 1 Title", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("col2", "Column 2 Title", ColumnDescriptor.TYPE_INT, "Column 2 footnote"), new ColumnDescriptor("col3", "Column 2 Title", ColumnDescriptor.TYPE_STRING) { { comparator = new MyComparator(); } } ); table.setColumnDescriptors(cols); Map expMap = new HashMap(); expMap.put("col1", cols.get(0)); expMap.put("col2", cols.get(1)); expMap.put("col3", cols.get(2)); assertEquals(expMap, table.getColumnDescriptorMap()); } public void testFilterColDescs() { List cols = ListUtil.list ( new ColumnDescriptor("col1", "Column 1 Title", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("col2", "Column 2 Title", ColumnDescriptor.TYPE_INT, "Column 2 footnote"), new ColumnDescriptor("col3", "Column 2 Title", ColumnDescriptor.TYPE_STRING) ); List def = ListUtil.list("col1", "col3"); String defstr = "col1;col3"; assertEquals(cols, table.filterColDescs(cols, null, null)); assertEquals(ListUtil.list(cols.get(0), cols.get(2)), table.filterColDescs(cols, def)); assertEquals(ListUtil.list(cols.get(0), cols.get(2)), table.filterColDescs(cols, defstr)); table.setColumnDescriptors(cols); assertEquals(ListUtil.list(cols.get(0), cols.get(1), cols.get(2)), table.getColumnDescriptors()); table.setColumnDescriptors(cols, def); assertEquals(ListUtil.list(cols.get(0), cols.get(2)), table.getColumnDescriptors()); table.setProperty("columns", "col3;col2"); assertEquals(ListUtil.list(cols.get(2), cols.get(1)), table.filterColDescs(cols, def)); assertEquals(ListUtil.list(cols.get(2), cols.get(1)), table.filterColDescs(cols, defstr)); table.setColumnDescriptors(cols); assertEquals(ListUtil.list(cols.get(2), cols.get(1)), table.getColumnDescriptors()); } public void testFilterColDescsNegated() { List cols = ListUtil.list ( new ColumnDescriptor("col1", "Column 1 Title", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("col2", "Column 2 Title", ColumnDescriptor.TYPE_INT, "Column 2 footnote"), new ColumnDescriptor("col3", "Column 2 Title", ColumnDescriptor.TYPE_STRING) ); List def = ListUtil.list("col1", "col3"); table.setColumnDescriptors(cols); assertEquals(ListUtil.list(cols.get(0), cols.get(1), cols.get(2)), table.getColumnDescriptors()); table.setProperty("columns", "-"); assertEquals(ListUtil.list(cols.get(0), cols.get(1), cols.get(2)), table.filterColDescs(cols, def)); table.setProperty("columns", "-col3;col2"); assertEquals(ListUtil.list(cols.get(0)), table.filterColDescs(cols, def)); table.setProperty("columns", "-col3"); table.setColumnDescriptors(cols); assertEquals(ListUtil.list(cols.get(0), cols.get(1)), table.getColumnDescriptors()); } public void testIsIncludeColumn() { List cols = ListUtil.list ( new ColumnDescriptor("col1", "Column 1 Title", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("col2", "Column 2 Title", ColumnDescriptor.TYPE_INT, "Column 2 footnote") ); table.setColumnDescriptors(cols); assertTrue(table.isIncludeColumn("col1")); assertTrue(table.isIncludeColumn("col2")); assertFalse(table.isIncludeColumn("col3")); } Map testMap(Object key, Object val) { Map map = new HashMap(); map.put(key, val); return map; } Map testMap(Object k1, Object v1, Object k2, Object v2) { Map map = testMap(k1, v1); map.put(k2, v2); return map; } public void testSortRule() throws Exception { MyComparator cmpr = new MyComparator(); List cols = ListUtil.list(new ColumnDescriptor("a", "Column 1 Title", ColumnDescriptor.TYPE_INT) .setComparator(cmpr), new ColumnDescriptor("b", "Column 2 Title", ColumnDescriptor.TYPE_STRING) ); table.setColumnDescriptors(cols); Map colMap = table.getColumnDescriptorMap(); StatusTable.SortRule rule1 = new StatusTable.SortRule("a", true); assertEquals(-1, rule1.getColumnType()); assertNull(rule1.getComparator()); rule1.inferColumnType(colMap); assertEquals(ColumnDescriptor.TYPE_INT, rule1.getColumnType()); assertSame(cmpr, rule1.getComparator()); assertTrue(rule1.compare("a", "b") < 0); cmpr.setReverse(true); assertTrue(rule1.compare("a", "b") > 0); cmpr.setReverse(false); StatusTable.SortRule rule2 = new StatusTable.SortRule("b", true); assertEquals(-1, rule2.getColumnType()); assertNull(rule2.getComparator()); rule2.inferColumnType(colMap); assertEquals(ColumnDescriptor.TYPE_STRING, rule2.getColumnType()); assertNull(rule2.getComparator()); assertEquals(0, rule2.compare("aaa", "aaa")); assertTrue(rule2.compare("aaa", "bbb") < 0); assertTrue(rule2.compare("bbb", "aaa") > 0); assertTrue(rule2.compare(null, "bbb") < 0); assertTrue(rule2.compare("bbb", null) > 0); StatusTable.SortRule rule3 = new StatusTable.SortRule("b", false); rule3.inferColumnType(colMap); assertTrue(rule3.compare("aaa", "bbb") > 0); assertTrue(rule3.compare("bbb", "aaa") < 0); StatusTable.SortRule rule4 = new StatusTable.SortRule("b", cmpr); assertTrue(rule4.compare("aaa", "bbb") < 0); assertTrue(rule4.compare("bbb", "aaa") > 0); cmpr.setReverse(true); assertTrue(rule4.compare("aaa", "bbb") > 0); assertTrue(rule4.compare("bbb", "aaa") < 0); cmpr.setReverse(false); StatusTable.SortRule rule5 = new StatusTable.SortRule("b", cmpr, false); assertTrue(rule5.compare("aaa", "bbb") > 0); assertTrue(rule5.compare("bbb", "aaa") < 0); cmpr.setReverse(true); assertTrue(rule5.compare("aaa", "bbb") < 0); assertTrue(rule5.compare("bbb", "aaa") > 0); cmpr.setReverse(false); } public void testSortRuleComparator() throws Exception { List cols = ListUtil.list( new ColumnDescriptor("a", "Column 1 Title", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("b", "Column 2 Title", ColumnDescriptor.TYPE_IP_ADDRESS) ); table.setColumnDescriptors(cols); Map colMap = table.getColumnDescriptorMap(); Map r1 = testMap("a", "a1", "b", IPAddr.getByName("2.2.2.2")); Map r2 = testMap("a", "a2", "b", IPAddr.getByName("1.1.1.1")); Map r3 = testMap("a", "a2", "b", IPAddr.getByName("1.1.1.1")); Map r4 = testMap("a", ListUtil.list("a2", "b"), "b", IPAddr.getByName("2.2.2.2")); List rules1 = ListUtil.list(new StatusTable.SortRule("a", true)); List rules2 = ListUtil.list(new StatusTable.SortRule("a", true), new StatusTable.SortRule("b", true)); List rules3 = ListUtil.list(new StatusTable.SortRule("b", true), new StatusTable.SortRule("a", true)); StatusTable.SortRuleComparator src; src = new StatusTable.SortRuleComparator(rules1, colMap); assertEquals(0, src.compare(r1, r1)); assertTrue(src.compare(r1, r2) < 0); assertTrue(src.compare(r2, r1) > 0); assertEquals(0, src.compare(r2, r3)); assertTrue(src.compare(r1, r4) < 0); src = new StatusTable.SortRuleComparator(rules2, colMap); // check that inferColumnType was invoked on the rules StatusTable.SortRule iprule = (StatusTable.SortRule)rules2.get(1); assertEquals(ColumnDescriptor.TYPE_IP_ADDRESS, iprule.getColumnType()); assertEquals(0, src.compare(r1, r1)); assertTrue(src.compare(r1, r2) < 0); assertTrue(src.compare(r2, r1) > 0); assertEquals(0, src.compare(r2, r3)); assertTrue(src.compare(r2, r4) < 0); src = new StatusTable.SortRuleComparator(rules3, colMap); assertEquals(0, src.compare(r1, r1)); assertTrue(src.compare(r1, r2) > 0); assertTrue(src.compare(r2, r1) < 0); assertEquals(0, src.compare(r2, r3)); assertTrue(src.compare(r2, r4) < 0); } class MyComparator implements Comparator { private boolean reverse = false; public int compare(Object o1, Object o2) { int res = ((Comparable)o1).compareTo((Comparable)o2); return reverse ? -res : res; } void setReverse(boolean reverse) { this.reverse = reverse; } } public void testEmbeddedValue() { Integer val = new Integer(3); StatusTable.DisplayedValue dval = new StatusTable.DisplayedValue(val); StatusTable.Reference rval = new StatusTable.Reference(val, "foo", "bar"); StatusTable.SrvLink lval = new StatusTable.SrvLink(val, srvDescr, args); // should be able to embed DisplayedValue in Reference or SrvLink new StatusTable.Reference(dval, "foo", "bar"); new StatusTable.SrvLink(dval, srvDescr, args); try { new StatusTable.DisplayedValue(rval); fail("Shouldn't be able to embed Reference in DisplayedValue"); } catch (IllegalArgumentException e) { } try { new StatusTable.DisplayedValue(lval); fail("Shouldn't be able to embed SrvLink in DisplayedValue"); } catch (IllegalArgumentException e) { } try { new StatusTable.DisplayedValue(dval); fail("Shouldn't be able to embed DisplayedValue in DisplayedValue"); } catch (IllegalArgumentException e) { } try { new StatusTable.Reference(rval, "foo", "bar"); fail("Shouldn't be able to embed Reference in Reference"); } catch (IllegalArgumentException e) { } try { new StatusTable.SrvLink(lval, srvDescr, args); fail("Shouldn't be able to embed SrvLink in SrvLink"); } catch (IllegalArgumentException e) { } try { new StatusTable.Reference(lval, "foo", "bar"); fail("Shouldn't be able to embed SrvLink in Reference"); } catch (IllegalArgumentException e) { } try { new StatusTable.SrvLink(rval, srvDescr, args); fail("Shouldn't be able to embed Reference in SrvLink"); } catch (IllegalArgumentException e) { } } public void testReferenceGetActualValue() { Integer val = new Integer(3); StatusTable.DisplayedValue dval = new StatusTable.DisplayedValue(val); StatusTable.Reference rval = new StatusTable.Reference(val, "foo", "bar"); StatusTable.Reference rdval = new StatusTable.Reference(dval, "foo", "bar"); assertEquals(val, StatusTable.getActualValue(val)); assertEquals(val, StatusTable.getActualValue(dval)); assertEquals(val, StatusTable.getActualValue(rval)); assertEquals(val, StatusTable.getActualValue(rdval)); } public void testReferenceProps() { StatusTable.Reference ref = new StatusTable.Reference("C", "blah", null); assertNull(ref.getProperties()); ref.setProperty("foo", "bar"); assertEquals("bar", ref.getProperties().getProperty("foo")); } public void testReferenceEquals() { StatusTable.Reference ref = new StatusTable.Reference("C", "blah", null); assertFalse(ref.equals("blah")); assertTrue(ref.equals(new StatusTable.Reference("C", "blah", null))); assertFalse(ref.equals(new StatusTable.Reference("D", "blah", null))); assertFalse(ref.equals(new StatusTable.Reference("C", "blah2", null))); assertFalse(ref.equals(new StatusTable.Reference("C", "blah", "key"))); ref = new StatusTable.Reference("C", "blah", "key1"); assertTrue(ref.equals(new StatusTable.Reference("C", "blah", "key1"))); assertFalse(ref.equals(new StatusTable.Reference("C", "blah", "key"))); } public void testReferencePeer() throws Exception { PeerIdentity pid1 = new MockPeerIdentity("TCP:[1.2.3.4]:1111"); PeerIdentity pid2 = new MockPeerIdentity("TCP:[1.2.3.4]:2222"); StatusTable.Reference ref1 = new StatusTable.Reference("C", pid1, "blah", null); StatusTable.Reference ref2 = new StatusTable.Reference("C", pid2, "blah", null); StatusTable.Reference ref3 = new StatusTable.Reference("C", pid1, "blah", null); assertTrue(ref1.equals(ref1)); assertTrue(ref1.equals(ref3)); assertFalse(ref1.equals(ref2)); assertFalse(ref1.equals(new StatusTable.Reference("C", "blah", null))); } public void testSrvLinkGetActualValue() { Integer val = new Integer(3); StatusTable.DisplayedValue dval = new StatusTable.DisplayedValue(val); StatusTable.SrvLink lval = new StatusTable.SrvLink(val, srvDescr, args); StatusTable.SrvLink ldval = new StatusTable.SrvLink(dval, srvDescr, args); assertEquals(val, StatusTable.getActualValue(val)); assertEquals(val, StatusTable.getActualValue(dval)); assertEquals(val, StatusTable.getActualValue(lval)); assertEquals(val, StatusTable.getActualValue(ldval)); } public void testSrvLink() { StatusTable.SrvLink lnk = new StatusTable.SrvLink("C", srvDescr, args); assertEquals("C", lnk.getValue()); assertEquals(srvDescr, lnk.getServletDescr()); assertEquals(args, lnk.getArgs()); } public void testSrvLinkEquals() { StatusTable.SrvLink lnk = new StatusTable.SrvLink("C", srvDescr, args); assertFalse(lnk.equals("blah")); assertTrue(lnk.equals(new StatusTable.SrvLink("C", srvDescr, args))); assertFalse(lnk.equals(new StatusTable.SrvLink("D", srvDescr, args))); assertFalse(lnk.equals(new StatusTable.SrvLink("C", srvDescr, null))); assertFalse(lnk.equals(new StatusTable.SrvLink("C", new ServletDescr("test", LockssServlet.class, "bar"), args))); assertFalse(lnk.equals(new StatusTable.SrvLink("C", srvDescr, new Properties()))); } public void testSummaryInfo() { StatusTable.SummaryInfo si = new StatusTable.SummaryInfo("Foo", ColumnDescriptor.TYPE_STRING, "val"); assertEquals("Foo", si.getTitle()); assertEquals(ColumnDescriptor.TYPE_STRING, si.getType()); assertEquals("val", si.getValue()); si = new StatusTable.SummaryInfo("bar", ColumnDescriptor.TYPE_INT, 23); assertEquals("bar", si.getTitle()); assertEquals(ColumnDescriptor.TYPE_INT, si.getType()); assertEquals(new Integer(23), si.getValue()); } }
/** * (TMS) */ package com.lhjz.portal.controller; import com.google.common.collect.Lists; import com.lhjz.portal.base.BaseController; import com.lhjz.portal.component.MailSender; import com.lhjz.portal.constant.SysConstant; import com.lhjz.portal.entity.security.Authority; import com.lhjz.portal.entity.security.AuthorityId; import com.lhjz.portal.entity.security.Group; import com.lhjz.portal.entity.security.GroupMember; import com.lhjz.portal.entity.security.User; import com.lhjz.portal.model.Mail; import com.lhjz.portal.model.MailAddr; import com.lhjz.portal.model.OnlineUser; import com.lhjz.portal.model.RespBody; import com.lhjz.portal.pojo.Enum.Action; import com.lhjz.portal.pojo.Enum.OnlineStatus; import com.lhjz.portal.pojo.Enum.Role; import com.lhjz.portal.pojo.Enum.Status; import com.lhjz.portal.pojo.Enum.Target; import com.lhjz.portal.pojo.GroupForm; import com.lhjz.portal.pojo.UserExtraForm; import com.lhjz.portal.pojo.UserForm; import com.lhjz.portal.repository.AuthorityRepository; import com.lhjz.portal.repository.GroupMemberRepository; import com.lhjz.portal.repository.GroupRepository; import com.lhjz.portal.service.ChannelService; import com.lhjz.portal.util.DateUtil; import com.lhjz.portal.util.MapUtil; import com.lhjz.portal.util.StringUtil; import com.lhjz.portal.util.TemplateUtil; import com.lhjz.portal.util.WebUtil; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.CacheManager; import org.springframework.security.access.annotation.Secured; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.security.Principal; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author xi * @date 2015328 1:19:05 */ @Controller @RequestMapping("admin/user") public class UserController extends BaseController { public static final String TRUE = "true"; static Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired AuthorityRepository authorityRepository; @Autowired PasswordEncoder passwordEncoder; @Autowired MailSender mailSender; @Autowired GroupRepository groupRepository; @Autowired GroupMemberRepository groupMemberRepository; @Autowired ChannelService channelService; @Autowired CacheManager cacheManager; @Value("${tms.base.url}") private String baseUrl; String loginAction = "admin/login"; private RespBody createUser(String role, String baseURL, UserForm userForm) { String username = StringUtils.trim(userForm.getUsername()); if (userRepository.exists(username)) { logger.error(", ID: {}", username); return RespBody.failed("!"); } // @all if ("all".equalsIgnoreCase(userForm.getUsername())) { return RespBody.failed(",!"); } // save username and password final User user = new User(); user.setUsername(username); user.setPassword(passwordEncoder.encode(StringUtils.trim(userForm.getPassword()))); user.setEnabled(userForm.getEnabled()); user.setCreateDate(new Date()); user.setName(StringUtils.trim(userForm.getName())); user.setMails(StringUtils.trim(userForm.getMail())); user.setCreator(WebUtil.getUsername()); User user2 = userRepository.saveAndFlush(user); log(Action.Create, Target.User, user.getUsername()); // save default authority `ROLE_USER` Authority authority = new Authority(); authority.setId(new AuthorityId(username, Role.ROLE_USER.name())); authorityRepository.saveAndFlush(authority); log(Action.Create, Target.Authority, authority.getId().toString()); if ("admin".equalsIgnoreCase(role)) { Authority authority2 = new Authority(); authority2.setId(new AuthorityId(username, Role.ROLE_ADMIN.name())); authorityRepository.saveAndFlush(authority2); log(Action.Create, Target.Authority, authority2.getId().toString()); } channelService.joinAll(user2); final String userRole = role; final String href = baseURL.endsWith("/") ? baseURL : baseURL + "/"; final UserForm userForm2 = userForm; final String loginUrl = baseURL + loginAction + "?username=" + userForm.getUsername() + "&password=" + userForm.getPassword(); try { mailSender .sendHtmlByQueue(String.format("TMS-_%s", DateUtil.format(new Date(), DateUtil.FORMAT7)), TemplateUtil.process("templates/mail/user-create", MapUtil.objArr2Map("user", userForm2, "userRole", userRole, "href", href, "loginUrl", loginUrl, "baseUrl", baseUrl)), new MailAddr(user.getMails(), user.getName())); } catch (Exception e) { e.printStackTrace(); } return RespBody.succeed(user.getUsername()); } @RequestMapping(value = "batchCreate", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN"}) public RespBody batchCreate(@RequestParam("baseURL") String baseURL, @RequestParam("data") String data) { // test,88888,user,,test@test.com,true String[] lines = data.split("\n"); int cnt = 0; for (String line : lines) { String[] infos = line.trim().split(","); if (infos.length >= 5) { UserForm userForm = new UserForm(); userForm.setEnabled(true); userForm.setMail(StringUtils.trim(infos[4])); userForm.setName(StringUtils.trim(infos[3])); userForm.setPassword(StringUtils.trim(infos[1])); userForm.setUsername(StringUtils.trim(infos[0])); userForm.setEnabled(TRUE.equalsIgnoreCase(StringUtils.trim(infos[5]))); RespBody respBody = createUser(StringUtils.trim(infos[2]), baseURL, userForm); if (respBody.isSuccess()) { cnt = cnt + 1; } } } if (cnt == 0) { return RespBody.failed(); } return RespBody.succeed(); } @RequestMapping(value = "batchMail", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_SUPER", "ROLE_ADMIN", "ROLE_USER"}) public RespBody batchMail(@RequestParam("baseURL") String baseURL, @RequestParam("users") String users, @RequestParam("title") String title, @RequestParam("content") String content) { if (StringUtil.isEmpty(users)) { return RespBody.failed("!"); } if (StringUtil.isEmpty(title)) { return RespBody.failed("!"); } if (StringUtil.isEmpty(content)) { return RespBody.failed("!"); } String[] usernames = users.split(","); List<User> users2 = userRepository.findAll(); final Mail mail = Mail.instance(); for (String username : usernames) { for (User user : users2) { if (user.getUsername().equals(username)) { mail.addUsers(user); break; } } } final User loginUser = getLoginUser(); final String href = baseURL; final String title1 = title; final String content1 = content; try { mailSender.sendHtmlByQueue(String.format("TMS-_%s", DateUtil.format(new Date(), DateUtil.FORMAT7)), TemplateUtil.process("templates/mail/mail-msg", MapUtil.objArr2Map("user", loginUser, "date", new Date(), "href", href, "title", title1, "content", content1)), getLoginUserName(loginUser), mail.get()); } catch (Exception e) { e.printStackTrace(); } return RespBody.succeed(); } @RequestMapping(value = "save", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN"}) public RespBody save(@RequestParam("role") String role, @RequestParam("baseURL") String baseURL, @Valid UserForm userForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage) .collect(Collectors.joining("<br/>"))); } return createUser(role, baseURL, userForm); } @RequestMapping(value = "update", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN"}) public RespBody update(@RequestParam(value = "role", required = false) String role, @Valid UserForm userForm, BindingResult bindingResult) { if (WebUtil.isRememberMeAuthenticated()) { return RespBody.failed("[],,!"); } if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage) .collect(Collectors.joining("<br/>"))); } User user = userRepository.findOne(userForm.getUsername()); if (user == null) { logger.error("! ID: {}", userForm.getUsername()); return RespBody.failed("!"); } if (Boolean.TRUE.equals(user.getLocked()) && !isSuper()) { return RespBody.failed(",!"); } if (StringUtil.isNotEmpty(userForm.getPassword())) { if (userForm.getPassword().length() < 6) { logger.error(", ID: {}", userForm.getUsername()); return RespBody.failed("!"); } user.setPassword(passwordEncoder.encode(userForm.getPassword())); } if (userForm.getEnabled() != null && user.getStatus() != Status.Bultin) { user.setEnabled(userForm.getEnabled()); } if (userForm.getMail() != null) { user.setMails(userForm.getMail()); } if (userForm.getName() != null) { user.setName(userForm.getName()); } if (StringUtil.isNotEmpty(role)) { Set<Authority> authorities = user.getAuthorities(); authorities.stream().forEach(auth -> auth.setUser(null) ); authorityRepository.delete(authorities); authorityRepository.flush(); user.getAuthorities().clear(); // add role_user Authority authority = new Authority(); authority.setId(new AuthorityId(StringUtils.trim(userForm.getUsername()), Role.ROLE_USER.name())); authority.setUser(user); Authority saveAndFlush = authorityRepository.saveAndFlush(authority); user.getAuthorities().add(saveAndFlush); // add role_user if ("admin".equalsIgnoreCase(role)) { Authority authority2 = new Authority(); authority2.setId(new AuthorityId(StringUtils.trim(userForm.getUsername()), Role.ROLE_ADMIN.name())); authority2.setUser(user); Authority saveAndFlush2 = authorityRepository.saveAndFlush(authority2); user.getAuthorities().add(saveAndFlush2); } } userRepository.saveAndFlush(user); log(Action.Update, Target.User, user.getUsername()); return RespBody.succeed(user.getUsername()); } @RequestMapping(value = "update2", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_USER"}) public RespBody update2(@Valid UserForm userForm, BindingResult bindingResult) { if (WebUtil.isRememberMeAuthenticated()) { return RespBody.failed("[],,!"); } if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage) .collect(Collectors.joining("<br/>"))); } User user = userRepository.findOne(userForm.getUsername()); if (user == null) { logger.error("! ID: {}", userForm.getUsername()); return RespBody.failed("!"); } if (!isSuperOrCreator(user.getCreator()) && !WebUtil.getUsername().equals(userForm.getUsername())) { logger.error("!"); return RespBody.failed("!"); } if (Boolean.TRUE.equals(user.getLocked()) && !isSuper()) { return RespBody.failed(",!"); } if (StringUtil.isNotEmpty(userForm.getPassword())) { if (userForm.getPassword().length() < 6) { logger.error(", ID: {}", userForm.getUsername()); return RespBody.failed("!"); } user.setPassword(passwordEncoder.encode(userForm.getPassword())); } if (userForm.getEnabled() != null && user.getStatus() != Status.Bultin) { user.setEnabled(userForm.getEnabled()); } if (userForm.getMail() != null) { user.setMails(userForm.getMail()); } if (userForm.getName() != null) { user.setName(userForm.getName()); } userRepository.saveAndFlush(user); log(Action.Update, Target.User, user.getUsername()); return RespBody.succeed(user.getUsername()); } @RequestMapping(value = "delete", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN"}) public RespBody delete(@RequestParam("username") String username) { if (WebUtil.isRememberMeAuthenticated()) { return RespBody.failed("[],,!"); } User user = userRepository.findOne(username); if (user == null) { logger.error("! ID: {}", username); return RespBody.failed("!"); } if (user.getStatus() == Status.Bultin) { logger.error(",! ID: {}", username); return RespBody.failed(",!"); } user.setEnabled(false); user.setStatus(Status.Deleted); userRepository.saveAndFlush(user); log(Action.Delete, Target.User, user.getUsername(), user); return RespBody.succeed(username); } @RequestMapping(value = "get", method = RequestMethod.GET) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody get(@RequestParam("username") String username) { User user = userRepository.findOne(username); if (user == null) { logger.error("! ID: {}", username); return RespBody.failed("!"); } List<GroupMember> gms = groupMemberRepository.findByUsername(username); List<String> gns = gms.stream().map(gm -> gm.getGroup().getGroupName() ).collect(Collectors.toList()); setOnlineStatus(user); return RespBody.succeed(user).addMsg(gns); } @RequestMapping(value = "loginUser", method = RequestMethod.GET) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody loginUser() { return RespBody.succeed(getLoginUser()); } @RequestMapping(value = "all", method = RequestMethod.GET) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody getAllUsers(@RequestParam(value = "enabled", required = false) Boolean enabled) { List<User> users = null; if (enabled != null) { users = userRepository.findByEnabled(enabled); } else { users = userRepository.findAll(); } users.forEach(this::setOnlineStatus); return RespBody.succeed(users); } @RequestMapping(value = "online", method = RequestMethod.GET) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody getOnlineUsers() { List<OnlineUser> users = Lists.newArrayList(); Set<String> usernames = new HashSet<>(); try { @SuppressWarnings("unchecked") ConcurrentHashMap<Object, Object> cache = (ConcurrentHashMap<Object, Object>) cacheManager .getCache(SysConstant.ONLINE_USERS).getNativeCache(); cache.forEachKey(1, key -> { String username = String.valueOf(key).split("@")[0]; if (!usernames.contains(username)) { usernames.add(username); users.add(new OnlineUser(username, (Date) cacheManager.getCache(SysConstant.ONLINE_USERS).get(key).get())); } }); } catch (Exception e) { logger.error(e.getMessage(), e); } return RespBody.succeed(users); } private void setOnlineStatus(User user) { Object obj = online(user); if (obj != null) { user.setOnlineStatus(OnlineStatus.Online); user.setOnlineDate((Date) obj); } else { if (user.getUsername().equals(WebUtil.getUsername())) { user.setOnlineStatus(OnlineStatus.Online); user.setOnlineDate(new Date()); } } } private Object online(User user) { final List<Object> res = new ArrayList<>(); try { @SuppressWarnings("unchecked") ConcurrentHashMap<Object, Object> cache = (ConcurrentHashMap<Object, Object>) cacheManager .getCache(SysConstant.ONLINE_USERS).getNativeCache(); cache.forEachKey(1, key -> { String username = String.valueOf(key).split("@")[0]; if (username.equals(user.getUsername())) { res.add(cache.get(key)); } }); } catch (Exception e) { logger.error(e.getMessage(), e); } return res.size() > 0 ? res.get(0) : null; } @RequestMapping(value = "getGroup", method = RequestMethod.GET) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody getGroup(@RequestParam("groupName") String groupName) { List<Group> groups = groupRepository.findByGroupName(groupName); if (groups.size() == 0) { logger.error("! ID: {}", groupName); return RespBody.failed("!"); } return RespBody.succeed(groups.get(0)); } @RequestMapping(value = "groups", method = RequestMethod.GET) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody getGroups() { List<Group> groups = groupRepository.findAll(); return RespBody.succeed(groups); } @RequestMapping(value = "groupMemembers", method = RequestMethod.GET) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody groupMemembers(@RequestParam("groupId") Long groupId) { Group group = groupRepository.findOne(groupId); if (group == null) { logger.error("! ID: {}", groupId); return RespBody.failed("!"); } List<GroupMember> groupMembers = groupMemberRepository.findByGroup(group); return RespBody.succeed(groupMembers); } @RequestMapping(value = "createGroup", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody createGroup(@Valid GroupForm groupForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage) .collect(Collectors.joining("<br/>"))); } List<Group> groups = groupRepository.findByGroupName(groupForm.getGroupName()); if (groups.size() > 0) { return RespBody.failed("!"); } Group group = new Group(groupForm.getGroupName()); group.setCreateDate(new Date()); group.setCreator(WebUtil.getUsername()); group.setStatus(Status.New); Group group2 = groupRepository.saveAndFlush(group); return RespBody.succeed(group2); } @RequestMapping(value = "updateGroup", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody updateGroup(@RequestParam("groupId") Long groupId, @RequestParam("groupName") String groupName) { Group group = groupRepository.findOne(groupId); if (group == null) { logger.error("! ID: {}", groupId); return RespBody.failed("!"); } group.setUpdateDate(new Date()); group.setUpdater(WebUtil.getUsername()); group.setStatus(Status.Updated); group.setGroupName(groupName); Group group2 = groupRepository.saveAndFlush(group); return RespBody.succeed(group2); } @RequestMapping(value = "deleteGroup", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody deleteGroup(@RequestParam("groupId") Long groupId) { Group group = groupRepository.findOne(groupId); if (group == null) { logger.error("! ID: {}", groupId); return RespBody.failed("!"); } List<GroupMember> groupMembers = groupMemberRepository.findByGroup(group); groupMemberRepository.deleteInBatch(groupMembers); groupMemberRepository.flush(); groupRepository.delete(group); groupRepository.flush(); return RespBody.succeed(groupId); } @RequestMapping(value = "addGroupMembers", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody addGroupMembers(@RequestParam("groupId") Long groupId, @RequestParam("usernames") String usernames) { Group group = groupRepository.findOne(groupId); if (group == null) { logger.error("! ID: {}", groupId); return RespBody.failed("!"); } String[] usernameArr = usernames.split(","); List<GroupMember> groupMembers = new ArrayList<>(); Stream.of(usernameArr).forEach(un -> { List<GroupMember> gms = groupMemberRepository.findByGroupAndUsername(group, un); if (gms.size() == 0) { GroupMember gm = new GroupMember(group, un); gm.setCreateDate(new Date()); gm.setCreator(WebUtil.getUsername()); gm.setStatus(Status.New); groupMembers.add(gm); } }); List<GroupMember> groupMembers2 = groupMemberRepository.save(groupMembers); groupMemberRepository.flush(); return RespBody.succeed(groupMembers2); } @RequestMapping(value = "deleteGroupMembers", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody deleteGroupMembers(@RequestParam("groupId") Long groupId, @RequestParam("usernames") String usernames) { Group group = groupRepository.findOne(groupId); if (group == null) { logger.error("! ID: {}", groupId); return RespBody.failed("!"); } String[] usernameArr = usernames.split(","); List<GroupMember> groupMembers = new ArrayList<>(); Stream.of(usernameArr).forEach(un -> { List<GroupMember> gms = groupMemberRepository.findByGroupAndUsername(group, un); groupMembers.addAll(gms); }); groupMemberRepository.deleteInBatch(groupMembers); groupMemberRepository.flush(); return RespBody.succeed(); } @RequestMapping(value = "updateGroupMembers", method = RequestMethod.POST) @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody updateGroupMembers(@RequestParam("groupId") Long groupId, @RequestParam("usernames") String usernames) { Group group = groupRepository.findOne(groupId); if (group == null) { logger.error("! ID: {}", groupId); return RespBody.failed("!"); } List<GroupMember> groupMembers2 = groupMemberRepository.findByGroup(group); groupMemberRepository.deleteInBatch(groupMembers2); groupMemberRepository.flush(); String[] usernameArr = usernames.split(","); List<GroupMember> groupMembers = new ArrayList<>(); Stream.of(usernameArr).forEach(un -> { List<GroupMember> gms = groupMemberRepository.findByGroupAndUsername(group, un); if (gms.size() == 0) { GroupMember gm = new GroupMember(group, un); gm.setCreateDate(new Date()); gm.setCreator(WebUtil.getUsername()); gm.setStatus(Status.New); groupMembers.add(gm); } }); List<GroupMember> groupMembers3 = groupMemberRepository.save(groupMembers); groupMemberRepository.flush(); return RespBody.succeed(groupMembers3); } @PostMapping("extra/update") @ResponseBody @Secured({"ROLE_ADMIN", "ROLE_USER"}) public RespBody updateExtra(@Valid UserExtraForm userExtraForm, BindingResult bindingResult) { if (WebUtil.isRememberMeAuthenticated()) { return RespBody.failed("[],,!"); } if (!isSuperOrCreator(WebUtil.getUsername()) && !WebUtil.getUsername().equals(userExtraForm.getUsername())) { logger.error("!"); return RespBody.failed("!"); } if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage) .collect(Collectors.joining("<br/>"))); } User user = userRepository.findOne(userExtraForm.getUsername()); if (userExtraForm.getPhone() != null) { user.setPhone(userExtraForm.getPhone()); } if (userExtraForm.getMobile() != null) { user.setMobile(userExtraForm.getMobile()); } if (userExtraForm.getPlace() != null) { user.setPlace(userExtraForm.getPlace()); } if (userExtraForm.getLevel() != null) { user.setLevel(userExtraForm.getLevel()); } if (userExtraForm.getHobby() != null) { user.setHobby(userExtraForm.getHobby()); } if (userExtraForm.getIntroduce() != null) { user.setIntroduce(userExtraForm.getIntroduce()); } User user2 = userRepository.saveAndFlush(user); return RespBody.succeed(user2); } }
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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 com.microsoft.graph.http; import com.google.common.annotations.VisibleForTesting; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.httpcore.middlewareoption.RedirectOptions; import com.microsoft.graph.httpcore.middlewareoption.RetryOptions; import com.microsoft.graph.logger.ILogger; import com.microsoft.graph.logger.LoggerLevel; import com.microsoft.graph.options.HeaderOption; import com.microsoft.graph.serializer.ISerializer; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Scanner; import javax.annotation.Nonnull; import javax.annotation.Nullable; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okio.BufferedSink; import static com.microsoft.graph.httpcore.middlewareoption.RedirectOptions.DEFAULT_MAX_REDIRECTS; import static com.microsoft.graph.httpcore.middlewareoption.RedirectOptions.DEFAULT_SHOULD_REDIRECT; import static com.microsoft.graph.httpcore.middlewareoption.RetryOptions.DEFAULT_DELAY; import static com.microsoft.graph.httpcore.middlewareoption.RetryOptions.DEFAULT_MAX_RETRIES; import static com.microsoft.graph.httpcore.middlewareoption.RetryOptions.DEFAULT_SHOULD_RETRY; /** * HTTP provider based off of OkHttp and msgraph-sdk-java-core library */ public class CoreHttpProvider implements IHttpProvider<Request> { /** * The content type header */ private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; /** * The encoding type for getBytes */ private static final Charset JSON_ENCODING = StandardCharsets.UTF_8; /** * The content type for JSON responses */ private static final String JSON_CONTENT_TYPE = "application/json"; /** * The binary content type header's value */ private static final String BINARY_CONTENT_TYPE = "application/octet-stream"; /** * The serializer */ private final ISerializer serializer; /** * The logger */ private final ILogger logger; /** * The OkHttpClient that handles all requests */ private OkHttpClient corehttpClient; /** * Creates the CoreHttpProvider * * @param serializer the serializer * @param logger the logger for diagnostic information * @param httpClient the client to send http requests with */ public CoreHttpProvider(@Nonnull final ISerializer serializer, @Nonnull final ILogger logger, @Nonnull final OkHttpClient httpClient) { Objects.requireNonNull(logger, "parameter logger cannot be null"); Objects.requireNonNull(serializer, "parameter serializer cannot be null"); Objects.requireNonNull(httpClient, "parameter httpClient cannot be null"); this.serializer = serializer; this.logger = logger; this.corehttpClient = httpClient; } /** * Gets the serializer for this HTTP provider * * @return the serializer for this provider */ @Override @Nullable public ISerializer getSerializer() { return serializer; } /** * Sends the HTTP request asynchronously * * @param request the request description * @param serializable the object to send to the service in the body of the request * @param <Result> the type of the response object * @param <Body> the type of the object to send to the service in the body of the request * @return a future with the result */ @Override @Nonnull public <Result, Body> java.util.concurrent.CompletableFuture<Result> sendAsync(@Nonnull final IHttpRequest request, @Nonnull final Class<Result> resultClass, @Nullable final Body serializable) { Objects.requireNonNull(request, "parameter request cannot be null"); Objects.requireNonNull(resultClass, "parameter resultClass cannot be null"); return sendAsync(request, resultClass, serializable, null); } /** * Sends the HTTP request * * @param request the request description * @param resultClass the class of the response from the service * @param serializable the object to send to the service in the body of the request * @param handler the handler for stateful response * @param <Result> the expected return type return * @param <BodyType> the type of the object to send to the service in the body of the request * @param <DeserializeType> the type of the HTTP response object * @return a future with the result * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nonnull public <Result, BodyType, DeserializeType> java.util.concurrent.CompletableFuture<Result> sendAsync(@Nonnull final IHttpRequest request, @Nonnull final Class<Result> resultClass, @Nullable final BodyType serializable, @Nullable final IStatefulResponseHandler<Result, DeserializeType> handler) throws ClientException { Objects.requireNonNull(request, "parameter request cannot be null"); Objects.requireNonNull(resultClass, "parameter resultClass cannot be null"); return sendRequestAsyncInternal(request, resultClass, serializable, handler); } /** * Sends the HTTP request * * @param request the request description * @param resultClass the class of the response from the service * @param serializable the object to send to the service in the body of the request * @param <Result> the type of the response object * @param <Body> the type of the object to send to the service in the body of the request * @return the result from the request * @throws ClientException an exception occurs if the request was unable to complete for any reason */ @Override @Nullable public <Result, Body> Result send(@Nonnull final IHttpRequest request, @Nonnull final Class<Result> resultClass, @Nullable final Body serializable) throws ClientException { Objects.requireNonNull(request, "parameter request cannot be null"); Objects.requireNonNull(resultClass, "parameter resultClass cannot be null"); return send(request, resultClass, serializable, null); } /** * Sends the HTTP request * * @param request the request description * @param resultClass the class of the response from the service * @param serializable the object to send to the service in the body of the request * @param handler the handler for stateful response * @param <Result> the type of the response object * @param <Body> the type of the object to send to the service in the body of the request * @param <DeserializeType> the response handler for stateful response * @return the result from the request * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public <Result, Body, DeserializeType> Result send(@Nonnull final IHttpRequest request, @Nonnull final Class<Result> resultClass, @Nullable final Body serializable, @Nullable final IStatefulResponseHandler<Result, DeserializeType> handler) throws ClientException { Objects.requireNonNull(request, "parameter request cannot be null"); Objects.requireNonNull(resultClass, "parameter resultClass cannot be null"); return sendRequestInternal(request, resultClass, serializable, handler); } /** * Sends the HTTP request * * @param request the request description * @param resultClass the class of the response from the service * @param serializable the object to send to the service in the body of the request * @param <Result> the type of the response object * @param <Body> the type of the object to send to the service in the body of the request * @return the result from the request * @throws ClientException an exception occurs if the request was unable to complete for any reason */ @Nullable public <Result, Body> Request getHttpRequest(@Nonnull final IHttpRequest request, @Nonnull final Class<Result> resultClass, @Nullable final Body serializable) throws ClientException { Objects.requireNonNull(request, "parameter request cannot be null"); Objects.requireNonNull(resultClass, "parameter resultClass cannot be null"); final int defaultBufferSize = 4096; final URL requestUrl = request.getRequestUrl(); logger.logDebug("Starting to send request, URL " + requestUrl.toString()); // Request level middleware options final RedirectOptions redirectOptions = request.getMaxRedirects() == DEFAULT_MAX_REDIRECTS && request.getShouldRedirect().equals(DEFAULT_SHOULD_REDIRECT) ? null : new RedirectOptions(request.getMaxRedirects(), request.getShouldRedirect()); final RetryOptions retryOptions = request.getMaxRetries() == DEFAULT_MAX_RETRIES && request.getDelay() == DEFAULT_DELAY && request.getShouldRetry().equals(DEFAULT_SHOULD_RETRY) ? null : new RetryOptions(request.getShouldRetry(), request.getMaxRetries(), request.getDelay()); final Request coreHttpRequest = convertIHttpRequestToOkHttpRequest(request); Request.Builder corehttpRequestBuilder = coreHttpRequest .newBuilder(); if(redirectOptions != null) { corehttpRequestBuilder = corehttpRequestBuilder.tag(RedirectOptions.class, redirectOptions); } if(retryOptions != null) { corehttpRequestBuilder = corehttpRequestBuilder.tag(RetryOptions.class, retryOptions); } String contenttype = null; logger.logDebug("Request Method " + request.getHttpMethod().toString()); final List<HeaderOption> requestHeaders = request.getHeaders(); for(HeaderOption headerOption : requestHeaders) { if(headerOption.getName().equalsIgnoreCase(CONTENT_TYPE_HEADER_NAME)) { contenttype = headerOption.getValue().toString(); break; } } final byte[] bytesToWrite; corehttpRequestBuilder.addHeader("Accept", "*/*"); if (serializable == null) { // Send an empty body through with a POST request // This ensures that the Content-Length header is properly set if (request.getHttpMethod() == HttpMethod.POST) { bytesToWrite = new byte[0]; } else { bytesToWrite = null; } } else if (serializable instanceof byte[]) { logger.logDebug("Sending byte[] as request body"); bytesToWrite = (byte[]) serializable; // If the user hasn't specified a Content-Type for the request if (!hasHeader(requestHeaders, CONTENT_TYPE_HEADER_NAME)) { corehttpRequestBuilder.addHeader(CONTENT_TYPE_HEADER_NAME, BINARY_CONTENT_TYPE); contenttype = BINARY_CONTENT_TYPE; } } else { logger.logDebug("Sending " + serializable.getClass().getName() + " as request body"); final String serializeObject = serializer.serializeObject(serializable); if(serializeObject == null) { throw new ClientException("Error during serialization of request body, the result was null", null); } bytesToWrite = serializeObject.getBytes(JSON_ENCODING); // If the user hasn't specified a Content-Type for the request if (!hasHeader(requestHeaders, CONTENT_TYPE_HEADER_NAME)) { corehttpRequestBuilder.addHeader(CONTENT_TYPE_HEADER_NAME, JSON_CONTENT_TYPE); contenttype = JSON_CONTENT_TYPE; } } RequestBody requestBody = null; // Handle cases where we've got a body to process. if (bytesToWrite != null) { final String mediaContentType = contenttype; requestBody = new RequestBody() { @Override public long contentLength() throws IOException { return bytesToWrite.length; } @Override public void writeTo(BufferedSink sink) throws IOException { int writtenSoFar = 0; try (final OutputStream out = sink.outputStream()) { try (final BufferedOutputStream bos = new BufferedOutputStream(out)){ int toWrite; do { toWrite = Math.min(defaultBufferSize, bytesToWrite.length - writtenSoFar); bos.write(bytesToWrite, writtenSoFar, toWrite); writtenSoFar = writtenSoFar + toWrite; } while (toWrite > 0); } } } @Override public MediaType contentType() { if(mediaContentType == null || mediaContentType.isEmpty()) { return null; } else { return MediaType.parse(mediaContentType); } } }; } corehttpRequestBuilder.method(request.getHttpMethod().toString(), requestBody); return corehttpRequestBuilder.build(); } /** * Sends the HTTP request * * @param request the request description * @param resultClass the class of the response from the service * @param serializable the object to send to the service in the body of the request * @param handler the handler for stateful response * @param <Result> the type of the response object * @param <Body> the type of the object to send to the service in the body of the request * @param <DeserializeType> the response handler for stateful response * @return the result from the request * @throws ClientException an exception occurs if the request was unable to complete for any reason */ @Nonnull private <Result, Body, DeserializeType> java.util.concurrent.CompletableFuture<Result> sendRequestAsyncInternal(@Nonnull final IHttpRequest request, @Nonnull final Class<Result> resultClass, @Nullable final Body serializable, @Nullable final IStatefulResponseHandler<Result, DeserializeType> handler) throws ClientException { final Request coreHttpRequest = getHttpRequest(request, resultClass, serializable); final CoreHttpCallbackFutureWrapper wrapper = new CoreHttpCallbackFutureWrapper(); corehttpClient.newCall(coreHttpRequest).enqueue(wrapper); return wrapper.future.thenApply(r -> processResponse(r, request, resultClass, serializable, handler)); } /** * Sends the HTTP request * * @param request the request description * @param resultClass the class of the response from the service * @param serializable the object to send to the service in the body of the request * @param handler the handler for stateful response * @param <Result> the type of the response object * @param <Body> the type of the object to send to the service in the body of the request * @param <DeserializeType> the response handler for stateful response * @return the result from the request * @throws ClientException an exception occurs if the request was unable to complete for any reason */ @Nullable private <Result, Body, DeserializeType> Result sendRequestInternal(@Nonnull final IHttpRequest request, @Nonnull final Class<Result> resultClass, @Nullable final Body serializable, @Nullable final IStatefulResponseHandler<Result, DeserializeType> handler) throws ClientException { final Request coreHttpRequest = getHttpRequest(request, resultClass, serializable); try { final Response response = corehttpClient.newCall(coreHttpRequest).execute(); return processResponse(response, request, resultClass, serializable, handler); } catch(IOException ex) { throw new ClientException("Error executing the request", ex); } } @SuppressWarnings("unchecked") private <Result, Body, DeserializeType> Result processResponse(final Response response, final IHttpRequest request, final Class<Result> resultClass, final Body serializable, final IStatefulResponseHandler<Result, DeserializeType> handler) { if (response == null) return null; final ResponseBody body = response.body(); try { InputStream in = null; boolean isBinaryStreamInput = false; try { // Call being executed logger.logDebug(String.format(Locale.ROOT, "Response code %d, %s", response.code(), response.message())); if (handler != null) { logger.logDebug("StatefulResponse is handling the HTTP response."); return handler.generateResult( request, response, this.serializer, this.logger); } if (response.code() >= HttpResponseCode.HTTP_CLIENT_ERROR && body != null) { logger.logDebug("Handling error response"); in = body.byteStream(); handleErrorResponse(request, serializable, response); } final Map<String, List<String>> responseHeaders = response.headers().toMultimap(); if (response.code() == HttpResponseCode.HTTP_NOBODY || response.code() == HttpResponseCode.HTTP_NOT_MODIFIED) { logger.logDebug("Handling response with no body"); return handleEmptyResponse(responseHeaders, resultClass); } if (response.code() == HttpResponseCode.HTTP_ACCEPTED) { logger.logDebug("Handling accepted response"); return handleEmptyResponse(responseHeaders, resultClass); } if (body == null || body.contentLength() == 0) return null; in = new BufferedInputStream(body.byteStream()); final MediaType contentType = body.contentType(); if (contentType != null && contentType.subtype().contains("json") && resultClass != InputStream.class) { logger.logDebug("Response json"); return handleJsonResponse(in, responseHeaders, resultClass); } else if (resultClass == InputStream.class) { logger.logDebug("Response binary"); isBinaryStreamInput = true; return (Result) handleBinaryStream(in); } else if (contentType != null && resultClass != InputStream.class && contentType.type().contains("text") && contentType.subtype().contains("plain")) { return handleRawResponse(in, resultClass); } else { return null; } } finally { if (!isBinaryStreamInput) { try{ if (in != null) in.close(); if (body != null) body.close(); }catch(IOException e) { logger.logError(e.getMessage(), e); } response.close(); } } } catch (final GraphServiceException ex) { final boolean shouldLogVerbosely = logger.getLoggingLevel() == LoggerLevel.DEBUG; logger.logError("Graph service exception " + ex.getMessage(shouldLogVerbosely), ex); throw ex; } catch (final Exception ex) { final ClientException clientException = new ClientException("Error during http request", ex); logger.logError("Error during http request", clientException); throw clientException; } } /** * Handles the event of an error response * * @param request the request that caused the failed response * @param serializable the body of the request * @param response the original response object * @throws IOException an exception occurs if there were any problems interacting with the connection object */ private <Body> void handleErrorResponse(final IHttpRequest request, final Body serializable, final Response response) throws IOException { throw GraphServiceException.createFromResponse(request, serializable, serializer, response, logger); } /** * Handles the cause where the response is a binary stream * * @param in the input stream from the response * @return the input stream to return to the caller */ private InputStream handleBinaryStream(final InputStream in) { return in; } /** * Handles the cause where the response is a JSON object * * @param in the input stream from the response * @param responseHeaders the response header * @param clazz the class of the response object * @param <Result> the type of the response object * @return the JSON object */ private <Result> Result handleJsonResponse(final InputStream in, Map<String, List<String>> responseHeaders, final Class<Result> clazz) { if (clazz == null) { return null; } return serializer.deserializeObject(in, clazz, responseHeaders); } /** * Handles the cause where the response is a Text object * * @param in the input stream from the response * @param clazz the class of the response object * @param <Result> the type of the response object * @return the Text object */ @SuppressWarnings("unchecked") private <Result> Result handleRawResponse(final InputStream in, final Class<Result> clazz) { if (clazz == null) { return null; } final String rawText = CoreHttpProvider.streamToString(in); if(clazz == Long.class) { try { return (Result) Long.valueOf(rawText); } catch (NumberFormatException ex) { return null; } } else { return null; } } /** * Handles the case where the response body is empty * * @param responseHeaders the response headers * @param clazz the type of the response object * @return the JSON object */ private <Result> Result handleEmptyResponse(Map<String, List<String>> responseHeaders, final Class<Result> clazz) throws UnsupportedEncodingException{ //Create an empty object to attach the response headers to Result result = null; try(final InputStream in = new ByteArrayInputStream("{}".getBytes(JSON_ENCODING))) { result = handleJsonResponse(in, responseHeaders, clazz); } catch (IOException ex) { //noop we couldnt close the byte array stream we just opened and its ok } return result; } private Request convertIHttpRequestToOkHttpRequest(IHttpRequest request) { if(request != null) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(request.getRequestUrl()); for (final HeaderOption header : request.getHeaders()) { requestBuilder.addHeader(header.getName(), header.getValue().toString()); } return requestBuilder.build(); } return null; } /** * Reads in a stream and converts it into a string * * @param input the response body stream * @return the string result */ @Nullable public static String streamToString(@Nonnull final InputStream input) { Objects.requireNonNull(input, "parameter input cannot be null"); final String endOfFile = "\\A"; try (final Scanner scanner = new Scanner(input, JSON_ENCODING)) { scanner.useDelimiter(endOfFile); if (scanner.hasNext()) { return scanner.next(); } return ""; } } /** * Searches for the given header in a list of HeaderOptions * * @param headers the list of headers to search through * @param header the header name to search for (case insensitive) * @return true if the header has already been set */ @VisibleForTesting static boolean hasHeader(List<HeaderOption> headers, String header) { for (HeaderOption option : headers) { if (option.getName().equalsIgnoreCase(header)) { return true; } } return false; } /** * Gets the logger in use * * @return the logger */ @VisibleForTesting @Nullable public ILogger getLogger() { return logger; } }
package com.rationaleemotions.server; import com.google.common.base.Preconditions; import com.rationaleemotions.config.ConfigReader; import com.rationaleemotions.config.MappingInfo; import com.rationaleemotions.server.docker.DeviceInfo; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.LoggingBuildHandler; import com.spotify.docker.client.ProgressHandler; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.*; import java.util.stream.Collectors; import org.openqa.selenium.net.PortProber; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import static com.rationaleemotions.config.ConfigReader.getInstance; /** * A Helper class that facilitates interaction with a Docker Daemon. */ class DockerHelper { private interface Marker { } private static final Logger LOG = Logger.getLogger(Marker.class.getEnclosingClass().getName()); public static final String UNIX_SCHEME = "unix"; private DockerHelper() { DockerClient client = getClient(); Runtime.getRuntime().addShutdownHook(new Thread(new DockerCleanup(client))); } /** * @param id - The ID of the container that is to be cleaned up. * @throws DockerException - In case of any issues. * @throws InterruptedException - In case of any issues. */ static void killAndRemoveContainer(String id) throws DockerException, InterruptedException { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Killing the container : [" + id + "]."); } getClient().killContainer(id); getClient().removeContainer(id); } /** * @param image - The name of the image for which a docker container is to be spun off. For e.g., you could * specify the image name as <code>selenium/standalone-chrome:3.0.1</code> to download the * <code>standalone-chrome</code> image with its tag as <code>3.0.1</code> * @param isPrivileged - <code>true</code> if the container is to be run in privileged mode. * @param devices - A List of {@link DeviceInfo} objects * @return - A {@link ContainerInfo} object that represents the newly spun off container. * @throws DockerException - In case of any issues. * @throws InterruptedException - In case of any issues. */ static ContainerInfo startContainerFor(String image, boolean isPrivileged, List<DeviceInfo> devices) throws DockerException, InterruptedException { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Commencing starting of container for the image [" + image + "]."); } Preconditions.checkState("ok".equalsIgnoreCase(getClient().ping()), "Ensuring that the Docker Daemon is up and running."); DockerHelper.predownloadImagesIfRequired(); final Map<String, List<PortBinding>> portBindings = new HashMap<>(); List<PortBinding> randomPort = new ArrayList<>(); int port = PortProber.findFreePort(); String localHost = ConfigReader.getInstance().getLocalhost(); PortBinding binding = PortBinding.create(localHost, Integer.toString(port)); randomPort.add(binding); portBindings.put(ConfigReader.getInstance().getDockerImagePort(), randomPort); List<Device> deviceList = new LinkedList<>(); for (DeviceInfo each : devices) { deviceList.add(new Device() { @Override public String pathOnHost() { return each.getPathOnHost(); } @Override public String pathInContainer() { return each.getPathOnContainer(); } @Override public String cgroupPermissions() { return each.getGroupPermissions(); } }); } HostConfig.Builder hostConfigBuilder = HostConfig.builder() .binds(ConfigReader.getInstance().getVolume()) .portBindings(portBindings) .privileged(isPrivileged); if (!deviceList.isEmpty()) { hostConfigBuilder = hostConfigBuilder.devices(deviceList); } final HostConfig hostConfig = hostConfigBuilder.build(); // add environmental variables List<String> envVariables = ConfigReader.getInstance().getEnvironment() .entrySet().stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.toList()); final ContainerConfig containerConfig = ContainerConfig.builder() .hostConfig(hostConfig) .image(image).exposedPorts(ConfigReader.getInstance().getDockerImagePort()).env(envVariables) .build(); final ContainerCreation creation = getClient().createContainer(containerConfig); final String id = creation.id(); // Inspect container final com.spotify.docker.client.messages.ContainerInfo containerInfo = getClient().inspectContainer(id); if (LOG.isLoggable(Level.FINE)) { LOG.fine(String.format("Container Information %s", containerInfo)); String msg = "Checking to see if the container with id [" + id + "] and name [" + containerInfo.name() + "]..."; LOG.fine(msg); } if (!containerInfo.state().running()) { // Start container getClient().startContainer(id); if (LOG.isLoggable(Level.FINE)) { LOG.info(containerInfo.name() + " is now running."); } } else { if (LOG.isLoggable(Level.FINE)) { LOG.info(containerInfo.name() + " was already running."); } } ContainerInfo info = new ContainerInfo(id, port); if (LOG.isLoggable(Level.FINE)) { LOG.fine("******" + info + "******"); } return info; } private static void predownloadImagesIfRequired() throws DockerException, InterruptedException { DockerClient client = getClient(); LOG.warning("Commencing download of images."); Collection<MappingInfo> images = getInstance().getMapping().values(); ProgressHandler handler = new LoggingBuildHandler(); for (MappingInfo image : images) { List<Image> foundImages = client.listImages(DockerClient.ListImagesParam.byName(image.getTarget())); if (! foundImages.isEmpty()) { LOG.warning(String.format("Skipping download for Image [%s] because it's already available.", image.getTarget())); continue; } client.pull(image.getTarget(), handler); } } private static DockerClient getClient() { return DefaultDockerClient.builder().uri(getInstance().getDockerRestApiUri()).build(); } /** * A Simple POJO that represents the newly spun off container, encapsulating the container Id and the port on which * the container is running. */ public static class ContainerInfo { private int port; private String containerId; ContainerInfo(String containerId, int port) { this.port = port; this.containerId = containerId; } public int getPort() { return port; } public String getContainerId() { return containerId; } @Override public String toString() { return String.format("%s running on %d", containerId, port); } } private static class DockerCleanup implements Runnable { private DockerClient client; DockerCleanup(DockerClient client) { this.client = client; } @Override public void run() { if (client != null) { client.close(); } } } }
package com.redv.jdigg.web.openid; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.consumer.ConsumerException; import org.openid4java.consumer.ConsumerManager; import org.openid4java.discovery.Identifier; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import com.redv.jdigg.Constants; import com.redv.jdigg.domain.User; import com.redv.jdigg.service.DiggService; /** * @author <a href="mailto:zhoushuqun@gmail.com">Sutra Zhou</a> * */ public class LoginController implements Controller { private final Log log = LogFactory.getLog(this.getClass()); private DiggService diggService; private Consumer consumer; public LoginController() { ConsumerManager manager; try { manager = new ConsumerManager(); } catch (ConsumerException e) { throw new RuntimeException(e); } consumer = new Consumer(manager); } /** * @param diggService * the diggService to set */ public void setDiggService(DiggService diggService) { this.diggService = diggService; } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { if (StringUtils.equalsIgnoreCase("post", request.getMethod())) { log.debug("A http post start."); this.consumer.authRequest(request.getParameter("openid_url"), request, response); return null; } else { log.debug("A http get start."); Identifier id = this.consumer.verifyResponse(request); String redirectUrl = (String) request.getSession().getAttribute( Constants.ORIGINAL_URL); if (id != null && StringUtils.isNotEmpty(id.getIdentifier())) { User user = diggService.getUserByOpenid(id.getIdentifier()); // If user is not in our system, add it. if (user == null) { log.debug("User is not in our system, add it."); user = new User(); user.setOpenid(id.getIdentifier()); diggService.saveUser(user); } request.getSession().setAttribute("currentUser", user); if (StringUtils.isNotBlank(redirectUrl)) { response.sendRedirect(redirectUrl); } log.debug("Session setted."); response.sendRedirect(request.getContextPath() + "/"); return null; } else { return new ModelAndView("login-fail"); } } } }
package org.twuni.common.crypto.rsa; import static java.math.BigInteger.ONE; import java.math.BigInteger; import java.util.Random; import org.twuni.common.crypto.Transformer; public class RSAPrivateKey implements Transformer<BigInteger, BigInteger> { private final RSAPublicKey publicKey; private final BigInteger p; private final BigInteger q; private final BigInteger dP; private final BigInteger dQ; private final BigInteger inverse; public RSAPrivateKey( RSAPublicKey publicKey, BigInteger p, BigInteger q, BigInteger dP, BigInteger dQ, BigInteger inverse ) { this.publicKey = publicKey; this.p = p; this.q = q; this.dP = dP; this.dQ = dQ; this.inverse = inverse; } public RSAPrivateKey( final int strength, final Random random ) { this( strength, random, BigInteger.valueOf( 0x10001 ) ); } public RSAPrivateKey( final int strength, final Random random, final BigInteger exponent ) { final int bitLength = ( strength + 1 ) / 2; BigInteger p = generatePrime( bitLength, exponent, random ); BigInteger q = ONE; BigInteger n; do { p = p.max( q ); do { q = generatePrime( strength - bitLength, exponent, random ); } while( q.subtract( p ).abs().bitLength() < strength / 3 ); n = p.multiply( q ); } while( n.bitLength() != strength ); if( p.compareTo( q ) < 0 ) { BigInteger t = p; p = q; q = t; } BigInteger d = exponent.modInverse( p.subtract( ONE ).multiply( q.subtract( ONE ) ) ); this.publicKey = new RSAPublicKey( n, exponent ); this.p = p; this.q = q; this.dP = d.remainder( p.subtract( ONE ) ); this.dQ = d.remainder( q.subtract( ONE ) ); this.inverse = q.modInverse( p ); } public RSAPublicKey getPublicKey() { return publicKey; } @Override public BigInteger transform( BigInteger input ) { BigInteger mP, mQ, h, m; mP = ( input.remainder( p ) ).modPow( dP, p ); mQ = ( input.remainder( q ) ).modPow( dQ, q ); h = mP.subtract( mQ ); h = h.multiply( inverse ); h = h.mod( p ); m = h.multiply( q ); m = m.add( mQ ); return m; } private BigInteger generatePrime( int bitLength, BigInteger e, Random random ) { BigInteger p; do { p = BigInteger.probablePrime( bitLength, random ); } while( p.mod( e ).equals( ONE ) || !e.gcd( p.subtract( ONE ) ).equals( ONE ) ); return p; } }
package com.andreabaccega.widget; import java.lang.reflect.Field; import java.lang.reflect.Method; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.EditText; import com.andreabaccega.formedittextvalidator.Validator; /** * EditText Extension to be used in order to create forms in android. * * @author Andrea Baccega <me@andreabaccega.com> */ public class FormEditText extends EditText { public FormEditText(Context context) { super(context); // FIXME how should this constructor be handled throw new RuntimeException("Not supported"); } public FormEditText(Context context, AttributeSet attrs) { super(context, attrs); editTextValidator = new DefaultEditTextValidator(this, attrs, context); } public FormEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); editTextValidator = new DefaultEditTextValidator(this, attrs, context); } public void addValidator(Validator theValidator) throws IllegalArgumentException { editTextValidator.addValidator(theValidator); } public EditTextValidator getEditTextValidator() { return editTextValidator; } public void setEditTextValidator(EditTextValidator editTextValidator) { this.editTextValidator = editTextValidator; } /** * Calling *testValidity()* will cause the EditText to go through * customValidators and call {@link com.andreabaccega.formedittextvalidator.Validator#isValid(EditText)} * * @return true if the validity passes false otherwise. */ public boolean testValidity() { return editTextValidator.testValidity(); } private EditTextValidator editTextValidator; /** * Keep track of which icon we used last */ private Drawable lastErrorIcon = null; /** * Don't send delete key so edit text doesn't capture it and close error */ @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (TextUtils.isEmpty(getText().toString()) && keyCode == KeyEvent.KEYCODE_DEL) return true; else return super.onKeyPreIme(keyCode, event); } @Override public void setError(CharSequence error, Drawable icon) { super.setError(error, icon); lastErrorIcon = icon; // if the error is not null, and we are in JB, force // the error to show if (error != null /* !isFocused() && */) { showErrorIconHax(icon); } } /** * In onFocusChanged() we also have to reshow the error icon as the Editor * hides it. Because Editor is a hidden class we need to cache the last used * icon and use that */ @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); showErrorIconHax(lastErrorIcon); } /** * Use reflection to force the error icon to show. Dirty but resolves the * issue in 4.2 */ private void showErrorIconHax(Drawable icon) { if (icon == null) return; // only for JB 4.2 and 4.2.1 if (android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN && android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN_MR1) return; try { Class<?> textview = Class.forName("android.widget.TextView"); Field tEditor = textview.getDeclaredField("mEditor"); tEditor.setAccessible(true); Class<?> editor = Class.forName("android.widget.Editor"); Method privateShowError = editor.getDeclaredMethod("setErrorIcon", Drawable.class); privateShowError.setAccessible(true); privateShowError.invoke(tEditor.get(this), icon); } catch (Exception e) { // e.printStackTrace(); // oh well, we tried } } }
package seedu.taskitty.logic.parser; import seedu.taskitty.commons.exceptions.IllegalValueException; import seedu.taskitty.commons.util.StringUtil; import seedu.taskitty.logic.commands.*; import seedu.taskitty.model.tag.Tag; import seedu.taskitty.model.task.TaskDate; import seedu.taskitty.model.task.TaskTime; import static seedu.taskitty.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.taskitty.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.text.ParseException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; /** * Parses user input. */ public class CommandParser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); //Used for checking for number date formats in arguments private static final Pattern LOCAL_DATE_FORMAT = Pattern.compile(".* (?<arguments>\\d(\\d)?[/-]\\d(\\d)?).*"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern TASK_DATA_ARGS_FORMAT = //Tags must be at the end Pattern.compile("(?<arguments>[\\p{Graph} ]+)"); // \p{Graph} is \p{Alnum} or \p{Punct} private static final Pattern EDIT_TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<targetIndex>.)" + "(?<name>[^/]+)" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags public CommandParser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case EditCommand.COMMAND_WORD: return prepareEdit(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); case UndoCommand.COMMAND_WORD: return new UndoCommand(); case DoneCommand.COMMAND_WORD: return prepareDone(arguments); case ViewDoneCommand.COMMAND_WORD: return new ViewDoneCommand(); case ViewCommand.COMMAND_WORD: if (userInput.equals("view")) { return prepareView(null); } return prepareView(arguments); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the view command. * * @param args full command args string * @return the prepared command */ private Command prepareView(String arguments) { if (arguments == null) { return new ViewCommand(); // view events today, and all deadlines and todos } if (arguments.trim().equals("done")) { return new ViewDoneCommand(); // defaults to viewDone command } String[] details = extractTaskDetailsNatty(arguments); if (details.length!= 3) { // no date was successfully extracted return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ViewCommand.MESSAGE_USAGE)); } else { assert details[1] != null; // contains date return new ViewCommand(details[1]); } } /** * Parses arguments in the context of the add task command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args){ final Matcher matcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { String arguments = matcher.group("arguments"); String taskDetailArguments = getTaskDetailArguments(arguments); String tagArguments = getTagArguments(arguments); return new AddCommand( extractTaskDetailsNatty(taskDetailArguments), getTagsFromArgs(tagArguments) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses the argument to get a string of all the relevant details of the task * * @param arguments command args string without command word */ private String getTaskDetailArguments(String arguments) { //Have 2 magic numbers.. where should I put them.. //-1 is NOT_FOUND //0 is START_OF_ARGUMENT int detailLastIndex = arguments.indexOf(Tag.TAG_VALIDATION_REGEX_PREFIX); if (detailLastIndex == -1) { detailLastIndex = arguments.length(); } return arguments.substring(0, detailLastIndex).trim(); } /** * Parses the argument to get a string of all tags, including the Tag prefix * * @param arguments command args string without command word */ private String getTagArguments(String arguments) { //This line is exactly the same as the 1st line of getTaskDetailArguments.. how? int tagStartIndex = arguments.indexOf(Tag.TAG_VALIDATION_REGEX_PREFIX); if (tagStartIndex == -1) { tagStartIndex = arguments.length(); } return arguments.substring(tagStartIndex); } /** * Extracts the task details into a String array representing the name, date, time. * Details are arranged according to index shown in Task * * @param dataArguments command args string with only name, date, time arguments */ private String[] extractTaskDetailsNatty(String dataArguments) { dataArguments = convertToNattyDateFormat(dataArguments); Parser dateTimeParser = new Parser(); List<DateGroup> dateGroups = dateTimeParser.parse(dataArguments); int nameEndIndex = dataArguments.length(); ArrayList<String> details = new ArrayList<String>(); for (DateGroup group : dateGroups) { List<Date> dates = group.getDates(); nameEndIndex = Math.min(nameEndIndex, group.getPosition() - 1); for (Date date : dates) { details.add(extractLocalDate(date)); details.add(extractLocalTime(date)); } } details.add(0, dataArguments.substring(0, nameEndIndex).trim()); String[] returnDetails = new String[details.size()]; details.toArray(returnDetails); return returnDetails; } /** * Converts any number formats of date from the local format to one which can be parsed by natty * @param arguments * @return arguments with converted dates if any */ private String convertToNattyDateFormat(String arguments) { Matcher matchDate = LOCAL_DATE_FORMAT.matcher(arguments); if (matchDate.matches()) { String localDateString = matchDate.group("arguments"); String dateSeparator = getDateSeparator(localDateString); return convertToNattyFormat(arguments, localDateString, dateSeparator); } else { return arguments; } } /** * Helper method to get the separator between day month and year in a date * @param localDateString the string representing the date * @return the separator character used in localDateString */ private String getDateSeparator(String localDateString) { // if 2nd char in string is an integer, then the 3rd char must be the separator // else 2nd char is the separator if (StringUtil.isUnsignedInteger(localDateString.substring(1,2))) { return localDateString.substring(2, 3); } else { return localDateString.substring(1, 2); } } /** * Helper method to convert the local date format inside arguments into a format * which can be parsed by natty * @param arguments the full argument string * @param localDateString the localDate extracted out from arguments * @param dateSeparator the separator for the date extracted out * @return converted string where the date format has been converted from local to natty format */ private String convertToNattyFormat(String arguments, String localDateString, String dateSeparator) { String[] dateComponents = localDateString.split(dateSeparator); int indexOfDate = arguments.indexOf(localDateString); StringBuilder nattyDateStringBuilder = new StringBuilder(); nattyDateStringBuilder.append(dateComponents[1]); nattyDateStringBuilder.append(dateSeparator); nattyDateStringBuilder.append(dateComponents[0]); StringBuilder convertDateStringBuilder = new StringBuilder(arguments); convertDateStringBuilder.replace(indexOfDate, indexOfDate + localDateString.length(), nattyDateStringBuilder.toString()); String stringFromConvertedDate = convertDateStringBuilder.substring(indexOfDate); String stringUpToConvertedDate = convertDateStringBuilder.substring(0, indexOfDate); return convertToNattyDateFormat(stringUpToConvertedDate) + stringFromConvertedDate; } /** * Takes in a date from Natty and converts it into a string representing date * Format of date returned is according to TaskDate * * @param date retrieved using Natty */ private String extractLocalDate(Date date) { SimpleDateFormat dateFormat = new SimpleDateFormat(TaskDate.DATE_FORMAT_STRING); return dateFormat.format(date); } /** * Takes in a date from Natty and converts it into a string representing time * Format of time returned is according to TaskTime * * @param date retrieved using Natty */ private String extractLocalTime(Date date) { SimpleDateFormat timeFormat = new SimpleDateFormat(TaskTime.TIME_FORMAT_STRING); String currentTime = timeFormat.format(new Date()); String inputTime = timeFormat.format(date); if (currentTime.equals(inputTime)) { //Natty parses the current time if string does not include time. //We want to ignore input when current time equal input time return null; } return inputTime; } /** * Extracts the new person's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete person command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { String[] splitArgs = args.trim().split(" "); if (splitArgs.length == 0 || splitArgs.length > 2) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } //takes the last argument given for parsing index Optional<Integer> index = parseIndex(splitArgs[splitArgs.length - 1]); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } if (splitArgs.length == 1) { return new DeleteCommand(index.get()); } else { return new DeleteCommand(index.get(), StringUtil.getCategoryIndex(splitArgs[0])); } } /** * Parses arguments in the context of the mark as done command. * * @param args full command args string * @return the prepared command */ private Command prepareDone(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE)); } return new DoneCommand(index.get()); } /** * Parses arguments in the context of the edit task command. * * @param args full command args string * @return the prepared command */ private Command prepareEdit(String args) { final Matcher matcher = EDIT_TASK_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } String index = matcher.group("targetIndex"); Optional<Integer> index1 = parseIndex(index); if(!index1.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } try { return new EditCommand( matcher.group("name"), getTagsFromArgs(matcher.group("tagArguments")), index1.get() ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the select person command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index. * Returns an {@code Optional.empty()} otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if(!StringUtil.isUnsignedInteger(index)){ return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find person command. * * @param args full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } }
package techreborn.tiles.tier1; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import org.apache.commons.lang3.tuple.Pair; import reborncore.api.IToolDrop; import reborncore.api.tile.IInventoryProvider; import reborncore.common.powerSystem.TilePowerAcceptor; import reborncore.common.registration.RebornRegistry; import reborncore.common.registration.impl.ConfigRegistry; import reborncore.common.util.Inventory; import reborncore.common.util.ItemUtils; import techreborn.api.RollingMachineRecipe; import reborncore.client.containerBuilder.IContainerProvider; import reborncore.client.containerBuilder.builder.BuiltContainer; import reborncore.client.containerBuilder.builder.ContainerBuilder; import techreborn.init.ModBlocks; import techreborn.lib.ModInfo; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; //TODO add tick and power bars. @RebornRegistry(modID = ModInfo.MOD_ID) public class TileRollingMachine extends TilePowerAcceptor implements IToolDrop, IInventoryProvider, IContainerProvider { @ConfigRegistry(config = "machines", category = "rolling_machine", key = "RollingMachineMaxInput", comment = "Rolling Machine Max Input (Value in EU)") public static int maxInput = 32; @ConfigRegistry(config = "machines", category = "rolling_machine", key = "RollingMachineEnergyPerTick", comment = "Rolling Machine Energy Per Tick (Value in EU)") public static int energyPerTick = 5; @ConfigRegistry(config = "machines", category = "rolling_machine", key = "RollingMachineEnergyRunTime", comment = "Rolling Machine Run Time") public static int runTime = 250; @ConfigRegistry(config = "machines", category = "rolling_machine", key = "RollingMachineMaxEnergy", comment = "Rolling Machine Max Energy (Value in EU)") public static int maxEnergy = 10000; public int[] craftingSlots = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; private InventoryCrafting craftCache; public Inventory inventory = new Inventory(12, "TileRollingMachine", 64, this); public boolean isRunning; public int tickTime; @Nonnull public ItemStack currentRecipeOutput; public IRecipe currentRecipe; private int outputSlot; public boolean locked = false; public int balanceSlot = 0; public TileRollingMachine() { super(); outputSlot = 9; } @Override public double getBaseMaxPower() { return maxEnergy; } @Override public boolean canAcceptEnergy(final EnumFacing direction) { return true; } @Override public boolean canProvideEnergy(final EnumFacing direction) { return false; } @Override public double getBaseMaxOutput() { return 0; } @Override public double getBaseMaxInput() { return maxInput; } @Override public void update() { super.update(); if (world.isRemote) { return; } charge(10); InventoryCrafting craftMatrix = getCraftingMatrix(); currentRecipe = RollingMachineRecipe.instance.findMatchingRecipe(craftMatrix, world); if (currentRecipe != null) { if (world.getTotalWorldTime() % 2 == 0) { Optional<InventoryCrafting> balanceResult = balanceRecipe(craftMatrix); if (balanceResult.isPresent()) { craftMatrix = balanceResult.get(); } } currentRecipeOutput = currentRecipe.getCraftingResult(craftMatrix); } else { currentRecipeOutput = ItemStack.EMPTY; } if (!currentRecipeOutput.isEmpty() && canMake(craftMatrix)) { if (tickTime >= Math.max((int) (runTime * (1.0 - getSpeedMultiplier())), 1)) { currentRecipeOutput = RollingMachineRecipe.instance.findMatchingRecipeOutput(craftMatrix, world); if (!currentRecipeOutput.isEmpty()) { boolean hasCrafted = false; if (inventory.getStackInSlot(outputSlot).isEmpty()) { inventory.setInventorySlotContents(outputSlot, currentRecipeOutput); tickTime = 0; hasCrafted = true; } else { if (inventory.getStackInSlot(outputSlot).getCount() + currentRecipeOutput.getCount() <= currentRecipeOutput.getMaxStackSize()) { final ItemStack stack = inventory.getStackInSlot(outputSlot); stack.setCount(stack.getCount() + currentRecipeOutput.getCount()); inventory.setInventorySlotContents(outputSlot, stack); tickTime = 0; hasCrafted = true; } } if (hasCrafted) { for (int i = 0; i < craftMatrix.getSizeInventory(); i++) { inventory.decrStackSize(i, 1); } currentRecipeOutput = ItemStack.EMPTY; currentRecipe = null; } } } } else { tickTime = 0; } if (!currentRecipeOutput.isEmpty()) { if (canUseEnergy(getEuPerTick(energyPerTick)) && tickTime < Math.max((int) (runTime * (1.0 - getSpeedMultiplier())), 1) && canMake(craftMatrix)) { useEnergy(getEuPerTick(energyPerTick)); tickTime++; } } if (currentRecipeOutput.isEmpty()) { tickTime = 0; currentRecipe = null; } } public Optional<InventoryCrafting> balanceRecipe(InventoryCrafting craftCache) { if (currentRecipe == null) { return Optional.empty(); } if (world.isRemote) { return Optional.empty(); } if (!locked) { return Optional.empty(); } if (craftCache.isEmpty()) { return Optional.empty(); } balanceSlot++; if (balanceSlot > craftCache.getSizeInventory()) { balanceSlot = 0; } //Find the best slot for each item in a recipe, and move it if needed ItemStack sourceStack = inventory.getStackInSlot(balanceSlot); if (sourceStack.isEmpty()) { return Optional.empty(); } List<Integer> possibleSlots = new ArrayList<>(); for (int s = 0; s < currentRecipe.getIngredients().size(); s++) { ItemStack stackInSlot = inventory.getStackInSlot(s); Ingredient ingredient = currentRecipe.getIngredients().get(s); if (ingredient != Ingredient.EMPTY && ingredient.apply(sourceStack)) { if (stackInSlot.isEmpty()) { possibleSlots.add(s); } else if (stackInSlot.getItem() == sourceStack.getItem() && stackInSlot.getItemDamage() == sourceStack.getItemDamage()) { possibleSlots.add(s); } } } if(!possibleSlots.isEmpty()){ int totalItems = possibleSlots.stream() .mapToInt(value -> inventory.getStackInSlot(value).getCount()).sum(); int slots = possibleSlots.size(); //This makes an array of ints with the best possible slot distribution int[] split = new int[slots]; int remainder = totalItems % slots; Arrays.fill(split, totalItems / slots); while (remainder > 0){ for (int i = 0; i < split.length; i++) { if(remainder > 0){ split[i] +=1; remainder } } } List<Integer> slotDistrubution = possibleSlots.stream() .mapToInt(value -> inventory.getStackInSlot(value).getCount()) .boxed().collect(Collectors.toList()); boolean needsBalance = false; for (int i = 0; i < split.length; i++) { int required = split[i]; if(slotDistrubution.contains(required)){ //We need to remove the int, not at the int, this seems to work around that slotDistrubution.remove(new Integer(required)); } else { needsBalance = true; } } if (!needsBalance) { return Optional.empty(); } } else { return Optional.empty(); } //Slot, count Pair<Integer, Integer> bestSlot = null; for (Integer slot : possibleSlots) { ItemStack slotStack = inventory.getStackInSlot(slot); if (slotStack.isEmpty()) { bestSlot = Pair.of(slot, 0); } if (bestSlot == null) { bestSlot = Pair.of(slot, slotStack.getCount()); } else if (bestSlot.getRight() >= slotStack.getCount()) { bestSlot = Pair.of(slot, slotStack.getCount()); } } if (bestSlot == null || bestSlot.getLeft() == balanceSlot || bestSlot.getRight() == sourceStack.getCount() || inventory.getStackInSlot(bestSlot.getLeft()).isEmpty() || !ItemUtils.isItemEqual(sourceStack, inventory.getStackInSlot(bestSlot.getLeft()), true, true, true)) { return Optional.empty(); } sourceStack.shrink(1); inventory.getStackInSlot(bestSlot.getLeft()).grow(1); inventory.hasChanged = true; return Optional.of(getCraftingMatrix()); } private InventoryCrafting getCraftingMatrix() { if (craftCache == null) { craftCache = new InventoryCrafting(new RollingTileContainer(), 3, 3); } if (inventory.hasChanged) { for (int i = 0; i < 9; i++) { craftCache.setInventorySlotContents(i, inventory.getStackInSlot(i).copy()); } inventory.hasChanged = false; } return craftCache; } public boolean canMake(InventoryCrafting craftMatrix) { ItemStack stack = RollingMachineRecipe.instance.findMatchingRecipeOutput(craftMatrix, this.world); if (locked) { for (int i = 0; i < craftMatrix.getSizeInventory(); i++) { ItemStack stack1 = craftMatrix.getStackInSlot(i); if (!stack1.isEmpty() && stack1.getCount() < 2) { return false; } } } if (stack.isEmpty()) { return false; } ItemStack output = getStackInSlot(outputSlot); if (output.isEmpty()) { return true; } return ItemUtils.isItemEqual(stack, output, true, true); } @Override public ItemStack getToolDrop(final EntityPlayer entityPlayer) { return new ItemStack(ModBlocks.ROLLING_MACHINE, 1); } @Override public void readFromNBT(final NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); this.isRunning = tagCompound.getBoolean("isRunning"); this.tickTime = tagCompound.getInteger("tickTime"); this.locked = tagCompound.getBoolean("locked"); } @Override public NBTTagCompound writeToNBT(final NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); tagCompound.setBoolean("isRunning", this.isRunning); tagCompound.setInteger("tickTime", this.tickTime); tagCompound.setBoolean("locked", locked); return tagCompound; } @Override public void invalidate() { super.invalidate(); } @Override public void onChunkUnload() { super.onChunkUnload(); } @Override public Inventory getInventory() { return inventory; } public int getBurnTime() { return tickTime; } public void setBurnTime(final int burnTime) { this.tickTime = burnTime; } public int getBurnTimeRemainingScaled(final int scale) { if (tickTime == 0 || Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1) == 0) { return 0; } return tickTime * scale / Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1); } @Override public BuiltContainer createContainer(final EntityPlayer player) { return new ContainerBuilder("rollingmachine").player(player.inventory) .inventory().hotbar() .addInventory().tile(this) .slot(0, 30, 22).slot(1, 48, 22).slot(2, 66, 22) .slot(3, 30, 40).slot(4, 48, 40).slot(5, 66, 40) .slot(6, 30, 58).slot(7, 48, 58).slot(8, 66, 58) .onCraft(inv -> this.inventory.setInventorySlotContents(1, RollingMachineRecipe.instance.findMatchingRecipeOutput(getCraftingMatrix(), this.world))) .outputSlot(9, 124, 40) .energySlot(10, 8, 70) .syncEnergyValue().syncIntegerValue(this::getBurnTime, this::setBurnTime).syncIntegerValue(this::getLockedInt, this::setLockedInt).addInventory().create(this); } //Easyest way to sync back to the client public int getLockedInt() { return locked ? 1 : 0; } public void setLockedInt(int lockedInt) { locked = lockedInt == 1; } public int getProgressScaled(final int scale) { if (tickTime != 0 && Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1) != 0) { return tickTime * scale / Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1); } return 0; } private static class RollingTileContainer extends Container { @Override public boolean canInteractWith(final EntityPlayer entityplayer) { return true; } } @Override public boolean canBeUpgraded() { return true; } }
package totemic_commons.pokefenn.item; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import net.minecraft.util.StringUtils; import totemic_commons.pokefenn.Totemic; import totemic_commons.pokefenn.lib.Strings; public class ItemTotemic extends Item { public ItemTotemic(String name, boolean creativeTab) { setNoRepair(); if(!name.equals("")) setUnlocalizedName(Strings.RESOURCE_PREFIX + name); if(creativeTab) setCreativeTab(Totemic.tabsTotem); } public ItemTotemic(String name) { this(name, true); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { if(!hasSubtypes) itemIcon = iconRegister.registerIcon(getUnlocalizedName().substring(getUnlocalizedName().indexOf(".") + 1)); } }
package uk.ac.ox.oucs.oxpoints.gaboto; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import net.sf.gaboto.Gaboto; import net.sf.gaboto.GabotoFactory; import net.sf.gaboto.GabotoRuntimeException; import net.sf.gaboto.node.GabotoEntity; import net.sf.gaboto.time.TimeInstant; import net.sf.gaboto.time.TimeSpan; import net.sf.gaboto.util.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import uk.ac.ox.oucs.oxpoints.gaboto.beans.Address; import uk.ac.ox.oucs.oxpoints.gaboto.beans.Location; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Building; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Carpark; import uk.ac.ox.oucs.oxpoints.gaboto.entities.College; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Department; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Image; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Library; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Museum; import uk.ac.ox.oucs.oxpoints.gaboto.entities.OxpEntity; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Place; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Room; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Unit; import uk.ac.ox.oucs.oxpoints.gaboto.entities.Website; /** * * @author Arno Mittelbach * */ public class TEIImporter { /** * @since 6 July 2009 * */ public class ElementRuntimeException extends RuntimeException { /** * Constructor. * @param message */ public ElementRuntimeException(String message) { } private static final long serialVersionUID = -6439480177218879551L; private String message; public ElementRuntimeException(Element el, String mess) { super(); NamedNodeMap nnm = el.getAttributes(); int len = nnm.getLength(); String atts = ""; for (int i = 0; i < len; i++ ) atts += nnm.item(i) + ", "; this.message = mess + ": " + atts; } /** * {@inheritDoc} * @see java.lang.Throwable#getMessage() */ @Override public String getMessage() { return message; } } private Document document; private Gaboto gaboto; public final static String XML_NS = "http: private Set<OxpEntity> entities = new HashSet<OxpEntity>(); private Map<String, OxpEntity> entityLookup = new HashMap<String, OxpEntity>(); public TEIImporter(Gaboto gaboto, File file) { try { this.document = XMLUtils.readInputFileIntoJAXPDoc(file); } catch (Exception e) { throw new GabotoRuntimeException(e); } this.gaboto = gaboto; } public void run(){ NodeList listPlaces = document.getElementsByTagName("listPlace"); // take care of entity creation for(int i = 0; i < listPlaces.getLength();i++){ NodeList places = listPlaces.item(i).getChildNodes(); for(int j = 0; j < places.getLength(); j++){ if(places.item(j) instanceof Element) processElement((Element)places.item(j), false); } } // take care of relations for(int i = 0; i < listPlaces.getLength();i++){ NodeList places = listPlaces.item(i).getChildNodes(); for(int j = 0; j < places.getLength(); j++){ if(places.item(j) instanceof Element) processElement((Element)places.item(j), true); } } // process figures NodeList figureList = document.getElementsByTagName("figure"); for(int i = 0; i < figureList.getLength(); i++){ if(! (figureList.item(i) instanceof Element)) continue; processFigure((Element)figureList.item(i)); } // add entities System.err.println("Have read in " + entities.size() + " entities"); for(GabotoEntity e : entities){ try { gaboto.add(e); } catch (net.sf.gaboto.EntityAlreadyExistsException e1) { throw new RuntimeException(e.getUri() + " has already been added to the system."); } } //System.err.println("Gaboto contains " + gaboto.getJenaModelViewOnNamedGraphSet().size() + " entities"); } private void processElement(Element el, boolean relations) { // create object String name = el.getNodeName(); if(name.equals("place") && !relations){ String type = el.getAttribute("type"); if (type == null) { throw new ElementRuntimeException(el, "No type defined for place"); } if(type.equals("college") || type.equals("ex-college")){ processUnit(el, new College()); } else if(type.equals("unit")){ processUnit(el, new Unit()); } else if(type.equals("library")){ processLibrary(el); } else if(type.equals("museum")){ processUnit(el, new Museum()); } else if(type.equals("department")){ processUnit(el, new Department()); } else if(type.equals("uas")){ processUnit(el, new Department()); } else if(type.equals("poi")){ processUnit(el, new Unit()); } else if(type.equals("building")){ processBuilding(el); } else if(type.equals("carpark")){ processCarpark(el); } else { throw new RuntimeException("Unknown place type: " + type); } } else if(name.equals("relation") && relations){ String relName = el.getAttribute("name"); try{ if(relName.equals("occupies")){ processOccupies(el); } else if(relName.equals("controls")){ processControls(el); } else { throw new RuntimeException("Unknown relation: " + relName); } } catch(NullPointerException e){ throw new RuntimeException("No name defined for relation", e); } } } private void processFigure(Element figureEl) { // try to find corresponding entity if(! figureEl.hasAttribute("corresp")){ throw new RuntimeException("Ambiguous figure element"); } String id = figureEl.getAttribute("corresp"); try{ OxpEntity oxpoint = entityLookup.get(id.substring(1)); Place entity = null; if (oxpoint instanceof Place) entity = (Place)oxpoint; else if (oxpoint instanceof Unit) { entity = ((Unit) oxpoint).getPrimaryPlace(); if (entity == null) throw new RuntimeException("No primary place found for " + oxpoint); } else throw new RuntimeException("Unexpected type " + oxpoint.getClass()); // try to find a graphic element NodeList graphics = figureEl.getElementsByTagName("graphic"); if(graphics.getLength() < 1){ throw new RuntimeException("Empty figure element for: " + id); } Element graphic = (Element) graphics.item(0); Image img = new Image(); img.setTimeSpan(entity.getTimeSpan()); String uri = graphic.getAttribute("url"); if (!uri.startsWith("http")) uri = "http: img.setUri(uri); img.setWidth(graphic.getAttribute("width")); img.setHeight(graphic.getAttribute("height")); entity.addImage(img); // add figure entities.add(img); } catch(NullPointerException e){ throw new RuntimeException("Could not load entity from id: " + id ); } } private void processControls(Element relation){ String activeID = relation.getAttribute("active"); String passiveID = relation.getAttribute("passive"); Unit active = (Unit) entityLookup.get(activeID.substring(1)); if(active == null) throw new RuntimeException("Could not load active entity from id: " + activeID ); Unit passive = (Unit) entityLookup.get(passiveID.substring(1)); if(passive == null ) throw new RuntimeException("Could not load passive entity from id: " + passiveID ); passive.setSubsetOf(active); } private void processOccupies(Element relation){ String type = relation.getAttribute("type"); String activeID = relation.getAttribute("active"); String passiveID = relation.getAttribute("passive"); Unit u = (Unit) entityLookup.get(activeID.substring(1)); if (u == null) throw new RuntimeException("Could not load entity from id: " + activeID); Building b = (Building) entityLookup.get(passiveID.substring(1)); if (b == null) throw new RuntimeException("Could not load entity from id: " + passiveID); if(type.equals("geo primary")){ u.setPrimaryPlace(b); } // If this is not a primary, but it has no other if(u.getPrimaryPlace() == null) u.setPrimaryPlace(b); u.addOccupiedBuilding(b); } private void processCarpark(Element el) { Carpark cp = new Carpark(); String id = el.getAttribute("oxpID"); if (id == null) throw new NullPointerException(); cp.setUri(gaboto.getConfig().getNSData() + id); String code = el.getAttribute("oucsCode"); cp.setOUCSCode(code); String obn = el.getAttribute("obnCode"); cp.setOBNCode(obn); cp.setName(findName(el)); cp.setLocation(findLocation(el)); // label NodeList nl = el.getElementsByTagName("label"); if(nl.getLength() > 0){ Element label = (Element) nl.item(0); String labelContent = label.getTextContent(); labelContent = labelContent.replaceAll("[a-zA-Z\\s]", ""); try{ Integer size = new Integer(Integer.parseInt(labelContent)); cp.setCapacity(size); } catch(NumberFormatException e){ throw new RuntimeException("Could not ascertain carpark size."); } } // add unit entities.add(cp); if(el.hasAttributeNS(XML_NS, "id")) entityLookup.put(el.getAttributeNS(XML_NS, "id"), cp); } /** * * @param buildingEl */ private void processBuilding(Element buildingEl){ getBuilding(buildingEl, null); } private void processLibrary(Element libraryEl) { Library lib = new Library(); processUnit(libraryEl, lib); // olis code String code = libraryEl.getAttribute("olisCode"); lib.setOLISCode(code); lib.setLibraryHomepage(findLibWebsite(libraryEl, lib.getTimeSpan())); if(lib.getOUCSCode() != null) entityLookup.put(lib.getOUCSCode(), lib); } /** * Processes a unit and adds it to the dataset. * * @param unitEl */ private void processUnit(Element unitEl, Unit unit) { _processUnit(unit, unitEl); // add unit entities.add(unit); if(unit.getOUCSCode() != null) entityLookup.put(unit.getOUCSCode(), unit); } /** * do the actual processing work * * @param unit * @param unitEl */ private void _processUnit(Unit unit, Element unitEl){ // get ID String id = unitEl.getAttribute("oxpID"); if (id == null) throw new NullPointerException(); unit.setUri(gaboto.getConfig().getNSData() + id); // get name unit.setName(findName(unitEl)); // oucs code String code = unitEl.getAttribute("oucsCode"); unit.setOUCSCode(code); // Do we have a foundation date? TimeSpan ts = null; TimeInstant start = null; TimeInstant end = null; NodeList events = unitEl.getChildNodes(); for(int i = 0; i < events.getLength(); i++){ if(events.item(i).getNodeName().equals("event")){ if(! (events.item(i) instanceof Element)) continue; Element event = (Element)events.item(i); // find out type if(event.hasAttribute("type") && event.getAttribute("type").equals("founded")){ try{ start = new TimeInstant(Integer.parseInt(event.getAttribute("when")), null, null); } catch(NumberFormatException e){ throw new RuntimeException("Could not parse date: " + event.getAttribute("when") + " for " + unit.getName() ); } } else if(event.hasAttribute("type") && event.getAttribute("type").equals("ended")){ try{ end = new TimeInstant(Integer.parseInt(event.getAttribute("when")), null, null); } catch(NumberFormatException e){ throw new RuntimeException("Could not parse date: " + event.getAttribute("when") + " for " + unit.getName() ); } } else if(event.hasAttribute("type") && event.getAttribute("type").equals("status")){ //FIXME What to do with status change events? System.err.println("FIXME What to do with status change events?"); } else throw new RuntimeException("Unrecognised event type: " + event.getAttribute("type")); } } // have we found something if(start != null) { if (end != null) ts = TimeSpan.createFromInstants(start, end); else ts = new TimeSpan(start.getStartYear(), start.getStartMonth(), start.getStartDay()); } // 1420 is the date of foundation of StAlban's Hall //if (start.getStartYear().equals(new Integer(1420))) // throw new RuntimeException("End:" + end + " ts:" + ts); unit.setHomepage(findHomepage(unitEl, ts)); unit.setItHomepage(findITWebsite(unitEl, ts)); unit.setWeblearn(findWeblearn(unitEl, ts)); unit.setAddress(findAddress(unitEl)); getBuildings(unit, unitEl, ts); unit.setTimeSpan(ts); } private Collection<Building> getBuildings(Unit unit, Element unitEl, TimeSpan ts) { Set<Building> buildings = new HashSet<Building>(); NodeList places = unitEl.getElementsByTagName("place"); for(int i = 0; i < places.getLength(); i++){ if(! (places.item(i) instanceof Element)) continue; Element place = (Element) places.item(i); // if building if(! place.hasAttribute("type") || ! place.getAttribute("type").equals("building")) continue; Building building = getBuilding(place, ts); // occupants unit.addOccupiedBuilding(building); // is it the primary building if(place.hasAttribute("subtype") && place.getAttribute("subtype").equals("primary")) unit.setPrimaryPlace(building); buildings.add(building); } return buildings; } private Room getRoom(Building building, Element roomEl) { Room room = new Room(); String id = roomEl.getAttribute("oxpID"); if (id == null) throw new NullPointerException(); room.setUri(gaboto.getConfig().getNSData() + id); // get name room.setName(findName(roomEl)); // oucs code String code = roomEl.getAttribute("oucsCode"); room.setOUCSCode(code); String obn = roomEl.getAttribute("obnCode"); room.setOBNCode(obn); // building room.setParent(building); // timespan room.setTimeSpan(building.getTimeSpan()); // name? room.setName(findName(roomEl)); entities.add(room); if(room.getOUCSCode() != null) entityLookup.put(room.getOUCSCode(), room); System.err.println("Found room " + room + " for building " + building); return room; } private Building getBuilding(Element buildingEl, TimeSpan ts) { Building building = new Building(); String id = buildingEl.getAttribute("oxpID"); if (id == null) throw new NullPointerException(); building.setUri(gaboto.getConfig().getNSData() + id); // get uri String code = buildingEl.getAttribute("oucsCode"); building.setOUCSCode(code); String obn = buildingEl.getAttribute("obnCode"); building.setOBNCode(obn); // time span building.setTimeSpan(ts); // get name building.setName(findName(buildingEl)); // find Website building.setHomepage(findHomepage(buildingEl, building.getTimeSpan())); // location building.setLocation(findLocation(buildingEl)); // rooms NodeList rooms = buildingEl.getElementsByTagName("place"); for(int j = 0; j < rooms.getLength(); j++){ if(! (rooms.item(j) instanceof Element)) continue; Element roomEl = (Element) rooms.item(j); getRoom(building, roomEl); } entities.add(building); if(building.getOUCSCode() != null) entityLookup.put(building.getOUCSCode(), building); return building; } private Website findHomepage(Element el, TimeSpan ts){ return findWebsite(el, ts, "url"); } private Website findITWebsite(Element el, TimeSpan ts){ return findWebsite(el, ts, "iturl"); } private Website findLibWebsite(Element el, TimeSpan ts){ return findWebsite(el, ts, "liburl"); } private Website findWeblearn(Element el, TimeSpan ts){ return findWebsite(el, ts, "weblearn"); } private Website findWebsite(Element el, TimeSpan ts, String type){ NodeList traits = el.getChildNodes(); for(int i = 0; i < traits.getLength(); i++){ if(traits.item(i).getNodeName().equals("trait")){ if(! (traits.item(i) instanceof Element)) continue; Element trait = (Element) traits.item(i); if(!trait.hasAttribute("type") || !trait.getAttribute("type").equals(type)) continue; // find ptr NodeList ptrs = trait.getElementsByTagName("ptr"); if(ptrs.getLength() > 0){ Website hp = new Website(); String uri = ((Element)ptrs.item(0)).getAttribute("target"); if (uri == null) throw new ElementRuntimeException(el, "URI Null"); if (uri.trim().equals("")) throw new ElementRuntimeException(el, "URI empty"); hp.setUri(uri); hp.setTimeSpan(ts); entities.add(hp); return hp; } else{ throw new RuntimeException("Missed pointer for " + type + "."); } } } return null; } private Address findAddress(Element el) { NodeList locations = el.getChildNodes(); for (int i = 0; i < locations.getLength(); i++) { if (locations.item(i).getNodeName().equals("location")) { if (! (locations.item(i) instanceof Element)) continue; Element location = (Element)locations.item(i); if (! location.hasAttribute("type") || ! location.getAttribute("type").equals("address")) continue; // get address element Element addressEl = (Element)location.getElementsByTagName("address").item(0); if (addressEl == null) throw new ElementRuntimeException(el, "Expected address missing"); String add = ""; String postCode = ""; Address address = new Address(); NodeList addressChildren = addressEl.getChildNodes(); for (int j = 0; j < addressChildren.getLength(); j++){ if (! (addressChildren.item(j) instanceof Element)) continue; Element addressPart = (Element) addressChildren.item(j); if (addressPart.getNodeName().equals("addrLine")) { if (add.length() > 0 ) add += ", "; add += addressPart.getTextContent(); } else if (addressPart.getNodeName().equals("postCode")) postCode += addressPart.getTextContent(); else throw new RuntimeException("Unrecognized element:" + addressPart); } address.setStreetAddress(add); address.setPostCode(postCode); return address; } } return null; } private Location findLocation(Element el) { NodeList children = el.getChildNodes(); for(int i = 0; i < children.getLength(); i++){ if(children.item(i).getNodeName().equals("location")){ if(! (children.item(i) instanceof Element)) continue; Element location = (Element) children.item(i); NodeList geos = location.getElementsByTagName("geo"); if(geos.getLength() > 0){ String geo = geos.item(0).getTextContent(); Location loc = new Location(); loc.setPos(geo); return loc; } } } return null; } private String findName(Element el) { NodeList placeNames = el.getChildNodes(); for(int i = 0; i < placeNames.getLength(); i++){ if(placeNames.item(i).getNodeName().equals("placeName")){ return placeNames.item(i).getTextContent(); } } return null; } /** * * @param args */ public static void main(String[] args) { String filename = args[0]; File file = new File(filename); if(! file.exists()) throw new RuntimeException("Argument one needs to be a file"); Gaboto gab = GabotoFactory.getPersistentGaboto(); new TEIImporter(gab, file).run(); } }
package com.google.refine.importers; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.refine.ProjectMetadata; import com.google.refine.importers.TreeImportUtilities.ImportColumnGroup; import com.google.refine.importers.parsers.JSONParser; import com.google.refine.importers.parsers.TreeParser; import com.google.refine.model.Project; public class JsonImporter implements StreamImporter{ final static Logger logger = LoggerFactory.getLogger("XmlImporter"); public static final int BUFFER_SIZE = 64 * 1024; @Override public void read(InputStream inputStream, Project project, ProjectMetadata metadata, Properties options) throws ImportException { //FIXME the below is a close duplicate of the XmlImporter code. //Should wrap a lot of the below into methods and put them in a common superclass logger.trace("JsonImporter.read"); PushbackInputStream pis = new PushbackInputStream(inputStream,BUFFER_SIZE); String[] recordPath = null; { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read = 0; try {//fill the buffer with data while (bytes_read < BUFFER_SIZE) { int c = pis.read(buffer, bytes_read, BUFFER_SIZE - bytes_read); if (c == -1) break; bytes_read +=c ; } pis.unread(buffer, 0, bytes_read); } catch (IOException e) { throw new ImportException("Read error",e); } InputStream iStream = new ByteArrayInputStream(buffer, 0, bytes_read); TreeParser parser = new JSONParser(iStream); if (options.containsKey("importer-record-tag")) { try{ recordPath = XmlImportUtilities.detectPathFromTag( parser, options.getProperty("importer-record-tag")); }catch(Exception e){ // silent // e.printStackTrace(); } } else { recordPath = XmlImportUtilities.detectRecordElement(parser); } } if (recordPath == null) return; ImportColumnGroup rootColumnGroup = new ImportColumnGroup(); XmlImportUtilities.importTreeData(new JSONParser(pis), project, recordPath, rootColumnGroup); XmlImportUtilities.createColumnsFromImport(project, rootColumnGroup); project.columnModel.update(); } @Override public boolean canImportData(String contentType, String fileName) { if (contentType != null) { contentType = contentType.toLowerCase().trim(); if("application/json".equals(contentType) || "text/json".equals(contentType)) { return true; } } else if (fileName != null) { fileName = fileName.toLowerCase(); if ( fileName.endsWith(".json") || fileName.endsWith(".js") ) { return true; } } return false; } }
package com.airhacks; import com.wordnik.swagger.config.ConfigFactory; import com.wordnik.swagger.config.ScannerFactory; import com.wordnik.swagger.config.SwaggerConfig; import com.wordnik.swagger.jaxrs.config.DefaultJaxrsScanner; import com.wordnik.swagger.jaxrs.reader.DefaultJaxrsApiReader; import com.wordnik.swagger.reader.ClassReaders; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @WebServlet(name = "SwaggerJaxrsConfig", loadOnStartup = 1) public class SwaggerJAXRSConfig extends HttpServlet { @Override public void init(ServletConfig servletConfig) { try { super.init(servletConfig); SwaggerConfig swaggerConfig = new SwaggerConfig(); ConfigFactory.setConfig(swaggerConfig); swaggerConfig.setBasePath("http://localhost:8080/findyourway/api"); swaggerConfig.setApiVersion("1.0.0"); ScannerFactory.setScanner(new DefaultJaxrsScanner()); ClassReaders.setReader(new DefaultJaxrsApiReader()); } catch (ServletException e) { System.err.println(e.getMessage()); } } }
/** * When a Bucket is created Simperium creates a Channel to sync changes between * a Bucket and simperium.com. * * A Channel is provided with a Simperium App ID, a Bucket to operate on, a User * who owns the bucket and a Channel.Listener that receives messages from the * Channel. * * To get messages into a Channel, Channel.receiveMessage receives a Simperium * websocket API message stripped of the channel ID prefix. * * TODO: instead of notifying the bucket about each individual item, there should be * a single event for when there's a "re-index" or after performing all changes in a * change operation. * */ package com.simperium.client; import com.simperium.Simperium; import com.simperium.util.JSONDiff; import com.simperium.util.Logger; import java.util.ArrayList; import java.util.Collections; import java.util.EventObject; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.Scanner; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import android.os.Handler; import android.os.HandlerThread; public class Channel<T extends Syncable> implements Bucket.ChannelProvider<T> { public static final String TAG="Simperium.Channel"; // key names for init command json object static final String FIELD_CLIENT_ID = "clientid"; static final String FIELD_API_VERSION = "api"; static final String FIELD_AUTH_TOKEN = "token"; static final String FIELD_APP_ID = "app_id"; static final String FIELD_BUCKET_NAME = "name"; static final String FIELD_COMMAND = "cmd"; // commands sent over the socket public static final String COMMAND_INIT = "init"; // init:{INIT_PROPERTIES} public static final String COMMAND_AUTH = "auth"; // received after an init: auth:expired or auth:email@example.com public static final String COMMAND_INDEX = "i"; // i:1:MARK:?:LIMIT public static final String COMMAND_CHANGE = "c"; public static final String COMMAND_VERSION = "cv"; public static final String COMMAND_ENTITY = "e"; static final String RESPONSE_UNKNOWN = "?"; static final String EXPIRED_AUTH = "expired"; // after unsuccessful init: // Parameters for querying bucket static final Integer INDEX_PAGE_SIZE = 500; static final Integer INDEX_BATCH_SIZE = 10; static final Integer INDEX_QUEUE_SIZE = 5; // Constants for parsing command messages static final Integer MESSAGE_PARTS = 2; static final Integer COMMAND_PART = 0; static final Integer PAYLOAD_PART = 1; static final String COMMAND_FORMAT = "%s:%s"; // bucket determines which bucket we are using on this channel private Bucket<T> bucket; // the object the receives the messages the channel emits private OnMessageListener listener; // track channel status private boolean started = false, connected = false, startOnConnect = false, disconnectOnIdle = false; private boolean haveIndex = false; private CommandInvoker commands = new CommandInvoker(); private String appId, sessionId; private Serializer serializer; // for sending and receiving changes final private ChangeProcessor changeProcessor; private IndexProcessor indexProcessor; public interface Serializer { public <T extends Syncable> void save(Bucket<T> bucket, SerializedQueue<T> data); public <T extends Syncable> SerializedQueue<T> restore(Bucket<T> bucket); public <T extends Syncable> void reset(Bucket<T> bucket); } public static class SerializedQueue<T extends Syncable> { final public Map<String,Change<T>> pending; final public List<Change<T>> queued; public SerializedQueue(){ this(new HashMap<String, Change<T>>(), new ArrayList<Change<T>>()); } public SerializedQueue(Map<String,Change<T>> pendingChanges, List<Change<T>> queuedChanges){ this.pending = pendingChanges; this.queued = queuedChanges; } } public Channel(String appId, String sessionId, final Bucket<T> bucket, Serializer serializer, OnMessageListener listener){ this.serializer = serializer; this.appId = appId; this.sessionId = sessionId; this.bucket = bucket; this.listener = listener; // Receive auth: command command(COMMAND_AUTH, new Command(){ public void run(String param){ if (EXPIRED_AUTH.equals(param.trim())) { getUser().setAuthenticationStatus(User.AuthenticationStatus.NOT_AUTHENTICATED); return; } } }); // Receive i: command command(COMMAND_INDEX, new Command(){ public void run(String param){ updateIndex(param); } }); // Receive c: command command(COMMAND_CHANGE, new Command(){ public void run(String param){ handleRemoteChanges(param); } }); // Receive e: command command(COMMAND_ENTITY, new Command(){ public void run(String param){ handleVersionResponse(param); } }); changeProcessor = new ChangeProcessor(new ChangeProcessorListener<T>(){ @Override public void onComplete(){ Logger.log(TAG, "Change processor done"); } @Override public Ghost onAcknowledged(RemoteChange remoteChange, Change<T> acknowledgedChange) throws RemoteChangeInvalidException { // if this isn't a removal, update the ghost for the relevant object return bucket.acknowledgeChange(remoteChange, acknowledgedChange); } @Override public void onError(RemoteChange remoteChange, Change<T> erroredChange){ Logger.log(TAG, String.format("We have an error! %s", remoteChange)); } @Override public Ghost onRemote(RemoteChange remoteChange) throws RemoteChangeInvalidException { Logger.log(TAG, "Time to apply change"); return bucket.applyRemoteChange(remoteChange); } }); } public boolean isIdle(){ return changeProcessor == null || changeProcessor.isIdle(); } @Override public void reset(){ changeProcessor.reset(); if (started) { getLatestVersions(); } else { startOnConnect = true; } } private boolean hasChangeVersion(){ return bucket.hasChangeVersion(); } private String getChangeVersion(){ return bucket.getChangeVersion(); } private void getLatestVersions(){ // TODO: should local changes still be stored? // abort any remote and local changes since we're getting new data // and top the processor changeProcessor.abort(); haveIndex = false; // initialize the new query for new index data IndexQuery query = new IndexQuery(); // send the i:::: messages sendMessage(query.toString()); } /** * Diffs and object's local modifications and queues up the changes */ public Change<T> queueLocalChange(T object){ Change<T> change = new Change<T>(Change.OPERATION_MODIFY, object); changeProcessor.addChange(change); return change; } public Change<T> queueLocalDeletion(T object){ Change<T> change = new Change<T>(Change.OPERATION_REMOVE, object); changeProcessor.addChange(change); return change; } private static final String INDEX_CURRENT_VERSION_KEY = "current"; private static final String INDEX_VERSIONS_KEY = "index"; private static final String INDEX_MARK_KEY = "mark"; private void updateIndex(String indexJson){ // if we don't have an index processor, create a new one for the associated cv // listen for when the index processor is done so we can start the changeprocessor again // if we do have an index processor and the cv's match, add the page of items // to the queue. if (indexJson.equals(RESPONSE_UNKNOWN)) { // refresh the index getLatestVersions(); return; } JSONObject index; try { index = new JSONObject(indexJson); } catch (Exception e) { Logger.log(TAG, String.format("Index had invalid json: %s", indexJson)); return; } // if we don't have a processor or we are getting a different cv if (indexProcessor == null || !indexProcessor.addIndexPage(index)) { // make sure we're not processing changes and clear pending changes changeProcessor.reset(); // start a new index String currentIndex; try { currentIndex = index.getString(INDEX_CURRENT_VERSION_KEY); } catch(JSONException e){ // we have an empty index currentIndex = ""; } indexProcessor = new IndexProcessor(getBucket(), currentIndex, indexProcessorListener); indexProcessor.addIndexPage(index); } else { // received an index page for a different change version // TODO: What do we do now? Logger.log(TAG, "Processing index?"); } } private IndexProcessorListener indexProcessorListener = new IndexProcessorListener(){ @Override public void onComplete(String cv){ Logger.log(TAG, String.format("Finished downloading index %s", cv)); haveIndex = true; changeProcessor.start(); } }; private void handleRemoteChanges(String changesJson){ JSONArray changes; if (changesJson.equals(RESPONSE_UNKNOWN)) { Logger.log(TAG, "CV is out of date"); changeProcessor.reset(); getLatestVersions(); return; } try { changes = new JSONArray(changesJson); } catch (JSONException e){ Logger.log(TAG, "Failed to parse remote changes JSON", e); return; } // Loop through each change? Convert changes to array list List<Object> changeList = Channel.convertJSON(changes); changeProcessor.addChanges(changeList); Logger.log(TAG, String.format("Received %d change(s)", changes.length())); } private static final String ENTITY_DATA_KEY = "data"; private void handleVersionResponse(String versionData){ // versionData will be: key.version\n{"data":ENTITY} // we need to parse out the key and version, parse the json payload and // retrieve the data if (indexProcessor == null || !indexProcessor.addObjectData(versionData)) { Logger.log(TAG, String.format("Unkown Object for index: %s", versionData)); } } public Bucket getBucket(){ return bucket; } public User getUser(){ return bucket.getUser(); } public String getSessionId(){ return sessionId; } /** * Send Bucket's init message to start syncing changes. */ @Override public void start(){ if (started) { // we've already started return; } // If socket isn't connected yet we have to wait until connection // is up and try starting then if (!connected) { startOnConnect = true; return; } disconnectOnIdle = false; started = true; // If the websocket isn't connected yet we'll automatically start // when we're notified that we've connected startOnConnect = true; // Build the required json object for initializing HashMap<String,Object> init = new HashMap<String,Object>(6); init.put(FIELD_API_VERSION, 1); init.put(FIELD_CLIENT_ID, sessionId); init.put(FIELD_APP_ID, appId); init.put(FIELD_AUTH_TOKEN, bucket.getUser().getAccessToken()); init.put(FIELD_BUCKET_NAME, bucket.getRemoteName()); if (!hasChangeVersion()) { // the bucket has never gotten an index haveIndex = false; init.put(FIELD_COMMAND, new IndexQuery()); } else { // retive changes since last cv haveIndex = true; init.put(FIELD_COMMAND, String.format("%s:%s", COMMAND_VERSION, getChangeVersion())); } String initParams = new JSONObject(init).toString(); String message = String.format(COMMAND_FORMAT, COMMAND_INIT, initParams); sendMessage(message); } /** * Completes all syncing operations and then disconnects */ @Override public void stop(){ startOnConnect = false; disconnectOnIdle = true; } /** * Called when ChangeProcessor has completed all activities */ private void onIdle(){ if (disconnectOnIdle) { Logger.log(TAG, String.format("%s Close up now", Thread.currentThread().getName())); } } // websocket public void onConnect(){ connected = true; if(startOnConnect) start(); } public void onDisconnect(){ changeProcessor.stop(); connected = false; started = false; } /** * Receive a message from the WebSocketManager which already strips the channel * prefix from the message. */ public void receiveMessage(String message){ // parse the message and react to it String[] parts = message.split(":", MESSAGE_PARTS); String command = parts[COMMAND_PART]; run(command, parts[1]); } // send without the channel id, the socket manager should know which channel is writing private void sendMessage(String message){ // send a message MessageEvent event = new MessageEvent(this, message); emit(event); } private void emit(MessageEvent event){ if (listener != null) { listener.onMessage(event); } else { Logger.log(TAG, String.format("No one listening to channel %s", this)); } } public static class MessageEvent extends EventObject { public String message; public MessageEvent(Channel source, String message){ super(source); this.message = message; } public String getMessage(){ return message; } public String toString(){ return getMessage(); } } private void command(String name, Command command){ commands.add(name, command); } private void run(String name, String params){ commands.run(name, params); } public interface OnMessageListener { void onMessage(MessageEvent event); } /** * Command and CommandInvoker provide a declaritive syntax for handling commands that come in * from Channel.onMessage. Takes a message like "auth:user@example.com" and finds the correct * command to run and stips the command from the message so the command can take care of * processing the params. * * channel.command("auth", new Command(){ * public void onRun(String params){ * // params is now either an email address or "expired" * } * }); */ private interface Command { void run(String params); } private class CommandInvoker { private HashMap<String,Command> commands = new HashMap<String,Command>(); protected CommandInvoker add(String name, Command command){ commands.put(name, command); return this; } protected void run(String name, String params){ if (commands.containsKey(name)) { Command command = commands.get(name); command.run(params); } else { Logger.log(TAG, String.format("Don't know how to run: %s", name)); } } } static final String CURSOR_FORMAT = "%s::%s::%s"; static final String QUERY_DELIMITER = ":"; // static final Integer INDEX_MARK = 2; // static final Integer INDEX_LIMIT = 5; /** * IndexQuery provides an interface for managing a query cursor and limit fields. * TODO: add a way to build an IndexQuery from an index response */ private class IndexQuery { private String mark = ""; private Integer limit = INDEX_PAGE_SIZE; public IndexQuery(){}; public IndexQuery(String mark){ this(mark, INDEX_PAGE_SIZE); } public IndexQuery(Integer limit){ this.limit = limit; } public IndexQuery(String mark, Integer limit){ this.mark = mark; this.limit = limit; } public String toString(){ String limitString = ""; if (limit > -1) { limitString = limit.toString(); } return String.format(CURSOR_FORMAT, COMMAND_INDEX, mark, limitString); } } private class ObjectVersion { private String key; private Integer version; public ObjectVersion(String key, Integer version){ this.key = key; this.version = version; } public String toString(){ return String.format("%s.%d", key, version); } } private interface IndexProcessorListener { void onComplete(String cv); } /** * When index data is received it should queue up entities in the IndexProcessor. * The IndexProcessor then receives the object data and on a seperate thread asks * the StorageProvider to persist the object data. The storageProvider's operation * should not block the websocket thread in any way. * * Build up a list of entities and versions we need for the index. Allow the * channel to pass in the version data */ private class IndexProcessor { public static final String INDEX_OBJECT_ID_KEY = "id"; public static final String INDEX_OBJECT_VERSION_KEY = "v"; final private String cv; final private Bucket bucket; private List<String> index = Collections.synchronizedList(new ArrayList<String>()); private boolean complete = false; private Handler handler; final private IndexProcessorListener listener; int indexedCount = 0; public IndexProcessor(Bucket bucket, String cv, IndexProcessorListener listener){ Logger.log(TAG, String.format("Starting index processor with version: %s for bucket %s", cv, bucket)); this.bucket = bucket; this.cv = cv; this.listener = listener; } public Boolean addObjectData(String versionData){ String[] objectParts = versionData.split("\n"); String prefix = objectParts[0]; int lastDot = prefix.lastIndexOf("."); if (lastDot == -1) { Logger.log(TAG, String.format("Missing version string: %s", prefix)); return false; } String key = prefix.substring(0, lastDot); String version = prefix.substring(lastDot + 1); String payload = objectParts[1]; if (payload.equals(RESPONSE_UNKNOWN)) { Logger.log(TAG, String.format("Object unkown to simperium: %s.%s", key, version)); return false; } ObjectVersion objectVersion = new ObjectVersion(key, Integer.parseInt(version)); synchronized(index){ if(!index.remove(objectVersion.toString())){ Logger.log(TAG, String.format("Index didn't have %s", objectVersion)); return false; } } Logger.log(TAG, String.format("We were waiting for %s.%s", key, version)); JSONObject data = null; try { JSONObject payloadJSON = new JSONObject(payload); data = payloadJSON.getJSONObject(ENTITY_DATA_KEY); } catch (JSONException e) { Logger.log(TAG, "Failed to parse object JSON", e); return false; } Integer remoteVersion = Integer.parseInt(version); // build the ghost and update Map<String,Object> properties = Channel.convertJSON(data); Ghost ghost = new Ghost(key, remoteVersion, properties); bucket.addObjectWithGhost(ghost); indexedCount ++; if (complete && index.size() == 0) { notifyDone(); } else if(indexedCount % 10 == 0) { notifyProgress(); } return true; } /** * Add the page of data, but only if indexPage cv matches. Detects when it's the * last page due to absence of cursor mark */ public Boolean addIndexPage(JSONObject indexPage){ String currentIndex; try { currentIndex = indexPage.getString(INDEX_CURRENT_VERSION_KEY); } catch(JSONException e){ Logger.log(TAG, String.format("Index did not have current version %s", cv)); currentIndex = ""; } if (!currentIndex.equals(cv)) { return false; } JSONArray indexVersions; try { indexVersions = indexPage.getJSONArray(INDEX_VERSIONS_KEY); } catch(JSONException e){ Logger.log(TAG, String.format("Index did not have entities: %s", indexPage)); return true; } Logger.log(TAG, String.format("received %d entities", indexVersions.length())); if (indexVersions.length() > 0) { // query for each item that we don't have locally in the bucket for (int i=0; i<indexVersions.length(); i++) { try { JSONObject version = indexVersions.getJSONObject(i); String key = version.getString(INDEX_OBJECT_ID_KEY); Integer versionNumber = version.getInt(INDEX_OBJECT_VERSION_KEY); ObjectVersion objectVersion = new ObjectVersion(key, versionNumber); if (!bucket.hasKeyVersion(key, versionNumber)) { // we need to get the remote object index.add(objectVersion.toString()); sendMessage(String.format("%s:%s.%d", COMMAND_ENTITY, key, versionNumber)); } else { Logger.log(TAG, String.format("Object is up to date: %s", version)); } } catch (JSONException e) { Logger.log(TAG, String.format("Error processing index: %d", i), e); } } } String nextMark = null; if (indexPage.has(INDEX_MARK_KEY)) { try { nextMark = indexPage.getString(INDEX_MARK_KEY); } catch (JSONException e) { nextMark = null; } } if (nextMark != null && nextMark.length() > 0) { IndexQuery nextQuery = new IndexQuery(nextMark); sendMessage(nextQuery.toString()); } else { setComplete(); } return true; } /** * Indicates that we have a complete index so when the entities are all populated * we know we have all the data */ private void setComplete(){ complete = true; // if we have no pending object data if (index.isEmpty()) { // fire off the done listener notifyDone(); } } /** * If the index is done processing */ public boolean isComplete(){ return complete; } private void notifyDone(){ bucket.indexComplete(cv); listener.onComplete(cv); } private void notifyProgress(){ bucket.notifyOnNetworkChangeListeners(Bucket.ChangeType.INDEX); } } private interface ChangeProcessorListener<T extends Syncable> { /** * Received a remote change that acknowledges local change */ public Ghost onAcknowledged(RemoteChange remoteChange, Change<T> change) throws RemoteChangeInvalidException; /** * Received a remote change indicating an error in change request */ public void onError(RemoteChange remoteChange, Change<T> change); /** * Received a remote change that did not originate locally */ public Ghost onRemote(RemoteChange change) throws RemoteChangeInvalidException; /** * All changes have been processed and entering idle state */ public void onComplete(); } private boolean haveCompleteIndex(){ return haveIndex; } /** * ChangeProcessor should perform operations on a seperate thread as to not block the websocket * ideally it will be a FIFO queue processor so as changes are brought in they can be appended. * We also need a way to pause and clear the queue when we download a new index. */ private class ChangeProcessor implements Runnable, Change.OnRetryListener<T> { // public static final Integer CAPACITY = 200; public static final long RETRY_DELAY_MS = 5000; // 5 seconds for retries? private ChangeProcessorListener listener; private Thread thread; private List<Map<String,Object>> remoteQueue = Collections.synchronizedList(new ArrayList<Map<String,Object>>(10)); private List<Change<T>> localQueue = Collections.synchronizedList(new ArrayList<Change<T>>()); private Map<String,Change<T>> pendingChanges = Collections.synchronizedMap(new HashMap<String,Change<T>>()); private Handler handler; private Timer retryTimer; private final Object lock = new Object(); public ChangeProcessor(ChangeProcessorListener listener) { this.listener = listener; String handlerThreadName = String.format("channel-handler-%s", bucket.getName()); HandlerThread handlerThread = new HandlerThread(handlerThreadName); handlerThread.start(); this.handler = new Handler(handlerThread.getLooper()); Logger.log(TAG, String.format("Starting change processor handler on thread %s", this.handler.getLooper().getThread().getName())); this.retryTimer = new Timer(); // restore(); } /** * not waiting for any remote changes and have no local or pending changes */ public boolean isIdle(){ return !isRunning() && pendingChanges.isEmpty() && localQueue.isEmpty() && remoteQueue.isEmpty(); } /** * If thread is running */ public boolean isRunning(){ return thread != null && thread.isAlive(); } private void save(){ synchronized(lock){ Logger.log(TAG, String.format("%s - Saving queue with %d pending and %d local", Thread.currentThread().getName(), pendingChanges.size(), localQueue.size())); serializer.save(bucket, new SerializedQueue(pendingChanges, localQueue)); } } private void restore(){ synchronized(lock){ SerializedQueue<T> serialized = serializer.restore(bucket); localQueue.addAll(serialized.queued); pendingChanges.putAll(serialized.pending); } } public void addChanges(List<Object> changes){ synchronized(lock){ Iterator iterator = changes.iterator(); while(iterator.hasNext()){ remoteQueue.add((Map<String,Object>)iterator.next()); } } start(); } public void addChange(Map<String,Object> change){ synchronized(lock){ remoteQueue.add(change); } start(); } /** * Local change to be queued */ public void addChange(Change change){ synchronized (lock){ // compress all changes for this same key Iterator<Change<T>> iterator = localQueue.iterator(); while(iterator.hasNext()){ Change<T> queued = iterator.next(); if(queued.getKey().equals(change.getKey())){ iterator.remove(); } } localQueue.add(change); } save(); start(); } public void start(){ // channel must be started and have complete index if (!started || !haveCompleteIndex()) { Logger.log( TAG, String.format( "Need an index before processing changes %d remote and %d local changes %d pending", remoteQueue.size(), localQueue.size(), pendingChanges.size() ) ); return; } if (thread == null || thread.getState() == Thread.State.TERMINATED) { Logger.log( TAG, String.format( "Starting up the change processor with %d remote and %d local changes %d pending", remoteQueue.size(), localQueue.size(), pendingChanges.size() ) ); thread = new Thread(this, String.format("simperium.processor.%s", getBucket().getName())); thread.start(); } } public void stop(){ // interrupt the thread if (this.thread != null) { this.thread.interrupt(); } } protected void reset(){ pendingChanges.clear(); serializer.reset(bucket); } protected void abort(){ reset(); stop(); } protected void notifyIdleState(){ onIdle(); } public void run(){ Logger.log(TAG, String.format("%s - Starting change queue", Thread.currentThread().getName())); boolean idle = false; while(true && !Thread.interrupted()){ // TODO: only process one remote change at a time processRemoteChanges(); // TODO: only process one local change at a time processLocalChanges(); boolean localActivity = !pendingChanges.isEmpty() || !localQueue.isEmpty(); if (!localActivity && !idle) { idle = true; notifyIdleState(); } else if(idle && localActivity) { idle = false; } } Logger.log(TAG, String.format("%s - Queue interrupted", Thread.currentThread().getName())); save(); } private void processRemoteChanges(){ synchronized(lock){ // bail if thread is interrupted while(remoteQueue.size() > 0 && !Thread.interrupted()){ // take an item off the queue RemoteChange remoteChange = RemoteChange.buildFromMap(remoteQueue.remove(0)); Logger.log(TAG, String.format("Received remote change with cv: %s", remoteChange.getChangeVersion())); Boolean acknowledged = false; // synchronizing on pendingChanges since we're looking up and potentially // removing an entry Change change = null; change = pendingChanges.get(remoteChange.getKey()); if (remoteChange.isAcknowledgedBy(change)) { // change is no longer pending so remove it pendingChanges.remove(change.getKey()); if (remoteChange.isError()) { Logger.log(TAG, String.format("Change error response! %d %s", remoteChange.getErrorCode(), remoteChange.getKey())); // TODO: determine if we can retry this change by reapplying listener.onError(remoteChange, change); } else { try { Ghost ghost = listener.onAcknowledged(remoteChange, change); Change compressed = null; Iterator<Change<T>> queuedChanges = localQueue.iterator(); while(queuedChanges.hasNext()){ Change queuedChange = queuedChanges.next(); if (queuedChange.getKey().equals(change.getKey())) { queuedChanges.remove(); Logger.log(String.format("Compressed queued local change for %s", queuedChange.getKey())); compressed = queuedChange.reapplyOrigin(ghost.getVersion(), ghost.getDiffableValue()); } } if (compressed != null) { localQueue.add(compressed); } } catch (RemoteChangeInvalidException e){ Logger.log(TAG, "Remote change could not be acknowledged", e); } } } else { if (remoteChange.isError()) { throw(new RuntimeException(String.format("Remote change %s was an error but not acknowledged", remoteChange))); } try { listener.onRemote(remoteChange); } catch (RemoteChangeInvalidException e) { Logger.log(TAG, "Remote change could not be applied", e); } } if (!remoteChange.isError() && remoteChange.isRemoveOperation()) { Iterator<Change<T>> iterator = localQueue.iterator(); while(iterator.hasNext()){ Change queuedChange = iterator.next(); if (queuedChange.getKey().equals(remoteChange.getKey())) { iterator.remove(); } } } } } } public void processLocalChanges(){ final List<Change<T>> sendLater = new ArrayList<Change<T>>(); synchronized(lock){ // find the first local change whose key does not exist in the pendingChanges and there are no remote changes while(localQueue.size() > 0 && !Thread.interrupted()){ // take the first change of the queue Change localChange = localQueue.remove(0); // check if there's a pending change with the same key if (pendingChanges.containsKey(localChange.getKey())) { // we have a change for this key that has not been acked // so send it later Logger.log(TAG, String.format("Changes pending for %s re-queueing %s", localChange.getKey(), localChange.getChangeId())); sendLater.add(localChange); // let's get the next change } else { // send the change to simperium, if the change ends up being empty // then we'll just skip it if(sendChange(localChange)) { // add the change to pending changes pendingChanges.put(localChange.getKey(), localChange); localChange.setOnRetryListener(this); // starts up the timer this.retryTimer.scheduleAtFixedRate(localChange.getRetryTimer(), RETRY_DELAY_MS, RETRY_DELAY_MS); } } } } // add the sendLater changes back on top of the queue synchronized(lock){ localQueue.addAll(0, sendLater); } } @Override public void onRetry(Change<T> change){ sendChange(change); } private Boolean sendChange(Change<T> change){ // send the change down the socket! if (!connected) { // channel is not initialized, send on reconnect Logger.log(TAG, String.format("Abort sending change, channel not initialized: %s", change.getChangeId())); return true; } Logger.log(TAG, String.format("send change ccid %s", change.getChangeId())); Map<String,Object> map = new HashMap<String,Object>(3); map.put(Change.ID_KEY, change.getKey()); map.put(Change.CHANGE_ID_KEY, change.getChangeId()); map.put(JSONDiff.DIFF_OPERATION_KEY, change.getOperation()); Integer version = change.getVersion(); if (version != null && version > 0) { map.put(Change.SOURCE_VERSION_KEY, version); } if (change.requiresDiff()) { Map<String,Object> diff = change.getDiff(); // jsondiff.diff(change.getOrigin(), change.getTarget()); if (diff.isEmpty()) { Logger.log(TAG, String.format("Discarding empty change %s diff: %s", change.getChangeId(), diff)); change.setComplete(); return false; } map.put(JSONDiff.DIFF_VALUE_KEY, diff.get(JSONDiff.DIFF_VALUE_KEY)); } JSONObject changeJSON = Channel.serializeJSON(map); sendMessage(String.format("c:%s", changeJSON.toString())); change.setSent(); return true; } } public static Map<String,Object> convertJSON(JSONObject json){ Map<String,Object> map = new HashMap<String,Object>(json.length()); Iterator keys = json.keys(); while(keys.hasNext()){ String key = (String)keys.next(); try { Object val = json.get(key); // Logger.log(String.format("Hello! %s", json.get(key).getClass().getName())); if (val.getClass().equals(JSONObject.class)) { map.put(key, convertJSON((JSONObject) val)); } else if (val.getClass().equals(JSONArray.class)) { map.put(key, convertJSON((JSONArray) val)); } else { map.put(key, val); } } catch (JSONException e) { Logger.log(TAG, String.format("Failed to convert JSON: %s", e.getMessage()), e); } } return map; } public static List<Object> convertJSON(JSONArray json){ List<Object> list = new ArrayList<Object>(json.length()); for (int i=0; i<json.length(); i++) { try { Object val = json.get(i); if (val.getClass().equals(JSONObject.class)) { list.add(convertJSON((JSONObject) val)); } else if (val.getClass().equals(JSONArray.class)) { list.add(convertJSON((JSONArray) val)); } else { list.add(val); } } catch (JSONException e) { Logger.log(TAG, String.format("Faile to convert JSON: %s", e.getMessage()), e); } } return list; } public static JSONObject serializeJSON(Map<String,Object>map){ JSONObject json = new JSONObject(); Iterator<String> keys = map.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); Object val = map.get(key); try { if (val instanceof Map) { json.put(key, serializeJSON((Map<String,Object>) val)); } else if(val instanceof List){ json.put(key, serializeJSON((List<Object>) val)); } else if(val instanceof Change){ json.put(key, serializeJSON(((Change) val).toJSONSerializable())); } else { json.put(key, val); } } catch(JSONException e){ Logger.log(TAG, String.format("Failed to serialize %s", val)); } } return json; } public static JSONArray serializeJSON(List<Object>list){ JSONArray json = new JSONArray(); Iterator<Object> vals = list.iterator(); while(vals.hasNext()){ Object val = vals.next(); if (val instanceof Map) { json.put(serializeJSON((Map<String,Object>) val)); } else if(val instanceof List) { json.put(serializeJSON((List<Object>) val)); } else if(val instanceof Change){ json.put(serializeJSON(((Change) val).toJSONSerializable())); } else { json.put(val); } } return json; } }
package test; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import TestaInte.EmptyDirectory; import TestaInte.SmallDirectory; public class EkvivalensklassTest { private LsOutputTemp outputTest; private ArrayList<String> test; @Before public void beforeTest(){ outputTest = new LsOutputTemp(); test = new ArrayList<>(); } @Test(expected = NullPointerException.class) public void nullTest(){ outputTest.showContentWithoutSize(null); } @Test public void showFilesTest(){ test.add("Directory: Directory1"); test.add("File: File1"); test.add("File: File2"); outputTest.showContentWithoutSize(new SmallDirectory("TestName")); assertEquals(test, outputTest.showFilesOutput); } @Test public void showEmpty(){ test.add("Directory is empty"); outputTest.showContentWithoutSize(new EmptyDirectory("TestName")); assertEquals(test, outputTest.showFilesOutput); } @Test public void showFilesSizeTest(){ test.add("Directory: Directory1 Size: 0"); test.add("File: File1 Size: 50"); test.add("File: File2 Size: 100"); outputTest.showContentSize(new SmallDirectory("TestName")); assertEquals(test, outputTest.showFilesOutput); } @Test public void showFilesSortedTest(){ test.add("Directory: Directory1 Size: 0"); test.add("File: File2 Size: 100"); test.add("File: File1 Size: 50"); outputTest.showContentSortedSize(new SmallDirectory("TestName")); assertEquals(test, outputTest.showFilesOutput); } @Test public void showFilesSizeEmptyDirectoryTest(){ test.add("Directory is empty"); outputTest.showContentSize(new EmptyDirectory("TestName")); assertEquals(test, outputTest.showFilesOutput); } @Test public void showFilesSortedEmptyDirectoryTest(){ test.add("Directory is empty"); outputTest.showContentSortedSize(new EmptyDirectory("TestName")); assertEquals(test, outputTest.showFilesOutput); } }
package com.ecyrd.jspwiki; import java.util.Properties; import java.io.*; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.auth.Users; import com.ecyrd.jspwiki.providers.*; /** * Simple test engine that always assumes pages are found. */ public class TestEngine extends WikiEngine { static Logger log = Logger.getLogger( TestEngine.class ); private HttpSession m_adminSession; private HttpSession m_janneSession; private WikiSession m_adminWikiSession; private WikiSession m_janneWikiSession; /** * Creates WikiSession with the privileges of the administrative user. * For testing purposes, obviously. * @return the wiki session */ public WikiSession adminSession() { return m_adminWikiSession; } /** * Creates WikiSession with the privileges of the Janne. * For testing purposes, obviously. * @return the wiki session */ public WikiSession janneSession() { return m_janneWikiSession; } public TestEngine( Properties props ) throws WikiException { super( props ); // Set up long-running admin session TestHttpServletRequest request = new TestHttpServletRequest(); request.setRemoteAddr( "53.33.128.9" ); m_adminWikiSession = WikiSession.getWikiSession( this, request ); this.getAuthenticationManager().login( m_adminWikiSession, Users.ADMIN, Users.ADMIN_PASS ); m_adminSession = request.getSession(); // Set up a test Janne session request = new TestHttpServletRequest(); request.setRemoteAddr( "42.22.17.8" ); m_janneWikiSession = WikiSession.getWikiSession( this, request ); this.getAuthenticationManager().login( m_janneWikiSession, Users.JANNE, Users.JANNE_PASS ); m_janneSession = request.getSession(); } public static void emptyWorkDir() { Properties properties = new Properties(); try { properties.load( findTestProperties() ); String workdir = properties.getProperty( WikiEngine.PROP_WORKDIR ); if( workdir != null ) { File f = new File( workdir ); if( f.exists() && f.isDirectory() && new File( f, "refmgr.ser" ).exists() ) { deleteAll( f ); } } } catch( IOException e ) {} // Fine } public static final InputStream findTestProperties() { return findTestProperties( "/jspwiki.properties" ); } public static final InputStream findTestProperties( String properties ) { InputStream in = TestEngine.class.getResourceAsStream( properties ); if( in == null ) throw new InternalWikiException("Unable to locate test property resource: "+properties); return in; } /** * Deletes all files under this directory, and does them recursively. */ public static void deleteAll( File file ) { if( file != null ) { if( file.isDirectory() ) { File[] files = file.listFiles(); if( files != null ) { for( int i = 0; i < files.length; i++ ) { if( files[i].isDirectory() ) { deleteAll(files[i]); } files[i].delete(); } } } file.delete(); } } /** * Copied from FileSystemProvider */ protected static String mangleName( String pagename ) throws IOException { Properties properties = new Properties(); String m_encoding = properties.getProperty( WikiEngine.PROP_ENCODING, AbstractFileProvider.DEFAULT_ENCODING ); pagename = TextUtil.urlEncode( pagename, m_encoding ); pagename = TextUtil.replaceString( pagename, "/", "%2F" ); return pagename; } /** * Removes a page, but not any auxiliary information. Works only * with FileSystemProvider. */ public static void deleteTestPage( String name ) { Properties properties = new Properties(); try { properties.load( findTestProperties() ); String files = properties.getProperty( FileSystemProvider.PROP_PAGEDIR ); File f = new File( files, mangleName(name)+FileSystemProvider.FILE_EXT ); f.delete(); // Remove the property file, too f = new File( files, mangleName(name)+".properties" ); if( f.exists() ) f.delete(); } catch( Exception e ) { log.error("Couldn't delete "+name, e ); } } /** * Deletes all attachments related to the given page. */ public void deleteAttachments( String page ) { try { String files = getWikiProperties().getProperty( BasicAttachmentProvider.PROP_STORAGEDIR ); File f = new File( files, TextUtil.urlEncodeUTF8( page ) + BasicAttachmentProvider.DIR_EXTENSION ); deleteAll( f ); } catch( Exception e ) { log.error("Could not remove attachments.",e); } } /** * Makes a temporary file with some content, and returns a handle to it. */ public File makeAttachmentFile() throws Exception { File tmpFile = File.createTempFile("test","txt"); tmpFile.deleteOnExit(); FileWriter out = new FileWriter( tmpFile ); FileUtil.copyContents( new StringReader( "asdfa???dfzbvasdjkfbwfkUg783gqdwog" ), out ); out.close(); return tmpFile; } /** * Adds an attachment to a page for testing purposes. * @param pageName * @param attachmentName * @param data */ public void addAttachment( String pageName, String attachmentName, byte[] data ) throws ProviderException, IOException { Attachment att = new Attachment(this,pageName,attachmentName); getAttachmentManager().storeAttachment(att, new ByteArrayInputStream(data)); } /** * Convenience method that saves a wiki page by constructing a fake * WikiContext and HttpServletRequest. We always want to do this using a * WikiContext whose subject contains Role.ADMIN. * @param pageName * @param content * @throws WikiException */ public void saveText( String pageName, String content ) throws WikiException { // Build new request and associate our admin session TestHttpServletRequest request = new TestHttpServletRequest(); request.m_session = m_adminSession; // Create page and wiki context WikiPage page = new WikiPage( this, pageName ); WikiContext context = new WikiContext( this, request, page ); saveText( context, content ); } public void saveTextAsJanne( String pageName, String content ) throws WikiException { // Build new request and associate our Janne session TestHttpServletRequest request = new TestHttpServletRequest(); request.m_session = m_janneSession; // Create page and wiki context WikiPage page = new WikiPage( this, pageName ); WikiContext context = new WikiContext( this, request, page ); saveText( context, content ); } public static void trace() { try { throw new Exception("Foo"); } catch( Exception e ) { e.printStackTrace(); } } }
package com.cloud.vm; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager.OnError; import com.cloud.agent.api.Answer; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; import com.cloud.cluster.ClusterManager; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; import com.cloud.deploy.DeploymentPlanner; import com.cloud.deploy.DeploymentPlanner.ExcludeList; import com.cloud.domain.dao.DomainDao; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventVO; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientServerCapacityException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuru; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; import com.cloud.storage.Volume.VolumeType; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.utils.Journal; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.StateListener; import com.cloud.utils.fsm.StateMachine2; import com.cloud.vm.ItWorkVO.Step; import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value=VirtualMachineManager.class) public class VirtualMachineManagerImpl implements VirtualMachineManager { private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class); String _name; @Inject protected StorageManager _storageMgr; @Inject protected NetworkManager _networkMgr; @Inject protected AgentManager _agentMgr; @Inject protected VMInstanceDao _vmDao; @Inject protected ServiceOfferingDao _offeringDao; @Inject protected VMTemplateDao _templateDao; @Inject protected UserDao _userDao; @Inject protected AccountDao _accountDao; @Inject protected DomainDao _domainDao; @Inject protected ClusterManager _clusterMgr; @Inject protected ItWorkDao _workDao; @Inject protected UserVmDao _userVmDao; @Inject protected DomainRouterDao _routerDao; @Inject protected ConsoleProxyDao _consoleDao; @Inject protected SecondaryStorageVmDao _secondaryDao; @Inject protected UsageEventDao _usageEventDao; @Inject protected NicDao _nicsDao; @Inject(adapter=DeploymentPlanner.class) protected Adapters<DeploymentPlanner> _planners; @Inject(adapter=StateListener.class) protected Adapters<StateListener<State, VirtualMachine.Event, VMInstanceVO>> _stateListner; Map<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>>(); Map<HypervisorType, HypervisorGuru> _hvGurus = new HashMap<HypervisorType, HypervisorGuru>(); protected StateMachine2<State, VirtualMachine.Event, VMInstanceVO> _stateMachine; ScheduledExecutorService _executor = null; protected int _retry; protected long _nodeId; protected long _cleanupWait; protected long _cleanupInterval; protected long _cancelWait; protected long _opWaitInterval; protected int _lockStateRetry; @Override public <T extends VMInstanceVO> void registerGuru(VirtualMachine.Type type, VirtualMachineGuru<T> guru) { synchronized(_vmGurus) { _vmGurus.put(type, guru); } } @Override @DB public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Pair<? extends DiskOfferingVO, Long> rootDiskOffering, List<Pair<DiskOfferingVO, Long>> dataDiskOfferings, List<Pair<NetworkVO, NicProfile>> networks, Map<String, Object> params, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { if (s_logger.isDebugEnabled()) { s_logger.debug("Allocating entries for VM: " + vm); } VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, serviceOffering, owner, params); vm.setDataCenterId(plan.getDataCenterId()); if (plan.getPodId() != null) { vm.setPodId(plan.getPodId()); } assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet"; @SuppressWarnings("unchecked") VirtualMachineGuru<T> guru = (VirtualMachineGuru<T>)_vmGurus.get(vm.getType()); Transaction txn = Transaction.currentTxn(); txn.start(); vm = guru.persist(vm); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocating nics for " + vm); } try { _networkMgr.allocate(vmProfile, networks); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e); } if (dataDiskOfferings == null) { dataDiskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(0); } if (s_logger.isDebugEnabled()) { s_logger.debug("Allocaing disks for " + vm); } if (template.getFormat() == ImageFormat.ISO) { _storageMgr.allocateRawVolume(VolumeType.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vm, owner); } else { _storageMgr.allocateTemplatedVolume(VolumeType.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), template, vm, owner); } for (Pair<DiskOfferingVO, Long> offering : dataDiskOfferings) { _storageMgr.allocateRawVolume(VolumeType.DATADISK, "DATA-" + vm.getId(), offering.first(), offering.second(), vm, owner); } stateTransitTo(vm, Event.OperationSucceeded, null); txn.commit(); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocation completed for VM: " + vm); } return vm; } protected void reserveNics(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { // List<NicVO> nics = _nicsDao.listBy(vmProfile.getId()); // for (NicVO nic : nics) { // Pair<NetworkGuru, NetworkVO> implemented = _networkMgr.implementNetwork(nic.getNetworkId(), dest, context); // NetworkGuru concierge = implemented.first(); // NetworkVO network = implemented.second(); // NicProfile profile = null; // if (nic.getReservationStrategy() == ReservationStrategy.Start) { // nic.setState(Resource.State.Reserving); // nic.setReservationId(context.getReservationId()); // _nicsDao.update(nic.getId(), nic); // URI broadcastUri = nic.getBroadcastUri(); // if (broadcastUri == null) { // network.getBroadcastUri(); // URI isolationUri = nic.getIsolationUri(); // profile = new NicProfile(nic, network, broadcastUri, isolationUri); // concierge.reserve(profile, network, vmProfile, dest, context); // nic.setIp4Address(profile.getIp4Address()); // nic.setIp6Address(profile.getIp6Address()); // nic.setMacAddress(profile.getMacAddress()); // nic.setIsolationUri(profile.getIsolationUri()); // nic.setBroadcastUri(profile.getBroadCastUri()); // nic.setReserver(concierge.getName()); // nic.setState(Resource.State.Reserved); // nic.setNetmask(profile.getNetmask()); // nic.setGateway(profile.getGateway()); // nic.setAddressFormat(profile.getFormat()); // _nicsDao.update(nic.getId(), nic); // } else { // profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri()); // for (NetworkElement element : _networkElements) { // if (s_logger.isDebugEnabled()) { // s_logger.debug("Asking " + element.getName() + " to prepare for " + nic); // element.prepare(network, profile, vmProfile, dest, context); // vmProfile.addNic(profile); // _networksDao.changeActiveNicsBy(network.getId(), 1); } protected void prepareNics(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, DeployDestination dest, ReservationContext context) { } @Override public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Long rootSize, Pair<DiskOfferingVO, Long> dataDiskOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { List<Pair<DiskOfferingVO, Long>> diskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(1); if (dataDiskOffering != null) { diskOfferings.add(dataDiskOffering); } return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, rootSize), diskOfferings, networks, null, plan, hyperType, owner); } @Override public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, null), null, networks, null, plan, hyperType, owner); } @SuppressWarnings("unchecked") private <T extends VMInstanceVO> VirtualMachineGuru<T> getVmGuru(T vm) { return (VirtualMachineGuru<T>)_vmGurus.get(vm.getType()); } @Override public <T extends VMInstanceVO> boolean expunge(T vm, User caller, Account account) throws ResourceUnavailableException { try { return advanceExpunge(vm, caller, account); } catch (OperationTimedoutException e) { throw new CloudRuntimeException("Operation timed out", e); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation ", e); } } @Override public <T extends VMInstanceVO> boolean advanceExpunge(T vm, User caller, Account account) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { if (vm == null || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vm); } return true; } if (!this.advanceStop(vm, false, caller, account)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to stop the VM so we can't expunge it."); } } if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm.toString()); return false; } if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm); } VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); _networkMgr.cleanupNics(profile); //Clean up volumes based on the vm's instance id _storageMgr.cleanupVolumes(vm.getId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Expunged " + vm); } return true; } @Override public boolean start() { _executor.scheduleAtFixedRate(new CleanupTask(), _cleanupInterval, _cleanupInterval, TimeUnit.SECONDS); return true; } @Override public boolean stop() { return true; } @Override public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException { _name = name; ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); Map<String, String> params = configDao.getConfiguration(xmlParams); _retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 10); ReservationContextImpl.setComponents(_userDao, _domainDao, _accountDao); VirtualMachineProfileImpl.setComponents(_offeringDao, _templateDao, _accountDao); Adapters<HypervisorGuru> hvGurus = locator.getAdapters(HypervisorGuru.class); for (HypervisorGuru guru : hvGurus) { _hvGurus.put(guru.getHypervisorType(), guru); } _cancelWait = NumbersUtil.parseLong(params.get(Config.VmOpCancelInterval.key()), 3600); _cleanupWait = NumbersUtil.parseLong(params.get(Config.VmOpCleanupWait.key()), 3600); _cleanupInterval = NumbersUtil.parseLong(params.get(Config.VmOpCleanupInterval.key()), 86400) * 1000; _opWaitInterval = NumbersUtil.parseLong(params.get(Config.VmOpWaitInterval.key()), 120) * 1000; _lockStateRetry = NumbersUtil.parseInt(params.get(Config.VmOpLockStateRetry.key()), 5); _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup")); _nodeId = _clusterMgr.getId(); setStateMachine(); return true; } @Override public String getName() { return _name; } protected VirtualMachineManagerImpl() { } @Override public <T extends VMInstanceVO> T start(T vm, Map<String, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException { try { return advanceStart(vm, params, caller, account); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e); } } private Answer getStartAnswer(Answer[] answers) { for (Answer ans : answers) { if (ans instanceof StartAnswer) { return ans; } } assert false : "Why there is no Start Answer???"; return null; } protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException { while (true) { ItWorkVO vo = _workDao.findByInstance(vm.getId(), state); if (vo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find work for " + vm); } return true; } if (vo.getStep() == Step.Done || vo.getStep() == Step.Cancelled) { if (s_logger.isDebugEnabled()) { s_logger.debug("Work for " + vm + " is " + vo.getStep()); } return true; } if (vo.getSecondsTaskIsInactive() > _cancelWait) { s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive()); return false; } try { Thread.sleep(_opWaitInterval); } catch (InterruptedException e) { s_logger.info("Waiting for " + vm + " but is interrupted"); throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted"); } s_logger.debug("Waiting some more to make sure there's no activity on " + vm); } } @DB protected <T extends VMInstanceVO> Ternary<T, ReservationContext, ItWorkVO> changeToStartState(VirtualMachineGuru<T> vmGuru, T vm, User caller, Account account) throws ConcurrentOperationException { long vmId = vm.getId(); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getId()); int retry = _lockStateRetry; while (retry Transaction txn = Transaction.currentTxn(); txn.start(); if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) { Journal journal = new Journal.LogJournal("Creating " + vm, s_logger); work = _workDao.persist(work); ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account); if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId()); } txn.commit(); return new Ternary<T, ReservationContext, ItWorkVO>(vmGuru.findById(vmId), context, work); } if (s_logger.isDebugEnabled()) { s_logger.debug("Determining why we're unable to update the state to Starting for " + vm); } VMInstanceVO instance = _vmDao.lockRow(vmId, true); if (instance == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + vm); } State state = instance.getState(); if (state == State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already started: " + vm); } txn.commit(); return null; } if (state.isTransitional()) { if (!checkWorkItems(vm, state)) { throw new ConcurrentOperationException("There are concurrent operations on the VM " + vm); } else { continue; } } if (state != State.Stopped) { s_logger.debug("VM " + vm + " is not in a state to be started: " + state); txn.commit(); return null; } } throw new ConcurrentOperationException("Unable to change the state of " + vm); } @Override public <T extends VMInstanceVO> T advanceStart(T vm, Map<String, Object> params, User caller, Account account) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { long vmId = vm.getId(); VirtualMachineGuru<T> vmGuru = getVmGuru(vm); Ternary<T, ReservationContext, ItWorkVO> start = changeToStartState(vmGuru, vm, caller, account); if (start == null) { return vmGuru.findById(vmId); } vm = start.first(); ReservationContext ctx = start.second(); ItWorkVO work = start.third(); T startedVm = null; try { ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId()); VMTemplateVO template = _templateDao.findById(vm.getTemplateId()); DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), vm.getPodId(), null, null); HypervisorGuru hvGuru = _hvGurus.get(vm.getHypervisorType()); VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, offering, null, params); Journal journal = start.second().getJournal(); ExcludeList avoids = new ExcludeList(); int retry = _retry; while (retry-- != 0) { // It's != so that it can match -1. DeployDestination dest = null; for (DeploymentPlanner planner : _planners) { dest = planner.plan(vmProfile, plan, avoids); if (dest != null) { avoids.addHost(dest.getHost().getId()); journal.record("Deployment found ", vmProfile, dest); break; } } if (dest == null) { throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId()); } stateTransitTo(vm, Event.OperationRetry, dest.getHost().getId()); try { _storageMgr.prepare(vmProfile, dest); _networkMgr.prepare(vmProfile, dest, ctx); } catch (ResourceUnavailableException e) { if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { throw e; } else { throw new CloudRuntimeException("Resource is not available to start the VM.", e); } } s_logger.info("Unable to contact resource.", e); continue; } catch (InsufficientCapacityException e) { if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { throw e; } else { throw new CloudRuntimeException("Insufficient capacity to start the VM.", e); } } s_logger.info("Insufficient capacity ", e); continue; } catch (RuntimeException e) { s_logger.warn("Failed to start instance " + vm, e); throw new CloudRuntimeException("Failed to start " + vm, e); } vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx); VirtualMachineTO vmTO = hvGuru.implement(vmProfile); Commands cmds = new Commands(OnError.Revert); cmds.addCommand(new StartCommand(vmTO)); vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx); vm.setPodId(dest.getPod().getId()); try { Answer[] answers = _agentMgr.send(dest.getHost().getId(), cmds); if (getStartAnswer(answers).getResult() && vmGuru.finalizeStart(cmds, vmProfile, dest, ctx)) { if (!stateTransitTo(vm, Event.OperationSucceeded, dest.getHost().getId())) { throw new CloudRuntimeException("Unable to transition to a new state."); } startedVm = vm; break; } s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + answers[0].getDetails()); } catch (AgentUnavailableException e) { s_logger.debug("Unable to send the start command to host " + dest.getHost()); continue; } catch (OperationTimedoutException e) { s_logger.debug("Unable to send the start command to host " + dest.getHost()); continue; } } if (s_logger.isDebugEnabled()) { s_logger.debug("Creation complete for VM " + vm); } } finally { if (startedVm == null) { stateTransitTo(vm, Event.OperationFailed, null); } work.setStep(Step.Done); _workDao.update(work.getId(), work); } return startedVm; } @Override public <T extends VMInstanceVO> boolean stop(T vm, User user, Account account) throws ResourceUnavailableException { try { return advanceStop(vm, false, user, account); } catch (OperationTimedoutException e) { throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", vm.getHostId(), e); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e); } } @Override public <T extends VMInstanceVO> boolean advanceStop(T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { State state = vm.getState(); if (state == State.Stopped) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already stopped: " + vm); } return true; } if (state == State.Creating || state == State.Destroyed || state == State.Expunging || state == State.Error) { s_logger.debug("Stopped called on " + vm + " but the state is " + state); return true; } if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) { throw new ConcurrentOperationException("VM is being operated on by someone else."); } if (vm.getHostId() == null) { s_logger.debug("Host id is null so we can't stop it. How did we get into here?"); return false; } String reservationId = vm.getReservationId(); StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null); boolean stopped = false; StopAnswer answer = null; try { answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop); stopped = answer.getResult(); if (!stopped) { throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails()); } else { UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_STOP, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), vm.getServiceOfferingId(), vm.getTemplateId(), null); _usageEventDao.persist(usageEvent); } } finally { if (!stopped) { if (!forced) { stateTransitTo(vm, Event.OperationFailed, vm.getHostId()); } else { s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop"); } } } if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is stopped on the host. Proceeding to release resource held."); } boolean cleanup = false; VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); try { _networkMgr.release(profile, forced); s_logger.debug("Successfully released network resources for the vm " + vm); } catch (Exception e) { s_logger.warn("Unable to release some network resources.", e); cleanup = true; } try { _storageMgr.release(profile); s_logger.debug("Successfully released storage resources for the vm " + vm); } catch (Exception e) { s_logger.warn("Unable to release storage resources.", e); cleanup = true; } @SuppressWarnings("unchecked") VirtualMachineGuru<T> guru = (VirtualMachineGuru<T>)_vmGurus.get(vm.getType()); try { guru.finalizeStop(profile, vm.getHostId(), vm.getReservationId(), answer); } catch (Exception e) { s_logger.warn("Guru " + guru.getClass() + " has trouble processing stop "); cleanup = true; } vm.setReservationId(null); stateTransitTo(vm, Event.OperationSucceeded, null); if (cleanup) { ItWorkVO work = new ItWorkVO(reservationId, _nodeId, State.Stopping, vm.getId()); _workDao.persist(work); } return stopped; } private void setStateMachine() { _stateMachine = new StateMachine2<State, VirtualMachine.Event, VMInstanceVO>(); _stateMachine.addTransition(null, VirtualMachine.Event.CreateRequested, State.Creating); _stateMachine.addTransition(State.Creating, VirtualMachine.Event.OperationSucceeded, State.Stopped); _stateMachine.addTransition(State.Creating, VirtualMachine.Event.OperationFailed, State.Error); _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.StartRequested, State.Starting); _stateMachine.addTransition(State.Error, VirtualMachine.Event.DestroyRequested, State.Expunging); _stateMachine.addTransition(State.Error, VirtualMachine.Event.ExpungeOperation, State.Expunging); _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.DestroyRequested, State.Destroyed); _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.StopRequested, State.Stopped); _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.AgentReportStopped, State.Stopped); _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.OperationFailed, State.Error); _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.ExpungeOperation, State.Expunging); _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.AgentReportShutdowned, State.Stopped); _stateMachine.addTransition(State.Starting, VirtualMachine.Event.OperationRetry, State.Starting); _stateMachine.addTransition(State.Starting, VirtualMachine.Event.OperationSucceeded, State.Running); _stateMachine.addTransition(State.Starting, VirtualMachine.Event.OperationFailed, State.Stopped); _stateMachine.addTransition(State.Starting, VirtualMachine.Event.AgentReportRunning, State.Running); _stateMachine.addTransition(State.Starting, VirtualMachine.Event.AgentReportStopped, State.Stopped); _stateMachine.addTransition(State.Starting, VirtualMachine.Event.AgentReportShutdowned, State.Stopped); _stateMachine.addTransition(State.Destroyed, VirtualMachine.Event.RecoveryRequested, State.Stopped); _stateMachine.addTransition(State.Destroyed, VirtualMachine.Event.ExpungeOperation, State.Expunging); _stateMachine.addTransition(State.Creating, VirtualMachine.Event.MigrationRequested, State.Destroyed); _stateMachine.addTransition(State.Running, VirtualMachine.Event.MigrationRequested, State.Migrating); _stateMachine.addTransition(State.Running, VirtualMachine.Event.AgentReportRunning, State.Running); _stateMachine.addTransition(State.Running, VirtualMachine.Event.AgentReportStopped, State.Stopped); _stateMachine.addTransition(State.Running, VirtualMachine.Event.StopRequested, State.Stopping); _stateMachine.addTransition(State.Running, VirtualMachine.Event.AgentReportShutdowned, State.Stopped); _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.MigrationRequested, State.Migrating); _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.OperationSucceeded, State.Running); _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.OperationFailed, State.Running); _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.MigrationFailedOnSource, State.Running); _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.MigrationFailedOnDest, State.Running); _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.AgentReportRunning, State.Running); _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.AgentReportStopped, State.Stopped); _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.OperationSucceeded, State.Stopped); _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.AgentReportShutdowned, State.Stopped); _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.OperationFailed, State.Running); _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.AgentReportRunning, State.Running); _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.AgentReportStopped, State.Stopped); _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.StopRequested, State.Stopping); _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.AgentReportShutdowned, State.Stopped); _stateMachine.addTransition(State.Expunging, VirtualMachine.Event.OperationFailed, State.Expunging); _stateMachine.addTransition(State.Expunging, VirtualMachine.Event.ExpungeOperation, State.Expunging); _stateMachine.registerListeners(_stateListner); } protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) { vm.setReservationId(reservationId); if (vm instanceof UserVmVO) { return _stateMachine.transitTO(vm, e, hostId, _userVmDao); } else if (vm instanceof ConsoleProxyVO) { return _stateMachine.transitTO(vm, e, hostId, _consoleDao); } else if (vm instanceof SecondaryStorageVmVO) { return _stateMachine.transitTO(vm, e, hostId, _secondaryDao); } else if (vm instanceof DomainRouterVO) { return _stateMachine.transitTO(vm, e, hostId, _routerDao); } else { return _stateMachine.transitTO(vm, e, hostId, _vmDao); } } @Override public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId) { if (vm instanceof UserVmVO) { return _stateMachine.transitTO(vm, e, hostId, _userVmDao); } else if (vm instanceof ConsoleProxyVO) { return _stateMachine.transitTO(vm, e, hostId, _consoleDao); } else if (vm instanceof SecondaryStorageVmVO) { return _stateMachine.transitTO(vm, e, hostId, _secondaryDao); } else if (vm instanceof DomainRouterVO) { return _stateMachine.transitTO(vm, e, hostId, _routerDao); } else { return _stateMachine.transitTO(vm, e, hostId, _vmDao); } } @Override public <T extends VMInstanceVO> boolean remove(T vm, User user, Account caller) { return _vmDao.remove(vm.getId()); } @Override public <T extends VMInstanceVO> boolean destroy(T vm, User user, Account caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm.toString()); } if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vm); } return true; } if (!advanceStop(vm, false, user, caller)) { s_logger.debug("Unable to stop " + vm); return false; } if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm.toString()); return false; } return true; } protected class CleanupTask implements Runnable { @Override public void run() { s_logger.trace("VM Operation Thread Running"); try { _workDao.cleanup(_cleanupWait); } catch (Exception e) { s_logger.error("VM Operations failed due to ", e); } } } }
package com.ecyrd.jspwiki; import java.util.Properties; public class TestEngine extends WikiEngine { public TestEngine( Properties props ) { super( props ); } public boolean pageExists( String page ) { return true; } }
package org._2585robophiles.frc2015.systems; import org._2585robophiles.frc2015.Environment; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; /* * The robot vision is implemented in this class. */ public class RoboRealmSystem implements RobotSystem, ITableListener { private final double MIN_AREA = 0; // The value is 0 for testing purposes // only. private final double MAX_AREA = 1; // The value is 1 for testing purposes // only. private double distance; private final double DISTANCE_CONSTANT = 0; // The value is 0 for testing // purposes only. private double area; private double xCoord; private double yCoord; private NetworkTable nt; /** * Nothing is done in this constructor */ public RoboRealmSystem() { } /* * (non-Javadoc) * * @see * org._2585robophiles.aerbot.systems.RobotSystem#init(org._2585robophiles * .aerbot.Environment) */ @Override public void init(Environment environment) { nt = NetworkTable.getTable("VisionTable"); nt.addTableListener(this); setNums(); } /* * (non-Javadoc) * * @see org._2585robophiles.aerbot.systems.RobotSystem#destroy() */ @Override public void destroy() { } /* * (non-Javadoc) * * @see * edu.wpi.first.wpilibj.tables.ITableListener#valueChanged(edu.wpi.first * .wpilibj.tables.ITable, java.lang.String, java.lang.Object, boolean) */ @Override public void valueChanged(ITable itable, String key, Object obj, boolean isNew) { SmartDashboard.putString(key, obj.toString()); setNums(); } public void setNums() { yCoord = nt.getNumber("COG_Y"); xCoord = nt.getNumber("COG_X"); area = nt.getNumber("COG_AREA"); if (MIN_AREA < area && area < MAX_AREA) { distance = area / DISTANCE_CONSTANT; } else { area = -5555; } } public double getDistance() { return distance; } public double getX() { return xCoord; } public double getY() { return yCoord; } }
package org.eclipse.hono; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.eclipse.hono.authorization.AuthorizationService; import org.eclipse.hono.registration.impl.BaseRegistrationAdapter; import org.eclipse.hono.server.HonoServer; import org.eclipse.hono.telemetry.TelemetryAdapter; import org.eclipse.hono.util.Constants; import org.eclipse.hono.util.EndpointFactory; import org.eclipse.hono.util.VerticleFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Verticle; import io.vertx.core.Vertx; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; /** * The Hono server main application class. * <p> * This class uses Spring Boot for configuring and wiring up Hono's components (Verticles). * By default there will be as many instances of each verticle created as there are CPU cores * available. The {@code hono.maxinstances} config property can be used to set the maximum number * of instances to create. This may be useful for executing tests etc. * </p> */ @ComponentScan @Configuration @EnableAutoConfiguration public class Application { private static final Logger LOG = LoggerFactory.getLogger(Application.class); @Value(value = "${hono.maxinstances:0}") private int maxInstances; @Value(value = "${hono.startuptimeout:20}") private int startupTimeout; @Autowired private Vertx vertx; @Autowired private VerticleFactory<TelemetryAdapter> adapterFactory; @Autowired private BaseRegistrationAdapter registration; @Autowired private VerticleFactory<AuthorizationService> authServiceFactory; @Autowired private VerticleFactory<HonoServer> serverFactory; @Autowired private List<EndpointFactory<?>> endpointFactories; private MessageConsumer<Object> restartListener; @PostConstruct public void registerVerticles() { final CountDownLatch startupLatch = new CountDownLatch(1); if (vertx == null) { throw new IllegalStateException("no Vert.x instance has been configured"); } final int instanceCount; if (maxInstances > 0 && maxInstances < Runtime.getRuntime().availableProcessors()) { instanceCount = maxInstances; } else { instanceCount = Runtime.getRuntime().availableProcessors(); } Future<Void> started = Future.future(); started.setHandler(ar -> { if (ar.failed()) { LOG.error("cannot start up HonoServer", ar.cause()); shutdown(); } else { startupLatch.countDown(); } }); CompositeFuture.all(deployVerticle(adapterFactory, instanceCount), deployVerticle(authServiceFactory, instanceCount), deployRegistrationService()).setHandler(ar -> { if (ar.succeeded()) { deployServer(instanceCount, started); } else { started.fail(ar.cause()); } }); restartListener = vertx.eventBus().consumer(Constants.APPLICATION_ENDPOINT).handler(message -> { JsonObject json = (JsonObject) message.body(); String action = json.getString(Constants.APP_PROPERTY_ACTION); if (Constants.ACTION_RESTART.equals(action)) { LOG.info("restarting Hono..."); vertx.eventBus().close(closeHandler -> { List<Future> results = new ArrayList<>(); vertx.deploymentIDs().forEach(id -> { Future<Void> result = Future.future(); vertx.undeploy(id, result.completer()); results.add(result); }); CompositeFuture.all(results).setHandler(ar -> { registerVerticles(); }); }); } else { LOG.warn("received unknown application action [{}], ignoring...", action); } }); try { if (startupLatch.await(startupTimeout, TimeUnit.SECONDS)) { LOG.info("Hono startup completed successfully"); } else { LOG.error("startup timed out after {} seconds, shutting down ...", startupTimeout); shutdown(); } } catch (InterruptedException e) { LOG.error("startup process has been interrupted, shutting down ..."); Thread.currentThread().interrupt(); shutdown(); } } private <T extends Verticle> Future<?> deployVerticle(VerticleFactory<T> factory, int instanceCount) { LOG.info("Starting component {}", factory); @SuppressWarnings("rawtypes") List<Future> results = new ArrayList<>(); for (int i = 1; i <= instanceCount; i++) { Future<String> result = Future.future(); vertx.deployVerticle(factory.newInstance(i, instanceCount), result.completer()); results.add(result); } return CompositeFuture.all(results); } private Future<String> deployRegistrationService() { LOG.info("Starting registration service {}", registration); Future<String> result = Future.future(); vertx.deployVerticle(registration, result.completer()); return result; } private void deployServer(final int instanceCount, Future<Void> startFuture) { @SuppressWarnings("rawtypes") List<Future> results = new ArrayList<>(); for (int i = 1; i <= instanceCount; i++) { HonoServer server = serverFactory.newInstance(i, instanceCount); for (EndpointFactory<?> ef : endpointFactories) { server.addEndpoint(ef.newInstance(i, instanceCount)); } Future<String> result = Future.future(); vertx.deployVerticle(server, result.completer()); results.add(result); } CompositeFuture.all(results).setHandler(ar -> { if (ar.failed()) { startFuture.fail(ar.cause()); } else { startFuture.complete(); } }); } @PreDestroy public void shutdown() { this.shutdown(startupTimeout, succeeded -> { // do nothing }); } public void shutdown(final long maxWaitTime, final Handler<Boolean> shutdownHandler) { try { final CountDownLatch latch = new CountDownLatch(1); if (vertx != null) { LOG.debug("shutting down Hono server..."); if (restartListener != null) { restartListener.unregister(); } vertx.close(r -> { if (r.failed()) { LOG.error("could not shut down Hono cleanly", r.cause()); } latch.countDown(); }); } if (latch.await(maxWaitTime, TimeUnit.SECONDS)) { LOG.info("Hono server has been shut down successfully"); shutdownHandler.handle(Boolean.TRUE); } else { LOG.error("shut down of Hono server timed out, aborting..."); shutdownHandler.handle(Boolean.FALSE); } } catch (InterruptedException e) { LOG.error("shut down of Hono server has been interrupted, aborting..."); Thread.currentThread().interrupt(); shutdownHandler.handle(Boolean.FALSE); } } public static void main(final String[] args) { SpringApplication.run(Application.class, args); } }
package org.ohmage.request.survey; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; 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.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.ohmage.annotator.Annotator.ErrorCode; import org.ohmage.domain.Location; import org.ohmage.domain.campaign.Campaign; import org.ohmage.domain.campaign.Prompt; import org.ohmage.domain.campaign.Prompt.LabelValuePair; import org.ohmage.domain.campaign.PromptResponse; import org.ohmage.domain.campaign.RepeatableSet; import org.ohmage.domain.campaign.RepeatableSetResponse; import org.ohmage.domain.campaign.Response; import org.ohmage.domain.campaign.Response.NoResponse; import org.ohmage.domain.campaign.Survey; import org.ohmage.domain.campaign.SurveyItem; import org.ohmage.domain.campaign.SurveyResponse; import org.ohmage.domain.campaign.SurveyResponse.ColumnKey; import org.ohmage.domain.campaign.SurveyResponse.OutputFormat; import org.ohmage.domain.campaign.SurveyResponse.SortParameter; import org.ohmage.domain.campaign.prompt.ChoicePrompt; import org.ohmage.domain.campaign.prompt.CustomChoicePrompt; import org.ohmage.domain.campaign.response.MultiChoiceCustomPromptResponse; import org.ohmage.domain.campaign.response.MultiChoicePromptResponse; import org.ohmage.domain.campaign.response.SingleChoiceCustomPromptResponse; import org.ohmage.domain.campaign.response.SingleChoicePromptResponse; import org.ohmage.exception.ServiceException; import org.ohmage.exception.ValidationException; import org.ohmage.request.InputKeys; import org.ohmage.request.UserRequest; import org.ohmage.service.CampaignServices; import org.ohmage.service.SurveyResponseReadServices; import org.ohmage.service.SurveyResponseServices; import org.ohmage.service.UserCampaignServices; import org.ohmage.util.DateUtils; import org.ohmage.util.TimeUtils; import org.ohmage.validator.CampaignValidators; import org.ohmage.validator.SurveyResponseValidators; /** * <p>Allows a requester to read survey responses. Supervisors can read survey * responses anytime. Survey response owners (i.e., participants) can read * their own responses anytime. Authors can only read shared responses. * Analysts can read shared responses only if the campaign is shared.</p> * <table border="1"> * <tr> * <td>Parameter Name</td> * <td>Description</td> * <td>Required</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#AUTH_TOKEN}</td> * <td>The requesting user's authentication token.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CLIENT}</td> * <td>A string describing the client that is making this request.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CAMPAIGN_URN}</td> * <td>The campaign URN to use when retrieving responses.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#USER_LIST}</td> * <td>A comma-separated list of usernames to retrieve responses for * or the value {@value URN_SPECIAL_ALL}</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#COLUMN_LIST}</td> * <td>A comma-separated list of the columns to retrieve responses for * or the value {@value #_URN_SPECIAL_ALL}. If {@value #_URN_SPECIAL_ALL} * is not used, the only allowed values are: * {@value org.ohmage.domain.campaign.SurveyResponse.ColumnKey#URN_CONTEXT_CLIENT}, * {@value #URN_CONTEXT_TIMESTAMP}, * {@value #URN_CONTEXT_TIMEZONE}, * {@value #URN_CONTEXT_UTC_TIMESTAMP}, * {@value #URN_CONTEXT_LAUNCH_CONTEXT_LONG}, * {@value #URN_CONTEXT_LAUNCH_CONTEXT_SHORT}, * {@value #URN_CONTEXT_LOCATION_STATUS}, * {@value #URN_CONTEXT_LOCATION_LONGITUDE}, * {@value #URN_CONTEXT_LOCATION_LATITUDE}, * {@value #URN_CONTEXT_LOCATION_TIMESTAMP}, * {@value #URN_CONTEXT_LOCATION_ACCURACY}, * {@value #URN_CONTEXT_LOCATION_PROVIDER}, * {@value #URN_USER_ID}, * {@value #URN_SURVEY_ID}, * {@value #URN_SURVEY_TITLE}, * {@value #URN_SURVEY_DESCRIPTION}, * {@value #URN_SURVEY_PRIVACY_STATE}, * {@value #URN_REPEATABLE_SET_ID}, * {@value #URN_REPEATABLE_SET_ITERATION}, * {@value #URN_PROMPT_RESPONSE} * </td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#OUTPUT_FORMAT}</td> * <td>The desired output format of the results. Must be one of * {@value #_OUTPUT_FORMAT_JSON_ROWS}, {@value #_OUTPUT_FORMAT_JSON_COLUMNS}, * or, {@value #_OUTPUT_FORMAT_CSV}</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#PROMPT_ID_LIST}</td> * <td>A comma-separated list of prompt ids to retrieve responses for * or the value {@link #_URN_SPECIAL_ALL}. This key is only * optional if {@value org.ohmage.request.InputKeys#SURVEY_ID_LIST} * is not present.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#SURVEY_ID_LIST}</td> * <td>A comma-separated list of survey ids to retrieve responses for * or the value {@link #_URN_SPECIAL_ALL}. This key is only * optional if {@value org.ohmage.request.InputKeys#PROMPT_ID_LIST} * is not present.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#START_DATE}</td> * <td>The start date to use for results between dates. * Required if end date is present.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#END_DATE}</td> * <td>The end date to use for results between dates. * Required if start date is present.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#SORT_ORDER}</td> * <td>The sort order to use i.e., the SQL order by.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#SUPPRESS_METADATA}</td> * <td>For {@value #_OUTPUT_FORMAT_CSV} output, whether to suppress the * metadata section from the output</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#PRETTY_PRINT}</td> * <td>For JSON-based output, whether to pretty print the output</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#RETURN_ID}</td> * <td>For {@value #_OUTPUT_FORMAT_JSON_ROWS} output, whether to return * the id on each result. The web front-end uses the id value to perform * updates.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#PRIVACY_STATE}</td> * <td>Filters the results by their associated privacy state.</td> * <td>false</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#COLLAPSE}</td> * <td>Filters the results by uniqueness.</td> * <td>false</td> * </tr> * </table> * * @author Joshua Selsky */ public final class SurveyResponseReadRequest extends UserRequest { private static final Logger LOGGER = Logger.getLogger(SurveyResponseReadRequest.class); /** * The JSON key for the metadata associated with a response read request. */ public static final String JSON_KEY_METADATA = "metadata"; /** * The, optional, additional JSON key associated with a prompt responses in * the * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_COLUMNS JSON_COLUMNS} * format representing additional information about the prompt's responses. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_COLUMNS */ public static final String JSON_KEY_CONTEXT = "context"; /** * The JSON key associated with a prompt responses in the * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_COLUMNS JSON_COLUMNS} * format representing the values for the prompt response. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_COLUMNS */ public static final String JSON_KEY_VALUES = "values"; /** * The JSON key in the metadata for * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS JSON_ROWS} * representing the number of unique surveys in the results. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS */ public static final String JSON_KEY_NUM_SURVEYS = "number_of_surveys"; /** * The JSON key in the metadata for * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS JSON_ROWS} * representing the number of unique prompts in the results. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS */ public static final String JSON_KEY_NUM_PROMPTS = "number_of_prompts"; /** * The JSON key in the metadata for * {@link org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS JSON_ROWS} * output representing the keys in the data portion of the response. * * @see org.ohmage.domain.campaign.SurveyResponse.OutputFormat#JSON_ROWS */ public static final String JSON_KEY_ITEMS = "items"; /** * The JSON key associated with every record if the input parameter * {@link org.ohmage.request.InputKeys#COLLAPSE collapse} is true. * * @see org.ohmage.request.InputKeys#COLLAPSE */ public static final String JSON_KEY_COUNT = "count"; public static final String URN_SPECIAL_ALL = "urn:ohmage:special:all"; public static final Collection<String> URN_SPECIAL_ALL_LIST; static { URN_SPECIAL_ALL_LIST = new HashSet<String>(); URN_SPECIAL_ALL_LIST.add(URN_SPECIAL_ALL); } private static final int MAX_NUMBER_OF_USERS = 10; private static final int MAX_NUMBER_OF_SURVEYS = 10; private static final int MAX_NUMBER_OF_PROMPTS = 10; private final String campaignId; private final Collection<SurveyResponse.ColumnKey> columns; private final Collection<String> usernames; private final SurveyResponse.OutputFormat outputFormat; private final Collection<String> surveyIds; private final Collection<String> promptIds; private final Date startDate; private final Date endDate; private final List<SortParameter> sortOrder; private final SurveyResponse.PrivacyState privacyState; private final Boolean collapse; private final Boolean prettyPrint; private final Boolean returnId; private final Boolean suppressMetadata; private Campaign campaign; private List<SurveyResponse> surveyResponseList; /** * Creates a survey response read request. * * @param httpRequest The request to retrieve parameters from. */ public SurveyResponseReadRequest(HttpServletRequest httpRequest) { // Handle user-password or token-based authentication super(httpRequest, TokenLocation.EITHER, false); String tCampaignId = null; Set<SurveyResponse.ColumnKey> tColumns = null; Set<String> tUsernames = null; SurveyResponse.OutputFormat tOutputFormat = null; Set<String> tSurveyIds = null; Set<String> tPromptIds = null; Date tStartDate = null; Date tEndDate = null; List<SortParameter> tSortOrder = null; SurveyResponse.PrivacyState tPrivacyState = null; Boolean tCollapse = null; Boolean tPrettyPrint = null; Boolean tReturnId = null; Boolean tSuppressMetadata = null; if(! isFailed()) { LOGGER.info("Creating a survey response read request."); String[] t; try { // Campaign ID t = getParameterValues(InputKeys.CAMPAIGN_URN); if(t.length == 0) { setFailed(ErrorCode.CAMPAIGN_INVALID_ID, "The required campaign ID was not present: " + InputKeys.CAMPAIGN_URN); throw new ValidationException("The required campaign ID was not present: " + InputKeys.CAMPAIGN_URN); } else if(t.length > 1) { setFailed(ErrorCode.CAMPAIGN_INVALID_ID, "Multiple campaign IDs were found: " + InputKeys.CAMPAIGN_URN); throw new ValidationException("Multiple campaign IDs were found: " + InputKeys.CAMPAIGN_URN); } else { tCampaignId = CampaignValidators.validateCampaignId(t[0]); if(tCampaignId == null) { setFailed(ErrorCode.CAMPAIGN_INVALID_ID, "The required campaign ID was not present: " + InputKeys.CAMPAIGN_URN); throw new ValidationException("The required campaign ID was not present: " + InputKeys.CAMPAIGN_URN); } } // Column List t = getParameterValues(InputKeys.COLUMN_LIST); if(t.length == 0) { setFailed(ErrorCode.SURVEY_INVALID_COLUMN_ID, "The required column list was missing: " + InputKeys.COLUMN_LIST); throw new ValidationException("The required column list was missing: " + InputKeys.COLUMN_LIST); } else if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_COLUMN_ID, "Multiple column lists were given: " + InputKeys.COLUMN_LIST); throw new ValidationException("Multiple column lists were given: " + InputKeys.COLUMN_LIST); } else { tColumns = SurveyResponseValidators.validateColumnList(t[0]); if(tColumns == null) { setFailed(ErrorCode.SURVEY_INVALID_COLUMN_ID, "The required column list was missing: " + InputKeys.COLUMN_LIST); throw new ValidationException("The required column list was missing: " + InputKeys.COLUMN_LIST); } } // User List t = getParameterValues(InputKeys.USER_LIST); if(t.length == 0) { setFailed(ErrorCode.SURVEY_MALFORMED_USER_LIST, "The user list is missing: " + InputKeys.USER_LIST); throw new ValidationException("The user list is missing: " + InputKeys.USER_LIST); } else if(t.length > 1) { setFailed(ErrorCode.SURVEY_MALFORMED_USER_LIST, "Mutliple user lists were given: " + InputKeys.USER_LIST); throw new ValidationException("Mutliple user lists were given: " + InputKeys.USER_LIST); } else { tUsernames = SurveyResponseValidators.validateUsernames(t[0]); if(tUsernames == null) { setFailed(ErrorCode.SURVEY_MALFORMED_USER_LIST, "The user list is missing: " + InputKeys.USER_LIST); throw new ValidationException("The user list is missing: " + InputKeys.USER_LIST); } else if(tUsernames.size() > MAX_NUMBER_OF_USERS) { setFailed(ErrorCode.SURVEY_TOO_MANY_USERS, "The user list contains more than " + MAX_NUMBER_OF_USERS + " users: " + tUsernames.size()); throw new ValidationException("The user list contains more than " + MAX_NUMBER_OF_USERS + " users: " + tUsernames.size()); } } // Output Format t = getParameterValues(InputKeys.OUTPUT_FORMAT); if(t.length == 0) { setFailed(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "The output format is missing: " + InputKeys.OUTPUT_FORMAT); throw new ValidationException("The output format is missing: " + InputKeys.OUTPUT_FORMAT); } else if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "Multiple output formats were given: " + InputKeys.OUTPUT_FORMAT); throw new ValidationException("Multiple output formats were given: " + InputKeys.OUTPUT_FORMAT); } else { tOutputFormat = SurveyResponseValidators.validateOutputFormat(t[0]); if(tOutputFormat == null) { setFailed(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "The output format is missing: " + InputKeys.OUTPUT_FORMAT); throw new ValidationException("The output format is missing: " + InputKeys.OUTPUT_FORMAT); } } // Survey ID List t = getParameterValues(InputKeys.SURVEY_ID_LIST); if(t.length > 1) { setFailed(ErrorCode.SURVEY_MALFORMED_SURVEY_ID_LIST, "Multiple survey ID lists were given: " + InputKeys.SURVEY_ID_LIST); throw new ValidationException("Multiple survey ID lists were given: " + InputKeys.SURVEY_ID_LIST); } else if(t.length == 1) { tSurveyIds = SurveyResponseValidators.validateSurveyIds(t[0]); if((tSurveyIds != null) && (tSurveyIds.size() > MAX_NUMBER_OF_SURVEYS)) { setFailed(ErrorCode.SURVEY_TOO_MANY_SURVEY_IDS, "More than " + MAX_NUMBER_OF_SURVEYS + " survey IDs were given: " + tSurveyIds.size()); throw new ValidationException("More than " + MAX_NUMBER_OF_SURVEYS + " survey IDs were given: " + tSurveyIds.size()); } } // Prompt ID List t = getParameterValues(InputKeys.PROMPT_ID_LIST); if(t.length > 1) { setFailed(ErrorCode.SURVEY_MALFORMED_PROMPT_ID_LIST, "Multiple prompt ID lists were given: " + InputKeys.PROMPT_ID_LIST); throw new ValidationException("Multiple prompt ID lists were given: " + InputKeys.PROMPT_ID_LIST); } else if(t.length == 1) { tPromptIds = SurveyResponseValidators.validatePromptIds(t[0]); if((tPromptIds != null) && (tPromptIds.size() > MAX_NUMBER_OF_PROMPTS)) { setFailed(ErrorCode.SURVEY_TOO_MANY_PROMPT_IDS, "More than " + MAX_NUMBER_OF_PROMPTS + " prompt IDs were given: " + tPromptIds.size()); throw new ValidationException("More than " + MAX_NUMBER_OF_PROMPTS + " prompt IDs were given: " + tPromptIds.size()); } } // Survey ID List and Prompt ID List Presence Check if(((tSurveyIds == null) || (tSurveyIds.size() == 0)) && ((tPromptIds == null) || (tPromptIds.size() == 0))) { setFailed(ErrorCode.SURVEY_SURVEY_LIST_OR_PROMPT_LIST_ONLY, "A survey list (" + InputKeys.SURVEY_ID_LIST + ") or a prompt list (" + InputKeys.PROMPT_ID_LIST + ") must be given."); throw new ValidationException("A survey list (" + InputKeys.SURVEY_ID_LIST + ") or prompt list (" + InputKeys.PROMPT_ID_LIST + ") must be given."); } else if(((tSurveyIds != null) && (tSurveyIds.size() > 0)) && ((tPromptIds != null) && (tPromptIds.size() > 0))) { setFailed(ErrorCode.SURVEY_SURVEY_LIST_OR_PROMPT_LIST_ONLY, "Both a survey list (" + InputKeys.SURVEY_ID_LIST + ") and a prompt list (" + InputKeys.PROMPT_ID_LIST + ") must be given."); throw new ValidationException("Both a survey list (" + InputKeys.SURVEY_ID_LIST + ") and a prompt list (" + InputKeys.PROMPT_ID_LIST + ") must be given."); } // Start Date t = getParameterValues(InputKeys.START_DATE); if(t.length > 1) { setFailed(ErrorCode.SERVER_INVALID_DATE, "Multiple start dates were given: " + InputKeys.START_DATE); throw new ValidationException("Multiple start dates were given: " + InputKeys.START_DATE); } else if(t.length == 1) { tStartDate = SurveyResponseValidators.validateStartDate(t[0]); } // End Date t = getParameterValues(InputKeys.END_DATE); if(t.length > 1) { setFailed(ErrorCode.SERVER_INVALID_DATE, "Multiple end dates were given: " + InputKeys.END_DATE); throw new ValidationException("Multiple end dates were given: " + InputKeys.END_DATE); } else if(t.length == 1) { tEndDate = SurveyResponseValidators.validateEndDate(t[0]); } // Sort Order t = getParameterValues(InputKeys.SORT_ORDER); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_SORT_ORDER, "Multiple sort order lists were given: " + InputKeys.SORT_ORDER); throw new ValidationException("Multiple sort order lists were given: " + InputKeys.SORT_ORDER); } else if(t.length == 1) { tSortOrder = SurveyResponseValidators.validateSortOrder(t[0]); } // Privacy State t = getParameterValues(InputKeys.PRIVACY_STATE); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_PRIVACY_STATE, "Multiple privacy state values were given: " + InputKeys.PRIVACY_STATE); throw new ValidationException("Multiple privacy state values were given: " + InputKeys.PRIVACY_STATE); } else if(t.length == 1) { tPrivacyState = SurveyResponseValidators.validatePrivacyState(t[0]); } // Collapse t = getParameterValues(InputKeys.COLLAPSE); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_COLLAPSE_VALUE, "Multiple collapse values were given: " + InputKeys.COLLAPSE); throw new ValidationException("Multiple collapse values were given: " + InputKeys.COLLAPSE); } else if(t.length == 1) { tCollapse = SurveyResponseValidators.validateCollapse(t[0]); } // Pretty print t = getParameterValues(InputKeys.PRETTY_PRINT); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_PRETTY_PRINT_VALUE, "Multiple pretty print values were given: " + InputKeys.PRETTY_PRINT); throw new ValidationException("Multiple pretty print values were given: " + InputKeys.PRETTY_PRINT); } else if(t.length == 1) { tPrettyPrint = SurveyResponseValidators.validatePrettyPrint(t[0]); } // Return ID t = getParameterValues(InputKeys.RETURN_ID); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_RETURN_ID, "Multiple return ID values were given: " + InputKeys.RETURN_ID); throw new ValidationException("Multiple return ID values were given: " + InputKeys.RETURN_ID); } else if(t.length == 1) { tReturnId = SurveyResponseValidators.validateReturnId(t[0]); } // Suppress metadata t = getParameterValues(InputKeys.SUPPRESS_METADATA); if(t.length > 1) { setFailed(ErrorCode.SURVEY_INVALID_SUPPRESS_METADATA_VALUE, "Multiple suppress metadata values were given: " + InputKeys.SUPPRESS_METADATA); throw new ValidationException("Multiple suppress metadata values were given: " + InputKeys.SUPPRESS_METADATA); } else if(t.length == 1) { tSuppressMetadata = SurveyResponseValidators.validateSuppressMetadata(t[0]); } } catch (ValidationException e) { e.failRequest(this); LOGGER.info(e); } } campaignId = tCampaignId; columns = tColumns; usernames = tUsernames; outputFormat = tOutputFormat; surveyIds = tSurveyIds; promptIds = tPromptIds; startDate = tStartDate; endDate = tEndDate; sortOrder = tSortOrder; privacyState = tPrivacyState; collapse = tCollapse; prettyPrint = tPrettyPrint; returnId = tReturnId; suppressMetadata = tSuppressMetadata; } /** * Services this request. */ @Override public void service() { LOGGER.info("Servicing a survey response read request."); if(! authenticate(AllowNewAccount.NEW_ACCOUNT_DISALLOWED)) { return; } try { // This is not necessarily the case because the user may no longer // belong to the campaign but still want to see their data. This // should only check that the campaign exists. LOGGER.info("Verifying that requester belongs to the campaign specified by campaign ID."); UserCampaignServices.instance().campaignExistsAndUserBelongs(campaignId, this.getUser().getUsername()); // We have removed this ACL check because it causes participants // to not be able to view their own data. The bigger problem // is that for "Browse Data" the front end always passes // user_list=urn:ohmage:special:all // LOGGER.info("Verifying that the requester has a role that allows reading of survey responses for each of the users in the list."); // UserCampaignServices.requesterCanViewUsersSurveyResponses(this, this.campaignUrn, this.getUser().getUsername(), (String[]) userList.toArray()); // The user may want to read survey responses from a user that no // longer belongs to the campaign. if(! usernames.equals(URN_SPECIAL_ALL_LIST)) { LOGGER.info("Checking the user list to make sure all of the users belong to the campaign ID."); UserCampaignServices.instance().verifyUsersExistInCampaign(campaignId, usernames); } LOGGER.info("Retrieving campaign configuration."); campaign = CampaignServices.instance().getCampaign(campaignId); if((promptIds != null) && (! promptIds.isEmpty()) && (! URN_SPECIAL_ALL_LIST.equals(promptIds))) { LOGGER.info("Verifying that the prompt ids in the query belong to the campaign."); SurveyResponseReadServices.instance().verifyPromptIdsBelongToConfiguration(promptIds, campaign); } if((surveyIds != null) && (! surveyIds.isEmpty()) && (! URN_SPECIAL_ALL_LIST.equals(surveyIds))) { LOGGER.info("Verifying that the survey ids in the query belong to the campaign."); SurveyResponseReadServices.instance().verifySurveyIdsBelongToConfiguration(surveyIds, campaign); } LOGGER.info("Dispatching to the data layer."); surveyResponseList = SurveyResponseServices.instance().readSurveyResponseInformation( campaign, (URN_SPECIAL_ALL_LIST.equals(usernames) ? null : usernames), null, startDate, endDate, privacyState, (URN_SPECIAL_ALL_LIST.equals(surveyIds)) ? null : surveyIds, (URN_SPECIAL_ALL_LIST.equals(promptIds)) ? null : promptIds, null ); LOGGER.info("Found " + surveyResponseList.size() + " results"); LOGGER.info("Filtering survey response results according to our privacy rules and the requester's role."); SurveyResponseReadServices.instance().performPrivacyFilter(this.getUser().getUsername(), campaignId, surveyResponseList); LOGGER.info("Found " + surveyResponseList.size() + " results after filtering."); if(sortOrder != null) { LOGGER.info("Sorting the results."); Collections.sort( surveyResponseList, new Comparator<SurveyResponse>() { @Override public int compare( SurveyResponse o1, SurveyResponse o2) { for(SortParameter sortParameter : sortOrder) { switch(sortParameter) { case SURVEY: if(! o1.getSurvey().equals(o2.getSurvey())) { return o1.getSurvey().getId().compareTo(o2.getSurvey().getId()); } break; case TIMESTAMP: if(o1.getTime() != o2.getTime()) { if((o1.getTime() - o2.getTime()) < 0) { return -1; } else { return 1; } } break; case USER: if(! o1.getUsername().equals(o2.getUsername())) { return o1.getUsername().compareTo(o2.getUsername()); } break; } } return 0; } } ); } } catch(ServiceException e) { e.failRequest(this); e.logException(LOGGER); } } /** * Builds the output depending on the state of this request and whatever * output format the requester selected. */ @Override public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Responding to the survey response read request."); if(isFailed()) { super.respond(httpRequest, httpResponse, null); return; } // Create a writer for the HTTP response object. Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(httpRequest, httpResponse))); } catch(IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); return; } // Sets the HTTP headers to disable caching. expireResponse(httpResponse); String resultString = ""; if(! isFailed()) { try { boolean allColumns = columns.equals(URN_SPECIAL_ALL_LIST); // TODO: I am fairly confident that these two branches can be // merged further and subsequently cleaned up, but I don't have // the time to tackle it right now. if(OutputFormat.JSON_ROWS.equals(outputFormat)) { httpResponse.setContentType("text/html"); JSONObject result = new JSONObject(); result.put(JSON_KEY_RESULT, RESULT_SUCCESS); List<String> uniqueSurveyIds = new LinkedList<String>(); List<String> uniquePromptIds = new LinkedList<String>(); JSONArray results = new JSONArray(); for(SurveyResponse surveyResponse : surveyResponseList) { uniqueSurveyIds.add(surveyResponse.getSurvey().getId()); uniquePromptIds.addAll(surveyResponse.getPromptIds()); JSONObject currResult = surveyResponse.toJson( allColumns || columns.contains(ColumnKey.USER_ID), allColumns || false, allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT), allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE), allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS), allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE), allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS), false, allColumns || columns.contains(ColumnKey.SURVEY_ID), allColumns || columns.contains(ColumnKey.SURVEY_TITLE), allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG), allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE), false, ((returnId == null) ? false : returnId) ); if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { currResult.put( "timestamp", TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime()))); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { currResult.put( "utc_timestamp", DateUtils.timestampStringToUtc( TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime())), TimeZone.getDefault().getID())); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_ACCURACY, JSONObject.NULL); } else { double accuracy = location.getAccuracy(); if(Double.isInfinite(accuracy) || Double.isNaN(accuracy)) { currResult.put(Location.JSON_KEY_ACCURACY, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_ACCURACY, accuracy); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_LATITUDE, JSONObject.NULL); } else { double latitude = location.getLatitude(); if(Double.isInfinite(latitude) || Double.isNaN(latitude)) { currResult.put(Location.JSON_KEY_LATITUDE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_LATITUDE, latitude); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_LONGITUDE, JSONObject.NULL); } else { double longitude = location.getLongitude(); if(Double.isInfinite(longitude) || Double.isNaN(longitude)) { currResult.put(Location.JSON_KEY_LONGITUDE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_LONGITUDE, longitude); } } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_PROVIDER, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_PROVIDER, location.getProvider()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_TIME, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_TIME, location.getTime()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { currResult.put(Location.JSON_KEY_TIME_ZONE, JSONObject.NULL); } else { currResult.put(Location.JSON_KEY_TIME_ZONE, location.getTimeZone().getID()); } } results.put(currResult); } if((collapse != null) && collapse) { int numResults = results.length(); Map<JSONObject, Integer> collapsedMap = new HashMap<JSONObject, Integer>(numResults); for(int i = 0; i < numResults; i++) { JSONObject currResult = results.getJSONObject(i); Integer prevCount = collapsedMap.put(currResult, 1); if(prevCount != null) { collapsedMap.put(currResult, prevCount + 1); results.remove(i); i numResults } } for(int i = 0; i < numResults; i++) { JSONObject currResult = results.getJSONObject(i); currResult.put(JSON_KEY_COUNT, collapsedMap.get(currResult)); } } result.put(JSON_KEY_DATA, results); // Metadata if((suppressMetadata == null) || (! suppressMetadata)) { JSONObject metadata = new JSONObject(); metadata.put(JSON_KEY_NUM_SURVEYS, uniqueSurveyIds.size()); metadata.put(JSON_KEY_NUM_PROMPTS, uniquePromptIds.size()); Collection<String> columnsResult = new HashSet<String>(columns.size()); // If it contains the special 'all' value, add them // all. if(columns.contains(URN_SPECIAL_ALL)) { ColumnKey[] values = SurveyResponse.ColumnKey.values(); for(int i = 0; i < values.length; i++) { columnsResult.add(values[i].toString()); } } // Otherwise, add cycle through them else { for(ColumnKey columnKey : columns) { columnsResult.add(columnKey.toString()); } } // Check if prompt responses were requested, and, if // so, add them to the list of columns. if(columns.contains(SurveyResponse.ColumnKey.PROMPT_RESPONSE) || columns.contains(URN_SPECIAL_ALL)) { for(String promptId : uniquePromptIds) { columnsResult.add(ColumnKey.URN_PROMPT_ID_PREFIX + promptId); } } // Add it to the metadata result. metadata.put(JSON_KEY_ITEMS, columnsResult); result.put(JSON_KEY_METADATA, metadata); } if((prettyPrint != null) && prettyPrint) { resultString = result.toString(4); } else { resultString = result.toString(); } } else if(OutputFormat.JSON_COLUMNS.equals(outputFormat) || OutputFormat.CSV.equals(outputFormat)) { JSONArray usernames = new JSONArray(); JSONArray clients = new JSONArray(); JSONArray privacyStates = new JSONArray(); JSONArray timestamps = new JSONArray(); JSONArray utcTimestamps = new JSONArray(); JSONArray epochMillisTimestamps = new JSONArray(); JSONArray timezones = new JSONArray(); JSONArray locationStatuses = new JSONArray(); JSONArray locationLongitude = new JSONArray(); JSONArray locationLatitude = new JSONArray(); JSONArray locationTimestamp = new JSONArray(); JSONArray locationTimeZone = new JSONArray(); JSONArray locationAccuracy = new JSONArray(); JSONArray locationProvider = new JSONArray(); JSONArray surveyIds = new JSONArray(); JSONArray surveyTitles = new JSONArray(); JSONArray surveyDescriptions = new JSONArray(); JSONArray launchContexts = new JSONArray(); Map<String, JSONObject> prompts = new HashMap<String, JSONObject>(); // If the results are empty, then we still want to populate // the resulting JSON with information about all of the // prompts even though they don't have any responses // associated with them. // FIXME: This shouldn't be conditional on the number of // responses found. We should create headers for all of the // requested prompt IDs (either via the list of survey IDs // or the list of prompt IDs) or none of the prompt IDs if // prompts aren't requested. if(surveyResponseList.isEmpty()) { // If the user-supplied list of survey IDs is present, if(this.surveyIds != null) { Map<String, Survey> campaignSurveys = campaign.getSurveys(); // If the user asked for all surveys for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // all of the surveys in this campaign. if(this.surveyIds.equals(URN_SPECIAL_ALL_LIST)) { for(Survey currSurvey : campaignSurveys.values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information only // with the data about the requested surveys. else { for(String surveyId : this.surveyIds) { populatePrompts(campaignSurveys.get(surveyId).getSurveyItems(), prompts); } } } // If the user-supplied list of prompt IDs is present, else if(promptIds != null) { // If the user asked for all prompts for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // this campaign. if(this.promptIds.equals(URN_SPECIAL_ALL_LIST)) { for(Survey currSurvey : campaign.getSurveys().values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information with // the data about only the requested prompts. else { int currNumPrompts = 0; Map<Integer, SurveyItem> tempPromptMap = new HashMap<Integer, SurveyItem>(promptIds.size()); for(String promptId : promptIds) { tempPromptMap.put(currNumPrompts, campaign.getPrompt(campaign.getSurveyIdForPromptId(promptId), promptId)); currNumPrompts++; } populatePrompts(tempPromptMap, prompts); } } } // If the results are non-empty, we need to populate the // prompt information only for those prompts to which the // user queried about. else { Set<String> unqiueSurveyIds = new HashSet<String>(); Set<String> uniquePromptIds = new HashSet<String>(); // For each of the survey responses in the result, for(SurveyResponse surveyResponse : surveyResponseList) { String surveyId = surveyResponse.getSurvey().getId(); // If the survey with which this survey response is // associated has not yet been processed, process if(! unqiueSurveyIds.contains(surveyId)) { // Add to the list of surveys that have been // processed so that no subsequent survey // responses that are associated with this // survey cause it to be processed again. unqiueSurveyIds.add(surveyId); // Keep track of the unique number of prompts // that we process. int currNumPrompts = 0; // Get all of the unique prompt IDs for this // survey response. Set<String> promptIds = surveyResponse.getPromptIds(); // Create a a temporary map of Integers to // Prompt objects. Map<Integer, SurveyItem> tempPrompts = new HashMap<Integer, SurveyItem>(promptIds.size()); // Retrieve all of the unique prompts that have // not yet been processed and add them to the // map. for(String promptId : promptIds) { if(! uniquePromptIds.contains(promptId)) { tempPrompts.put(currNumPrompts, campaign.getPrompt(surveyId, promptId)); currNumPrompts++; } } // Populate the prompts JSON with the // information about all of the distinct // prompts from this survey response. populatePrompts(tempPrompts, prompts); } } } // Process each of the survey responses and keep track of // the number of prompt responses. int numSurveyResponses = surveyResponseList.size(); int numPromptResponses = 0; for(SurveyResponse surveyResponse : surveyResponseList) { numPromptResponses += processResponses(allColumns, surveyResponse, surveyResponse.getResponses(), prompts, usernames, clients, privacyStates, timestamps, utcTimestamps, epochMillisTimestamps, timezones, locationStatuses, locationLongitude, locationLatitude, locationTimestamp, locationTimeZone, locationAccuracy, locationProvider, surveyIds, surveyTitles, surveyDescriptions, launchContexts ); } // Add all of the applicable output stuff. JSONObject result = new JSONObject(); JSONArray keysOrdered = new JSONArray(); // For each of the requested columns, add their respective // data to the result in a specific order per Hongsuda's // request. if(allColumns || columns.contains(ColumnKey.SURVEY_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyIds); result.put(ColumnKey.SURVEY_ID.toString(), values); keysOrdered.put(ColumnKey.SURVEY_ID.toString()); } if(allColumns || columns.contains(ColumnKey.SURVEY_TITLE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyTitles); result.put(ColumnKey.SURVEY_TITLE.toString(), values); keysOrdered.put(ColumnKey.SURVEY_TITLE.toString()); } if(allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyDescriptions); result.put(ColumnKey.SURVEY_DESCRIPTION.toString(), values); keysOrdered.put(ColumnKey.SURVEY_DESCRIPTION.toString()); } if(allColumns || columns.contains(ColumnKey.USER_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, usernames); result.put(ColumnKey.USER_ID.toString(), values); keysOrdered.put(ColumnKey.USER_ID.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, clients); result.put(ColumnKey.CONTEXT_CLIENT.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_CLIENT.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, utcTimestamps); result.put(ColumnKey.CONTEXT_UTC_TIMESTAMP.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_UTC_TIMESTAMP.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, epochMillisTimestamps); result.put(ColumnKey.CONTEXT_EPOCH_MILLIS.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_EPOCH_MILLIS.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timestamps); result.put(ColumnKey.CONTEXT_TIMESTAMP.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_TIMESTAMP.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timezones); result.put(ColumnKey.CONTEXT_TIMEZONE.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_TIMEZONE.toString()); } if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { List<String> unorderedList = new LinkedList<String>(); for(String promptId : prompts.keySet()) { result.put( SurveyResponse.ColumnKey.URN_PROMPT_ID_PREFIX + promptId, prompts.get(promptId)); unorderedList.add(SurveyResponse.ColumnKey.URN_PROMPT_ID_PREFIX + promptId); } Collections.sort(unorderedList); for(String columnId : unorderedList) { keysOrdered.put(columnId); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationStatuses); result.put(ColumnKey.CONTEXT_LOCATION_STATUS.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_STATUS.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLatitude); result.put(ColumnKey.CONTEXT_LOCATION_LATITUDE.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_LATITUDE.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLongitude); result.put(ColumnKey.CONTEXT_LOCATION_LONGITUDE.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_LONGITUDE.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationProvider); result.put(ColumnKey.CONTEXT_LOCATION_PROVIDER.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_PROVIDER.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { JSONObject timeValues = new JSONObject(); timeValues.put(JSON_KEY_VALUES, locationTimestamp); result.put(ColumnKey.CONTEXT_LOCATION_TIMESTAMP.toString(), timeValues); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_TIMESTAMP.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMEZONE)) { JSONObject timeZoneValues = new JSONObject(); timeZoneValues.put(JSON_KEY_VALUES, locationTimeZone); result.put(ColumnKey.CONTEXT_LOCATION_TIMEZONE.toString(), timeZoneValues); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_TIMEZONE.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationAccuracy); result.put(ColumnKey.CONTEXT_LOCATION_ACCURACY.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_ACCURACY.toString()); } if(allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, privacyStates); result.put(ColumnKey.SURVEY_PRIVACY_STATE.toString(), values); keysOrdered.put(ColumnKey.SURVEY_PRIVACY_STATE.toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG.toString()); } if(columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT.toString()); } // If the user requested to collapse the results, create a // new column called count and set the initial value for // every existing row to 1. Then, create a map of string // representations of data to their original row. Cycle // through the indices creating a string by concatenating // the value at the given index for each column and // checking the map if the string already exists. If it // does not exist, add the string value and have it point // to the current index. If it does exist, go to that // column, increase the count, and delete this row by // deleting whatever is at the current index in every // column. if((collapse != null) && collapse) { // Get the key for each row. JSONArray keys = new JSONArray(); Iterator<?> keysIter = result.keys(); while(keysIter.hasNext()) { keys.put(keysIter.next()); } int keyLength = keys.length(); // Create a new "count" column and initialize every // count to 1. JSONArray counts = new JSONArray(); for(int i = 0; i < numSurveyResponses; i++) { counts.put(1); } JSONObject countObject = new JSONObject(); countObject.put(JSON_KEY_VALUES, counts); result.put("urn:ohmage:context:count", countObject); keys.put("urn:ohmage:context:count"); // Cycle through the responses. Map<String, Integer> valueToIndexMap = new HashMap<String, Integer>(); for(int i = 0; i < numSurveyResponses; i++) { // Build the string. StringBuilder currResultBuilder = new StringBuilder(); for(int j = 0; j < keyLength; j++) { currResultBuilder.append(result.getJSONObject(keys.getString(j)).getJSONArray(JSON_KEY_VALUES).get(i)); if((j + 1) != keyLength) { currResultBuilder.append(','); } } // Check if the string exists. String currResultString = currResultBuilder.toString(); // If so, go to that index in every column // including the count and delete it, effectively // deleting that row. if(valueToIndexMap.containsKey(currResultString)) { int count = result.getJSONObject("urn:ohmage:context:count").getJSONArray(JSON_KEY_VALUES).getInt(valueToIndexMap.get(currResultString)) + 1; result.getJSONObject("urn:ohmage:context:count").getJSONArray(JSON_KEY_VALUES).put(valueToIndexMap.get(currResultString).intValue(), count); for(int j = 0; j < keyLength + 1; j++) { result.getJSONObject(keys.getString(j)).getJSONArray(JSON_KEY_VALUES).remove(i); } i numSurveyResponses } // If not, add it to the map. else { valueToIndexMap.put(currResultString, i); } } } // If metadata is not suppressed, create it. JSONObject metadata = null; if((suppressMetadata == null) || (! suppressMetadata)) { metadata = new JSONObject(); metadata.put(InputKeys.CAMPAIGN_URN, campaignId); metadata.put(JSON_KEY_NUM_SURVEYS, surveyResponseList.size()); metadata.put(JSON_KEY_NUM_PROMPTS, numPromptResponses); } if(OutputFormat.JSON_COLUMNS.equals(outputFormat)) { httpResponse.setContentType("text/html"); JSONObject resultJson = new JSONObject(); resultJson.put(JSON_KEY_RESULT, RESULT_SUCCESS); int numHeaders = keysOrdered.length(); for(int i = 0; i < numHeaders; i++) { String header = keysOrdered.getString(i); if(header.endsWith(":value") || header.endsWith(":key")) { result.remove(header); keysOrdered.remove(i); i numHeaders } else if(header.endsWith(":label")) { String prunedHeader = header.substring(0, header.length() - 6); result.put(prunedHeader, result.get(header)); result.remove(header); keysOrdered.put(i, prunedHeader); } } if((suppressMetadata == null) || (! suppressMetadata)) { JSONArray itemsJson = new JSONArray(); Iterator<?> keys = result.keys(); while(keys.hasNext()) { itemsJson.put(keys.next()); } metadata.put("items", itemsJson); resultJson.put(JSON_KEY_METADATA, metadata); } resultJson.put(JSON_KEY_DATA, result); if((prettyPrint != null) && prettyPrint) { resultString = resultJson.toString(4); } else { resultString = resultJson.toString(); } } // For CSV output, else if(OutputFormat.CSV.equals(outputFormat)) { // Mark it as an attachment. httpResponse.setContentType("text/csv"); httpResponse.setHeader( "Content-Disposition", "attachment; filename=SurveyResponses.csv"); StringBuilder resultBuilder = new StringBuilder(); // If the metadata is not suppressed, add it to the // output builder. if((suppressMetadata == null) || (! suppressMetadata)) { metadata.put(JSON_KEY_RESULT, RESULT_SUCCESS); resultBuilder.append("## begin metadata\n"); resultBuilder.append('#').append(metadata.toString().replace(',', ';')).append('\n'); resultBuilder.append("## end metadata\n"); } // Add the prompt contexts to the output builder if // prompts were desired. if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { resultBuilder.append("## begin prompt contexts\n"); for(String promptId : prompts.keySet()) { JSONObject promptJson = new JSONObject(); // Use the already-generated JSON from each of // the prompts. promptJson.put( promptId, prompts .get(promptId) .get(JSON_KEY_CONTEXT)); resultBuilder .append(' .append(promptJson.toString()) .append('\n'); } resultBuilder.append("## end prompt contexts\n"); } // Begin the data section of the CSV. resultBuilder.append("## begin data\n"); // Get the number of keys. int keyLength = keysOrdered.length(); // Create a comma-separated list of the header names. resultBuilder.append(' for(int i = 0; i < keyLength; i++) { String header = keysOrdered.getString(i); if(header.startsWith("urn:ohmage:")) { header = header.substring(11); if(header.startsWith("prompt:id:")) { header = header.substring(10); } } resultBuilder.append(header); if((i + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); // For each of the responses, for(int i = 0; i < numSurveyResponses; i++) { for(int j = 0; j < keyLength; j++) { Object currResult = result .getJSONObject(keysOrdered.getString(j)) .getJSONArray(JSON_KEY_VALUES) .get(i); if(JSONObject.NULL.equals(currResult)) { resultBuilder.append(""); } else { resultBuilder.append(currResult); } if((j + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); } resultBuilder.append("## end data"); resultString = resultBuilder.toString(); } } } catch(JSONException e) { LOGGER.error(e.toString(), e); setFailed(); } catch(IllegalStateException e) { LOGGER.error(e.toString(), e); setFailed(); } } if(isFailed()) { httpResponse.setContentType("text/html"); resultString = this.getFailureMessage(); } try { writer.write(resultString); } catch(IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); } try { writer.flush(); writer.close(); } catch(IOException e) { LOGGER.error("Unable to flush or close the writer.", e); } } /** * Populates the prompts map with all of the prompts from all of the survey * items. * * @param surveyItems The map of survey item indices to the survey item. * * @param prompts The prompts to be populated with all of the prompts in * the survey item including all of the sub-prompts of * repeatable sets. * * @throws JSONException Thrown if there is an error building the JSON. */ private void populatePrompts( final Map<Integer, SurveyItem> surveyItems, Map<String, JSONObject> prompts) throws JSONException { for(SurveyItem surveyItem : surveyItems.values()) { if(surveyItem instanceof Prompt) { if((surveyItem instanceof ChoicePrompt) && (OutputFormat.CSV.equals(outputFormat))) { ChoicePrompt prompt = (ChoicePrompt) surveyItem; JSONObject promptJsonKey = new JSONObject(); promptJsonKey.put(JSON_KEY_CONTEXT, prompt.toJson()); promptJsonKey.put(JSON_KEY_VALUES, new JSONArray()); JSONObject promptJsonLabel = new JSONObject(); promptJsonLabel.put(JSON_KEY_CONTEXT, prompt.toJson()); promptJsonLabel.put(JSON_KEY_VALUES, new JSONArray()); JSONObject promptJsonValue = new JSONObject(); promptJsonValue.put(JSON_KEY_CONTEXT, prompt.toJson()); promptJsonValue.put(JSON_KEY_VALUES, new JSONArray()); prompts.put(prompt.getId() + ":key", promptJsonKey); prompts.put(prompt.getId() + ":value", promptJsonLabel); prompts.put(prompt.getId() + ":label", promptJsonValue); } else { Prompt prompt = (Prompt) surveyItem; JSONObject promptJson = new JSONObject(); promptJson.put(JSON_KEY_CONTEXT, prompt.toJson()); promptJson.put(JSON_KEY_VALUES, new JSONArray()); prompts.put(prompt.getId(), promptJson); } } else if(surveyItem instanceof RepeatableSet) { RepeatableSet repeatableSet = (RepeatableSet) surveyItem; populatePrompts(repeatableSet.getSurveyItems(), prompts); } } } /** * Processes each of the responses in map to populate the JSONObjects by * placing the value from the response into its corresponding JSONObject. * * @param allColumns Whether or not to populate all JSONObjects. * * @param surveyResponse The current survey response. * * @param responses The map of response index from the survey response to * the actual response. * * @param surveys The map of survey IDs to Survey objects. * * @param prompts The map of prompt IDs to Prompt objects. * * @param usernames The usernames JSONArray. * * @param clients The clients JSONArray. * * @param privacyStates The privacy states JSONArray. * * @param timestamps The timestamps JSONArray. * * @param utcTimestamps The timestamps JSONArray where the timestamps are * converted to UTC. * * @param epochMillisTimestamps The epoch millis JSONArray. * * @param timezones The timezones JSONArray. * * @param locationStatuses The location statuses JSONArray. * * @param locations The locations JSONArray. * * @param surveyIds The survey IDs JSONArray. * * @param surveyTitles The survey titles JSONArray. * * @param surveyDescriptions The survey description JSONArray. * * @param launchContexts The launch contexts JSONArray. * * @return The total number of prompt responses that were processed. * * @throws JSONException Thrown if there is an error populating any of the * JSONArrays. */ private int processResponses(final boolean allColumns, final SurveyResponse surveyResponse, final Map<Integer, Response> responses, Map<String, JSONObject> prompts, JSONArray usernames, JSONArray clients, JSONArray privacyStates, JSONArray timestamps, JSONArray utcTimestamps, JSONArray epochMillisTimestamps, JSONArray timezones, JSONArray locationStatuses, JSONArray locationLongitude, JSONArray locationLatitude, JSONArray locationTime, JSONArray locationTimeZone, JSONArray locationAccuracy, JSONArray locationProvider, JSONArray surveyIds, JSONArray surveyTitles, JSONArray surveyDescriptions, JSONArray launchContexts) throws JSONException { // Add each of the survey response-wide pieces of information. if(allColumns || columns.contains(ColumnKey.USER_ID)) { usernames.put(surveyResponse.getUsername()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT)) { clients.put(surveyResponse.getClient()); } if(allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE)) { privacyStates.put(surveyResponse.getPrivacyState().toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { timestamps.put( TimeUtils.getIso8601DateTimeString( new Date( surveyResponse.getTime()))); } if(allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { utcTimestamps.put( DateUtils.timestampStringToUtc( TimeUtils.getIso8601DateTimeString( new Date(surveyResponse.getTime())), TimeZone.getDefault().getID())); } if(allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS)) { epochMillisTimestamps.put(surveyResponse.getTime()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE)) { timezones.put(surveyResponse.getTimezone().getID()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS)) { locationStatuses.put(surveyResponse.getLocationStatus().toString()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { locationLongitude.put(JSONObject.NULL); } else { locationLongitude.put(location.getLongitude()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { Location location = surveyResponse.getLocation(); if(location == null) { locationLatitude.put(JSONObject.NULL); } else { locationLatitude.put(location.getLatitude()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { locationTime.put(JSONObject.NULL); } else { locationTime.put(location.getTime()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if(location == null) { locationTimeZone.put(JSONObject.NULL); } else { locationTimeZone.put(location.getTimeZone().getID()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { Location location = surveyResponse.getLocation(); if(location == null) { locationAccuracy.put(JSONObject.NULL); } else { locationAccuracy.put(location.getAccuracy()); } } if(allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { Location location = surveyResponse.getLocation(); if(location == null) { locationProvider.put(JSONObject.NULL); } else { locationProvider.put(location.getProvider()); } } if(allColumns || columns.contains(ColumnKey.SURVEY_ID)) { surveyIds.put(surveyResponse.getSurvey().getId()); } if(allColumns || columns.contains(ColumnKey.SURVEY_TITLE)) { surveyTitles.put(surveyResponse.getSurvey().getTitle()); } if(allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION)) { surveyDescriptions.put(surveyResponse.getSurvey().getDescription()); } if(allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG) || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT)) { launchContexts.put(surveyResponse.getLaunchContext().toJson(allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG))); } int numResponses = 0; // Create a map of which prompts were given a response in this // iteration. Set<String> promptIdsWithResponse = new HashSet<String>(); // Get the indices of each response in the list of responses and then // sort them to ensure that we process each response in the correct // numeric order. List<Integer> indices = new ArrayList<Integer>(responses.keySet()); Collections.sort(indices); // Now, add each of the responses. for(Integer index : indices) { Response response = responses.get(index); // If the response is a prompt response, add its appropriate // columns. if(response instanceof PromptResponse) { numResponses++; if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { PromptResponse promptResponse = (PromptResponse) response; Prompt prompt = promptResponse.getPrompt(); String responseId = response.getId(); // If it's a ChoicePrompt response, populate all three // columns, <id>:key, <id>:label, and <id>:value. if((prompt instanceof ChoicePrompt) && (OutputFormat.CSV.equals(outputFormat))) { // Get the response object. Object responseObject = response.getResponseValue(); // If the response was not really a response, e.g. // skipped, not displayed, etc., put a JSONObject.NULL // object in for the key and value and put a quoted // string-representation of the non-response. if(responseObject instanceof NoResponse) { JSONArray keys = prompts.get(responseId + ":key") .getJSONArray(JSON_KEY_VALUES); keys.put(JSONObject.NULL); JSONArray labels = prompts.get(responseId + ":label") .getJSONArray(JSON_KEY_VALUES); labels.put("\"" + responseObject + "\""); JSONArray values = prompts.get(responseId + ":value") .getJSONArray(JSON_KEY_VALUES); values.put(JSONObject.NULL); } // Otherwise, get the key, label, and, potentially, // value and populate their corresponding columns. else { Object key; Object label; Object value; ChoicePrompt choicePrompt = (ChoicePrompt) promptResponse.getPrompt(); Map<Integer, LabelValuePair> choices; if(prompt instanceof CustomChoicePrompt) { choices = ((CustomChoicePrompt) choicePrompt) .getAllChoices(); } else { choices = choicePrompt.getChoices(); } if(response instanceof SingleChoicePromptResponse) { key = (Integer) responseObject; LabelValuePair lvp = choices.get(key); label = lvp.getLabel(); value = lvp.getValue(); } else if(response instanceof SingleChoiceCustomPromptResponse) { label = (String) responseObject; key = choicePrompt.getChoiceKey((String) label); value = choices.get(key).getValue(); } else if(response instanceof MultiChoicePromptResponse) { @SuppressWarnings("unchecked") List<Integer> keys = (List<Integer>) responseObject; List<Object> labels = new ArrayList<Object>(keys.size()); List<Object> values = new ArrayList<Object>(keys.size()); for(Integer currKey : keys) { LabelValuePair lvp = choices.get(currKey); labels.add(lvp.getLabel()); Number currValue = lvp.getValue(); if(currValue == null) { values.add(""); } else { values.add(currValue); } } key = new JSONArray(keys); label = labels; value = values; } else if(response instanceof MultiChoiceCustomPromptResponse) { @SuppressWarnings("unchecked") Collection<String> labels = (Collection<String>) responseObject; List<Object> keys = new ArrayList<Object>(labels.size()); List<Object> values = new ArrayList<Object>(labels.size()); for(String currLabel : labels) { Integer currKey = choicePrompt.getChoiceKey(currLabel); keys.add(currKey); Number currValue = choices.get(currKey).getValue(); if(currValue == null) { values.add(""); } else { values.add(currValue); } } key = keys; label = labels; value = values; } else { throw new IllegalStateException("There exists a choice prompt that is not a (single/multi) [custom] choice."); } promptIdsWithResponse.add(responseId + ":key"); JSONArray keys = prompts.get(responseId + ":key") .getJSONArray(JSON_KEY_VALUES); keys.put("\"" + key + "\""); promptIdsWithResponse.add(responseId + ":label"); JSONArray labels = prompts.get(responseId + ":label") .getJSONArray(JSON_KEY_VALUES); labels.put("\"" + label + "\""); promptIdsWithResponse.add(responseId + ":value"); JSONArray values = prompts.get(responseId + ":value") .getJSONArray(JSON_KEY_VALUES); if(value == null) { values.put(""); } else { values.put("\"" + value + "\""); } } // Finally, indicate that these prompts were given // values so that the others may be populated with // JSONObject.NULLs. promptIdsWithResponse.add(responseId + ":key"); promptIdsWithResponse.add(responseId + ":label"); promptIdsWithResponse.add(responseId + ":value"); } // Otherwise, only populate the value. else { promptIdsWithResponse.add(responseId); JSONArray values = prompts.get(responseId).getJSONArray(JSON_KEY_VALUES); Object responseValue = response.getResponseValue(); if(OutputFormat.CSV.equals(outputFormat)) { responseValue = "\"" + responseValue + "\""; } values.put(responseValue); } } } // FIXME // The problem is that we need to recurse, but if we have already // added all of the survey response stuff then we don't want to // add that again. If I remember correctly, we need to create new // columns with headers that are like, "prompt1name1", // "prompt1name2", etc. where we append the iteration number after // the prompt name. The problem is that before this function is // called we called a generic header creator for each prompt. This // prompt would have had a header that was created but only the // one. We need to duplicate that header, JSONObject.NULL-out all // of the previous responses, and give it a new header with the // iteration number. else if(response instanceof RepeatableSetResponse) { /* RepeatableSetResponse repeatableSetResponse = (RepeatableSetResponse) response; Map<Integer, Map<Integer, Response>> repeatableSetResponses = repeatableSetResponse.getResponseGroups(); List<Integer> rsIterations = new ArrayList<Integer>(repeatableSetResponses.keySet()); for(Integer rsIndex : rsIterations) { numResponses += processResponses(allColumns, surveyResponse, repeatableSetResponses.get(rsIndex), prompts, usernames, clients, privacyStates, timestamps, utcTimestamps, epochMillisTimestamps, timezones, locationStatuses, locationLongitude, locationLatitude, locationTime, locationTimeZone, locationAccuracy, locationProvider, surveyIds, surveyTitles, surveyDescriptions, launchContexts ); } */ } } // Finally, get all of the prompts that didn't receive a value in this // iteration and give them a value of JSONObject.NULL. if(allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { Set<String> promptIdsWithoutResponse = new HashSet<String>(prompts.keySet()); promptIdsWithoutResponse.removeAll(promptIdsWithResponse); for(String currPromptId : promptIdsWithoutResponse) { prompts .get(currPromptId) .getJSONArray(JSON_KEY_VALUES) .put(JSONObject.NULL); } } return numResponses; } }
package edu.wustl.common.query.impl; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.naming.InitialContext; import javax.sql.DataSource; import edu.common.dynamicextensions.domaininterface.AssociationInterface; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.BooleanTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.DateTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.DoubleTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.common.dynamicextensions.domaininterface.IntegerTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.StringTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.databaseproperties.ConstraintKeyPropertiesInterface; import edu.common.dynamicextensions.domaininterface.databaseproperties.ConstraintPropertiesInterface; import edu.common.dynamicextensions.entitymanager.EntityManager; import edu.common.dynamicextensions.util.global.Constants.InheritanceStrategy; import edu.wustl.cab2b.server.category.CategoryOperations; import edu.wustl.cab2b.server.queryengine.querybuilders.CategoryPreprocessor; import edu.wustl.common.query.queryobject.impl.OutputTreeDataNode; import edu.wustl.common.query.queryobject.util.InheritanceUtils; import edu.wustl.common.query.queryobject.util.QueryObjectProcessor; import edu.wustl.common.querysuite.exceptions.MultipleRootsException; import edu.wustl.common.querysuite.exceptions.SqlException; import edu.wustl.common.querysuite.factory.QueryObjectFactory; import edu.wustl.common.querysuite.metadata.associations.IAssociation; import edu.wustl.common.querysuite.metadata.associations.IIntraModelAssociation; import edu.wustl.common.querysuite.metadata.category.Category; import edu.wustl.common.querysuite.queryobject.ICondition; import edu.wustl.common.querysuite.queryobject.IConnector; import edu.wustl.common.querysuite.queryobject.IExpression; import edu.wustl.common.querysuite.queryobject.IOutputTerm; import edu.wustl.common.querysuite.queryobject.IQuery; import edu.wustl.common.querysuite.queryobject.IQueryEntity; import edu.wustl.common.querysuite.queryobject.IRule; import edu.wustl.common.querysuite.queryobject.LogicalOperator; import edu.wustl.common.querysuite.queryobject.RelationalOperator; import edu.wustl.common.querysuite.queryobject.TimeInterval; import edu.wustl.common.querysuite.queryobject.impl.Expression; import edu.wustl.common.querysuite.queryobject.impl.JoinGraph; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.global.Variables; import edu.wustl.common.util.logger.Logger; import edu.wustl.metadata.util.DyExtnObjectCloner; import edu.wustl.query.util.global.Constants; import edu.wustl.query.util.global.Utility; import edu.wustl.query.util.querysuite.QueryModuleError; import edu.wustl.query.util.querysuite.QueryModuleException; /** * To generate SQL from the given Query Object. * * @author prafull_kadam * */ public class SqlGenerator extends QueryGenerator { /** * Default Constructor to instantiate SQL generator object. */ public SqlGenerator() { } /** * Generates SQL for the given Query Object. * * @param query The Reference to Query Object. * @return the String representing SQL for the given Query object. * @throws MultipleRootsException When there are multpile roots present in a * graph. * @throws SqlException When there is error in the passed IQuery object. * @see edu.wustl.common.querysuite.queryengine.ISqlGenerator#generateSQL(edu.wustl.common.querysuite.queryobject.IQuery) */ public String generateQuery(IQuery query) throws QueryModuleException, RuntimeException { Logger.out.debug("Srarted SqlGenerator.generateSQL()....."); String sql; try { sql = buildQuery(query); } catch (MultipleRootsException e) { throw new QueryModuleException("problem while trying to build xquery" + e.getMessage(), QueryModuleError.MULTIPLE_ROOT); } catch (SqlException e) { throw new QueryModuleException("problem while trying to build xquery" + e.getMessage(), QueryModuleError.SQL_EXCEPTION); } Logger.out.debug("Finished SqlGenerator.generateSQL()...SQL:" + sql); return sql; } /** * Changes made for adding new rule in expression which do not have rule * provided that expression contains Activity status attribute. * * @param expressionId Root Expression Id */ private void addactivityStatusToEmptExpr(int expressionId) { Expression expression = (Expression) constraints.getExpression(expressionId); List<IExpression> operandList = joinGraph.getChildrenList(expression); for (IExpression subExpression : operandList) { // TODO check this code. // if (subExpression.isSubExpressionOperand()) { addactivityStatusToEmptExpr(subExpression.getExpressionId()); } if (!expression.containsRule()) { if (getActivityStatusAttribute(expression.getQueryEntity().getDynamicExtensionsEntity()) != null) { IRule rule = QueryObjectFactory.createRule(); IConnector<LogicalOperator> logicalConnector = QueryObjectFactory .createLogicalConnector(LogicalOperator.And); expression.addOperand(0, rule, logicalConnector); } } } /** * To initialize map the variables. & build the SQL for the Given Query * Object. * * @param query the IQuery reference. * @return The Root Expetssion of the IQuery. * @throws MultipleRootsException When there exists multiple roots in * joingraph. * @throws SqlException When there is error in the passed IQuery object. */ String buildQuery(IQuery query) throws MultipleRootsException, SqlException, RuntimeException { IQuery queryClone = new DyExtnObjectCloner().clone(query); // IQuery queryClone = query; constraints = queryClone.getConstraints(); QueryObjectProcessor.replaceMultipleParents(constraints); processExpressionsWithCategories(queryClone); this.joinGraph = (JoinGraph) constraints.getJoinGraph(); IExpression rootExpression = constraints.getRootExpression(); // Initializin map variables. aliasNameMap = new HashMap<String, String>(); createAliasAppenderMap(); addactivityStatusToEmptExpr(rootExpression.getExpressionId()); // Identifying empty Expressions. checkForEmptyExpression(rootExpression.getExpressionId()); //pAndExpressions = new HashSet<IExpression>(); // Generating output tree. createTree(); // Creating SQL. String wherePart = getCompleteWherePart(rootExpression); String fromPart = getFromPartSQL(rootExpression, null, new HashSet<Integer>()); StringBuilder selectPart = new StringBuilder(getSelectPart()); // SRINATH if (selectPart.length() > 0) { selectPart.append(Constants.QUERY_COMMA); } selectPart.append(getSelectForOutputTerms(queryClone.getOutputTerms())); Utility.removeLastComma(selectPart); String sql = selectPart + " " + fromPart + " " + wherePart; log(sql); return sql; } private void log(String sql) { // TODO format. try { new SQLLogger().log(sql); } catch (IOException e) { Logger.out.error("Error while logging sql.\n" + e); } } /** * Returns complete where part //including PAND conditions. * * @param rootExpression * @return * @throws SqlException */ private String getCompleteWherePart(IExpression rootExpression) throws SqlException, RuntimeException { String wherePart = buildWherePart(rootExpression, null); // Adding extra where condition for PAND to check activity status value // as disabled or null StringBuffer extraWherePAnd = new StringBuffer(); //Set<Integer> expressionIDs = new HashSet<Integer>(); // set to hold // values of // aliasAppender, // so that // duplicate // condition // should not // get added in // Query. /*for (IExpression expression : pAndExpressions) { if (expressionIDs.add(aliasAppenderMap.get(expression))) { AttributeInterface attributeObj = getActivityStatusAttribute(expression .getQueryEntity().getDynamicExtensionsEntity()); if (attributeObj != null) { // creating activityStatus is null condition, this is // required in case of Pseudo-Anded expressions. ICondition condition = QueryObjectFactory.createCondition(attributeObj, RelationalOperator.IsNull, null); extraWherePAnd.append('(').append(processOperator(condition, expression)).append(" OR "); // creating activityStatus != disabled condition. condition = createActivityStatusCondition(attributeObj); extraWherePAnd.append(processOperator(condition, expression)); extraWherePAnd.append(')').append(LogicalOperator.And).append(' '); } } // expression.getQueryEntity() }*/ wherePart = Constants.WHERE + extraWherePAnd.toString() + wherePart; return wherePart; } /** * Creates condition ActivitiStatus!='disabled' * * @param attributeObj * @return */ private ICondition createActivityStatusCondition(AttributeInterface attributeObj) { List<String> values = new ArrayList<String>(); values.add(Constants.ACTIVITY_STATUS_DISABLED); ICondition condition = QueryObjectFactory.createCondition(attributeObj, RelationalOperator.NotEquals, values); return condition; } /** * To handle Expressions constrained on Categories. If Query contains an * Expression having Constraint Entity as Category, then that Expression is * expanded in such a way that it will look as if it is constrained on * Classes without changing Query criteria. * * @throws SqlException if there is any error in processing category. */ private void processExpressionsWithCategories(IQuery query) throws SqlException { if (containsCategrory()) { Connection connection = null; try { EntityInterface rootDEEntity = constraints.getRootExpression().getQueryEntity() .getDynamicExtensionsEntity(); boolean isCategory = edu.wustl.cab2b.common.util.Utility.isCategory(rootDEEntity); // This is temporary work around, This connection parameter will // be reomoved in future. InitialContext context = new InitialContext(); DataSource dataSource = (DataSource) context.lookup("java:/catissuecore"); connection = dataSource.getConnection(); /** * if the root entity itself is category, then get the root * entity of the category & pass it to the processCategory() * method. */ if (isCategory) { Category category = new CategoryOperations().getCategoryByEntityId(rootDEEntity .getId(), connection); EntityManager.getInstance().getEntityByIdentifier( category.getRootClass().getDeEntityId()); } new CategoryPreprocessor().processCategories(query); } catch (Exception e) { Logger.out.error(e.getMessage(), e); throw new SqlException("Error in preprocessing category!!!!", e); } finally { if (connection != null) // Closing connection. { try { connection.close(); } catch (SQLException e) { Logger.out.error(e.getMessage(), e); throw new SqlException( "Error in closing connection while preprocessing category!!!!", e); } } } } } /** * To check whether there is any Expression having Constraint Entity as * category or not. * * @return true if there is any constraint put on category. */ private boolean containsCategrory() { Set<IQueryEntity> constraintEntities = constraints.getQueryEntities(); for (IQueryEntity entity : constraintEntities) { boolean isCategory = edu.wustl.cab2b.common.util.Utility.isCategory(entity .getDynamicExtensionsEntity()); if (isCategory) { return true; } } return false; } /** * To get the select part of the SQL. * * @return The SQL for the select part of the query. */ private String getSelectPart() { // columnMapList = new // ArrayList<Map<Long,Map<AttributeInterface,String>>>(); StringBuilder selectAttribute = new StringBuilder(); for (OutputTreeDataNode rootOutputTreeNode : rootOutputTreeNodeList) { selectAttribute.append(getSelectAttributes(rootOutputTreeNode)); } //Deepti : added quick fix for bug 6950. Add distinct only when columns do not include CLOB type. if (containsCLOBTypeColumn) { selectAttribute.insert(0, Constants.SELECT); } else { selectAttribute.insert(0, Constants.SELECT_DISTINCT); } Utility.removeLastComma(selectAttribute); return selectAttribute.toString(); } /** * To get the From clause of the Query. * * @param expression The Root Expression. * @param leftAlias the String representing alias of left table. This will * be alias of table represented by Parent Expression. Will be * null for the Root Expression. * @param processedAlias The set of aliases processed. * @return the From clause of the SQL. * @throws SqlException When there is problem in creating from part. problem * can be like: no primary key found in entity for join. */ private String getFromPartSQL(IExpression expression, String leftAlias, Set<Integer> processedAlias) throws SqlException { StringBuffer buffer = new StringBuffer(); if (processedAlias.isEmpty()) // this will be true only for root node. { EntityInterface leftEntity = expression.getQueryEntity().getDynamicExtensionsEntity(); leftAlias = getAliasName(expression); buffer.append(Constants.FROM); buffer.append(leftEntity.getTableProperties().getName()); buffer.append(Constants.SPACE).append(leftAlias); createFromPartForDerivedEntity(expression, buffer); } Integer parentExpressionAliasAppender = aliasAppenderMap.get(expression); processedAlias.add(parentExpressionAliasAppender); // Processing children buffer.append(processChildExpressions(leftAlias, processedAlias, expression)); return buffer.toString(); } /** * To create From path for the deirved entity. * * @param expression the reference to expression. * @param buffer The buffer to which the Output will be appended. * @throws SqlException */ private void createFromPartForDerivedEntity(IExpression expression, StringBuffer buffer) throws SqlException { EntityInterface leftEntity = expression.getQueryEntity().getDynamicExtensionsEntity(); EntityInterface superClassEntity = leftEntity.getParentEntity(); // processing Parent class heirarchy. if (superClassEntity != null) { EntityInterface theLeftEntity = leftEntity; while (superClassEntity != null) { InheritanceStrategy inheritanceType = theLeftEntity.getInheritanceStrategy(); if (InheritanceStrategy.TABLE_PER_SUB_CLASS.equals(inheritanceType)) // only // need // handle // this // type // inheritance // here. { AttributeInterface primaryKey = getPrimaryKey(theLeftEntity); String primaryKeyColumnName = primaryKey.getColumnProperties().getName(); String subClassAlias = getAliasFor(expression, theLeftEntity); String superClassAlias = getAliasFor(expression, superClassEntity); buffer.append(Constants.LEFT_JOIN); buffer.append(superClassEntity.getTableProperties().getName()); buffer.append(' ').append(superClassAlias).append(Constants.ON); String leftAttribute = subClassAlias + Constants.QUERY_DOT + primaryKeyColumnName; String rightAttribute = superClassAlias + Constants.QUERY_DOT + primaryKeyColumnName; buffer.append(Constants.QUERY_DOT).append(leftAttribute).append( Constants.QUERY_EQUALS).append(rightAttribute).append( Constants.QUERY_CLOSING_PARENTHESIS); } theLeftEntity = superClassEntity; superClassEntity = superClassEntity.getParentEntity(); } } } /** * To process all child expression of the given Expression & get their SQL * representation for where part. * * @param leftAlias left table alias in join. * @param processedAlias The list of precessed alias. * @param parentExpressionId The reference to expression whose children to * be processed. * @return the left join sql for children expression. * @throws SqlException when there is error in the passed IQuery object. */ private String processChildExpressions(String leftAlias, Set<Integer> processedAlias, IExpression parentExpression) throws SqlException { StringBuffer buffer = new StringBuffer(); List<IExpression> children = joinGraph.getChildrenList(parentExpression); if (!children.isEmpty()) { // processing all outgoing edges/nodes from the current node in the // joingraph. for (IExpression childExpression : children) { // IExpression childExpression = // constraints.getExpression(childExpressionId); IAssociation association = joinGraph.getAssociation(parentExpression, childExpression); AssociationInterface actualEavAssociation = ((IIntraModelAssociation) association) .getDynamicExtensionsAssociation(); AssociationInterface eavAssociation = actualEavAssociation; EntityInterface rightEntity = eavAssociation.getTargetEntity(); String actualRightAlias = getAliasFor(childExpression, rightEntity); String rightAlias = actualRightAlias; if (!processedAlias.contains(aliasAppenderMap.get(childExpression))) { if (InheritanceUtils.getInstance().isInherited(eavAssociation)) { eavAssociation = InheritanceUtils.getInstance().getActualAassociation( eavAssociation); rightEntity = eavAssociation.getTargetEntity(); leftAlias = getAliasFor(parentExpression, eavAssociation.getEntity()); rightAlias = getAliasFor(childExpression, eavAssociation.getTargetEntity()); } else { leftAlias = getAliasFor(parentExpression, eavAssociation.getEntity()); } EntityInterface childEntity = childExpression.getQueryEntity() .getDynamicExtensionsEntity(); //EntityInterface leftEntity = eavAssociation.getEntity(); ConstraintPropertiesInterface constraintProperties = eavAssociation .getConstraintProperties(); Collection<ConstraintKeyPropertiesInterface> srcCnstrKeyPropColl = constraintProperties .getSrcEntityConstraintKeyPropertiesCollection(); Collection<ConstraintKeyPropertiesInterface> tgtCnstrKeyPropColl = constraintProperties .getTgtEntityConstraintKeyPropertiesCollection(); AttributeInterface primaryKey; String leftAttribute = null; String rightAttribute = null; if (!srcCnstrKeyPropColl.isEmpty() && !tgtCnstrKeyPropColl.isEmpty())// Many // Many // Case { String middleTableName = constraintProperties.getName(); String middleTableAlias = getAliasForMiddleTable(childExpression, middleTableName); for (ConstraintKeyPropertiesInterface cnstrKeyProp : srcCnstrKeyPropColl) { primaryKey = cnstrKeyProp.getSrcPrimaryKeyAttribute();//getPrimaryKey(leftEntity); leftAttribute = leftAlias + Constants.QUERY_DOT + primaryKey.getColumnProperties().getName(); rightAttribute = middleTableAlias + Constants.QUERY_DOT + cnstrKeyProp.getTgtForiegnKeyColumnProperties().getName(); // Forming joing with middle table. buffer.append(Constants.LEFT_JOIN).append(middleTableName).append( Constants.SPACE).append(middleTableAlias).append(Constants.ON); buffer.append(Constants.QUERY_OPENING_PARENTHESIS) .append(leftAttribute).append(Constants.QUERY_EQUALS).append( rightAttribute); /* * Adding descriminator column condition for the 1st * parent node while forming FROM part left joins. This * will be executed only once i.e. when only one node is * processed. */ if (processedAlias.size() == 1) { buffer.append(getDescriminatorCondition(actualEavAssociation .getEntity(), leftAlias)); } buffer.append(Constants.QUERY_CLOSING_PARENTHESIS); } for (ConstraintKeyPropertiesInterface cnstrKeyProp : tgtCnstrKeyPropColl) { // Forming join with child table. leftAttribute = middleTableAlias + Constants.QUERY_DOT + cnstrKeyProp.getTgtForiegnKeyColumnProperties().getName(); primaryKey = cnstrKeyProp.getSrcPrimaryKeyAttribute();//getPrimaryKey(rightEntity); rightAttribute = rightAlias + Constants.QUERY_DOT + primaryKey.getColumnProperties().getName(); buffer.append(Constants.LEFT_JOIN).append( rightEntity.getTableProperties().getName()).append( Constants.SPACE).append(rightAlias).append(Constants.ON); buffer.append(Constants.QUERY_OPENING_PARENTHESIS) .append(leftAttribute).append(Constants.QUERY_EQUALS).append( rightAttribute); /* * Adding descriminator column condition for the child * node while forming FROM part left joins. */ buffer.append( getDescriminatorCondition(actualEavAssociation .getTargetEntity(), rightAlias)).append( Constants.QUERY_CLOSING_PARENTHESIS); } } else { if (srcCnstrKeyPropColl.isEmpty())// Many // Side { for (ConstraintKeyPropertiesInterface cnstrKeyProp : srcCnstrKeyPropColl) { leftAttribute = leftAlias + Constants.QUERY_DOT + cnstrKeyProp.getTgtForiegnKeyColumnProperties().getName(); primaryKey = cnstrKeyProp.getSrcPrimaryKeyAttribute(); rightAttribute = rightAlias + Constants.QUERY_DOT + primaryKey.getColumnProperties().getName(); } } else // One Side { for (ConstraintKeyPropertiesInterface cnstrKeyProp : tgtCnstrKeyPropColl) { primaryKey = cnstrKeyProp.getSrcPrimaryKeyAttribute(); leftAttribute = leftAlias + Constants.QUERY_DOT + primaryKey.getColumnProperties().getName(); rightAttribute = rightAlias + Constants.QUERY_DOT + cnstrKeyProp.getTgtForiegnKeyColumnProperties().getName(); } } buffer.append(Constants.LEFT_JOIN).append( rightEntity.getTableProperties().getName()).append(Constants.SPACE) .append(rightAlias).append(Constants.ON); buffer.append(Constants.QUERY_OPENING_PARENTHESIS).append(leftAttribute) .append(Constants.QUERY_EQUALS).append(rightAttribute); /* * Adding descriminator column condition for the 1st * parent node while forming FROM part left joins. This * will be executed only once i.e. when only one node is * processed. */ if (processedAlias.size() == 1) { buffer.append(getDescriminatorCondition(actualEavAssociation .getEntity(), leftAlias)); } /* * Adding descriminator column condition for the child * node while forming FROM part left joins. */ buffer.append( getDescriminatorCondition(actualEavAssociation.getTargetEntity(), rightAlias)).append(Constants.QUERY_CLOSING_PARENTHESIS); } buffer.append(getParentHeirarchy(childExpression, childEntity, rightEntity)); } // append from part SQL for the next Expressions. buffer.append(getFromPartSQL(childExpression, actualRightAlias, processedAlias)); } } return buffer.toString(); } /** * To get the SQL for the descriminator column condition for the given * entity. It will return SQL for condition in format: " AND * <DescriminatorColumnName> = '<DescriminatorColumnValue>'" * * @param entity The reference to the entity. * @param aliasName The alias Name assigned to that entity table in the SQL. * @return The String representing SQL for the descriminator column * condition for the given entity, if inheritance strategy is * TABLE_PER_HEIRARCHY. Returns empty String if there is no * Descriminator column condition present for the Entity. i.e. when * either of following is true: 1. when entity is not derived * entity.(Parent entity is null) 2. Inheritance strategy is not * TABLE_PER_HEIRARCHY. */ protected String getDescriminatorCondition(EntityInterface entity, String aliasName) { String sql = null; EntityInterface parentEntity = entity.getParentEntity(); // Checking whether the entity is derived or not. if (parentEntity != null) { InheritanceStrategy inheritanceType = entity.getInheritanceStrategy(); if (inheritanceType.equals(InheritanceStrategy.TABLE_PER_HEIRARCHY)) { String columnName = entity.getDiscriminatorColumn(); String columnValue = entity.getDiscriminatorValue(); // Assuming Discrimanator is of type String. String condition = aliasName + Constants.QUERY_DOT + columnName + Constants.QUERY_EQUALS + "'" + columnValue + "'"; sql = " " + LogicalOperator.And + " " + condition; } } return sql; } /** * To get the alias name for the Many to Many table. * * @param childExpression The child Expression of the association. * @param middleTableName The Many to Mant table name. * @return The String representing aliasName for the Many to Many table. */ private String getAliasForMiddleTable(IExpression childExpression, String middleTableName) { return getAliasForClassName(Constants.QUERY_DOT + middleTableName) + Constants.QUERY_UNDERSCORE + aliasAppenderMap.get(childExpression); } /** * To add the Parent Heirarchy to the join part. * * @param childExpression The Expression to which the entity belongs. * @param childEntity The entity whose parent heirarchy to be joined. * @param alreadyAddedEntity The entity already added in join part. * @return left join sql for childEntity. * @throws SqlException when there is error in the passed IQuery object. */ private String getParentHeirarchy(IExpression childExpression, EntityInterface childEntity, EntityInterface alreadyAddedEntity) throws SqlException { StringBuffer combinedJoinPart = new StringBuffer(); if (childEntity.getParentEntity() != null) // Joining Parent & child // classes of the entity. { EntityInterface entity = childEntity; EntityInterface parent = childEntity.getParentEntity(); boolean isReverse = false; List<String> joinSqlList = new ArrayList<String>(); while (parent != null) { if (entity.equals(alreadyAddedEntity)) { isReverse = true; } if (entity.getInheritanceStrategy().equals(InheritanceStrategy.TABLE_PER_SUB_CLASS)) { String leftEntityalias = getAliasFor(childExpression, entity); String rightEntityalias = getAliasFor(childExpression, parent); AttributeInterface primaryKey = getPrimaryKey(entity); String primaryKeyColumnName = primaryKey.getColumnProperties().getName(); String leftAttributeColumn = leftEntityalias + Constants.QUERY_DOT + primaryKeyColumnName; String rightAttributeColumn = rightEntityalias + Constants.QUERY_DOT + primaryKeyColumnName; String sql = null; if (isReverse) { sql = Constants.INNER_JOIN + parent.getTableProperties().getName() + " " + rightEntityalias + Constants.ON; sql += Constants.QUERY_OPENING_PARENTHESIS + leftAttributeColumn + Constants.QUERY_EQUALS + rightAttributeColumn + Constants.QUERY_CLOSING_PARENTHESIS; } else { sql = Constants.INNER_JOIN + entity.getTableProperties().getName() + " " + leftEntityalias + Constants.ON; sql += Constants.QUERY_OPENING_PARENTHESIS + rightAttributeColumn + Constants.QUERY_EQUALS + leftAttributeColumn + Constants.QUERY_CLOSING_PARENTHESIS; } // joinSqlList.add(0, sql); joinSqlList.add(sql); } entity = parent; parent = parent.getParentEntity(); } if (isReverse) { for (String joinSql : joinSqlList) { combinedJoinPart.append(joinSql); } } else { for (String joinSql : joinSqlList) { combinedJoinPart.insert(0, joinSql); } } } return combinedJoinPart.toString(); } /** * To form the Pseudo-And condition for the expression. * * @param expression The child Expression reference. * @param parentExpression The parent Expression. * @param eavAssociation The association between parent & child expression. * @return The Pseudo-And SQL condition. * @throws SqlException When there is problem in creating from part. problem * can be like: no primary key found in entity for join. */ protected String createPseudoAndCondition(IExpression expression, IExpression parentExpression, AssociationInterface eavAssociation) throws SqlException { String pseudoAndSQL; EntityInterface entity = expression.getQueryEntity().getDynamicExtensionsEntity(); String tableName = entity.getTableProperties().getName() + ' '; String leftAlias = getAliasName(expression); String selectAttribute = leftAlias + '.'; ConstraintPropertiesInterface constraintProperties = eavAssociation .getConstraintProperties(); Collection<ConstraintKeyPropertiesInterface> srcCnstrKeyPopColl = constraintProperties .getSrcEntityConstraintKeyPropertiesCollection(); Collection<ConstraintKeyPropertiesInterface> tgtCnstrKeyPopColl = constraintProperties .getTgtEntityConstraintKeyPropertiesCollection(); if (!srcCnstrKeyPopColl.isEmpty() && !tgtCnstrKeyPopColl.isEmpty())// Many // many // case. { // This will start FROM part of SQL from the parent table. selectAttribute = getAliasName(parentExpression) + '.' + getPrimaryKey(parentExpression.getQueryEntity().getDynamicExtensionsEntity()) .getColumnProperties().getName(); pseudoAndSQL = Constants.SELECT + selectAttribute; Set<Integer> processedAlias = new HashSet<Integer>(); String fromPart = getFromPartSQL(parentExpression, leftAlias, processedAlias); pseudoAndSQL += ' ' + fromPart + Constants.WHERE; } else { if (tgtCnstrKeyPopColl.isEmpty()) { selectAttribute += getPrimaryKey(entity).getColumnProperties().getName(); } else { selectAttribute += constraintProperties.getTgtEntityConstraintKeyProperties() .getTgtForiegnKeyColumnProperties().getName(); } pseudoAndSQL = Constants.SELECT + selectAttribute; Set<Integer> processedAlias = new HashSet<Integer>(); processedAlias.add(aliasAppenderMap.get(expression)); String fromPart = getFromPartSQL(expression, leftAlias, processedAlias); StringBuffer buffer = new StringBuffer(); buffer.append(Constants.FROM).append(tableName).append(' ').append(leftAlias); createFromPartForDerivedEntity(expression, buffer); buffer.append(fromPart).append(Constants.WHERE); pseudoAndSQL += buffer.toString(); } return pseudoAndSQL; } public void addActivityStatusCondition(IRule rule) { IExpression expression = rule.getContainingExpression(); AttributeInterface attributeObj = getActivityStatusAttribute(expression.getQueryEntity() .getDynamicExtensionsEntity()); if (attributeObj != null) { ICondition condition = createActivityStatusCondition(attributeObj); rule.addCondition(condition); } } /** * Check for activity status present in entity. * * @param entityInterfaceObj The Entity for which we required to check if * activity status present. * @return Reference to the AttributeInterface if activityStatus attribute * present in the entity, else null. */ private AttributeInterface getActivityStatusAttribute(EntityInterface entityInterfaceObj) { Collection<AttributeInterface> attributes = entityInterfaceObj .getEntityAttributesForQuery(); for (AttributeInterface attribute : attributes) { if (attribute.getName().equals(Constants.ACTIVITY_STATUS)) { return attribute; } } return null; } /** * Get the query specific representation for Attribute ie the LHS of a condition. * * @param attribute The reference to AttributeInterface * @param expression The reference to Expression to which this attribute * belongs. * @return The query specific representation for Attribute. */ protected String getConditionAttributeName(AttributeInterface attribute, IExpression expression) { AttributeInterface actualAttribute = attribute; if (InheritanceUtils.getInstance().isInherited(attribute)) { actualAttribute = InheritanceUtils.getInstance().getActualAttribute(attribute); } EntityInterface attributeEntity = actualAttribute.getEntity(); String aliasName = getAliasFor(expression, attributeEntity); String attributeName = aliasName + Constants.QUERY_DOT + actualAttribute.getColumnProperties().getName(); return attributeName; } /** * To Modify value as per the Data type. 1. In case of String datatype, * replace occurence of single quote by singlequote twice. 2. Enclose the * Given values by single Quotes for String & Date Data type. 3. For Boolean * DataType it will change value to 1 if its TRUE, else 0. * * @param value the Modified value. * @param dataType The DataType of the passed value. * @return The String representing encoded value for the given value & * datatype. * @throws SqlException when there is problem with the values, for Ex. * unable to parse date/integer/double etc. */ protected String modifyValueForDataType(String value, AttributeTypeInformationInterface dataType) throws SqlException { if (dataType instanceof StringTypeInformationInterface)// for data type // String it will be enclosed in single quote. { value = value.replaceAll("'", "''"); value = "'" + value + "'"; } else if (dataType instanceof DateTypeInformationInterface) // for // data type date it will be enclosed in single quote. { try { Date date = new Date(); date = Utility.parseDate(value); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); value = (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH) + "-" + calendar.get(Calendar.YEAR); String strToDateFunction = Variables.strTodateFunction; if (strToDateFunction == null || strToDateFunction.trim().equals("")) { strToDateFunction = Constants.STR_TO_DATE; // using MySQL function // if the Value is not // defined. } String datePattern = Variables.datePattern; if (datePattern == null || datePattern.trim().equals("")) { datePattern = "%m-%d-%Y"; // using MySQL function if the // Value is not defined. } value = strToDateFunction + "('" + value + "','" + datePattern + "')"; } catch (ParseException parseExp) { Logger.out.error(parseExp.getMessage(), parseExp); throw new SqlException(parseExp.getMessage(), parseExp); } } else if (dataType instanceof BooleanTypeInformationInterface) // defining // value // for // boolean // datatype. { if (value == null || !(value.equalsIgnoreCase(Constants.TRUE) || value .equalsIgnoreCase(Constants.FALSE))) { throw new SqlException( "Incorrect value found in value part for boolean operator!!!"); } if (value.equalsIgnoreCase(Constants.TRUE)) { value = "1"; } else { value = "0"; } } else if (dataType instanceof IntegerTypeInformationInterface) { if (!new Validator().isNumeric(value)) { throw new SqlException("Non numeric value found in value part!!!"); } } else if (dataType instanceof DoubleTypeInformationInterface) { if (!new Validator().isDouble(value)) { throw new SqlException("Non numeric value found in value part!!!"); } } return value; } private String getSelectForOutputTerms(List<IOutputTerm> terms) { outputTermsColumns = new HashMap<String, IOutputTerm>(); StringBuilder s = new StringBuilder(); for (IOutputTerm term : terms) { String termString = Constants.QUERY_OPENING_PARENTHESIS + getTermString(term.getTerm()) + Constants.QUERY_CLOSING_PARENTHESIS; termString = modifyForTimeInterval(termString, term.getTimeInterval()); String columnName = Constants.COLUMN_NAME + selectIndex++; s.append(termString + " " + columnName + Constants.QUERY_COMMA); outputTermsColumns.put(columnName, term); } Utility.removeLastComma(s); return s.toString(); } private String modifyForTimeInterval(String termString, TimeInterval<?> timeInterval) { if (timeInterval == null) { return termString; } termString = termString + "/" + timeInterval.numSeconds(); termString = "ROUND" + Constants.QUERY_OPENING_PARENTHESIS + termString + Constants.QUERY_CLOSING_PARENTHESIS; return termString; } protected String getTemporalCondition(String operandquery) { return operandquery; } }
package ca.mjdsystems.jmatio.test; import ca.mjdsystems.jmatio.io.MatFileFilter; import ca.mjdsystems.jmatio.io.MatFileReader; import ca.mjdsystems.jmatio.io.MatFileType; import ca.mjdsystems.jmatio.io.SimulinkDecoder; import ca.mjdsystems.jmatio.types.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.*; import java.util.Map; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; /** This test verifies that ReducedHeader generated mat files work correctly. * * @author Matthew Dawson <matthew@mjdsystems.ca> */ @RunWith(JUnit4.class) public class SimulinkMatTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testParsingQuadraticRootsTET() throws IOException { File file = fileFromStream("/simulink_tet_out.mat"); MatFileReader reader = new MatFileReader(file, new MatFileFilter(), MatFileType.ReducedHeader); MLObject data = (MLObject)reader.getContent().get("@"); // First check that the root element is correct. assertThat(data, is(notNullValue())); assertThat(data.getClassName(), is("Data")); assertThat(data.getSize(), is(1)); Map<String, MLArray> dataO = data.getFields(0); assertThat(dataO.size(), is(10)); assertThat(((MLChar) dataO.get("function_name")).getString(0), is("quad_fcn_subtype")); assertThat(((MLChar) dataO.get("function_inputs")).getString(0), is("c,a,b:{x:real|(a=0 => x /= 0) AND (a /= 0 => (x^2) - 4*a*c >= 0)}")); assertThat(((MLDouble) dataO.get("open")).get(0), is(1.0)); assertThat(((MLDouble) dataO.get("fig")).get(0), is(notNullValue())); // This can be anything, just not null! assertThat(((MLDouble) dataO.get("multi_mode")).get(0), is(1.0)); assertThat(((MLDouble) dataO.get("checked")).get(0), is(0.0)); // Next, make sure the settings structure came out right. Not super important, but a good test. MLStructure settings = (MLStructure) dataO.get("settings"); assertThat(settings.getAllFields().size(), is(5)); assertThat(((MLDouble) settings.getField("set")).get(0), is(1.0)); assertThat((settings.getField("inputs")), is(instanceOf(MLDouble.class))); assertThat(((MLDouble) settings.getField("count")).get(0), is(1000.0)); assertThat(((MLDouble) settings.getField("range")).get(0), is(100.0)); assertThat(((MLDouble) settings.getField("except")).get(0), is(0.0)); // Next, verify Grid2, as it is easiest. MLObject Grid2 = (MLObject) dataO.get("Grid2"); assertThat(Grid2.getClassName(), is("Grid")); assertThat(Grid2.getSize(), is(1)); Map<String, MLArray> gridO = Grid2.getFields(0); assertThat(((MLDouble) gridO.get("num_cells")).get(0), is(2.0)); MLObject cells = (MLObject) gridO.get("cells"); assertThat(cells.getSize(), is(2)); } // This just ensures the SimulinkDecoder actually decodes correctly. @Test public void testParsingSimulinkEncoding() throws IOException {
package no.stelar7.api.l4j8.tests.cache; import no.stelar7.api.l4j8.basic.cache.*; import no.stelar7.api.l4j8.basic.calling.DataCall; import no.stelar7.api.l4j8.basic.constants.api.*; import no.stelar7.api.l4j8.basic.constants.flags.ChampDataFlags; import no.stelar7.api.l4j8.impl.L4J8; import no.stelar7.api.l4j8.impl.builders.match.MatchListBuilder; import no.stelar7.api.l4j8.impl.builders.summoner.SummonerBuilder; import no.stelar7.api.l4j8.pojo.match.MatchReference; import no.stelar7.api.l4j8.tests.SecretFile; import org.junit.*; import org.junit.rules.Stopwatch; import java.util.*; import java.util.concurrent.TimeUnit; public class CacheTest { final L4J8 l4j8 = new L4J8(SecretFile.CREDS); @Rule public Stopwatch stopwatch = new Stopwatch() {}; @Test public void testMemoryCache() throws InterruptedException { DataCall.setCacheProvider(new MemoryCacheProvider(5)); DataCall.setLogLevel(LogLevel.INFO); doCacheStuff(); } @Test public void testFileSystemCache() throws InterruptedException { DataCall.setCacheProvider(new FileSystemCacheProvider(null, -1)); DataCall.setLogLevel(LogLevel.INFO); doCacheStuff(); } @Test public void testStaticDataCache() { DataCall.setCacheProvider(new FileSystemCacheProvider(null, -1)); DataCall.setLogLevel(LogLevel.INFO); l4j8.getStaticAPI().getChampions(Platform.NA1, EnumSet.allOf(ChampDataFlags.class), null, null); l4j8.getStaticAPI().getChampions(Platform.NA1, EnumSet.allOf(ChampDataFlags.class), null, null); l4j8.getStaticAPI().getChampions(Platform.EUW1, null, null, null); } @Test public void testCacheStuff() throws InterruptedException { DataCall.setLogLevel(LogLevel.INFO); DataCall.setCacheProvider(new FileSystemCacheProvider(null, -1)); new SummonerBuilder().withPlatform(Constants.TEST_PLATFORM[0]).withSummonerId(Constants.TEST_SUMMONER_IDS[0]).get(); new SummonerBuilder().withPlatform(Constants.TEST_PLATFORM[0]).withSummonerId(Constants.TEST_SUMMONER_IDS[0]).get(); Thread.sleep(6000); new SummonerBuilder().withPlatform(Constants.TEST_PLATFORM[0]).withSummonerId(Constants.TEST_SUMMONER_IDS[0]).get(); new SummonerBuilder().withPlatform(Constants.TEST_PLATFORM[0]).withSummonerId(Constants.TEST_SUMMONER_IDS[0]).get(); } @Test public void testTieredMemoryCache() throws InterruptedException { DataCall.setLogLevel(LogLevel.INFO); DataCall.setCacheProvider(new TieredCacheProvider(new MemoryCacheProvider(3), new FileSystemCacheProvider(null, -1))); doCacheStuff(); } @After public void clearCacheProvider() { DataCall.setCacheProvider(CacheProvider.EmptyProvider.INSTANCE); } private void doCacheStuff() throws InterruptedException { List<MatchReference> recents = new MatchListBuilder().withPlatform(Constants.TEST_PLATFORM[0]).withAccountId(Constants.TEST_ACCOUNT_IDS[0]).get(); if (recents.isEmpty()) { return; } MatchReference ref = recents.get(0); System.out.println("Starting timer"); long start = stopwatch.runtime(TimeUnit.MICROSECONDS); ref.getFullMatch(); System.out.printf("1x url fetch time: %dµs%n", stopwatch.runtime(TimeUnit.MICROSECONDS) - start); start = stopwatch.runtime(TimeUnit.MICROSECONDS); ref.getFullMatch(); System.out.printf("1x cache fetch time: %dµs%n", stopwatch.runtime(TimeUnit.MICROSECONDS) - start); start = stopwatch.runtime(TimeUnit.MICROSECONDS); for (int i = 0; i < 10; i++) { ref.getFullMatch(); } System.out.printf("10x cache fetch time: %dµs%n", stopwatch.runtime(TimeUnit.MICROSECONDS) - start); System.out.println(); System.out.println("clearing cache"); System.out.println(); DataCall.getCacheProvider().clear(URLEndpoint.V3_MATCH); start = stopwatch.runtime(TimeUnit.MICROSECONDS); ref.getFullMatch(); System.out.printf("1x url fetch time: %dµs%n", stopwatch.runtime(TimeUnit.MICROSECONDS) - start); start = stopwatch.runtime(TimeUnit.MICROSECONDS); for (int i = 0; i < 10; i++) { ref.getFullMatch(); } System.out.printf("10x cache fetch time: %dµs%n", stopwatch.runtime(TimeUnit.MICROSECONDS) - start); System.out.println(); System.out.println("Fetching 3 aditional matches"); recents.get(1).getFullMatch(); recents.get(2).getFullMatch(); recents.get(3).getFullMatch(); System.out.printf("Cache size: %d%n", DataCall.getCacheProvider().getSize()); System.out.println("Waiting for cache timeout"); TimeUnit.SECONDS.sleep(5); System.out.printf("Cache size: %d%n", DataCall.getCacheProvider().getSize()); System.out.println("Re-fetching cached items"); start = stopwatch.runtime(TimeUnit.MICROSECONDS); recents.get(0).getFullMatch(); recents.get(1).getFullMatch(); recents.get(2).getFullMatch(); recents.get(3).getFullMatch(); System.out.printf("4x fetches took: %dµs%n", stopwatch.runtime(TimeUnit.MICROSECONDS) - start); System.out.printf("Cache size: %d%n", DataCall.getCacheProvider().getSize()); System.out.println(); } }
package camp.pixels.signage.receivers; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.SystemClock; import android.support.v4.content.WakefulBroadcastReceiver; import static android.support.v4.content.WakefulBroadcastReceiver.startWakefulService; import android.util.Log; import camp.pixels.signage.FullScreenWebViewActivity; import camp.pixels.signage.services.PollingService; import camp.pixels.signage.R; import static camp.pixels.signage.util.DeviceIdentifier.getHardwareID; import static camp.pixels.signage.util.NetworkInterfaces.getIPAddress; import static camp.pixels.signage.util.NetworkInterfaces.getMACAddress; import static camp.pixels.signage.util.TrustManager.overrideCertificateChainValidation; // Begin polling upon starting application public class StartingReceiver extends WakefulBroadcastReceiver { private static final String TAG = "PollingReceiver"; @Override public void onReceive(Context context, Intent intent) { AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent service = new Intent(context, PollingService.class); int polling_interval = context.getResources().getInteger(R.integer.polling_interval); // Format the request URL and send it over to the service as initial data service.setData(Uri.parse(context.getResources().getString(R.string.polling_url) + getHardwareID(context) + '/' + getMACAddress(null) + '/' + getIPAddress(null, true))); // Set up a pending intent from our service PendingIntent pendingService = PendingIntent.getService(context, 0, service, 0); // Cancel any existing alarms for this service, just in case am.cancel(pendingService); //Log.i(TAG, "Setting alarm for " + polling_interval); am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + polling_interval, polling_interval, pendingService); //Log.i(TAG, "Starting service @ " + SystemClock.elapsedRealtime()); startWakefulService(context, service); Intent viewer = new Intent(context, FullScreenWebViewActivity.class); viewer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(viewer); } }
package com.afollestad.silk.fragments; import android.os.Bundle; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ProgressBar; import android.widget.TextView; import com.afollestad.silk.R; import com.afollestad.silk.adapters.SilkAdapter; import com.afollestad.silk.cache.SilkComparable; import com.afollestad.silk.views.list.SilkGridView; import com.afollestad.silk.views.list.SilkListView; /** * A {@link com.afollestad.silk.fragments.SilkFragment} that shows a list, with an empty text, and has progress bar support. Has other various * convenience methods and handles a lot of things on its own to make things easy. * <p/> * The fragment uses a {@link com.afollestad.silk.adapters.SilkAdapter} to display items of type T. * * @param <T> The type of items held in the fragment's list. * @author Aidan Follestad (afollestad) */ public abstract class SilkListFragment<T extends SilkComparable> extends SilkFragment { private AbsListView mListView; private TextView mEmpty; private ProgressBar mProgress; private SilkAdapter<T> mAdapter; private boolean mLoading; /** * Gets the ListView contained in the Fragment's layout. */ public final AbsListView getListView() { return mListView; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = initializeAdapter(); } /** * Uses a list layout by default but this can be overridden if necessary. If you do override this method, * the returned layout must have the same views with the same IDs in addition to whatever you add or change. */ @Override public int getLayout() { return R.layout.fragment_list; } @Override public String getTitle() { // This isn't needed but can be overridden by inheriting classes if needed. return null; } /** * Inheriting classes return a string resource for the list's empty text value here. * <p/> * The text will be shown when the list is not loading and the list is empty. */ public abstract int getEmptyText(); /** * Updates the edit text that was initially set to the value of {@link #getEmptyText()}. */ public final void setEmptyText(CharSequence text) { mEmpty.setText(text); } /** * Gets the SilkAdapter used to add and remove items from the list. */ public final SilkAdapter<T> getAdapter() { return mAdapter; } /** * Only called once to cause inheriting classes to create a new SilkAdapter that can later be retrieved using * {#getAdapter}. */ protected abstract SilkAdapter<T> initializeAdapter(); /** * Called when an item in the list is tapped by the user. * * @param index The index of the tapped item. * @param item The actual tapped item from the adapter. * @param view The view in the list that was tapped. */ public abstract void onItemTapped(int index, T item, View view); /** * Called when an item in the list is long-tapped by the user. * * @param index The index of the long-tapped item. * @param item The actual long-tapped item from the adapter. * @param view The view in the list that was long-tapped. * @return Whether or not the event was handled. */ public abstract boolean onItemLongTapped(int index, T item, View view); /** * Gets whether or not the list is currently loading. * <p/> * This value is changed using {#setLoading} and {#setLoadComplete}. */ public final boolean isLoading() { return mLoading; } private void setListShown(boolean shown) { if (!shown) { mEmpty.setVisibility(View.GONE); } else { mListView.setEmptyView(mEmpty); getAdapter().notifyDataSetChanged(); } mProgress.setVisibility(shown ? View.GONE : View.VISIBLE); } /** * Notifies the fragment that it is currently loading data. * <p/> * If true is passed as a parameter, the list or empty text will be hidden, and the progress view to be shown. * * @param progress Whether or not the progress view will be shown and the list will be hidden. */ public final void setLoading(boolean progress) { if (progress) setListShown(false); mLoading = true; } /** * Notifies the fragment that it is done loading data. This causes the progress view to become invisible, and the list * or empty text become visible again. * * @param error Whether or not an error occurred while loading. This value is not used in the default implementation * but can be used by overriding classes. */ public void setLoadComplete(boolean error) { mLoading = false; setListShown(true); } /** * References to views are created here, along with hooks to event handlers. If you override this method in a sub-class, * make sure you make a call to the super method. */ @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mListView = (AbsListView) view.findViewById(R.id.list); if (mListView instanceof SilkListView) ((SilkListView) mListView).setSilkAdapter(mAdapter); else if (mListView instanceof SilkGridView) ((SilkGridView) mListView).setSilkAdapter(mAdapter); else mListView.setAdapter(mAdapter); mEmpty = (TextView) view.findViewById(R.id.empty); mListView.setEmptyView(mEmpty); mProgress = (ProgressBar) view.findViewById(R.id.progress); if (getEmptyText() > 0) mEmpty.setText(getEmptyText()); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) { T item = getAdapter().getItem(index); onItemTapped(index, item, view); } }); mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int index, long id) { T item = getAdapter().getItem(index); return onItemLongTapped(index, item, view); } }); } }
package com.cesidiodibenedetto.filechooser; import java.util.HashMap; import java.util.Map; import org.apache.cordova.CordovaActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Intent; import android.net.Uri; import android.text.Html; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaResourceApi; import org.apache.cordova.PluginResult; /** * FileChooser is a PhoneGap plugin that acts as polyfill for Android KitKat and web * applications that need support for <input type="file"> * */ public class FileChooser extends CordovaPlugin { //private String onNewIntentCallback = null; private CallbackContext callbackContext = null; //public boolean execute(String action, JSONArray args, String callbackId) { @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { try { this.callbackContext = callbackContext; if (action.equals("startActivity")) { if (args.length() != 1) { //return new PluginResult(PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } // Parse the arguments final CordovaResourceApi resourceApi = webView.getResourceApi(); JSONObject obj = args.getJSONObject(0); String type = obj.has("type") ? obj.getString("type") : null; Uri uri = obj.has("url") ? resourceApi.remapUri(Uri.parse(obj.getString("url"))) : null; JSONObject extras = obj.has("extras") ? obj.getJSONObject("extras") : null; Map<String, String> extrasMap = new HashMap<String, String>(); // Populate the extras if any exist if (extras != null) { JSONArray extraNames = extras.names(); for (int i = 0; i < extraNames.length(); i++) { String key = extraNames.getString(i); String value = extras.getString(key); extrasMap.put(key, value); } } startActivity(obj.getString("action"), uri, type, extrasMap); //return new PluginResult(PluginResult.Status.OK); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; } else if (action.equals("hasExtra")) { if (args.length() != 1) { //return new PluginResult(PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } Intent i = ((CordovaActivity)this.cordova.getActivity()).getIntent(); String extraName = args.getString(0); //return new PluginResult(PluginResult.Status.OK, i.hasExtra(extraName)); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, i.hasExtra(extraName))); return true; } else if (action.equals("getExtra")) { if (args.length() != 1) { //return new PluginResult(PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } Intent i = ((CordovaActivity)this.cordova.getActivity()).getIntent(); String extraName = args.getString(0); if (i.hasExtra(extraName)) { //return new PluginResult(PluginResult.Status.OK, i.getStringExtra(extraName)); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, i.getStringExtra(extraName))); return true; } else { //return new PluginResult(PluginResult.Status.ERROR); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); return false; } } else if (action.equals("getUri")) { if (args.length() != 0) { //return new PluginResult(PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } Intent i = ((CordovaActivity)this.cordova.getActivity()).getIntent(); String uri = i.getDataString(); //return new PluginResult(PluginResult.Status.OK, uri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, uri)); return true; } else if (action.equals("onNewIntent")) { if (args.length() != 0) { //return new PluginResult(PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } //this.onNewIntentCallback = callbackId; PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); callbackContext.sendPluginResult(result); return true; //return result; } else if (action.equals("sendBroadcast")) { if (args.length() != 1) { //return new PluginResult(PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } // Parse the arguments JSONObject obj = args.getJSONObject(0); JSONObject extras = obj.has("extras") ? obj.getJSONObject("extras") : null; Map<String, String> extrasMap = new HashMap<String, String>(); // Populate the extras if any exist if (extras != null) { JSONArray extraNames = extras.names(); for (int i = 0; i < extraNames.length(); i++) { String key = extraNames.getString(i); String value = extras.getString(key); extrasMap.put(key, value); } } sendBroadcast(obj.getString("action"), extrasMap); //return new PluginResult(PluginResult.Status.OK); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; } //return new PluginResult(PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } catch (JSONException e) { e.printStackTrace(); String errorMessage=e.getMessage(); //return new PluginResult(PluginResult.Status.JSON_EXCEPTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION,errorMessage)); return false; } } @Override public void onNewIntent(Intent intent) { if (this.callbackContext != null) { this.callbackContext.success(intent.getDataString()); } } void startActivity(String action, Uri uri, String type, Map<String, String> extras) { Intent i = (uri != null ? new Intent(action, uri) : new Intent(action)); if (type != null && uri != null) { i.setDataAndType(uri, type); //Fix the crash problem with android 2.3.6 } else { if (type != null) { i.setType(type); } } for (String key : extras.keySet()) { String value = extras.get(key); // If type is text html, the extra text must sent as HTML if (key.equals(Intent.EXTRA_TEXT) && type.equals("text/html")) { i.putExtra(key, Html.fromHtml(value)); } else if (key.equals(Intent.EXTRA_STREAM)) { // allowes sharing of images as attachments. // value in this case should be a URI of a file final CordovaResourceApi resourceApi = webView.getResourceApi(); i.putExtra(key, resourceApi.remapUri(Uri.parse(value))); } else if (key.equals(Intent.EXTRA_EMAIL)) { // allows to add the email address of the receiver i.putExtra(Intent.EXTRA_EMAIL, new String[] { value }); } else { i.putExtra(key, value); } } ((CordovaActivity)this.cordova.getActivity()).startActivity(i); } void sendBroadcast(String action, Map<String, String> extras) { Intent intent = new Intent(); intent.setAction(action); for (String key : extras.keySet()) { String value = extras.get(key); intent.putExtra(key, value); } ((CordovaActivity)this.cordova.getActivity()).sendBroadcast(intent); } }
package org.jvnet.hudson.test; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.model.FreeStyleProject; import hudson.model.Hudson; import hudson.model.Item; import junit.framework.TestCase; import org.jvnet.hudson.test.HudsonHomeLoader.CopyExisting; import org.jvnet.hudson.test.recipes.Recipe; import org.jvnet.hudson.test.recipes.Recipe.Runner; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.security.HashUserRealm; import org.mortbay.jetty.security.UserRealm; import org.mortbay.jetty.webapp.Configuration; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.jetty.webapp.WebXmlConfiguration; import org.xml.sax.SAXException; import javax.servlet.ServletContext; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Base class for all Hudson test cases. * * @author Kohsuke Kawaguchi */ public abstract class HudsonTestCase extends TestCase { protected Hudson hudson; protected final TestEnvironment env = new TestEnvironment(); protected HudsonHomeLoader homeLoader = HudsonHomeLoader.NEW; /** * TCP/IP port that the server is listening on. */ protected int localPort; protected Server server; /** * Where in the {@link Server} is Hudson deploed? */ protected String contextPath = "/"; /** * {@link Runnable}s to be invoked at {@link #tearDown()}. */ protected List<LenientRunnable> tearDowns = new ArrayList<LenientRunnable>(); protected HudsonTestCase(String name) { super(name); } protected HudsonTestCase() { } protected void setUp() throws Exception { env.pin(); recipe(); hudson = newHudson(); hudson.servletContext.setAttribute("app",hudson); hudson.servletContext.setAttribute("version","?"); } protected void tearDown() throws Exception { for (LenientRunnable r : tearDowns) r.run(); hudson.cleanUp(); env.dispose(); server.stop(); } protected Hudson newHudson() throws Exception { return new Hudson(homeLoader.allocate(), createWebServer()); } /** * Prepares a webapp hosting environment to get {@link ServletContext} implementation * that we need for testing. */ protected ServletContext createWebServer() throws Exception { server = new Server(); WebAppContext context = new WebAppContext(WarExploder.EXPLODE_DIR.getPath(), contextPath); context.setClassLoader(getClass().getClassLoader()); context.setConfigurations(new Configuration[]{new WebXmlConfiguration(),new NoListenerConfiguration()}); server.setHandler(context); SocketConnector connector = new SocketConnector(); server.addConnector(connector); server.addUserRealm(configureUserRealm()); server.start(); localPort = connector.getLocalPort(); return context.getServletContext(); } /** * Configures a security realm for a test. */ protected UserRealm configureUserRealm() { HashUserRealm realm = new HashUserRealm(); realm.setName("default"); // this is the magic realm name to make it effective on everywhere realm.put("alice","alice"); realm.put("bob","bob"); realm.put("charlie","charlie"); realm.addUserToRole("alice","female"); realm.addUserToRole("bob","male"); realm.addUserToRole("charlie","male"); return realm; } // Convenience methods protected FreeStyleProject createFreeStyleProject() throws IOException { return createFreeStyleProject("test"); } protected FreeStyleProject createFreeStyleProject(String name) throws IOException { return (FreeStyleProject)hudson.createProject(FreeStyleProject.DESCRIPTOR,name); } // recipe methods. Control the test environments. /** * Called during the {@link #setUp()} to give a test case an opportunity to * control the test environment in which Hudson is run. * * <p> * From here, call a series of {@code withXXX} methods. */ protected void recipe() throws Exception { // look for recipe meta-annotation Method runMethod= getClass().getMethod(getName()); for( final Annotation a : runMethod.getAnnotations() ) { Recipe r = a.annotationType().getAnnotation(Recipe.class); if(r==null) continue; final Runner runner = r.value().newInstance(); tearDowns.add(new LenientRunnable() { public void run() throws Exception { runner.tearDown(HudsonTestCase.this,a); } }); runner.setup(this,a); } } public HudsonTestCase withNewHome() { homeLoader = HudsonHomeLoader.NEW; return this; } public HudsonTestCase withExistingHome(File source) { homeLoader = new CopyExisting(source); return this; } public HudsonTestCase withPresetData(String name) { name = "/" + name + ".zip"; URL res = getClass().getResource(name); if(res==null) throw new IllegalArgumentException("No such data set found: "+name); homeLoader = new CopyExisting(res); return this; } /** * Extends {@link com.gargoylesoftware.htmlunit.WebClient} and provide convenience methods * for accessing Hudson. */ public class WebClient extends com.gargoylesoftware.htmlunit.WebClient { public WebClient() { setJavaScriptEnabled(false); } /** * Logs in to Hudson. */ public WebClient login(String username, String password) throws Exception { HtmlPage page = goTo("login"); // page = (HtmlPage) page.getFirstAnchorByText("Login").click(); HtmlForm form = page.getFormByName("login"); form.getInputByName("j_username").setValueAttribute(username); form.getInputByName("j_password").setValueAttribute(password); form.submit(null); return this; } /** * Logs in to Hudson, by using the user name as the password. * * <p> * See {@link HudsonTestCase#configureUserRealm()} for how the container is set up with the user names * and passwords. All the test accounts have the same user name and password. */ public WebClient login(String username) throws Exception { login(username,username); return this; } public HtmlPage getPage(Item item) throws IOException, SAXException { return getPage(item,""); } public HtmlPage getPage(Item item, String relative) throws IOException, SAXException { return goTo(item.getUrl()+relative); } /** * @deprecated * This method expects a full URL. This method is marked as deprecated to warn you * that you probably should be using {@link #goTo(String)} method, which accepts * a relative path within the Hudson being tested. (IOW, if you really need to hit * a website on the internet, there's nothing wrong with using this method.) */ public Page getPage(String url) throws IOException, FailingHttpStatusCodeException { return super.getPage(url); } /** * Requests a page within Hudson. * * @param relative * Relative path within Hudson. Starts without '/'. * For example, "job/test/" to go to a job top page. */ public HtmlPage goTo(String relative) throws IOException, SAXException { return (HtmlPage)goTo(relative, "text/html"); } public Page goTo(String relative, String expectedContentType) throws IOException, SAXException { return super.getPage("http://localhost:"+localPort+contextPath+relative); } } }
package com.ecyrd.jspwiki.attachment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.parser.MarkupParser; import com.ecyrd.jspwiki.providers.ProviderException; import com.ecyrd.jspwiki.providers.WikiAttachmentProvider; import com.ecyrd.jspwiki.util.ClassUtil; public class AttachmentManager { /** * The property name for defining the attachment provider class name. */ public static final String PROP_PROVIDER = "jspwiki.attachmentProvider"; /** * The maximum size of attachments that can be uploaded. */ public static final String PROP_MAXSIZE = "jspwiki.attachment.maxsize"; static Logger log = Logger.getLogger( AttachmentManager.class ); private WikiAttachmentProvider m_provider; private WikiEngine m_engine; /** * Creates a new AttachmentManager. Note that creation will never fail, * but it's quite likely that attachments do not function. * <p> * <b>DO NOT CREATE</b> an AttachmentManager on your own, unless you really * know what you're doing. Just use WikiEngine.getAttachmentManager() if * you're making a module for JSPWiki. * * @param engine The wikiengine that owns this attachment manager. * @param props A list of properties from which the AttachmentManager will seek * its configuration. Typically this is the "jspwiki.properties". */ // FIXME: Perhaps this should fail somehow. public AttachmentManager( WikiEngine engine, Properties props ) { String classname; m_engine = engine; // If user wants to use a cache, then we'll use the CachingProvider. boolean useCache = "true".equals(props.getProperty( PageManager.PROP_USECACHE )); if( useCache ) { classname = "com.ecyrd.jspwiki.providers.CachingAttachmentProvider"; } else { classname = props.getProperty( PROP_PROVIDER ); } // If no class defined, then will just simply fail. if( classname == null ) { log.info( "No attachment provider defined - disabling attachment support." ); return; } // Create and initialize the provider. try { Class providerclass = ClassUtil.findClass( "com.ecyrd.jspwiki.providers", classname ); m_provider = (WikiAttachmentProvider)providerclass.newInstance(); m_provider.initialize( m_engine, props ); } catch( ClassNotFoundException e ) { log.error( "Attachment provider class not found",e); } catch( InstantiationException e ) { log.error( "Attachment provider could not be created", e ); } catch( IllegalAccessException e ) { log.error( "You may not access the attachment provider class", e ); } catch( NoRequiredPropertyException e ) { log.error( "Attachment provider did not find a property that it needed: "+e.getMessage(), e ); m_provider = null; // No, it did not work. } catch( IOException e ) { log.error( "Attachment provider reports IO error", e ); m_provider = null; } } /** * Returns true, if attachments are enabled and running. */ public boolean attachmentsEnabled() { return m_provider != null; } /** * Gets info on a particular attachment, latest version. * * @param name A full attachment name. * @return Attachment, or null, if no such attachment exists. * @throws ProviderException If something goes wrong. */ public Attachment getAttachmentInfo( String name ) throws ProviderException { return getAttachmentInfo( name, WikiProvider.LATEST_VERSION ); } /** * Gets info on a particular attachment with the given version. * * @param name A full attachment name. * @param version A version number. * @return Attachment, or null, if no such attachment or version exists. * @throws ProviderException If something goes wrong. */ public Attachment getAttachmentInfo( String name, int version ) throws ProviderException { if( name == null ) { return null; } return getAttachmentInfo( null, name, version ); } /** * Figures out the full attachment name from the context and * attachment name. * * @param context The current WikiContext * @param attachmentname The file name of the attachment. * @return Attachment, or null, if no such attachment exists. * @throws ProviderException If something goes wrong. */ public Attachment getAttachmentInfo( WikiContext context, String attachmentname ) throws ProviderException { return getAttachmentInfo( context, attachmentname, WikiProvider.LATEST_VERSION ); } /** * Figures out the full attachment name from the context and * attachment name. * * @param context The current WikiContext * @param attachmentname The file name of the attachment. * @param version A particular version. * @return Attachment, or null, if no such attachment or version exists. * @throws ProviderException If something goes wrong. */ public Attachment getAttachmentInfo( WikiContext context, String attachmentname, int version ) throws ProviderException { if( m_provider == null ) { return( null ); } WikiPage currentPage = null; if( context != null ) { currentPage = context.getPage(); } // Figure out the parent page of this attachment. If we can't find it, // we'll assume this refers directly to the attachment. int cutpt = attachmentname.lastIndexOf('/'); if( cutpt != -1 ) { String parentPage = attachmentname.substring(0,cutpt); parentPage = MarkupParser.cleanLink( parentPage ); attachmentname = attachmentname.substring(cutpt+1); // If we for some reason have an empty parent page name; // this can't be an attachment if(parentPage.length() == 0) return null; currentPage = m_engine.getPage( parentPage ); } // If the page cannot be determined, we cannot possibly find the // attachments. if( currentPage == null || currentPage.getName().length() == 0 ) { return null; } // System.out.println("Seeking info on "+currentPage+"::"+attachmentname); return m_provider.getAttachmentInfo( currentPage, attachmentname, version ); } /** * Returns the list of attachments associated with a given wiki page. * If there are no attachments, returns an empty Collection. * * @param wikipage The wiki page from which you are seeking attachments for. * @return a valid collection of attachments. */ // FIXME: This API should be changed to return a List. public Collection listAttachments( WikiPage wikipage ) throws ProviderException { if( m_provider == null ) { return new ArrayList(); } Collection atts = m_provider.listAttachments( wikipage ); // This is just a sanity check; all of our providers return a Collection. if( atts instanceof List ) { Collections.sort( (List) atts ); } return atts; } /** * Returns true, if the page has any attachments at all. This is * a convinience method. * * * @param wikipage The wiki page from which you are seeking attachments for. * @return True, if the page has attachments, else false. */ public boolean hasAttachments( WikiPage wikipage ) { try { return listAttachments( wikipage ).size() > 0; } catch( Exception e ) {} return false; } /** * Finds an attachment from the repository as a stream. * * @param att Attachment * @return An InputStream to read from. May return null, if * attachments are disabled. */ public InputStream getAttachmentStream( Attachment att ) throws IOException, ProviderException { if( m_provider == null ) { return( null ); } return m_provider.getAttachmentData( att ); } /** * Stores an attachment that lives in the given file. * If the attachment did not exist previously, this method * will create it. If it did exist, it stores a new version. * * @param att Attachment to store this under. * @param source A file to read from. * * @throws IOException If writing the attachment failed. * @throws ProviderException If something else went wrong. */ public void storeAttachment( Attachment att, File source ) throws IOException, ProviderException { FileInputStream in = null; try { in = new FileInputStream( source ); storeAttachment( att, in ); } finally { if( in != null ) in.close(); } } /** * Stores an attachment directly from a stream. * If the attachment did not exist previously, this method * will create it. If it did exist, it stores a new version. * * @param att Attachment to store this under. * @param in InputStream from which the attachment contents will be read. * * @throws IOException If writing the attachment failed. * @throws ProviderException If something else went wrong. */ public void storeAttachment( Attachment att, InputStream in ) throws IOException, ProviderException { if( m_provider == null ) { return; } m_provider.putAttachmentData( att, in ); m_engine.getReferenceManager().updateReferences( att.getName(), new java.util.Vector() ); WikiPage parent = new WikiPage( m_engine, att.getParentName() ); m_engine.updateReferences( parent ); m_engine.getSearchManager().reindexPage( att ); } /** * Returns a list of versions of the attachment. * * @param attachmentName A fully qualified name of the attachment. * * @return A list of Attachments. May return null, if attachments are * disabled. * @throws ProviderException If the provider fails for some reason. */ public List getVersionHistory( String attachmentName ) throws ProviderException { if( m_provider == null ) { return( null ); } Attachment att = getAttachmentInfo( (WikiContext)null, attachmentName ); if( att != null ) { return m_provider.getVersionHistory( att ); } return null; } /** * Returns a collection of Attachments, containing each and every attachment * that is in this Wiki. * * @return A collection of attachments. If attachments are disabled, will * return an empty collection. */ public Collection getAllAttachments() throws ProviderException { if( attachmentsEnabled() ) { return m_provider.listAllChanged( new Date(0L) ); } return new ArrayList(); } /** * Returns the current attachment provider. * * @return The current provider. May be null, if attachments are disabled. */ public WikiAttachmentProvider getCurrentProvider() { return m_provider; } /** * Deletes the given attachment version. */ public void deleteVersion( Attachment att ) throws ProviderException { m_provider.deleteVersion( att ); } /** * Deletes all versions of the given attachment. */ // FIXME: Should also use events! public void deleteAttachment( Attachment att ) throws ProviderException { m_provider.deleteAttachment( att ); m_engine.getSearchManager().pageRemoved( att ); m_engine.getReferenceManager().clearPageEntries( att.getName() ); } }
package com.example.basiccameraapp; import android.graphics.Bitmap; import android.util.Log; public class BlurArtifactInducer extends ArtifactInducer { private static String TAG = BlurArtifactInducer.class.getName(); @Override public Bitmap induceArtifacts(Bitmap image, float artifactIntensity) { // offset map artifactIntensity to be bwn 0.8, 1 float scale = 1.001f - (artifactIntensity*0.2f + 0.8f); int scaledHeight = (int) (image.getHeight() * scale); scaledHeight = scaledHeight == 0 ? 1 : scaledHeight; int scaledWidth = (int) (image.getWidth() * scale); scaledWidth = scaledWidth == 0 ? 1 : scaledWidth; Log.d(TAG, "H: " + image.getHeight() + ", W: " + image.getWidth()); Log.d(TAG, "Scaled H: " + scaledHeight + ", W: " + scaledWidth); return Bitmap.createScaledBitmap( Bitmap.createScaledBitmap(image, scaledHeight, scaledWidth, true), image.getWidth(), image.getHeight(), true); } }
package com.github.pkunk.progressquest.ui; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.AsyncTask; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.widget.TextView; import com.github.pkunk.progressquest.R; import com.github.pkunk.progressquest.gameplay.Equips; import com.github.pkunk.progressquest.gameplay.Player; import com.github.pkunk.progressquest.gameplay.Stats; import com.github.pkunk.progressquest.gameplay.Traits; import com.github.pkunk.progressquest.service.GameplayService; import com.github.pkunk.progressquest.service.GameplayService.GameplayBinder; import com.github.pkunk.progressquest.service.GameplayServiceListener; import com.github.pkunk.progressquest.util.PqUtils; import com.github.pkunk.progressquest.util.Roman; import java.util.Map; public class TestActivity extends Activity implements GameplayServiceListener { private static final String TAG = TestActivity.class.getCanonicalName(); private GameplayService service; private volatile boolean isBound = false; private TaskBarUpdater taskBarUpdater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); } @Override protected void onStart() { super.onStart(); // Bind to GameplayService Intent intent = new Intent(this, GameplayService.class); startService(intent); //todo: remove to let service die bindService(intent, connection, Context.BIND_AUTO_CREATE); taskBarUpdater = new TaskBarUpdater(); taskBarUpdater.execute(); } @Override protected void onStop() { super.onStop(); taskBarUpdater.cancel(true); // Unbind from the service if (isBound) { TestActivity.this.service.removeGameplayListener(TestActivity.this); unbindService(connection); isBound = false; } } @Override public void onGameplay() { if (isBound) { // Call a method from the GameplayService. // However, if this call were something that might hang, then this request should // occur in a separate thread to avoid slowing down the activity performance. Player player = service.getPlayer(); // Toast.makeText(this, player.getCurrentTask(), Toast.LENGTH_LONG).show(); updateUi(player); } } private void updateUi(Player player) { this.runOnUiThread(new UiUpdater(player)); } private static Player createPlayer() { Traits traits = new Traits("Tester", "Gremlin", "Dancer"); Stats stats = new Stats(new int[]{10,11,12,13,14,15,80,60}); Player player = Player.newPlayer(traits, stats); return player; } /** Defines callbacks for service binding, passed to bindService() */ private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { Log.d(TAG, "onServiceConnected"); // We've bound to GameplayService, cast the IBinder and get GameplayService instance GameplayBinder binder = (GameplayBinder) service; TestActivity.this.service = binder.getService(); isBound = true; TestActivity.this.service.addGameplayListener(TestActivity.this); Player player = TestActivity.this.service.getPlayer(); if (player == null) { TestActivity.this.service.setPlayer(createPlayer()); player = TestActivity.this.service.getPlayer(); } if (player != null) { updateUi(player); } } @Override public void onServiceDisconnected(ComponentName arg0) { Log.d(TAG, "onServiceDisconnected"); isBound = false; } }; private class TaskBarUpdater extends AsyncTask { @Override protected Object doInBackground(Object... params) { while (!isCancelled()) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } publishProgress(); } return null; } @Override protected void onProgressUpdate(Object... values) { TextProgressBar taskBar = (TextProgressBar) findViewById(R.id.taskBar); taskBar.incrementProgressBy(100); taskBar.setText((taskBar.getProgress()*100/taskBar.getMax()) + "%"); } } private class UiUpdater implements Runnable { private final Player player; public UiUpdater(Player player) { this.player = player; } @Override public void run() { // Task updateTask(); updateTaskBar(); // Character updateTraits(); updateStats(); updateLevelBar(); // Spells updateSpellBook(); // Inventory updateEquipment(); updateInventory(); updateEncumbranceBar(); // Plot updatePlot(); updatePlotBar(); // Quest updateQuests(); updateQuestsBar(); } private void updateTask() { TextView taskView = (TextView) findViewById(R.id.task); taskView.setText(player.getCurrentTask()); } private void updateTaskBar() { TextProgressBar taskBar = (TextProgressBar) findViewById(R.id.taskBar); int max = player.getCurrentTaskTime(); taskBar.setMax(max); taskBar.setProgress(0); taskBar.setText("0%"); } private void updateTraits() { StringBuilder builder = new StringBuilder(); builder.append("Trait").append("\n"); builder.append("Name").append("\t\t\t").append(player.getTraits().getName()).append("\n"); builder.append("Race").append("\t\t\t").append(player.getTraits().getRace()).append("\n"); builder.append("Class").append("\t\t\t").append(player.getTraits().getRole()).append("\n"); builder.append("Level").append("\t\t\t").append(player.getTraits().getLevel()).append("\n"); TextView traitsView = (TextView) findViewById(R.id.traits); traitsView.setText(builder); } private void updateStats() { StringBuilder builder = new StringBuilder(); builder.append("Stat").append("\n"); for (int i=0; i<Stats.STATS_NUM; i++) { builder.append(Stats.label[i]).append("\t\t\t").append(player.getStats().get(i)).append("\n"); } TextView statsView = (TextView) findViewById(R.id.stats); statsView.setText(builder); } private void updateLevelBar() { TextProgressBar levelBar = (TextProgressBar) findViewById(R.id.levelBar); int current = player.getCurrentExp(); int max = player.getMaxExp(); int remaining = max - current; levelBar.setMax(max); levelBar.setProgress(current); levelBar.setText(remaining + " XP needed for next level"); } private void updateSpellBook() { StringBuilder builder = new StringBuilder(); builder.append("Spell").append("\n"); for (Map.Entry<String,Roman> spell : player.getSpellBook().entrySet()) { builder.append(spell.getKey()).append("\t\t\t").append(spell.getValue().getRoman()).append("\n"); } TextView spellbookView = (TextView) findViewById(R.id.spellbook); spellbookView.setText(builder); } private void updateEquipment() { StringBuilder builder = new StringBuilder(); for (int i=0; i< Equips.EQUIP_NUM; i++) { builder.append(Equips.label[i]).append("\t\t\t").append(player.getEquip().get(i)).append("\n"); } TextView equipmentView = (TextView) findViewById(R.id.equipment); equipmentView.setText(builder); } private void updateInventory() { StringBuilder builder = new StringBuilder(); builder.append("Item").append("\n"); for (Map.Entry<String,Integer> spell : player.getInventory().entrySet()) { builder.append(spell.getKey()).append("\t\t\t").append(spell.getValue()).append("\n"); } TextView inventoryView = (TextView) findViewById(R.id.inventory); inventoryView.setText(builder); } private void updateEncumbranceBar() { TextProgressBar encumbranceBar = (TextProgressBar) findViewById(R.id.encumbranceBar); int current = player.getCurrentEncumbrance(); int max = player.getMaxEncumbrance(); encumbranceBar.setMax(max); encumbranceBar.setProgress(current); StringBuilder builder = new StringBuilder(); builder.append(current).append("/").append(max).append(" cubits"); encumbranceBar.setText(builder.toString()); } private void updatePlot() { StringBuilder builder = new StringBuilder(); for (String plot : player.getPlot()) { builder.append(plot).append("\n"); } TextView plotView = (TextView) findViewById(R.id.plot); plotView.setText(builder); } private void updatePlotBar() { TextProgressBar plotBar = (TextProgressBar) findViewById(R.id.plotBar); int current = player.getCurrentPlotProgress(); int max = player.getMaxPlotProgress(); int remaining = max - current; plotBar.setMax(max); plotBar.setProgress(current); plotBar.setText(PqUtils.roughTime(remaining) + " remaining"); } private void updateQuests() { StringBuilder builder = new StringBuilder(); for (String quest : player.getQuests()) { builder.append(quest).append("\n"); } TextView questsView = (TextView) findViewById(R.id.quests); questsView.setText(builder); } private void updateQuestsBar() { TextProgressBar plotBar = (TextProgressBar) findViewById(R.id.questsBar); int current = player.getCurrentQuestProgress(); int max = player.getMaxQuestProgress(); plotBar.setMax(max); plotBar.setProgress(current); StringBuilder builder = new StringBuilder(); builder.append(current*100/max).append("% complete"); plotBar.setText(builder.toString()); } } }
package se.sics.cooja.plugins; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.NumberFormat; import java.util.*; import javax.swing.*; import javax.swing.event.*; import org.apache.log4j.Logger; import se.sics.cooja.*; /** * The Control Panel is a simple control panel for simulations. * * @author Fredrik Osterlind */ @ClassDescription("Control Panel") @PluginType(PluginType.SIM_STANDARD_PLUGIN) public class SimControl extends VisPlugin { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(SimControl.class); private Simulation simulation; private static final int SLIDE_MAX = 921; // e^9.21 => ~10000 private static final int TIME_MAX = 10000; private JSlider sliderDelay; private JLabel simulationTime, delayLabel; private JButton startButton, stopButton; private JFormattedTextField stopTimeTextField; private int simulationStopTime = -1; private Observer simObserver; private Observer tickObserver; private long lastTextUpdateTime = -1; /** * Create a new simulation control panel. * * @param simulationToControl Simulation to control */ public SimControl(Simulation simulationToControl, GUI gui) { super("Control Panel - " + simulationToControl.getTitle(), gui); simulation = simulationToControl; JButton button; JPanel smallPanel; // Register as tickobserver simulation.addTickObserver(tickObserver = new Observer() { public void update(Observable obs, Object obj) { if (simulation == null || simulationTime == null) return; // During simulation running, only update text 10 times each second if (lastTextUpdateTime < System.currentTimeMillis() - 100) { lastTextUpdateTime = System.currentTimeMillis(); simulationTime.setText("Current simulation time: " + simulation.getSimulationTime()); } if (simulationStopTime > 0 && simulationStopTime <= simulation.getSimulationTime() && simulation.isRunning()) { // Time to stop simulation now simulation.stopSimulation(); simulationStopTime = -1; } } }); // Register as simulation observer simulation.addObserver(simObserver = new Observer() { public void update(Observable obs, Object obj) { if (simulation.isRunning()) { startButton.setEnabled(false); stopButton.setEnabled(true); } else { startButton.setEnabled(true); stopButton.setEnabled(false); simulationStopTime = -1; } sliderDelay.setValue(convertTimeToSlide(simulation.getDelayTime())); simulationTime.setText("Current simulation time: " + simulation.getSimulationTime()); } }); // Main panel JPanel controlPanel = new JPanel(); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS)); getContentPane().add(controlPanel, BorderLayout.NORTH); // Add control buttons smallPanel = new JPanel(); smallPanel.setLayout(new BoxLayout(smallPanel, BoxLayout.X_AXIS)); smallPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); button = new JButton("Start"); button.setActionCommand("start"); button.addActionListener(myEventHandler); startButton = button; smallPanel.add(button); button = new JButton("Stop"); button.setActionCommand("stop"); button.addActionListener(myEventHandler); stopButton = button; smallPanel.add(button); button = new JButton("Tick all motes once"); button.setActionCommand("tickall"); button.addActionListener(myEventHandler); smallPanel.add(button); smallPanel.setAlignmentX(Component.LEFT_ALIGNMENT); controlPanel.add(smallPanel); smallPanel = new JPanel(); smallPanel.setLayout(new BoxLayout(smallPanel, BoxLayout.X_AXIS)); smallPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 10, 5)); button = new JButton("Run until"); button.setActionCommand("rununtil"); button.addActionListener(myEventHandler); smallPanel.add(button); smallPanel.add(Box.createHorizontalStrut(10)); NumberFormat integerFormat = NumberFormat.getIntegerInstance(); stopTimeTextField = new JFormattedTextField(integerFormat); stopTimeTextField.setValue(simulation.getSimulationTime()); stopTimeTextField.addPropertyChangeListener("value", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { JFormattedTextField numberTextField = (JFormattedTextField) e.getSource(); int untilTime = ((Number) numberTextField.getValue()).intValue(); if (untilTime < simulation.getSimulationTime()) { numberTextField.setValue(new Integer(simulation.getSimulationTime() + simulation.getTickTime())); } } }); smallPanel.add(stopTimeTextField); smallPanel.setAlignmentX(Component.LEFT_ALIGNMENT); controlPanel.add(smallPanel); // Add delay slider smallPanel = new JPanel(); smallPanel.setLayout(new BoxLayout(smallPanel, BoxLayout.Y_AXIS)); smallPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); simulationTime = new JLabel(); simulationTime.setText("Current simulation time: " + simulation.getSimulationTime()); smallPanel.add(simulationTime); smallPanel.add(Box.createRigidArea(new Dimension(0, 10))); delayLabel = new JLabel(); if (simulation.getDelayTime() > 0) { delayLabel.setText("Delay between tick loops: " + simulation.getDelayTime() + " ms"); } else { delayLabel.setText("Zero simulation delay"); } smallPanel.add(delayLabel); JSlider slider; slider = new JSlider(JSlider.HORIZONTAL, 0, SLIDE_MAX, convertTimeToSlide(simulation.getDelayTime())); slider.addChangeListener(myEventHandler); Hashtable labelTable = new Hashtable(); for (int i=0; i < 100; i += 5) { labelTable.put(new Integer(convertTimeToSlide(i)), new JLabel(".")); } for (int i=200; i < 10000; i += 100) { labelTable.put(new Integer(convertTimeToSlide(i)), new JLabel(":")); } slider.setLabelTable(labelTable); slider.setPaintLabels(true); sliderDelay = slider; smallPanel.add(slider); controlPanel.add(smallPanel); pack(); try { setSelected(true); } catch (java.beans.PropertyVetoException e) { // Could not select } } private int convertSlideToTime(int slide) { if (slide == SLIDE_MAX) return TIME_MAX; return (int) Math.round(Math.exp((double)slide/100.0) - 1.0); } private int convertTimeToSlide(int time) { if (time == TIME_MAX) return SLIDE_MAX; return (int) Math.round((Math.log(time + 1)*100.0)); } private class MyEventHandler implements ActionListener, ChangeListener { public void stateChanged(ChangeEvent e) { if (e.getSource() == sliderDelay) { simulation.setDelayTime(convertSlideToTime(sliderDelay.getValue())); if (simulation.getDelayTime() > 0) { delayLabel.setText("Delay between tick loops: " + simulation.getDelayTime() + " ms"); } else { delayLabel.setText("No simulation delay"); } } else logger.debug("Unhandled state change: " + e); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("start")) { simulationStopTime = -1; // Reset until time simulation.startSimulation(); } else if (e.getActionCommand().equals("stop")) { simulationStopTime = -1; // Reset until time if (simulation.isRunning()) simulation.stopSimulation(); } else if (e.getActionCommand().equals("tickall")) { simulationStopTime = -1; // Reset until time simulation.tickSimulation(); } else if (e.getActionCommand().equals("rununtil")) { // Set new stop time simulationStopTime = ((Number) stopTimeTextField.getValue()).intValue(); if (simulationStopTime > simulation.getSimulationTime() && !simulation.isRunning()) { simulation.startSimulation(); } else { if (simulation.isRunning()) simulation.stopSimulation(); simulationStopTime = -1; } } else logger.debug("Unhandled action: " + e.getActionCommand()); } } MyEventHandler myEventHandler = new MyEventHandler(); public void closePlugin() { // Remove log observer from all log interfaces if (simObserver != null) simulation.deleteObserver(simObserver); if (tickObserver != null) simulation.deleteTickObserver(tickObserver); } }
package com.fsck.k9; import java.io.File; import android.app.Application; import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.util.Config; import android.util.Log; import com.fsck.k9.activity.MessageCompose; import com.fsck.k9.mail.internet.BinaryTempFileBody; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.service.BootReceiver; import com.fsck.k9.service.MailService; public class k9 extends Application { public static final String LOG_TAG = "k9"; public static File tempDirectory; /** * If this is enabled there will be additional logging information sent to * Log.d, including protocol dumps. */ public static boolean DEBUG = false; /** * If this is enabled than logging that normally hides sensitive information * like passwords will show that information. */ public static boolean DEBUG_SENSITIVE = false; /** * The MIME type(s) of attachments we're willing to send. At the moment it is not possible * to open a chooser with a list of filter types, so the chooser is only opened with the first * item in the list. The entire list will be used to filter down attachments that are added * with Intent.ACTION_SEND. */ public static final String[] ACCEPTABLE_ATTACHMENT_SEND_TYPES = new String[] { /** * The MIME type(s) of attachments we're willing to view. */ public static final String[] ACCEPTABLE_ATTACHMENT_VIEW_TYPES = new String[] { /** * The MIME type(s) of attachments we're not willing to view. */ public static final String[] UNACCEPTABLE_ATTACHMENT_VIEW_TYPES = new String[] { "image/gif", }; /** * The MIME type(s) of attachments we're willing to download to SD. */ public static final String[] ACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES = new String[] { "*/*", }; /** * The MIME type(s) of attachments we're not willing to download to SD. */ public static final String[] UNACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES = new String[] { }; /** * The special name "INBOX" is used throughout the application to mean "Whatever folder * the server refers to as the user's Inbox. Placed here to ease use. */ public static final String INBOX = "INBOX"; /** * Specifies how many messages will be shown in a folder by default. This number is set * on each new folder and can be incremented with "Load more messages..." by the * VISIBLE_LIMIT_INCREMENT */ public static final int DEFAULT_VISIBLE_LIMIT = 25; /** * Number of additional messages to load when a user selectes "Load more messages..." */ public static final int VISIBLE_LIMIT_INCREMENT = 25; /** * The maximum size of an attachment we're willing to download (either View or Save) * Attachments that are base64 encoded (most) will be about 1.375x their actual size * so we should probably factor that in. A 5MB attachment will generally be around * 6.8MB downloaded but only 5MB saved. */ public static final int MAX_ATTACHMENT_DOWNLOAD_SIZE = (5 * 1024 * 1024); /** * Called throughout the application when the number of accounts has changed. This method * enables or disables the Compose activity, the boot receiver and the service based on * whether any accounts are configured. */ public static void setServicesEnabled(Context context) { setServicesEnabled(context, Preferences.getPreferences(context).getAccounts().length > 0); } public static void setServicesEnabled(Context context, boolean enabled) { PackageManager pm = context.getPackageManager(); if (!enabled && pm.getComponentEnabledSetting(new ComponentName(context, MailService.class)) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { /* * If no accounts now exist but the service is still enabled we're about to disable it * so we'll reschedule to kill off any existing alarms. */ MailService.actionReschedule(context); } pm.setComponentEnabledSetting( new ComponentName(context, MessageCompose.class), enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); pm.setComponentEnabledSetting( new ComponentName(context, BootReceiver.class), enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); pm.setComponentEnabledSetting( new ComponentName(context, MailService.class), enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); if (enabled && pm.getComponentEnabledSetting(new ComponentName(context, MailService.class)) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { /* * And now if accounts do exist then we've just enabled the service and we want to * schedule alarms for the new accounts. */ MailService.actionReschedule(context); } } @Override public void onCreate() { super.onCreate(); Preferences prefs = Preferences.getPreferences(this); DEBUG = prefs.geteEnableDebugLogging(); DEBUG_SENSITIVE = prefs.getEnableSensitiveLogging(); MessagingController.getInstance(this).resetVisibleLimits(prefs.getAccounts()); /* * We have to give MimeMessage a temp directory because File.createTempFile(String, String) * doesn't work in Android and MimeMessage does not have access to a Context. */ BinaryTempFileBody.setTempDirectory(getCacheDir()); /* * Enable background sync of messages */ setServicesEnabled(this); } }
package org.epics.graphene; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.Line2D; import java.util.Arrays; import java.util.List; import org.epics.util.array.ArrayDouble; import org.epics.util.array.ListDouble; import org.epics.util.array.ListInt; import org.epics.util.array.ListNumber; /** * * @author carcassi */ public abstract class Graph2DRenderer<T extends Graph2DRendererUpdate> { protected double xPlotValueStart; protected double yPlotValueStart; protected double xPlotValueEnd; protected double yPlotValueEnd; protected int areaHeight; protected int areaWidth; protected double xPlotCoordStart; protected double yPlotCoordStart; protected double yPlotCoordEnd; protected double xPlotCoordEnd; protected int xAreaStart; protected int yAreaStart; protected int yAreaEnd; protected int xAreaEnd; public Graph2DRenderer(int imageWidth, int imageHeight) { this.imageWidth = imageWidth; this.imageHeight = imageHeight; } public int getImageHeight() { return imageHeight; } public int getImageWidth() { return imageWidth; } protected Graphics2D g; // Renderer external parameter // // Size of the image private int imageWidth; private int imageHeight; // Strategy for calculating the axis range private AxisRange xAxisRange = AxisRanges.integrated(); private AxisRange yAxisRange = AxisRanges.integrated(); // Colors and fonts protected Color backgroundColor = Color.WHITE; protected Color labelColor = Color.BLACK; protected Color referenceLineColor = new Color(240, 240, 240); protected Font labelFont = FontUtil.getLiberationSansRegular(); // Image margins protected int bottomMargin = 2; protected int topMargin = 2; protected int leftMargin = 2; protected int rightMargin = 2; // area margins protected int bottomAreaMargin = 0; protected int topAreaMargin = 0; protected int leftAreaMargin = 0; protected int rightAreaMargin = 0; // Axis label margins protected int xLabelMargin = 3; protected int yLabelMargin = 3; // Computed parameters, visible to outside // private Range xAggregatedRange; private Range yAggregatedRange; private Range xPlotRange; private Range yPlotRange; protected FontMetrics labelFontMetrics; protected ListDouble xReferenceCoords; protected ListDouble xReferenceValues; protected List<String> xReferenceLabels; protected ListDouble yReferenceCoords; protected ListDouble yReferenceValues; protected List<String> yReferenceLabels; protected Range xCoordRange; protected Range yCoordRange; private int xLabelMaxHeight; private int yLabelMaxWidth; public AxisRange getXAxisRange() { return xAxisRange; } public AxisRange getYAxisRange() { return yAxisRange; } public Range getXAggregatedRange() { return xAggregatedRange; } public Range getYAggregatedRange() { return yAggregatedRange; } public Range getXPlotRange() { return xPlotRange; } public Range getYPlotRange() { return yPlotRange; } public void update(T update) { if (update.getImageHeight() != null) { imageHeight = update.getImageHeight(); } if (update.getImageWidth() != null) { imageWidth = update.getImageWidth(); } if (update.getXAxisRange() != null) { xAxisRange = update.getXAxisRange(); } if (update.getYAxisRange() != null) { yAxisRange = update.getYAxisRange(); } } static Range aggregateRange(Range dataRange, Range aggregatedRange) { if (aggregatedRange == null) { return dataRange; } else { return RangeUtil.sum(dataRange, aggregatedRange); } } public abstract T newUpdate(); protected void calculateRanges(Range xDataRange, Range yDataRange) { xAggregatedRange = aggregateRange(xDataRange, xAggregatedRange); yAggregatedRange = aggregateRange(yDataRange, yAggregatedRange); xPlotRange = xAxisRange.axisRange(xDataRange, xAggregatedRange); yPlotRange = yAxisRange.axisRange(yDataRange, yAggregatedRange); } protected void drawHorizontalReferenceLines() { g.setColor(referenceLineColor); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); ListNumber yTicks = yReferenceCoords; for (int i = 0; i < yTicks.size(); i++) { Shape line = new Line2D.Double(xAreaStart, yTicks.getDouble(i), xAreaEnd, yTicks.getDouble(i)); g.draw(line); } } protected void drawVerticalReferenceLines() { g.setColor(referenceLineColor); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); ListNumber xTicks = xReferenceCoords; for (int i = 0; i < xTicks.size(); i++) { Shape line = new Line2D.Double(xTicks.getDouble(i), yAreaStart, xTicks.getDouble(i), yAreaEnd); g.draw(line); } } protected void calculateGraphArea() { ValueAxis xAxis = ValueAxis.createAutoAxis(xPlotRange.getMinimum().doubleValue(), xPlotRange.getMaximum().doubleValue(), Math.max(2, getImageWidth() / 60)); ValueAxis yAxis = ValueAxis.createAutoAxis(yPlotRange.getMinimum().doubleValue(), yPlotRange.getMaximum().doubleValue(), Math.max(2, getImageHeight() / 60)); xReferenceLabels = Arrays.asList(xAxis.getTickLabels()); yReferenceLabels = Arrays.asList(yAxis.getTickLabels()); xReferenceValues = new ArrayDouble(xAxis.getTickValues()); yReferenceValues = new ArrayDouble(yAxis.getTickValues()); labelFontMetrics = g.getFontMetrics(labelFont); // Compute x axis spacing xLabelMaxHeight = labelFontMetrics.getHeight() - labelFontMetrics.getLeading(); int areaFromBottom = bottomMargin + xLabelMaxHeight + xLabelMargin; // Compute y axis spacing int[] yLabelWidths = new int[yReferenceLabels.size()]; yLabelMaxWidth = 0; for (int i = 0; i < yLabelWidths.length; i++) { yLabelWidths[i] = labelFontMetrics.stringWidth(yReferenceLabels.get(i)); yLabelMaxWidth = Math.max(yLabelMaxWidth, yLabelWidths[i]); } int areaFromLeft = leftMargin + yLabelMaxWidth + yLabelMargin; xCoordRange = RangeUtil.range(areaFromLeft + 0.5, getImageWidth() - rightMargin - 0.5); yCoordRange = RangeUtil.range(topMargin + 0.5, getImageHeight() - areaFromBottom - 0.5); xPlotValueStart = getXPlotRange().getMinimum().doubleValue(); yPlotValueStart = getYPlotRange().getMinimum().doubleValue(); xPlotValueEnd = getXPlotRange().getMaximum().doubleValue(); yPlotValueEnd = getYPlotRange().getMaximum().doubleValue(); areaWidth = (int) (xCoordRange.getMaximum().doubleValue() - xCoordRange.getMinimum().doubleValue()); areaHeight = (int) (yCoordRange.getMaximum().doubleValue() - yCoordRange.getMinimum().doubleValue()); xAreaStart = areaFromLeft; yAreaStart = topMargin; xAreaEnd = getImageWidth() - rightMargin - 1; yAreaEnd = getImageHeight() - areaFromBottom - 1; xPlotCoordStart = xAreaStart + topAreaMargin + 0.5; yPlotCoordStart = yAreaStart + leftAreaMargin + 0.5; xPlotCoordEnd = xAreaEnd - bottomAreaMargin + 0.5; yPlotCoordEnd = yAreaEnd - rightAreaMargin + 0.5; double[] xRefCoords = new double[xReferenceValues.size()]; for (int i = 0; i < xRefCoords.length; i++) { xRefCoords[i] = scaledX(xReferenceValues.getDouble(i)); } xReferenceCoords = new ArrayDouble(xRefCoords); double[] yRefCoords = new double[yReferenceValues.size()]; for (int i = 0; i < yRefCoords.length; i++) { yRefCoords[i] = scaledY(yReferenceValues.getDouble(i)); } yReferenceCoords = new ArrayDouble(yRefCoords); } protected void drawBackground() { g.setColor(backgroundColor); g.fillRect(0, 0, getImageWidth(), getImageHeight()); } protected void drawGraphArea() { drawBackground(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // When drawing the reference line, align them to the pixel drawVerticalReferenceLines(); drawHorizontalReferenceLines();; drawYLabels(); drawXLabels(); } private static final int MIN = 0; private static final int MAX = 1; private static void drawHorizontalReferencesLabel(Graphics2D graphics, FontMetrics metrics, String text, int yCenter, int[] drawRange, int xRight, boolean updateMin, boolean centeredOnly) { // If the center is not in the range, don't draw anything if (drawRange[MAX] < yCenter || drawRange[MIN] > yCenter) return; // If there is no space, don't draw anything if (drawRange[MAX] - drawRange[MIN] < metrics.getHeight()) return; Java2DStringUtilities.Alignment alignment = Java2DStringUtilities.Alignment.RIGHT; int targetY = yCenter; int halfHeight = metrics.getAscent() / 2; if (yCenter < drawRange[MIN] + halfHeight) { // Can't be drawn in the center if (centeredOnly) return; alignment = Java2DStringUtilities.Alignment.TOP_RIGHT; targetY = drawRange[MIN]; } else if (yCenter > drawRange[MAX] - halfHeight) { // Can't be drawn in the center if (centeredOnly) return; alignment = Java2DStringUtilities.Alignment.BOTTOM_RIGHT; targetY = drawRange[MAX]; } Java2DStringUtilities.drawString(graphics, alignment, xRight, targetY, text); if (updateMin) { drawRange[MAX] = targetY - metrics.getHeight(); } else { drawRange[MIN] = targetY + metrics.getHeight(); } } private static void drawVerticalReferenceLabel(Graphics2D graphics, FontMetrics metrics, String text, int xCenter, int[] drawRange, int yTop, boolean updateMin, boolean centeredOnly) { // If the center is not in the range, don't draw anything if (drawRange[MAX] < xCenter || drawRange[MIN] > xCenter) return; // If there is no space, don't draw anything if (drawRange[MAX] - drawRange[MIN] < metrics.getHeight()) return; Java2DStringUtilities.Alignment alignment = Java2DStringUtilities.Alignment.TOP; int targetX = xCenter; int halfWidth = metrics.stringWidth(text) / 2; if (xCenter < drawRange[MIN] + halfWidth) { // Can't be drawn in the center if (centeredOnly) return; alignment = Java2DStringUtilities.Alignment.TOP_LEFT; targetX = drawRange[MIN]; } else if (xCenter > drawRange[MAX] - halfWidth) { // Can't be drawn in the center if (centeredOnly) return; alignment = Java2DStringUtilities.Alignment.TOP_RIGHT; targetX = drawRange[MAX]; } Java2DStringUtilities.drawString(graphics, alignment, targetX, yTop, text); if (updateMin) { drawRange[MIN] = targetX + metrics.getHeight(); } else { drawRange[MAX] = targetX - metrics.getHeight(); } } protected final double scaledX(double value) { return xPlotCoordStart + NumberUtil.scale(value, xPlotValueStart, xPlotValueEnd, areaWidth); } protected final double scaledY(double value) { return yPlotCoordEnd - NumberUtil.scale(value, yPlotValueStart, yPlotValueEnd, areaHeight); } protected void setClip(Graphics2D g) { g.setClip(xAreaStart, yAreaStart, xAreaEnd - xAreaStart + 1, yAreaEnd - yAreaStart + 1); } protected void drawYLabels() { // Draw Y labels ListNumber yTicks = yReferenceCoords; if (yReferenceLabels != null && !yReferenceLabels.isEmpty()) { //g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g.setColor(labelColor); g.setFont(labelFont); FontMetrics metrics = g.getFontMetrics(); // Draw first and last label int[] drawRange = new int[] {(int) yCoordRange.getMinimum().intValue(), (int) yCoordRange.getMaximum().intValue()}; int xRightLabel = (int) (xCoordRange.getMinimum().doubleValue() - yLabelMargin - 1); drawHorizontalReferencesLabel(g, metrics, yReferenceLabels.get(0), (int) Math.floor(yTicks.getDouble(0)), drawRange, xRightLabel, true, false); drawHorizontalReferencesLabel(g, metrics, yReferenceLabels.get(yReferenceLabels.size() - 1), (int) Math.floor(yTicks.getDouble(yReferenceLabels.size() - 1)), drawRange, xRightLabel, false, false); for (int i = 1; i < yReferenceLabels.size() - 1; i++) { drawHorizontalReferencesLabel(g, metrics, yReferenceLabels.get(i), (int) Math.floor(yTicks.getDouble(i)), drawRange, xRightLabel, true, false); } } } protected void drawXLabels() { // Draw X labels ListNumber xTicks = xReferenceCoords; if (xReferenceLabels != null && !xReferenceLabels.isEmpty()) { //g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g.setColor(labelColor); g.setFont(labelFont); FontMetrics metrics = g.getFontMetrics(); // Draw first and last label int[] drawRange = new int[] {(int) xCoordRange.getMinimum().intValue(), (int) xCoordRange.getMaximum().intValue()}; int yTop = (int) (yCoordRange.getMaximum().doubleValue() + xLabelMargin + 1); drawVerticalReferenceLabel(g, metrics, xReferenceLabels.get(0), (int) Math.floor(xTicks.getDouble(0)), drawRange, yTop, true, false); drawVerticalReferenceLabel(g, metrics, xReferenceLabels.get(xReferenceLabels.size() - 1), (int) Math.floor(xTicks.getDouble(xReferenceLabels.size() - 1)), drawRange, yTop, false, false); for (int i = 1; i < xReferenceLabels.size() - 1; i++) { drawVerticalReferenceLabel(g, metrics, xReferenceLabels.get(i), (int) Math.floor(xTicks.getDouble(i)), drawRange, yTop, true, false); } } } }
import java.util.ArrayList; import java.util.Arrays; public class MancalaAI { int ply = 3; Tuple bad = new Tuple(Integer.MIN_VALUE, "i"); Tuple max = new Tuple(Integer.MAX_VALUE, "a"); int[] weights = { 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1 }; public MancalaAI(int[] gaValues) { weights = gaValues; } public MancalaAI() { } public String nextmove(int[] board) { return search(ply, board).move; } public String nextmove(int[] board, boolean flip) { return searchFlipped(ply, board).move; } public Tuple search(int ply, int[] mboard) { int alphaPrune = Integer.MIN_VALUE; // if on last layer then search for last ply and then evaluate if (ply - 1 == 0) { // set current best move to -inf Tuple bb = bad; // create instance of board for local search instance ArrayList<int[]> board = new ArrayList<int[]>(); if (this.isGameOver(mboard)) { return new Tuple(this.hueristic(mboard), "n"); } // search for max's move for (int j = 0; j <= 5; j++) { // find possible board states from starting move (accounts for // "free" moves) // find possible board outcomes of mins move aj // check if there are pieces in the position selected if (!this.invalid("b" + j, mboard)) { board = this.untilQuite(Arrays.copyOf(mboard, mboard.length), "b" + j); Tuple b = null; // System.out.println(board.size()); // run through all of mins move aj for (int[] curBoard : board) { // System.out.println("hi"); // calculate max's move b0 by finding all boards // possible // from b0 and taking the min and then creating a board // state from that // set min to +inf b = max; // run through all possible starting moves for (int i = 0; i <= 5; i++) { // if we have found a value less then the current // prune // then stop // if (b.value < alphaPrune) { // return b; // check if there are pieces in the position // selected if (!this.invalid("a" + i, curBoard)) { // else calculate next branch same as we did for b = Tuple.min(b, new Tuple(this.hueristic(this.min( this.untilQuite(Arrays.copyOf(curBoard, curBoard.length), "a" + i))), "a" + i)); } } // find the max of all the current min moves bb = Tuple.max(bb, b); bb.move = "b" + j; // if this max is less than the current prune then set // prune // to this new max // if (bb.value < alphaPrune) { // alphaPrune = bb.value; } } } // return best state move return bb; } else { Tuple bb = bad; ArrayList<int[]> aboards = new ArrayList<int[]>(); ArrayList<int[]> bboards = null; if (this.isGameOver(mboard)) { return new Tuple(this.hueristic(mboard), "n"); } for (int j = 0; j <= 5; j++) { if (!this.invalid("b" + j, mboard)) { // System.out.println("b"+j); aboards = this.untilQuite(Arrays.copyOf(mboard, mboard.length), "b" + j); Tuple b = max; boolean found = false; // System.out.println(aboards.size()); for (int[] curBoard : aboards) { if (!this.isGameOver(curBoard)) { if (!this.invalid("a0", curBoard)) { found = true; bboards = this.untilQuite(curBoard, "a0"); for (int[] bboard : bboards) { b = Tuple.min(b, search(ply - 1, Arrays.copyOf(bboard, bboard.length))); } } for (int i = 1; i <= 5; i++) { // if (b.value < alphaPrune) { // return b; if (!this.invalid("a" + i, curBoard)) { found = true; bboards = this.untilQuite(curBoard, "a" + i); for (int[] bboard : bboards) { b = Tuple.min(b, search(ply - 1, Arrays.copyOf(bboard, bboard.length))); } } } } else { b = new Tuple(this.hueristic(curBoard), "m"); found = true; // System.out.println(b.value); } if (found && b.value > bb.value) { bb = b; bb.move = "b" + j; } // bb = Tuple.max(bb, b); // if (bb.value < alphaPrune) { // alphaPrune = bb.value; } } } return bb; } } public Tuple searchFlipped(int ply, int[] mboard) { int alphaPrune = Integer.MIN_VALUE; // if on last layer then search for last ply and then evaluate if (ply - 1 == 0) { // set current best move to -inf Tuple bb = bad; // create instance of board for local search instance ArrayList<int[]> board = new ArrayList<int[]>(); if (this.isGameOver(mboard)) { return new Tuple(this.hueristic(mboard), "n"); } // search for max's move for (int j = 0; j <= 5; j++) { // find possible board states from starting move (accounts for // "free" moves) // find possible board outcomes of mins move aj // check if there are pieces in the position selected if (!this.invalid("a" + j, mboard)) { board = this.untilQuite(Arrays.copyOf(mboard, mboard.length), "a" + j); Tuple b = null; // System.out.println(board.size()); // run through all of mins move aj for (int[] curBoard : board) { // System.out.println("hi"); // calculate max's move b0 by finding all boards // possible // from b0 and taking the min and then creating a board // state from that // set min to +inf b = max; // run through all possible starting moves for (int i = 0; i <= 5; i++) { // if we have found a value less then the current // prune // then stop // if (b.value < alphaPrune) { // return b; // check if there are pieces in the position // selected if (!this.invalid("b" + i, curBoard)) { // else calculate next branch same as we did for b = Tuple.min(b, new Tuple(this.hueristic(this.min( this.untilQuite(Arrays.copyOf(curBoard, curBoard.length), "b" + i))), "b" + i)); } } // find the max of all the current min moves bb = Tuple.max(bb, b); bb.move = "a" + j; // if this max is less than the current prune then set // prune // to this new max // if (bb.value < alphaPrune) { // alphaPrune = bb.value; } } } // return best state move return bb; } else { Tuple bb = bad; ArrayList<int[]> aboards = new ArrayList<int[]>(); ArrayList<int[]> bboards = null; if (this.isGameOver(mboard)) { return new Tuple(this.hueristic(mboard), "n"); } for (int j = 0; j <= 5; j++) { if (!this.invalid("a" + j, mboard)) { // System.out.println("b"+j); aboards = this.untilQuite(Arrays.copyOf(mboard, mboard.length), "a" + j); Tuple b = max; boolean found = false; // System.out.println(aboards.size()); for (int[] curBoard : aboards) { if (!this.isGameOver(curBoard)) { if (!this.invalid("b0", curBoard)) { found = true; bboards = this.untilQuite(curBoard, "b0"); for (int[] bboard : bboards) { b = Tuple.min(b, search(ply - 1, Arrays.copyOf(bboard, bboard.length))); } } for (int i = 1; i <= 5; i++) { // if (b.value < alphaPrune) { // return b; if (!this.invalid("b" + i, curBoard)) { found = true; bboards = this.untilQuite(curBoard, "b" + i); for (int[] bboard : bboards) { b = Tuple.min(b, search(ply - 1, Arrays.copyOf(bboard, bboard.length))); } } } } else { b = new Tuple(this.hueristic(curBoard), "m"); found = true; // System.out.println(b.value); } if (found && b.value > bb.value) { bb = b; bb.move = "a" + j; } // bb = Tuple.max(bb, b); // if (bb.value < alphaPrune) { // alphaPrune = bb.value; } } } return bb; } } public int hueristic(int[] board) { // Mancala m = new Mancala(null); // System.out.println("board value: " + (board[13] - board[6])); // m.displayBoard(board); // System.out.println("\n\n\n"); if (board == null) { return Integer.MAX_VALUE; } if (isGameOver(board) && board[13] - board[6] > 0) return Integer.MIN_VALUE + 2; else if (this.isGameOver(board)) return Integer.MAX_VALUE - 1; int sum = 0; for (int i = 0; i < board.length; i++) { sum += (weights[i] * board[i]); } return sum; } public int hueristic2(int[] board) { // Mancala m = new Mancala(null); // System.out.println("board value: " + (board[13] - board[6])); // m.displayBoard(board); // System.out.println("\n\n\n"); if (board == null) { return Integer.MAX_VALUE; } if (isGameOver(board) && board[6] - board[13] > 0) return Integer.MIN_VALUE + 1; else if (this.isGameOver(board)) return Integer.MAX_VALUE - 1; int sum = 0; for (int i = 0; i < board.length; i++) { sum += (weights[i] * board[i]); } return sum; } private int[] min(ArrayList<int[]> boards) { if (boards.size() == 0) { return null; } int b = this.hueristic(boards.get(0)); int[] ba = boards.get(0); int nb; for (int[] bc : boards) { nb = this.hueristic(bc); if (nb < b) { b = nb; ba = bc; } } return ba; } private ArrayList<int[]> untilQuite(int[] board, String startMove) { // System.out.println(startMove); boolean playerTurn = false; Mancala m = new Mancala(null); String ab = startMove.substring(0, 1); ArrayList<int[]> inboards = new ArrayList<int[]>(); ArrayList<int[]> outboards = new ArrayList<int[]>(); playerTurn = makeMove(startMove, playerTurn, board); // m.displayBoard(board); if (playerTurn || this.isGameOver(board)) { outboards.add(board); } else { inboards.add(board); } int[] cur = null; int[] aBoard = null; while (inboards.size() > 0) { // System.out.println((inboards.size())); aBoard = inboards.get(0); inboards.remove(0); // m.displayBoard(inboards.get(0)); for (int i = 0; i <= 5; i++) { if (!this.invalid(ab + i, aBoard)) { playerTurn = false; cur = Arrays.copyOf(aBoard, aBoard.length); playerTurn = makeMove(ab + i, playerTurn, cur); if (playerTurn || this.isGameOver(cur)) { outboards.add(cur); } else { inboards.add(cur); // System.out.println("\n\n\nadd\t" + ab + i); // m.displayBoard(aBoard); // m.displayBoard(cur); } } } } return outboards; } private boolean makeMove(String move, boolean playerTurn, int[] board) { int piecesInHand; int pos; if (move.charAt(0) == 'a') { piecesInHand = board[Math.abs((move.charAt(1) - '0') - 5)]; pos = Math.abs((move.charAt(1) - '0') - 5); board[Math.abs((move.charAt(1) - '0') - 5)] = 0; } else { piecesInHand = board[(move.charAt(1) - '0') + 7]; pos = (move.charAt(1) - '0') + 7; board[(move.charAt(1) - '0') + 7] = 0; } while (piecesInHand > 0) { pos = (pos + 1) % board.length; board[pos]++; piecesInHand } if ((pos == 6 && move.charAt(0) == 'a') || (pos == 13 && move.charAt(0) == 'b')) return playerTurn; return !playerTurn; } private boolean invalid(String input, int[] board) { boolean inrange = input.matches("[a-b][0-5]"); if (!inrange) return true; if (input.charAt(0) == 'b' && board[(input.charAt(1) - '0') + 7] == 0) return true; if (input.charAt(0) == 'a' && board[Math.abs((input.charAt(1) - '0') - 5)] == 0) return true; return false; } private boolean isGameOver(int[] board) { return (sumOfSubArray(board, 0, 6) == 0 || sumOfSubArray(board, 7, 13) == 0); } private int sumOfSubArray(int[] board, int start, int end) { int count = 0; for (int i = start; i < end; i++) count += board[i]; return count; } }
package com.netzarchitekten.tools; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.LocaleList; import android.util.DisplayMetrics; import java.util.Locale; /** * Encapsulates deprecation warning for * <ul> * <li>{@link android.content.res.Resources#getColor(int)} since Marshmallow (API 23)</li> * <li>{@link android.content.res.Resources#getDrawable(int)} since Lollipop MR1 (API 22)</li> * <li>{@link android.content.res.Configuration#locale} since N (API 24)</li> * </ul> * <p> * Contains a static and an OO interface. * </p> * * @author Benjamin Erhart {@literal <berhart@netzarchitekten.com>} */ public class Resources { private final android.content.res.Resources mResources; /** * @param context * A context object to access the * {@link android.content.res.Resources} of the app. */ public Resources(Context context) { mResources = context.getResources(); } /** * Honor deprecation of {@link android.content.res.Resources#getColor(int)} * since API 23. * * @param id * The desired resource identifier, as generated by the aapt * tool. This integer encodes the package, type, and resource * entry. The value 0 is an invalid identifier. * @return a single color value in the form 0xAARRGGBB. * @see android.content.res.Resources#getColor(int, android.content.res.Resources.Theme) */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public int getColor(int id) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) return mResources.getColor(id, null); return mResources.getColor(id); } /** * Honor deprecation of * {@link android.content.res.Resources#getDrawable(int)} since API 22. * * @param id * The desired resource identifier, as generated by the aapt * tool. This integer encodes the package, type, and resource * entry. The value 0 is an invalid identifier. * @return an object that can be used to draw this resource. */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public Drawable getDrawable(int id) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) return mResources.getDrawable(id, null); return mResources.getDrawable(id); } /** * Honor deprecation of {@link Configuration#locale} since API 24. * * @return the currently used primary locale. */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public Locale getPrimaryLocale() { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) return mResources.getConfiguration().getLocales().get(0); return mResources.getConfiguration().locale; } /** * <p> * Sets a new (and only) locale for this app until it is reset using {@link #resetLocale()}, * <b>as long</b>, as the primary locale isn't already the same. * </p> * <p> * Makes use of a side-effect of * {@link android.content.res.Resources#Resources(AssetManager, DisplayMetrics, Configuration)}, * which propagates the localization change. * </p> * * @param newLocale * The new {@link Locale}. * @return this object for fluency. */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public Resources setLocale(Locale newLocale) { if (!getPrimaryLocale().equals(newLocale)) { Configuration newConfig = new Configuration(mResources.getConfiguration()); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { newConfig.setLocales(new LocaleList(newLocale)); } else { newConfig.locale = newLocale; } new android.content.res.Resources(mResources.getAssets(), mResources.getDisplayMetrics(), newConfig); } return this; } /** * <p> * Sets a new (and only) locale for this app until it is reset using {@link #resetLocale()}. * </p> * <p> * Makes use of a side-effect of * {@link android.content.res.Resources#Resources(AssetManager, DisplayMetrics, Configuration)}, * which propagates the localization change. * </p> * * @param newLocale * The new locale as {@link String}. * @return this object for fluency. */ public Resources setLocale(String newLocale) { return setLocale(new Locale(newLocale)); } /** * Reset the current primary locale to the originally set device's locale using a * side-effect of * {@link android.content.res.Resources#Resources(AssetManager, DisplayMetrics, Configuration)}. * @return this object for fluency. */ public Resources resetLocale() { new android.content.res.Resources(mResources.getAssets(), mResources.getDisplayMetrics(), mResources.getConfiguration()); return this; } /** * @param context * A context object to access the * {@link android.content.res.Resources} of the app. * @param id * The desired resource identifier, as generated by the aapt * tool. This integer encodes the package, type, and resource * entry. The value 0 is an invalid identifier. * @return a single color value in the form 0xAARRGGBB. */ public static int getColor(Context context, int id) { return new Resources(context).getColor(id); } /** * @param context * A context object to access the * {@link android.content.res.Resources} of the app. * @param id * The desired resource identifier, as generated by the aapt * tool. This integer encodes the package, type, and resource * entry. The value 0 is an invalid identifier. * @return an object that can be used to draw this resource. */ public static Drawable getDrawable(Context context, int id) { return new Resources(context).getDrawable(id); } /** * @param context * A context object to access the * {@link android.content.res.Resources} of the app. * @return the currently used primary locale. */ public static Locale getPrimaryLocale(Context context) { return new Resources(context).getPrimaryLocale(); } /** * @param context * A context object to access the * {@link android.content.res.Resources} of the app. * @param newLocale * The new {@link Locale}. * @return this object for fluency. */ public static Resources setLocale(Context context, Locale newLocale) { return new Resources(context).setLocale(newLocale); } /** * @param context * A context object to access the * {@link android.content.res.Resources} of the app. * @param newLocale * The new locale as {@link String}. * @return this object for fluency. */ public static Resources setLocale(Context context, String newLocale) { return new Resources(context).setLocale(newLocale); } /** * @param context * A context object to access the * {@link android.content.res.Resources} of the app. * @return this object for fluency. */ public static Resources resetLocale(Context context) { return new Resources(context).resetLocale(); } }
package org.epics.graphene; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.Line2D; import java.util.Arrays; import java.util.List; import org.epics.util.array.ArrayDouble; import org.epics.util.array.ListDouble; import org.epics.util.array.ListInt; import org.epics.util.array.ListNumber; /** * * @author carcassi */ public abstract class Graph2DRenderer<T extends Graph2DRendererUpdate> { protected double xPlotValueStart; protected double yPlotValueStart; protected double xPlotValueEnd; protected double yPlotValueEnd; protected int areaHeight; protected int areaWidth; protected int xPlotCoordStart; protected int yPlotCoordStart; protected int yPlotCoordEnd; protected int xPlotCoordEnd; protected int xAreaStart; protected int yAreaStart; protected int yAreaEnd; protected int xAreaEnd; public Graph2DRenderer(int imageWidth, int imageHeight) { this.imageWidth = imageWidth; this.imageHeight = imageHeight; } public int getImageHeight() { return imageHeight; } public int getImageWidth() { return imageWidth; } protected Graphics2D g; // Renderer external parameter // // Size of the image private int imageWidth; private int imageHeight; // Strategy for calculating the axis range private AxisRange xAxisRange = AxisRanges.integrated(); private AxisRange yAxisRange = AxisRanges.integrated(); // Colors and fonts protected Color backgroundColor = Color.WHITE; protected Color labelColor = Color.BLACK; protected Color referenceLineColor = new Color(240, 240, 240); protected Font labelFont = FontUtil.getLiberationSansRegular(); // Image margins protected int bottomMargin = 2; protected int topMargin = 2; protected int leftMargin = 2; protected int rightMargin = 2; // area margins protected int bottomAreaMargin = 0; protected int topAreaMargin = 0; protected int leftAreaMargin = 0; protected int rightAreaMargin = 0; // Axis label margins protected int xLabelMargin = 3; protected int yLabelMargin = 3; // Computed parameters, visible to outside // private Range xAggregatedRange; private Range yAggregatedRange; private Range xPlotRange; private Range yPlotRange; protected FontMetrics labelFontMetrics; protected ListDouble xReferenceCoords; protected ListDouble xReferenceValues; protected List<String> xReferenceLabels; protected ListDouble yReferenceCoords; protected ListDouble yReferenceValues; protected List<String> yReferenceLabels; protected Range xCoordRange; protected Range yCoordRange; private int xLabelMaxHeight; private int yLabelMaxWidth; public AxisRange getXAxisRange() { return xAxisRange; } public AxisRange getYAxisRange() { return yAxisRange; } public Range getXAggregatedRange() { return xAggregatedRange; } public Range getYAggregatedRange() { return yAggregatedRange; } public Range getXPlotRange() { return xPlotRange; } public Range getYPlotRange() { return yPlotRange; } public void update(T update) { if (update.getImageHeight() != null) { imageHeight = update.getImageHeight(); } if (update.getImageWidth() != null) { imageWidth = update.getImageWidth(); } if (update.getXAxisRange() != null) { xAxisRange = update.getXAxisRange(); } if (update.getYAxisRange() != null) { yAxisRange = update.getYAxisRange(); } } static Range aggregateRange(Range dataRange, Range aggregatedRange) { if (aggregatedRange == null) { return dataRange; } else { return RangeUtil.sum(dataRange, aggregatedRange); } } public abstract T newUpdate(); protected void calculateRanges(Range xDataRange, Range yDataRange) { xAggregatedRange = aggregateRange(xDataRange, xAggregatedRange); yAggregatedRange = aggregateRange(yDataRange, yAggregatedRange); xPlotRange = xAxisRange.axisRange(xDataRange, xAggregatedRange); yPlotRange = yAxisRange.axisRange(yDataRange, yAggregatedRange); } protected void drawHorizontalReferenceLines() { g.setColor(referenceLineColor); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); ListNumber yTicks = yReferenceCoords; for (int i = 0; i < yTicks.size(); i++) { Shape line = new Line2D.Double(xCoordRange.getMinimum().doubleValue(), yTicks.getDouble(i), xCoordRange.getMaximum().doubleValue(), yTicks.getDouble(i)); g.draw(line); } } protected void drawVerticalReferenceLines() { g.setColor(referenceLineColor); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); ListNumber xTicks = xReferenceCoords; for (int i = 0; i < xTicks.size(); i++) { Shape line = new Line2D.Double(xTicks.getDouble(i), yCoordRange.getMinimum().doubleValue(), xTicks.getDouble(i), yCoordRange.getMaximum().doubleValue()); g.draw(line); } } protected void calculateGraphArea() { ValueAxis xAxis = ValueAxis.createAutoAxis(xPlotRange.getMinimum().doubleValue(), xPlotRange.getMaximum().doubleValue(), Math.max(2, getImageWidth() / 60)); ValueAxis yAxis = ValueAxis.createAutoAxis(yPlotRange.getMinimum().doubleValue(), yPlotRange.getMaximum().doubleValue(), Math.max(2, getImageHeight() / 60)); xReferenceLabels = Arrays.asList(xAxis.getTickLabels()); yReferenceLabels = Arrays.asList(yAxis.getTickLabels()); xReferenceValues = new ArrayDouble(xAxis.getTickValues()); yReferenceValues = new ArrayDouble(yAxis.getTickValues()); labelFontMetrics = g.getFontMetrics(labelFont); // Compute x axis spacing xLabelMaxHeight = labelFontMetrics.getHeight() - labelFontMetrics.getLeading(); int areaFromBottom = bottomMargin + xLabelMaxHeight + xLabelMargin; // Compute y axis spacing int[] yLabelWidths = new int[yReferenceLabels.size()]; yLabelMaxWidth = 0; for (int i = 0; i < yLabelWidths.length; i++) { yLabelWidths[i] = labelFontMetrics.stringWidth(yReferenceLabels.get(i)); yLabelMaxWidth = Math.max(yLabelMaxWidth, yLabelWidths[i]); } int areaFromLeft = leftMargin + yLabelMaxWidth + yLabelMargin; xCoordRange = RangeUtil.range(areaFromLeft + 0.5, getImageWidth() - rightMargin - 0.5); yCoordRange = RangeUtil.range(topMargin + 0.5, getImageHeight() - areaFromBottom - 0.5); xPlotValueStart = getXPlotRange().getMinimum().doubleValue(); yPlotValueStart = getYPlotRange().getMinimum().doubleValue(); xPlotValueEnd = getXPlotRange().getMaximum().doubleValue(); yPlotValueEnd = getYPlotRange().getMaximum().doubleValue(); areaWidth = (int) (xCoordRange.getMaximum().doubleValue() - xCoordRange.getMinimum().doubleValue()); areaHeight = (int) (yCoordRange.getMaximum().doubleValue() - yCoordRange.getMinimum().doubleValue()); xAreaStart = areaFromLeft; yAreaStart = topMargin; xAreaEnd = getImageWidth() - rightMargin - 1; yAreaEnd = getImageHeight() - areaFromBottom - 1; xPlotCoordStart = xAreaStart + topAreaMargin; yPlotCoordStart = yAreaStart + leftAreaMargin; xPlotCoordEnd = xAreaEnd - bottomAreaMargin; yPlotCoordEnd = yAreaEnd - rightAreaMargin; double[] xRefCoords = new double[xReferenceValues.size()]; for (int i = 0; i < xRefCoords.length; i++) { xRefCoords[i] = scaledX(xReferenceValues.getDouble(i)); } xReferenceCoords = new ArrayDouble(xRefCoords); double[] yRefCoords = new double[yReferenceValues.size()]; for (int i = 0; i < yRefCoords.length; i++) { yRefCoords[i] = scaledY(yReferenceValues.getDouble(i)); } yReferenceCoords = new ArrayDouble(yRefCoords); } protected void drawBackground() { g.setColor(backgroundColor); g.fillRect(0, 0, getImageWidth(), getImageHeight()); } protected void drawGraphArea() { drawBackground(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // When drawing the reference line, align them to the pixel drawVerticalReferenceLines(); drawHorizontalReferenceLines();; drawYLabels(); drawXLabels(); } private static final int MIN = 0; private static final int MAX = 1; private static void drawHorizontalReferencesLabel(Graphics2D graphics, FontMetrics metrics, String text, int yCenter, int[] drawRange, int xRight, boolean updateMin, boolean centeredOnly) { // If the center is not in the range, don't draw anything if (drawRange[MAX] < yCenter || drawRange[MIN] > yCenter) return; // If there is no space, don't draw anything if (drawRange[MAX] - drawRange[MIN] < metrics.getHeight()) return; Java2DStringUtilities.Alignment alignment = Java2DStringUtilities.Alignment.RIGHT; int targetY = yCenter; int halfHeight = metrics.getAscent() / 2; if (yCenter < drawRange[MIN] + halfHeight) { // Can't be drawn in the center if (centeredOnly) return; alignment = Java2DStringUtilities.Alignment.TOP_RIGHT; targetY = drawRange[MIN]; } else if (yCenter > drawRange[MAX] - halfHeight) { // Can't be drawn in the center if (centeredOnly) return; alignment = Java2DStringUtilities.Alignment.BOTTOM_RIGHT; targetY = drawRange[MAX]; } Java2DStringUtilities.drawString(graphics, alignment, xRight, targetY, text); if (updateMin) { drawRange[MAX] = targetY - metrics.getHeight(); } else { drawRange[MIN] = targetY + metrics.getHeight(); } } private static void drawVerticalReferenceLabel(Graphics2D graphics, FontMetrics metrics, String text, int xCenter, int[] drawRange, int yTop, boolean updateMin, boolean centeredOnly) { // If the center is not in the range, don't draw anything if (drawRange[MAX] < xCenter || drawRange[MIN] > xCenter) return; // If there is no space, don't draw anything if (drawRange[MAX] - drawRange[MIN] < metrics.getHeight()) return; Java2DStringUtilities.Alignment alignment = Java2DStringUtilities.Alignment.TOP; int targetX = xCenter; int halfWidth = metrics.stringWidth(text) / 2; if (xCenter < drawRange[MIN] + halfWidth) { // Can't be drawn in the center if (centeredOnly) return; alignment = Java2DStringUtilities.Alignment.TOP_LEFT; targetX = drawRange[MIN]; } else if (xCenter > drawRange[MAX] - halfWidth) { // Can't be drawn in the center if (centeredOnly) return; alignment = Java2DStringUtilities.Alignment.TOP_RIGHT; targetX = drawRange[MAX]; } Java2DStringUtilities.drawString(graphics, alignment, targetX, yTop, text); if (updateMin) { drawRange[MIN] = targetX + metrics.getHeight(); } else { drawRange[MAX] = targetX - metrics.getHeight(); } } protected final double scaledX(double value) { return xPlotCoordStart + NumberUtil.scale(value, xPlotValueStart, xPlotValueEnd, areaWidth) + 0.5; } protected final double scaledY(double value) { return yPlotCoordEnd - NumberUtil.scale(value, yPlotValueStart, yPlotValueEnd, areaHeight) + 0.5; } protected void setClip(Graphics2D g) { g.setClip(xPlotCoordStart, yPlotCoordStart, areaWidth + 1, areaHeight + 1); } protected void drawYLabels() { // Draw Y labels ListNumber yTicks = yReferenceCoords; if (yReferenceLabels != null && !yReferenceLabels.isEmpty()) { //g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g.setColor(labelColor); g.setFont(labelFont); FontMetrics metrics = g.getFontMetrics(); // Draw first and last label int[] drawRange = new int[] {(int) yCoordRange.getMinimum().intValue(), (int) yCoordRange.getMaximum().intValue()}; int xRightLabel = (int) (xCoordRange.getMinimum().doubleValue() - yLabelMargin - 1); drawHorizontalReferencesLabel(g, metrics, yReferenceLabels.get(0), (int) Math.floor(yTicks.getDouble(0)), drawRange, xRightLabel, true, false); drawHorizontalReferencesLabel(g, metrics, yReferenceLabels.get(yReferenceLabels.size() - 1), (int) Math.floor(yTicks.getDouble(yReferenceLabels.size() - 1)), drawRange, xRightLabel, false, false); for (int i = 1; i < yReferenceLabels.size() - 1; i++) { drawHorizontalReferencesLabel(g, metrics, yReferenceLabels.get(i), (int) Math.floor(yTicks.getDouble(i)), drawRange, xRightLabel, true, false); } } } protected void drawXLabels() { // Draw X labels ListNumber xTicks = xReferenceCoords; if (xReferenceLabels != null && !xReferenceLabels.isEmpty()) { //g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g.setColor(labelColor); g.setFont(labelFont); FontMetrics metrics = g.getFontMetrics(); // Draw first and last label int[] drawRange = new int[] {(int) xCoordRange.getMinimum().intValue(), (int) xCoordRange.getMaximum().intValue()}; int yTop = (int) (yCoordRange.getMaximum().doubleValue() + xLabelMargin + 1); drawVerticalReferenceLabel(g, metrics, xReferenceLabels.get(0), (int) Math.floor(xTicks.getDouble(0)), drawRange, yTop, true, false); drawVerticalReferenceLabel(g, metrics, xReferenceLabels.get(xReferenceLabels.size() - 1), (int) Math.floor(xTicks.getDouble(xReferenceLabels.size() - 1)), drawRange, yTop, false, false); for (int i = 1; i < xReferenceLabels.size() - 1; i++) { drawVerticalReferenceLabel(g, metrics, xReferenceLabels.get(i), (int) Math.floor(xTicks.getDouble(i)), drawRange, yTop, true, false); } } } }
package com.markehme.factionsalias.support; import java.util.List; /** * Just our Support Base. Nothing fancy. * * @author MarkehMe<mark@markeh.me> * */ public interface SupportBase { public void add(List<String> aliases, Boolean requiresFactionsEnabled, Boolean requiresIsPlayer, Boolean requiresInFaction, String permission, String permissionDeniedMessage, String desc, String executingCommand); public void unregister(); public void finishCall(); }
package org.epics.graphene; import java.awt.Color; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A utility class that provides implementations of {@link NumberColorMap}, * a set standard utilities and a directory for color maps. * * @author carcassi */ public class NumberColorMaps { // TODO: add more color schemes like the ones that can be found: /** * JET ranges from blue to red, going through cyan and yellow. */ public static final NumberColorMap JET = new NumberColorMapGradient(new Color[]{new Color(0,0,138), Color.BLUE, Color.CYAN, Color.YELLOW, Color.RED, new Color(138,0,0), Color.BLACK}, "JET"); /** * GRAY ranges from black to white. */ public static final NumberColorMap GRAY = new NumberColorMapGradient(new Color[]{Color.BLACK, Color.WHITE, Color.RED}, "GRAY"); /** * BONE ranges from black to white passing from blue. */ public static final NumberColorMap BONE = new NumberColorMapGradient(new Color[]{Color.BLACK, new Color(57, 57, 86), new Color(107, 115, 140), new Color(165, 198, 198), Color.WHITE, Color.RED}, "BONE"); /** * HOT ranges from black to white passing from red and yellow. */ public static final NumberColorMap HOT = new NumberColorMapGradient(new Color[]{Color.BLACK, Color.RED, Color.YELLOW, Color.WHITE, Color.RED}, "HOT"); private static final Map<String, NumberColorMap> registeredColorSchemes = new ConcurrentHashMap<>(); static { registeredColorSchemes.put(JET.toString(), JET); registeredColorSchemes.put(GRAY.toString(), GRAY); registeredColorSchemes.put(BONE.toString(), BONE); registeredColorSchemes.put(HOT.toString(), HOT); } /** * A set of registered color maps available to all applications. * * @return a set of color maps and their names */ public static Map<String, NumberColorMap> getRegisteredColorSchemes() { return Collections.unmodifiableMap(registeredColorSchemes); } public static NumberColorMapInstance optimize(NumberColorMapInstance instance, Range range){ return new NumberColorMapInstanceOptimized(instance, range); } /** * TODO: what is this about? * * @param instance * @param oldRange * @param newRange * @return */ public static NumberColorMapInstance optimize(NumberColorMapInstance instance, Range oldRange, Range newRange){ return new NumberColorMapInstanceOptimized(instance, oldRange, newRange); } }
// $RCSfile: PlainShape.java,v $ // @version $Revision: 1.5 $ // $Log: PlainShape.java,v $ // Revision 1.5 2006/05/02 13:21:38 Ian.Mayo // Make things draggable // Revision 1.4 2006/04/21 07:48:37 Ian.Mayo // Make things draggable // Revision 1.3 2006/03/31 14:29:21 Ian.Mayo // Switch default color to off-white, from RED // Revision 1.2 2004/05/25 15:37:15 Ian.Mayo // Commit updates from home // Revision 1.1.1.1 2004/03/04 20:31:22 ian // no message // Revision 1.1.1.1 2003/07/17 10:07:33 Ian.Mayo // Initial import // Revision 1.11 2003-07-03 14:59:18+01 ian_mayo // Always provide default colour for shapes (the same colour as the default in the colour editor) // Revision 1.10 2003-06-23 08:28:52+01 ian_mayo // Only return the Anchor point if we know our size (bounds) // Revision 1.9 2003-03-18 12:07:17+00 ian_mayo // extended support for transparent filled shapes // Revision 1.8 2003-03-14 16:01:21+00 ian_mayo // improve efficiency of naming label // Revision 1.7 2003-03-03 11:54:33+00 ian_mayo // Implement filled shape management // Revision 1.6 2003-02-10 16:26:05+00 ian_mayo // tidy comments, remove // Revision 1.5 2003-02-07 09:49:20+00 ian_mayo // rationalise unnecessary to da comments (that's do really) // Revision 1.4 2003-01-23 11:02:46+00 ian_mayo // Add method to return points of shape as collection // Revision 1.3 2003-01-21 16:30:44+00 ian_mayo // minor comment improvement // Revision 1.2 2002-05-28 09:25:52+01 ian_mayo // after switch to new system // Revision 1.1 2002-05-28 09:14:23+01 ian_mayo // Initial revision // Revision 1.1 2002-04-11 14:01:08+01 ian_mayo // Initial revision // Revision 1.1 2002-03-19 11:04:04+00 administrator // Add a "type" property to indicate type of shape (label, rectangle, etc) // Revision 1.0 2001-07-17 08:43:16+01 administrator // Initial revision // Revision 1.1 2001-01-03 13:42:24+00 novatech // Initial revision // Revision 1.1.1.1 2000/12/12 21:49:14 ianmayo // initial version // Revision 1.6 2000-04-19 11:36:44+01 ian_mayo // provide isVisible parameter // Revision 1.5 1999-11-26 15:45:04+00 ian_mayo // adding toString method // Revision 1.4 1999-10-15 12:36:50+01 ian_mayo // improved relative label locating // Revision 1.3 1999-10-14 11:59:20+01 ian_mayo // added property support and location editing // Revision 1.2 1999-10-12 15:39:48+01 ian_mayo // changed default constructor to use main constructor // Revision 1.1 1999-10-12 15:36:36+01 ian_mayo // Initial revision // Revision 1.1 1999-07-27 10:50:37+01 administrator // Initial revision // Revision 1.3 1999-07-23 14:03:48+01 administrator // Updating MWC utilities, & catching up on changes (removed deprecated code from PtPlot) // Revision 1.2 1999-07-19 12:39:42+01 administrator // Added painting to a metafile // Revision 1.1 1999-07-07 11:10:04+01 administrator // Initial revision // Revision 1.1 1999-06-16 15:37:57+01 sm11td // Initial revision // Revision 1.2 1999-02-01 14:25:01+00 sm11td // Skeleton there, opening new sessions, window management. // Revision 1.1 1999-01-31 13:33:02+00 sm11td // Initial revision package MWC.GUI.Shapes; import java.awt.Color; import java.awt.Point; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import MWC.GUI.CanvasType; import MWC.GUI.Layer; import MWC.GUI.Layers; import MWC.GUI.Shapes.HasDraggableComponents.ComponentConstruct; import MWC.GenericData.WorldArea; import MWC.GenericData.WorldDistance; import MWC.GenericData.WorldLocation; /** parent for Shapes. Shapes are screen entities * which are scaled using geographic coordinates, not * like @see PlainSymbol which is scaled using a * screen scale factor */ abstract public class PlainShape implements Serializable, DraggableItem { // member variables // keep track of versions static final long serialVersionUID = 1; /** the style the lines of this shape are drawn in */ private int _lineStyle; /** the colour this shape is drawn in */ private Color _foreColor; /** the width of the lines this shape is drawn in */ private int _lineWidth; /** the name of this shape */ private String _myName; /** property change support for this shape, this allows us * to store a list of objects which are intererested * in modification to this */ private PropertyChangeSupport _pSupport; private boolean _isVisible; /** the type of this shape * */ protected String _myType; /** whether this shape is filled * */ private boolean _isFilled = false; /** how transparent do we make the filled shapes? * */ protected static final int TRANSPARENCY_SHADE = 160; /** our default colour for new features */ public static final java.awt.Color DEFAULT_COLOR = new java.awt.Color(150, 150, 150); // constructor /** constructor.. * * @param theLineStyle * @param theLineWidth * @param myType */ protected PlainShape(int theLineStyle, int theLineWidth, String myType){ _lineStyle = theLineStyle; _foreColor = DEFAULT_COLOR; // set the colour to the default one for our colour editor _lineWidth = theLineWidth; StringBuffer sb = new StringBuffer(); sb.append("Shape"); sb.append(System.currentTimeMillis()); _myName = sb.toString(); // declare the property support _pSupport = new PropertyChangeSupport(this); _myType = myType; _isVisible = true; } // member functions /** paint the shape onto the destination. note that the shape knows * <i> where </i> to plot itself to * @param dest - the place to paint to */ public abstract void paint(CanvasType dest); /** get the are covered by the shape * @return WorldArea representing geographic coverage */ public abstract MWC.GenericData.WorldArea getBounds(); /** get the range from the indicated world location - * making this abstract allows for individual shapes * to have 'hit-spots' in various locations. */ public abstract double rangeFrom(MWC.GenericData.WorldLocation point); /** get the shape as a series of WorldLocation points. Joined up, these form a representation of the shape * */ abstract public java.util.Collection<WorldLocation> getDataPoints(); /** is this shape filled? (where applicable) * * @return */ public boolean getFilled() { return _isFilled; } /** is this shape filled? (where applicable) * * @param isFilled yes/no */ public void setFilled(boolean isFilled) { this._isFilled = isFilled; } /** accessor to get the type of this shape * */ public String getType() { return _myType; } /** setter function for name * @param val String representing name of shape */ final public void setName(String val) { _myName = val; } /** return this item as a string */ public String toString() { return getName(); } /** getter function for name * @return String representing name of this shape */ final public String getName() { return _myName; } public int getLineStyle(){ return _lineStyle; } public void setLineStyle(int lineStyle){ _lineStyle = lineStyle; } public int getLineWidth(){ return _lineWidth; } public void setLineWidth(int lineWidth){ _lineWidth = lineWidth; } public Color getColor(){ return _foreColor; } public void setColor(Color Color){ _foreColor = Color; } public void move(){ } public boolean getVisible() { return _isVisible; } public void setVisible(boolean val) { _isVisible = val; } // property change support public void addPropertyListener(PropertyChangeListener list) { _pSupport.addPropertyChangeListener(list); } public void removePropertyListener(PropertyChangeListener list) { _pSupport.removePropertyChangeListener(list); } protected void firePropertyChange(String name, Object oldValue, Object newValue) { _pSupport.firePropertyChange(name, oldValue, newValue); } // label/anchor support public WorldLocation getAnchor(int location) { WorldLocation loc = null; WorldArea wa = getBounds(); // did we find our bounds? if(wa != null) { WorldLocation centre = wa.getCentre(); switch(location) { case MWC.GUI.Properties.LocationPropertyEditor.TOP: { WorldLocation res = new WorldLocation(wa.getTopLeft().getLat(), centre.getLong(), 0); loc = res; break; } case MWC.GUI.Properties.LocationPropertyEditor.BOTTOM: { WorldLocation res = new WorldLocation(wa.getBottomRight().getLat(), centre.getLong(), 0); loc = res; break; } case MWC.GUI.Properties.LocationPropertyEditor.LEFT: { WorldLocation res = new WorldLocation(centre.getLat(), wa.getTopLeft().getLong(), 0); loc = res; break; } case MWC.GUI.Properties.LocationPropertyEditor.RIGHT: { WorldLocation res = new WorldLocation(centre.getLat(), wa.getBottomRight().getLong(), 0); loc = res; break; } case MWC.GUI.Properties.LocationPropertyEditor.CENTRE: { loc = centre; } } } return loc; } /** ok - see if we are any close to the target * * @param cursorPos * @param cursorLoc * @param currentNearest * @param parentLayer */ public final void findNearestHotSpotIn(Point cursorPos, WorldLocation cursorLoc, LocationConstruct currentNearest, Layer parentLayer, Layers theLayers) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist = new WorldDistance(rangeFrom(cursorLoc), WorldDistance.DEGS); // is this our first item? currentNearest.checkMe(this, thisDist, null, parentLayer); } /** utility method to assist in checking draggable components * * @param thisLocation * @param cursorLoc * @param currentNearest * @param shape * @param parentLayer */ protected static void checkThisOne(WorldLocation thisLocation, WorldLocation cursorLoc, ComponentConstruct currentNearest, HasDraggableComponents shape, Layer parentLayer) { // now for the BL WorldDistance blRange = new WorldDistance(thisLocation.rangeFrom(cursorLoc), WorldDistance.DEGS); // try range currentNearest.checkMe(shape, blRange, null, parentLayer, thisLocation); } }
package com.ra4king.circuitsim.gui.peers.wiring; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.ra4king.circuitsim.gui.ComponentManager.ComponentManagerInterface; import com.ra4king.circuitsim.gui.ComponentPeer; import com.ra4king.circuitsim.gui.Connection.PortConnection; import com.ra4king.circuitsim.gui.GuiUtils; import com.ra4king.circuitsim.gui.Properties; import com.ra4king.circuitsim.gui.Properties.Direction; import com.ra4king.circuitsim.gui.Properties.Property; import com.ra4king.circuitsim.simulator.Circuit; import com.ra4king.circuitsim.simulator.CircuitState; import com.ra4king.circuitsim.simulator.Component; import com.ra4king.circuitsim.simulator.Port; import com.ra4king.circuitsim.simulator.WireValue; import javafx.geometry.Bounds; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.util.Pair; /** * @author Roi Atalla */ public class Tunnel extends ComponentPeer<Component> { private static Map<Circuit, Map<String, Set<Tunnel>>> tunnels = new HashMap<>(); public static void installComponent(ComponentManagerInterface manager) { manager.addComponent(new Pair<>("Wiring", "Tunnel"), new Image(Tunnel.class.getResourceAsStream("/resources/Tunnel.png")), new Properties(new Property<>(Properties.DIRECTION, Direction.WEST))); } private final Component tunnel; public Tunnel(Properties props, int x, int y) { super(x, y, 0, 2); Properties properties = new Properties(); properties.ensureProperty(Properties.LABEL); properties.ensureProperty(Properties.DIRECTION); properties.ensureProperty(Properties.BITSIZE); properties.mergeIfExists(props); String label = properties.getValue(Properties.LABEL); int bitSize = properties.getValue(Properties.BITSIZE); Bounds bounds = GuiUtils.getBounds(GuiUtils.getFont(13), label); setWidth(Math.max((int)Math.ceil(bounds.getWidth() / GuiUtils.BLOCK_SIZE), 1)); tunnel = new Component(label, new int[] { bitSize }) { @Override public void setCircuit(Circuit circuit) { Circuit oldCircuit = getCircuit(); super.setCircuit(circuit); if(circuit == null) { Map<String, Set<Tunnel>> tunnelSet = tunnels.get(oldCircuit); if(tunnelSet != null) { Set<Tunnel> tunnels = tunnelSet.get(label); if(tunnels != null) { tunnels.remove(Tunnel.this); } } } else if(!label.isEmpty()) { Map<String, Set<Tunnel>> tunnelSet = tunnels.computeIfAbsent(circuit, l -> new HashMap<>()); tunnelSet.computeIfAbsent(label, c -> new HashSet<>()).add(Tunnel.this); } } @Override public void init(CircuitState state, Object lastProperty) { Map<String, Set<Tunnel>> tunnelSet = tunnels.get(getCircuit()); if(tunnelSet != null && tunnelSet.containsKey(label)) { Set<Tunnel> toNotify = tunnelSet.get(label); WireValue value = new WireValue(bitSize); for(Tunnel tunnel : toNotify) { if(tunnel != Tunnel.this && tunnel.getComponent().getCircuit() == getComponent().getCircuit()) { Port port = tunnel.getComponent().getPort(0); try { WireValue portValue = state.getMergedValue(port.getLink()); if(portValue.getBitSize() == value.getBitSize()) { value.merge(portValue); } } catch(Exception exc) { break; } } } state.pushValue(getPort(0), value); } } @Override public void valueChanged(CircuitState state, WireValue value, int portIndex) { Map<String, Set<Tunnel>> tunnelSet = tunnels.get(getCircuit()); if(tunnelSet != null && tunnelSet.containsKey(label)) { Set<Tunnel> toNotify = tunnelSet.get(label); for(Tunnel tunnel : toNotify) { if(tunnel != Tunnel.this) { state.pushValue(tunnel.getComponent().getPort(0), value); } } } } }; List<PortConnection> connections = new ArrayList<>(); switch(properties.getValue(Properties.DIRECTION)) { case EAST: setWidth(getWidth() + 2); connections.add(new PortConnection(this, tunnel.getPort(0), getWidth(), getHeight() / 2)); break; case WEST: setWidth(getWidth() + 2); connections.add(new PortConnection(this, tunnel.getPort(0), 0, getHeight() / 2)); break; case NORTH: setWidth(Math.max(((getWidth() - 1) / 2) * 2 + 2, 2)); setHeight(3); connections.add(new PortConnection(this, tunnel.getPort(0), getWidth() / 2, 0)); break; case SOUTH: setWidth(Math.max(((getWidth() - 1) / 2) * 2 + 2, 2)); setHeight(3); connections.add(new PortConnection(this, tunnel.getPort(0), getWidth() / 2, getHeight())); break; } init(tunnel, properties, connections); } private boolean isIncompatible() { String label = getComponent().getName(); int bitSize = getComponent().getPort(0).getLink().getBitSize(); Map<String, Set<Tunnel>> tunnelSet = tunnels.get(tunnel.getCircuit()); if(tunnelSet != null && tunnelSet.containsKey(label)) { for(Tunnel tunnel : tunnelSet.get(label)) { if(tunnel.getComponent().getCircuit() == getComponent().getCircuit() && tunnel.getComponent().getPort(0).getLink().getBitSize() != bitSize) { return true; } } } return false; } @Override public void paint(GraphicsContext graphics, CircuitState circuitState) { Direction direction = getProperties().getValue(Properties.DIRECTION); boolean isIncompatible = isIncompatible(); graphics.setStroke(Color.BLACK); graphics.setFill(isIncompatible ? Color.ORANGE : Color.WHITE); int block = GuiUtils.BLOCK_SIZE; int x = getScreenX(); int y = getScreenY(); int width = getScreenWidth(); int height = getScreenHeight(); int xOff = 0; int yOff = 0; switch(direction) { case EAST: xOff = -block; graphics.beginPath(); graphics.moveTo(x + width, y + height * 0.5); graphics.lineTo(x + width - block, y + height); graphics.lineTo(x, y + height); graphics.lineTo(x, y); graphics.lineTo(x + width - block, y); graphics.closePath(); break; case WEST: xOff = block; graphics.beginPath(); graphics.moveTo(x, y + height * 0.5); graphics.lineTo(x + block, y); graphics.lineTo(x + width, y); graphics.lineTo(x + width, y + height); graphics.lineTo(x + block, y + height); graphics.closePath(); break; case NORTH: yOff = block; graphics.beginPath(); graphics.moveTo(x + width * 0.5, y); graphics.lineTo(x + width, y + block); graphics.lineTo(x + width, y + height); graphics.lineTo(x, y + height); graphics.lineTo(x, y + block); graphics.closePath(); break; case SOUTH: yOff = -block; graphics.beginPath(); graphics.moveTo(x + width * 0.5, y + height); graphics.lineTo(x, y + height - block); graphics.lineTo(x, y); graphics.lineTo(x + width, y); graphics.lineTo(x + width, y + height - block); graphics.closePath(); break; } graphics.fill(); graphics.stroke(); if(!getComponent().getName().isEmpty()) { Bounds bounds = GuiUtils.getBounds(graphics.getFont(), getComponent().getName()); graphics.setFill(Color.BLACK); graphics.fillText(getComponent().getName(), x + xOff + ((width - xOff) - bounds.getWidth()) * 0.5, y + yOff + ((height - yOff) + bounds.getHeight()) * 0.4); } if(isIncompatible) { PortConnection port = getConnections().get(0); graphics.setFill(Color.BLACK); graphics.fillText(String.valueOf(port.getPort().getLink().getBitSize()), port.getScreenX() + 11, port.getScreenY() + 21); graphics.setStroke(Color.ORANGE); graphics.setFill(Color.ORANGE); graphics.strokeOval(port.getScreenX() - 2, port.getScreenY() - 2, 10, 10); graphics.fillText(String.valueOf(port.getPort().getLink().getBitSize()), port.getScreenX() + 10, port.getScreenY() + 20); } } }
package io.warp10.script.functions; import io.warp10.script.WarpScriptException; import io.warp10.script.WarpScriptStack; import io.warp10.script.formatted.FormattedWarpScriptFunction; import java.util.ArrayList; import java.util.List; import java.util.Map; public class PERMUTE extends FormattedWarpScriptFunction { public static final String TENSOR = "tensor"; public static final String PATTERN = "pattern"; public static final String FAST = "fast"; private final Arguments args; private final Arguments output; protected Arguments getArguments() { return args; } protected Arguments getOutput() { return output; } public PERMUTE(String name) { super(name); getDocstring().append("Permute the dimensions of a nested LIST as if it were a tensor or a multidimensional array."); args = new ArgumentsBuilder() .addArgument(List.class, TENSOR, "The nested LIST for which dimensions will be permuted as if it were a tensor.") .addListArgument(Long.class, PATTERN, "The permutation pattern (a LIST of LONG).") .addOptionalArgument(Boolean.class, FAST, "If True, it does not check if the sizes of the nested lists are coherent before operating. Default to False.", false) .build(); output = new ArgumentsBuilder() .addArgument(List.class, TENSOR, "The resulting nested LIST.") .build(); } private List<Long> pattern; private List<Long> newShape; protected WarpScriptStack apply(Map<String, Object> formattedArgs, WarpScriptStack stack) throws WarpScriptException { List<Object> tensor = (List) formattedArgs.get(TENSOR); pattern = (List) formattedArgs.get(PATTERN); boolean fast = ((Boolean) formattedArgs.get(FAST)).booleanValue(); List<Long> shape = SHAPE.candidate_shape(tensor); if (!(fast || CHECKSHAPE.recValidateShape(tensor, shape))) { throw new WarpScriptException(getName() + " expects that the sizes of the nested lists are coherent together to form a tensor (or multidimensional array)."); } newShape = new ArrayList<>(); for (int r = 0; r < pattern.size(); r++) { newShape.add(shape.get(pattern.get(r).intValue())); } List<Object> result = new ArrayList<>(); recPermute(tensor, result, new ArrayList<Long>(), 0); stack.push(result); return stack; } private void recPermute(List<Object> tensor, List<Object> result, List<Long> indices, int dimension) throws WarpScriptException { for (int i = 0; i < newShape.get(dimension); i++) { indices = new ArrayList(indices); indices.add(new Long(i)); if (newShape.size() - 1 == dimension) { List<Number> permutedIndices = new ArrayList<>(); for (int r = 0; r < pattern.size(); r++) { permutedIndices.add(indices.get(pattern.get(r).intValue())); } result.add(GET.recNestedGet(this, tensor, permutedIndices)); } else { List<Object> nested = new ArrayList<>(); result.add(nested); recPermute(tensor, nested, indices, dimension++); } } } }
package com.temporaryteam.noticeditor.model; import org.json.JSONException; import org.json.JSONObject; public class NoticeTree { private final NoticeTreeItem root; public NoticeTree(NoticeTreeItem root) { this.root = root; } public NoticeTree(JSONObject jsobj) throws JSONException { root = new NoticeTreeItem(jsobj); } public NoticeTreeItem getRoot() { return root; } /** * @param item * @param parent if null, item will be added to root item. */ public void addItem(NoticeTreeItem item, NoticeTreeItem parent) { if (parent == null) { parent = root; } else if (parent.isLeaf()) { parent = (NoticeTreeItem) parent.getParent(); } parent.getChildren().add(item); parent.setExpanded(true); } public void removeItem(NoticeTreeItem item) { if (item == null) return; item.getParent().getChildren().remove(item); } public JSONObject toJson() throws JSONException { return root.toJson(); } }
package com.valkryst.generator; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public final class ConsonantVowelGenerator extends NameGenerator { /** The consonants. */ private final String[] consonants; /** The vowels. */ private final String[] vowels; public ConsonantVowelGenerator(final List<String> consonants, final List<String> vowels) { // Ensure lists aren't empty: if (consonants == null || consonants.size() == 0) { throw new IllegalArgumentException("The list of consonants is empty or null."); } if (vowels == null || vowels.size() == 0) { throw new IllegalArgumentException("The list of vowels is empty or null."); } this.consonants = consonants.toArray(new String[0]); this.vowels = vowels.toArray(new String[0]); } @Override public String generateName(int length) { if (length < 2) { length = 2; } final StringBuilder sb = new StringBuilder(); final ThreadLocalRandom rand = ThreadLocalRandom.current(); while (sb.length() < length) { if (length % 2 == 0) { sb.append(vowels[rand.nextInt(vowels.length)]); } else { sb.append(consonants[rand.nextInt(consonants.length)]); } } if (sb.length() > length) { sb.deleteCharAt(sb.length() - (sb.length() - length)); } return super.capitalizeFirstCharacter(sb.toString()); } }
package net.galvin.hadoop.web; import net.galvin.hadoop.comm.hdfs.HdfsService; import net.galvin.hadoop.comm.utils.Logging; import org.apache.hadoop.fs.FileStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/hdfs") public class HdfsAction { @Autowired private HdfsService hdfsService; @RequestMapping("/listDir") @ResponseBody public Object listDir(HttpServletRequest request){ String dirName = request.getParameter("dirName"); List<FileStatus> fileStatusList = hdfsService.listDir(dirName); List<String> fileList = new ArrayList<String>(); for(FileStatus fileStatus : fileStatusList){ fileList.add(fileStatus.toString()); } return fileList; } }
package org.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import org.common.Utils; public class SupServer { private int port; public SupServer(int port) { this.port = port; } public class SupClientHandler implements Runnable { BufferedReader reader; String clientname = ""; Socket sock; public SupClientHandler(Socket clientSocket) { try { sock = clientSocket; InputStreamReader isReader = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isReader); } catch(Exception ex) { ex.printStackTrace(); } } public void run() { // Run until connection is broken or user terminates String message = ""; try { // if connection is broken, receiveMessage will return empty string. while((message = Utils.receiveMessage(this.reader)) != "") { // now we have the message read in. this might be more verbose than we want. System.out.println("read \"" + message + "\" from " + Thread.currentThread().getName()); // at this point, for the first message only, we'll need to parse the message // for a username and add it to contact list, like: // Only the first time expect this! if(clientname.isEmpty()) { String requestedName = message.split(" ")[1]; if (Contacts.getInstance().hasContact(requestedName)) { // return error, username taken System.out.println("Contact name taken: " + requestedName ); Utils.sendMessage(new PrintWriter(sock.getOutputStream()), Utils.FAIL_LOGIN_USERNAME_TAKEN); } else { // success, add them to the collection of online contacts. clientname = requestedName; System.out.println("New contact name: " + clientname ); Contacts.getInstance().addContact( clientname, new PrintWriter(sock.getOutputStream()) ); try { Utils.sendMessage(Contacts.getInstance().getContact(clientname), Utils.SUCCESS_STS); } catch (Exception e) { System.out.println("Failed to send confirmation message to new client"); e.printStackTrace(); } } } else { // they've already successfully logged in. // if it's not a login message, it's a chat message. parse it and forward. String toname = "TODO"; // need to parse that out of the chat message tellSomeone(message, this.clientname, toname ); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // if they were actually authenticated and left, log them off.. if(!clientname.isEmpty()) { System.out.println(clientname + " is no longer online."); // remove user from active contacts Contacts.getInstance().removeContact(clientname); } } } public void start () { ServerSocket supServer = null; try{ supServer = new ServerSocket(this.port); // everytime receive a socket from a server, create a new thread. put the printwriter into userlist and set the name for client while(true) { Socket supClient = supServer.accept(); Thread t = new Thread(new SupClientHandler(supClient)); t.start(); System.out.println("Received a new connection"); } } catch(IOException ex) { ex.printStackTrace(); } catch(Exception ex) { System.out.println(ex.getMessage()); } // all done, clean up. try { supServer.close(); } catch (IOException e) { System.out.println("Failed to clean up socket, finishing anyway."); e.printStackTrace(); } } // send the message to the specific user. find the socket by searching userlist // this needs to be thread safe. public void tellSomeone(String message, String fromname, String toname) { if (Contacts.getInstance().hasContact(toname)) { try { PrintWriter writer = Contacts.getInstance().getContact(toname); String msg = createFormattedChatMessage(message, fromname, toname); Utils.sendMessage(writer, msg); } catch (Exception ex) { ex.printStackTrace(); } } } /** * * @param message * @param fromname - sender username * @param toname - recipient username * @return string of formatted message, ready for sending */ private String createFormattedChatMessage(String message, String fromname, String toname ) { // TODO return "TODO make this valid " + message; } /** * return the status to the specific one * * @param * status - status info * toname - the specific one to transfer status * */ public void tellSomeoneStatus(String status, String toname) { System.out.println("Return the \"" + status +"\" to " + toname); if (Contacts.getInstance().hasContact(toname)) { try { PrintWriter writer = Contacts.getInstance().getContact(toname); Utils.sendMessage(writer, toname); } catch (Exception ex) { ex.printStackTrace(); } } } /** * remove contact from active list and send the online list to everyone * * @param * name - the contact removed from the list * */ public void removeContact(String name) { Contacts.getInstance().removeContact(name); System.out.println(name + "has been removed from the contact"); } /** * send user list after remove someone * * */ public void sendList() { try { List<String> users = Contacts.getInstance().getUserList(); List<PrintWriter> list = Contacts.getInstance().getWriterList(); for(int i=0; i<list.size(); i++) { PrintWriter writer = list.get(i); System.out.println("Send the user list"); Utils.sendMessage(writer, users.toArray()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.yidejia.app.mall.fragment; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragment; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshScrollView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.ImageLoadingListener; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.yidejia.app.mall.ActiveGoActivity; import com.yidejia.app.mall.GoodsInfoActivity; import com.yidejia.app.mall.MyApplication; import com.yidejia.app.mall.R; import com.yidejia.app.mall.SearchActivity; import com.yidejia.app.mall.SlideImageLayout; import com.yidejia.app.mall.exception.TimeOutEx; import com.yidejia.app.mall.initview.HotSellView; import com.yidejia.app.mall.model.BaseProduct; import com.yidejia.app.mall.model.MainProduct; import com.yidejia.app.mall.net.ConnectionDetector; import com.yidejia.app.mall.net.homepage.GetHomePage; import com.yidejia.app.mall.view.AllOrderActivity; import com.yidejia.app.mall.view.HistoryActivity; import com.yidejia.app.mall.view.IntegeralActivity; import com.yidejia.app.mall.view.LoginActivity; import com.yidejia.app.mall.view.MyCollectActivity; import com.yidejia.app.mall.view.SkinHomeActivity; import com.yidejia.app.mall.view.SkinQuesActivity; import com.yidejia.app.mall.widget.YLProgressDialog; import com.yidejia.app.mall.widget.YLViewPager; public class MainPageFragment extends SherlockFragment { public static MainPageFragment newInstance(int title) { MainPageFragment fragment = new MainPageFragment(); Bundle bundle = new Bundle(); bundle.putInt("main", title); fragment.setArguments(bundle); return fragment; } private int main; private int defaultInt = -1; private String TAG = "MainPageFragment"; private PullToRefreshScrollView mPullToRefreshScrollView; private TextView main_mall_notice_content; private MyApplication myApplication; private AlertDialog dialog; // private RelativeLayout myorderLayout; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); Bundle bundle = getArguments(); main = (bundle != null) ? bundle.getInt("main") : defaultInt; getSherlockActivity().getSupportActionBar().setCustomView(R.layout.actionbar_main_home_title); // getSherlockActivity().getSupportActionBar().setCustomView(R.layout.actionbar_main_home_title); } private View view; private LayoutInflater inflater; private FrameLayout layout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.activity_main_layout, container, false); myApplication = (MyApplication) getSherlockActivity().getApplication(); dialog = new Builder(getSherlockActivity()) .setTitle(getResources().getString(R.string.tips)) .setIcon(R.drawable.ic_launcher) .setMessage(getResources().getString(R.string.waiting4open)) // .setNegativeButton( // getSherlockActivity().getResources().getString( // R.string.cancel), null) .setPositiveButton( getSherlockActivity().getResources().getString( R.string.sure), null).create(); view = inflater .inflate(R.layout.activity_main_layout, container, false); this.inflater = inflater; switch (main) { case 0: break; default: break; } return view; } /** * activity * * @param view * @param inflater */ private void createView(View view, LayoutInflater inflater) { RelativeLayout shorcutLayout = (RelativeLayout) view.findViewById(R.id.function_parent_layout); View child = inflater.inflate(R.layout.main_function, null); shorcutLayout.addView(child); functionIntent(child); mPullToRefreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.main_pull_refresh_scrollview); mPullToRefreshScrollView.setScrollingWhileRefreshingEnabled(true); mPullToRefreshScrollView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); mPullToRefreshScrollView.setVerticalScrollBarEnabled(false); mPullToRefreshScrollView.setHorizontalScrollBarEnabled(false); String label = getResources().getString(R.string.update_time) + DateUtils.formatDateTime(getSherlockActivity() .getApplicationContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL); mPullToRefreshScrollView.getLoadingLayoutProxy().setLastUpdatedLabel(label); mPullToRefreshScrollView.getLoadingLayoutProxy().setLastUpdatedLabel( label); mPullToRefreshScrollView.setOnRefreshListener(listener); main_mall_notice_content = (TextView) view .findViewById(R.id.main_mall_notice_content); layout = (FrameLayout) view.findViewById(R.id.layout); // mMainView = (ViewGroup) inflater.inflate( // R.layout.layout_first_item_in_main_listview, null); } private boolean isLogin() { if (!myApplication.getIsLogin()) { Toast.makeText(getSherlockActivity(), getResources().getString(R.string.please_login), Toast.LENGTH_LONG).show(); Intent intent1 = new Intent(getSherlockActivity(), LoginActivity.class); startActivity(intent1); return true; } else { return false; } } private OnRefreshListener<ScrollView> listener = new OnRefreshListener<ScrollView>() { @Override public void onRefresh(PullToRefreshBase<ScrollView> refreshView) { // TODO Auto-generated method stub try { // String label = getResources().getString(R.string.update_time) // + DateUtils.formatDateTime(getSherlockActivity() // .getApplicationContext(), System // .currentTimeMillis(), // DateUtils.FORMAT_SHOW_TIME // | DateUtils.FORMAT_SHOW_DATE // | DateUtils.FORMAT_ABBREV_ALL); // refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); // mPullToRefreshScrollView.setRefreshing(); if(!ConnectionDetector.isConnectingToInternet(getSherlockActivity())){ Toast.makeText(getSherlockActivity(), getResources().getString(R.string.no_network), Toast.LENGTH_LONG).show(); mPullToRefreshScrollView.onRefreshComplete(); return; } closeTask(); task = new Task(); task.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(getSherlockActivity(), getResources().getString(R.string.bad_network), Toast.LENGTH_SHORT).show(); mPullToRefreshScrollView.onRefreshComplete(); } } }; private void closeTask(){ if(task != null && task.getStatus().RUNNING == AsyncTask.Status.RUNNING){ task.cancel(true); } } /** * hotsell,acymer,inerbty * * @param view */ private void intentToView(View view) { try { // hot sell RelativeLayout hotsellLeft = (RelativeLayout)view.findViewById(R.id.main_hot_sell_left); hotsellLeft.setOnClickListener(new MainGoodsOnclick(hotsellArray.get(0).getUId())); hotsellLeft.setOnClickListener(new MainGoodsOnclick(hotsellArray .get(0).getUId())); // hot sell RelativeLayout hotsellRightTop = (RelativeLayout)view.findViewById(R.id.main_hot_sell_right_top); hotsellRightTop.setOnClickListener(new MainGoodsOnclick(hotsellArray.get(1).getUId())); hotsellRightTop.setOnClickListener(new MainGoodsOnclick( hotsellArray.get(1).getUId())); // hot sell RelativeLayout hotsellRightDown = (RelativeLayout)view.findViewById(R.id.main_hot_sell_right_down); hotsellRightDown.setOnClickListener(new MainGoodsOnclick(hotsellArray.get(2).getUId())); hotsellRightDown.setOnClickListener(new MainGoodsOnclick( hotsellArray.get(2).getUId())); // acymer RelativeLayout acymeiLeft = (RelativeLayout)view.findViewById(R.id.main_acymei_left); acymeiLeft.setOnClickListener(new MainGoodsOnclick(acymerArray.get(0).getUId())); acymeiLeft.setOnClickListener(new MainGoodsOnclick(acymerArray.get( 0).getUId())); // acymer RelativeLayout acymeiRightTop = (RelativeLayout)view.findViewById(R.id.main_acymei_right_top); acymeiRightTop.setOnClickListener(new MainGoodsOnclick(acymerArray.get(1).getUId())); acymeiRightTop.setOnClickListener(new MainGoodsOnclick(acymerArray .get(1).getUId())); // acymer RelativeLayout acymeiRightDown = (RelativeLayout)view.findViewById(R.id.main_acymei_right_down); acymeiRightDown.setOnClickListener(new MainGoodsOnclick(acymerArray.get(2).getUId())); acymeiRightDown.setOnClickListener(new MainGoodsOnclick(acymerArray .get(2).getUId())); // inerbty RelativeLayout inerbtyTopLeft = (RelativeLayout)view.findViewById(R.id.main_inerbty_top_left); inerbtyTopLeft.setOnClickListener(new MainGoodsOnclick(inerbtyArray.get(0).getUId())); inerbtyTopLeft.setOnClickListener(new MainGoodsOnclick(inerbtyArray .get(0).getUId())); // inerbty RelativeLayout inerbtyTopRight = (RelativeLayout)view.findViewById(R.id.main_inerbty_top_right); inerbtyTopRight.setOnClickListener(new MainGoodsOnclick(inerbtyArray.get(1).getUId())); inerbtyTopRight.setOnClickListener(new MainGoodsOnclick( inerbtyArray.get(1).getUId())); // inerbty RelativeLayout nerbtyMidLeft = (RelativeLayout)view.findViewById(R.id.main_inerbty_mid_left); nerbtyMidLeft.setOnClickListener(new MainGoodsOnclick(inerbtyArray.get(2).getUId())); nerbtyMidLeft.setOnClickListener(new MainGoodsOnclick(inerbtyArray .get(2).getUId())); // inerbty RelativeLayout inerbtyMidRight = (RelativeLayout)view.findViewById(R.id.main_inerbty_mid_right); inerbtyMidRight.setOnClickListener(new MainGoodsOnclick(inerbtyArray.get(3).getUId())); inerbtyMidRight.setOnClickListener(new MainGoodsOnclick( inerbtyArray.get(3).getUId())); // inerbty RelativeLayout inerbtyDownLeft = (RelativeLayout)view.findViewById(R.id.main_inerbty_down_left); inerbtyDownLeft.setOnClickListener(new MainGoodsOnclick(inerbtyArray.get(4).getUId())); inerbtyDownLeft.setOnClickListener(new MainGoodsOnclick( inerbtyArray.get(4).getUId())); // inerbty RelativeLayout inerbtyDownRight = (RelativeLayout)view.findViewById(R.id.main_inerbty_down_right); inerbtyDownRight.setOnClickListener(new MainGoodsOnclick(inerbtyArray.get(5).getUId())); inerbtyDownRight.setOnClickListener(new MainGoodsOnclick( inerbtyArray.get(5).getUId())); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(getSherlockActivity(), getResources().getString(R.string.bad_network), Toast.LENGTH_SHORT).show(); Toast.makeText(getSherlockActivity(), getResources().getString(R.string.bad_network), Toast.LENGTH_SHORT).show(); } } /** * hotsell,acymer,inerbty * * @author long bin * */ private class MainGoodsOnclick implements OnClickListener { private String goodsId; public MainGoodsOnclick(String goodsId) { this.goodsId = goodsId; } @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intentLeft = new Intent(getSherlockActivity(), GoodsInfoActivity.class); Bundle bundle = new Bundle(); bundle.putString("goodsId", goodsId); intentLeft.putExtras(bundle); getSherlockActivity().startActivity(intentLeft); } } /** * * * @param child */ private void functionIntent(View child) { RelativeLayout myOrder = (RelativeLayout) child.findViewById(R.id.function_my_order); myOrder.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intentOrder = new Intent(getSherlockActivity(),AllOrderActivity.class); if (!isLogin()) { getSherlockActivity().startActivity(intentOrder); } } }); RelativeLayout myCollect = (RelativeLayout) child.findViewById(R.id.function_my_favorite); myCollect.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intentOrder = new Intent(getSherlockActivity(),MyCollectActivity.class); if (!isLogin()) { getSherlockActivity().startActivity(intentOrder); } } }); RelativeLayout myEvent = (RelativeLayout) child.findViewById(R.id.function_event); myEvent.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // Intent intentOrder = new Intent(getSherlockActivity(),MyCollectActivity.class); // getSherlockActivity().startActivity(intentOrder); Intent intent = new Intent(getSherlockActivity(), ActiveGoActivity.class); getSherlockActivity().startActivity(intent); } }); RelativeLayout myMember = (RelativeLayout) child.findViewById(R.id.function_member); myMember.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // Intent intentOrder = new Intent(getSherlockActivity(),MyCollectActivity.class); // getSherlockActivity().startActivity(intentOrder); dialog.show(); // Intent intentOrder = new // Intent(getSherlockActivity(),MyCollectActivity.class); // getSherlockActivity().startActivity(intentOrder); } }); RelativeLayout myHistory = (RelativeLayout) child.findViewById(R.id.function_history); myHistory.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intentOrder = new Intent(getSherlockActivity(), HistoryActivity.class); // if (!isLogin()) { getSherlockActivity().startActivity(intentOrder); } }); RelativeLayout myCoupon = (RelativeLayout) child.findViewById(R.id.function_coupon); myCoupon.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intentOrder = new Intent(getSherlockActivity(),IntegeralActivity.class); if (!isLogin()) { getSherlockActivity().startActivity(intentOrder); } } }); RelativeLayout mySkin = (RelativeLayout) child.findViewById(R.id.function_skin); mySkin.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intentOrder = new Intent(getSherlockActivity(),SkinHomeActivity.class); getSherlockActivity().startActivity(intentOrder); // dialog.show(); // Intent intentOrder = new // Intent(getSherlockActivity(),IntegeralActivity.class); // getSherlockActivity().startActivity(intentOrder); } }); RelativeLayout myMessage = (RelativeLayout) child.findViewById(R.id.function_message); myMessage.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // Intent intentOrder = new Intent(getSherlockActivity(),PersonActivity.class); // getSherlockActivity().startActivity(intentOrder); // if (!isLogin()) { // Intent intentOrder = new Intent(getSherlockActivity(), // PersonActivity.class); // getSherlockActivity().startActivity(intentOrder); dialog.show(); } }); } private ArrayList<BaseProduct> bannerArray = new ArrayList<BaseProduct>(); private ArrayList<MainProduct> acymerArray = new ArrayList<MainProduct>(); private ArrayList<MainProduct> inerbtyArray = new ArrayList<MainProduct>(); private ArrayList<MainProduct> hotsellArray = new ArrayList<MainProduct>(); private ArrayList<String> ggTitleArray = new ArrayList<String>(); @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub try { super.onActivityCreated(savedInstanceState); Log.d(TAG, "TestFragment // intentToView(view); // MainPageDataManage manage = new MainPageDataManage( // getSherlockActivity(), null); // manage.getMainPageData(); // bannerArray = manage.getBannerArray(); // acymerArray = manage.getAcymerArray(); // inerbtyArray = manage.getInerbtyArray(); // hotsellArray = manage.getHotSellArray(); // ggTitleArray = manage.getGGTitle(); // createView(view, inflater); // HotSellView hotSellView = new HotSellView(view, // getSherlockActivity()); // hotSellView.initHotSellView(hotsellArray); // hotSellView.initAcymerView(acymerArray); // hotSellView.initInerbtyView(inerbtyArray); // intentToView(view); // main_mall_notice_content.setText(ggTitleArray.get(0)); bar = new ProgressDialog(getSherlockActivity(), R.style.StyleProgressDialog); bar.setCancelable(true); // bar.setProgressStyle(ProgressDialog.STYLE_SPINNER); // bar.setMessage(getSherlockActivity().getResources().getString(R.string.loading)); bar.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub isFirstIn = false; closeTask(); } }); createView(view, inflater); if(!ConnectionDetector.isConnectingToInternet(getSherlockActivity())){ Toast.makeText(getSherlockActivity(), getResources().getString(R.string.no_network), Toast.LENGTH_LONG).show(); isFirstIn = false; return; } closeTask(); task = new Task(); task.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(getSherlockActivity(), getResources().getString(R.string.bad_network), Toast.LENGTH_SHORT).show(); } } private boolean isFirstIn = true; private Task task; private ProgressDialog bar; private boolean isTimeOut = false; private class Task extends AsyncTask<Void, Void, Boolean>{ ProgressDialog bar2; @Override protected Boolean doInBackground(Void... params) { // TODO Auto-gene|rated method stub GetHomePage getHomePage = new GetHomePage(); String httpresp; try { try { httpresp = getHomePage.getHomePageJsonString(); boolean issuccess = getHomePage.analysisGetHomeJson(httpresp); bannerArray = getHomePage.getBannerArray(); acymerArray = getHomePage.getAcymerArray(); inerbtyArray = getHomePage.getInerbtyArray(); hotsellArray = getHomePage.getHotSellArray(); ggTitleArray = getHomePage.getGGTitle(); return issuccess; } catch (TimeOutEx e) { // TODO Auto-generated catch block e.printStackTrace(); isTimeOut = true; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); if (isFirstIn) { // bar.show(); bar2 = (ProgressDialog) new YLProgressDialog(getSherlockActivity()) .createLoadingDialog(getSherlockActivity(), null); // bar2.show(); bar2.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub isFirstIn = false; closeTask(); } }); } stopTimer(); if(!bannerArray.isEmpty())bannerArray.clear(); if(!inerbtyArray.isEmpty()) inerbtyArray.clear(); if(!hotsellArray.isEmpty()) hotsellArray.clear(); if(!acymerArray.isEmpty())acymerArray.clear(); } @Override protected void onPostExecute(Boolean result) { // TODO Auto-generated method stub super.onPostExecute(result); // try{ if (isAdded()) { if (result) { try { stopTimer(); bannerIndex = 0; layout.removeAllViews(); getMainListFirstItem(); layout.addView(mMainView); HotSellView hotSellView = new HotSellView(view, getSherlockActivity()); hotSellView.initHotSellView(hotsellArray); hotSellView.initAcymerView(acymerArray); hotSellView.initInerbtyView(inerbtyArray); try { intentToView(view); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } startTimer(); timer.schedule(timetask, DELAY, DELAY); main_mall_notice_content.setText(ggTitleArray.get(0)); } catch (Exception e) { // TODO: handle exception } // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // Toast.makeText(getSherlockActivity(), // getResources().getString(R.string.bad_network), // Toast.LENGTH_SHORT).show(); } else { if(isTimeOut) { Toast.makeText(getSherlockActivity(), getResources().getString(R.string.time_out), Toast.LENGTH_SHORT).show(); isTimeOut = false; } else Toast.makeText(getSherlockActivity(), getResources().getString(R.string.bad_network), Toast.LENGTH_SHORT).show(); } } if (isFirstIn) { // bar.dismiss(); bar2.dismiss(); // if(result) timer.schedule(timetask, DELAY, DELAY); isFirstIn = false; } else { mPullToRefreshScrollView.onRefreshComplete(); String label = getResources().getString(R.string.update_time) + DateUtils.formatDateTime(getSherlockActivity() .getApplicationContext(), System .currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL); mPullToRefreshScrollView.getLoadingLayoutProxy() .setLastUpdatedLabel(label); } } } @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); Log.d(TAG, "TestFragment startTimer(); // timer.schedule(timetask, DELAY, DELAY); } @Override public void onDestroyView() { // TODO Auto-generated method stub super.onDestroyView(); stopTimer(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); stopTimer(); } private long DELAY = 5000; private void stopTimer(){ if (timer != null) { timer.cancel(); timer = null; } if (timetask != null) { timetask.cancel(); timetask = null; } } private void startTimer(){ if (timer == null) { timer = new Timer(); } if(timetask == null) { timetask = new TimerTask(){ public void run() { Message message = new Message(); message.what = 1; handler.sendMessage(message); } }; } } Timer timer = new Timer();; TimerTask timetask = new TimerTask(){ public void run() { Message message = new Message(); message.what = 1; handler.sendMessage(message); } }; Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 1: setBannerImageShow(); break; } super.handleMessage(msg); } }; private int bannerIndex = 0; private void setBannerImageShow(){ int indexTemp = bannerIndex + 1; if(length != 0)indexTemp = indexTemp % length; mViewPager.setCurrentItem(indexTemp); bannerIndex = indexTemp; } private ViewGroup mMainView = null; private YLViewPager mViewPager; private ViewGroup mImageCircleView = null; private SlideImageLayout mSlideLayout; private ImageView[] mImageCircleViews; // private static final int[] ids = { R.drawable.banner1, R.drawable.banner2, R.drawable.banner3}; // private static final int[] ids = { R.drawable.banner1, // R.drawable.banner2, R.drawable.banner3}; private int length = 0; /** * * @return */ private ViewGroup getMainListFirstItem() { length = bannerArray.size(); LayoutInflater inflater = getActivity().getLayoutInflater(); mMainView = (ViewGroup) inflater.inflate( R.layout.layout_first_item_in_main_listview, null); if(length == 0) return mMainView; mViewPager = (YLViewPager) mMainView.findViewById(R.id.image_slide_page); // if (length == 0) // return mMainView; // mViewPager = (YLViewPager) mMainView // .findViewById(R.id.image_slide_page); mSlideLayout = new SlideImageLayout(getActivity(), mMainView.getContext(), width); mSlideLayout.setCircleImageLayout(length); mImageCircleViews = new ImageView[length]; mImageCircleView = (ViewGroup) mMainView .findViewById(R.id.layout_circle_images); Log.i(TAG, "length Log.i(TAG, "length // Timer timer = new Timer(); // timer.schedule(new TimerTask() { // @Override // public void run() { // int i=0; // // TODO Auto-generated method stub // Log.i("voucher",i+""); // }, 3000); for (int i = 0; i < length; i++) { // mainImageData.getBitmaps().get(i) // mImagePageViewList.add(mSlideLayout // .getSlideImageLayout((Bitmap)topAdImage.get(i)));//mainImageData.getBitmaps().get(i) mImageCircleViews[i] = mSlideLayout.getCircleImageLayout(i); mImageCircleView.addView(mSlideLayout.getLinearLayout( mImageCircleViews[i], 9, 9)); } // ViewPager mViewPager.setAdapter(new SlideImageAdapter(bannerArray)); mViewPager.setOnPageChangeListener(new ImagePageChangeListener()); mViewPager.setCurrentItem(0); mViewPager.setOffscreenPageLimit(2); return mMainView; } private class SlideImageAdapter extends PagerAdapter { // int i =0; private LayoutInflater inflater; private ArrayList<BaseProduct> bannerArray; public SlideImageAdapter(ArrayList<BaseProduct> bannerArray) { this.bannerArray = bannerArray; inflater = getActivity().getLayoutInflater(); initDisplayImageOption(); } // private int height = (int)((float)width / 320) * 160; // public SlideImageAdapter(){ public int getCount() { return length;// 1000; } public boolean isViewFromObject(View view, Object object) { return view == object; } public int getItemPosition(Object object) { return POSITION_NONE; } public void destroyItem(ViewGroup container, int position, Object object) { // ((ViewPager) view).removeView(mImagePageViewList.get(arg1)); ((ViewPager) container).removeView((View) object); } public Object instantiateItem(ViewGroup view, int position) { // ((ViewPager) view).addView(mImagePageViewList.get(position)); View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false); final ImageView imageView = (ImageView) imageLayout .findViewById(R.id.image); // Toast.makeText(getSherlockActivity(), // bannerArray.get(position).getImgUrl(), // Toast.LENGTH_SHORT).show(); imageLoader.displayImage(bannerArray.get(position).getImgUrl(), imageView, options, animateFirstListener); // imageView.setBackgroundResource(ids[position%length]); imageView.setOnClickListener(new ImageOnClickListener(position)); ((ViewPager) view).addView(imageLayout, 0); return imageLayout; } public void restoreState(Parcelable arg0, ClassLoader arg1) { } public Parcelable saveState() { return null; } public void startUpdate(View arg0) { } public void finishUpdate(View arg0) { } // public void setPageIndex(int index){ // pageIndex = index; public class ImageOnClickListener implements OnClickListener { private int index; public ImageOnClickListener(int index) { this.index = index; } @Override public void onClick(View v) { // Toast.makeText(getActivity(), ""+"["+pageIndex%length+"]", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getSherlockActivity(), GoodsInfoActivity.class); // Toast.makeText(getActivity(), // ""+"["+pageIndex%length+"]", // Toast.LENGTH_SHORT).show(); Bundle bundle = new Bundle(); bundle.putString("goodsId", bannerArray.get(index).getUId()); intent.putExtras(bundle); getSherlockActivity().startActivity(intent); } } } // private int pageIndex = 0; private class ImagePageChangeListener implements OnPageChangeListener { @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // mViewPager.setCurrentItem(pageIndex); } @Override public void onPageSelected(int index) { // mSlideLayout.setPageIndex(index); // SlideImageAdapter slideImageAdapter = new SlideImageAdapter(); // slideImageAdapter.setPageIndex(index); // pageIndex = index; int length = mImageCircleViews.length; mImageCircleViews[index%length].setBackgroundResource(R.drawable.dot1); mImageCircleViews[index % length] .setBackgroundResource(R.drawable.dot1); for (int i = 0; i < length; i++) { // mSlideTitle.setText(""+i); if (index % length != i) { mImageCircleViews[i%length].setBackgroundResource(R.drawable.dot2); mImageCircleViews[i % length] .setBackgroundResource(R.drawable.dot2); } } } } private int width; private DisplayImageOptions options; protected ImageLoader imageLoader = ImageLoader.getInstance(); private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(); private void initDisplayImageOption() { options = new DisplayImageOptions.Builder() // .showStubImage(R.drawable.hot_sell_right_top_image) // .showImageOnFail(R.drawable.hot_sell_right_top_image) // .showImageForEmptyUri(R.drawable.hot_sell_right_top_image) // .cacheInMemory(true) // .cacheOnDisc(true) // .build(); .showStubImage(R.drawable.banner_bg) .showImageOnFail(R.drawable.banner_bg) .showImageForEmptyUri(R.drawable.banner_bg).cacheInMemory(true) .cacheOnDisc(true).build(); } static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>()); private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); displayedImages.add(imageUri); } } } } }
package ro.isdc.wro.http; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.mockito.Mockito; public class TestWroFilter { @Test public void testGzipParam() throws Exception { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final FilterChain chain = Mockito.mock(FilterChain.class); //new WroFilter().doFilter(request, response, chain); } }
package org.mapdb; import java.util.List; import java.util.concurrent.*; public class Exec { public static void execNTimes(int n, final Callable r){ ExecutorService s = Executors.newFixedThreadPool(n); final CountDownLatch wait = new CountDownLatch(n); List<Future> f = new CopyOnWriteArrayList<Future>(); Runnable r2 = new Runnable(){ @Override public void run() { wait.countDown(); try { wait.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } try { r.call(); } catch (Exception e) { throw new RuntimeException(e); } } }; for(int i=0;i<n;i++){ f.add(s.submit(r2)); } s.shutdown(); while(!f.isEmpty()) { for (Future ff : f) { try { ff.get(1, TimeUnit.SECONDS); f.remove(ff); } catch (TimeoutException e) { //ignored } catch (Exception e) { throw new AssertionError(e); } } } } }
package com.explore.git.options; public class GitHelloWorld { public static void main(String[] args) { System.out.println("Hello, welcome to git..........!!!"); System.out.println("Committing code from user2"); } }
package de.mrapp.android.adapter; import de.mrapp.android.adapter.util.Group; /** * Defines the interface, an adapter, whose underlying data is managed as a * two-dimensional list of items, which are categorized by groups, must * implement. Such an adapter is meant to provide the underlying data for * visualization using a {@link ExpandableListView} widget. * * @param <GroupDataType>> The type of the group's underlying data * @param <ChildDataType> * The type of the children's underlying data * @param <GroupAdapterType> * The type of the adapter, which manages the groups * @param <ChildAdapterType>> The type of the adapter, which manages the * children * * @author Michael Rapp * * @since 1.0.0 */ public interface ExpandableListAdapter<GroupDataType, ChildDataType, GroupAdapterType extends ListAdapter<Group<GroupDataType, ChildDataType, ChildAdapterType>>, ChildAdapterType extends ListAdapter<ChildDataType>> extends Adapter { @Override ExpandableListAdapter<GroupDataType, ChildDataType, GroupAdapterType, ChildAdapterType> clone() throws CloneNotSupportedException; }
package de.unipaderborn.visuflow.builder; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import de.unipaderborn.visuflow.Logger; import de.unipaderborn.visuflow.Visuflow; import de.unipaderborn.visuflow.model.DataModel; import de.unipaderborn.visuflow.model.VFClass; import de.unipaderborn.visuflow.model.graph.ICFGStructure; import de.unipaderborn.visuflow.model.graph.JimpleModelAnalysis; import de.unipaderborn.visuflow.util.ServiceUtil; /** * @author PAH-Laptop * This is the Builder Class for our Project. * It triggers on the automatic builds of eclipse and checks which files have changed. * It only triggers a build on Project with the Visuflow Nature that have issued a fullbuild * or contain changed java files. * Then it gathers all the necessary information on the target code and runs a soot analysis * to compute the structure and jimple necessary for the other views. */ public class JimpleBuilder extends IncrementalProjectBuilder { private Logger logger = Visuflow.getDefault().getLogger(); private String classpath; private boolean executeBuild; class JimpleDeltaVisitor implements IResourceDeltaVisitor { public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); if (resource.getFileExtension() != null){ switch (delta.getKind()) { case IResourceDelta.ADDED: if(resource.getFileExtension().equals("java")){ executeBuild = true; return false; } break; case IResourceDelta.REMOVED: if(resource.getFileExtension().equals("java")){ executeBuild = true; return false; } break; case IResourceDelta.CHANGED: if( resource.getFileExtension().equals("java")){ executeBuild = true; return false; } break; } } return true; } } /** * @param javaProject * @return * @throws JavaModelException */ protected String getClassFilesLocation(IJavaProject javaProject) throws JavaModelException { String path = javaProject.getOutputLocation().toString(); IResource binFolder = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (binFolder != null) return binFolder.getLocation().toString(); throw new RuntimeException("Could not retrieve Soot classpath for project " + javaProject.getElementName()); } /** * @param javaProject * @return String with the complete Classpath for the soot run * Computes the classpath necessary for the soot run */ private String getSootCP(IJavaProject javaProject) { String sootCP = ""; try { for (String resource : getJarFilesLocation(javaProject)) sootCP = sootCP + File.pathSeparator + resource; } catch (JavaModelException e) { } sootCP = sootCP + File.pathSeparator; return sootCP; } /** * @param javaProject * @return Set of the locations of jars for the soot classpath * @throws JavaModelException * * This method computes the locations of the jar files necessary for the soot run */ protected Set<String> getJarFilesLocation(IJavaProject javaProject) throws JavaModelException { Set<String> jars = new HashSet<>(); IClasspathEntry[] resolvedClasspath = javaProject.getResolvedClasspath(true); for (IClasspathEntry classpathEntry : resolvedClasspath) { String path = classpathEntry.getPath().toOSString(); File jar = new File(path); if (jar.exists() && path.endsWith(".jar")) { IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(classpathEntry.getPath()); if (file != null && file.getRawLocation() != null) path = file.getRawLocation().toOSString(); jars.add(path); } } return jars; } @SuppressWarnings("unused") private String getOutputLocation(IJavaProject project) { String outputLocation = ""; IPath path; try { path = project.getOutputLocation(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFolder folder = root.getFolder(path); outputLocation = folder.getLocation().toOSString(); } catch (JavaModelException e) { e.printStackTrace(); } return outputLocation; } private void fillDataModel(ICFGStructure icfg, List<VFClass> jimpleClasses) { DataModel data = ServiceUtil.getService(DataModel.class); data.setIcfg(icfg); data.setClassList(jimpleClasses); // data.setSelectedClass(jimpleClasses.get(0)); } public static final String BUILDER_ID = "JimpleBuilder.JimpleBuilder"; @Override protected IProject[] build(int kind, Map<String, String> args, IProgressMonitor monitor) throws CoreException { executeBuild = false; if(getProject() != null && getProject().getName().equals(GlobalSettings.get("AnalysisProject"))){ if (kind == FULL_BUILD) { fullBuild(monitor); } else { IResourceDelta delta = getDelta(getProject()); if (delta == null) { fullBuild(monitor); } else { checkForBuild(delta, monitor); } } } return null; } protected void fullBuild(IProgressMonitor monitor) throws CoreException{ Visuflow.getDefault().getLogger().info("Build Start"); String targetFolder = "sootOutput"; IJavaProject project = JavaCore.create(getProject()); IResourceDelta delta = getDelta(project.getProject()); if (delta == null || !delta.getAffectedChildren()[0].getProjectRelativePath().toString().equals(targetFolder)) { classpath = getSootCP(project); String location = GlobalSettings.get("Target_Path"); IFolder folder = project.getProject().getFolder(targetFolder); // at this point, no resources have been created if (!folder.exists()) { // Changed to force because of bug id vis-119 folder.create(IResource.FORCE, true, monitor); } else { for (IResource resource : folder.members()) { resource.delete(IResource.FORCE, monitor); } } classpath = location + classpath; String[] sootString = new String[] { "-cp", classpath, "-exclude", "javax", "-allow-phantom-refs", "-no-bodies-for-excluded", "-process-dir", location, "-src-prec", "only-class", "-w", "-output-format", "J", "-keep-line-number", "-output-dir", folder.getLocation().toOSString()/* , "tag.ln","on" */ }; ICFGStructure icfg = new ICFGStructure(); JimpleModelAnalysis analysis = new JimpleModelAnalysis(); analysis.setSootString(sootString); List<VFClass> jimpleClasses = new ArrayList<>(); try { analysis.createICFG(icfg, jimpleClasses); fillDataModel(icfg, jimpleClasses); } catch(Exception e) { logger.error("Couldn't execute analysis", e); } folder.refreshLocal(IResource.DEPTH_INFINITE, monitor); } } protected void checkForBuild(IResourceDelta delta, IProgressMonitor monitor) throws CoreException { delta.accept(new JimpleDeltaVisitor()); if(executeBuild){ fullBuild(monitor); executeBuild = false; } } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; /** * Provides logging services to this library and others which depend on this library in such a way * that they can be used in a larger project and easily be made to log to the logging framework in * use by that project. * * <p> The default implementation uses log4j if it is available and falls back to the Java logging * services if not. A specific (or custom) logging implementation can be configured like so: * <pre>-Dcom.samskivert.util.Logger=com.samskivert.util.Log4Logger</pre> * * <p> One additional enhancement is the use of varargs log methods to allow for some handy * automatic formatting. The methods take a log message and list of zero or more additional * parameters. Those parameters should be key/value pairs which will be logged like so: * <pre>message [key=value, key=value, key=value]</pre> * * <p> The final parameter can optionally be a Throwable, which will be supplied to the underlying * log system as an exception to accompany the log message. */ public abstract class Logger { /** * Used to create logger instances. This is only public so that the log factory can be * configured programmatically via {@link Logger#setFactory}. */ public static interface Factory { public void init (); public Logger getLogger (String name); public Logger getLogger (Class clazz); } /** * Obtains a logger with the specified name. */ public static Logger getLogger (String name) { return _factory.getLogger(name); } /** * Obtains a logger with a name equal to the supplied class's name. */ public static Logger getLogger (Class clazz) { return _factory.getLogger(clazz); } /** * Configures the logging factory be used by the logging system. Normally you would not do this * and would instead use the <code>com.samskivert.util.Logger</code> system property instead, * but in some situations, like in an applet, you cannot pass system properties and we can't * read them anyway because we're running in a security sandbox. */ public static void setFactory (Factory factory) { _factory = factory; _factory.init(); } /** * Logs a debug message. * * @param message the message to be logged. * @param args a list of key/value pairs and an optional final Throwable. */ public abstract void debug (Object message, Object... args); /** * Logs an info message. * * @param message the message to be logged. * @param args a list of key/value pairs and an optional final Throwable. */ public abstract void info (Object message, Object... args); /** * Logs a warning message. * * @param message the message to be logged. * @param args a list of key/value pairs and an optional final Throwable. */ public abstract void warning (Object message, Object... args); /** * Logs an error message. * * @param message the message to be logged. * @param args a list of key/value pairs and an optional final Throwable. */ public abstract void error (Object message, Object... args); /** * Format messages and arguments. For use by logger implementations. */ protected String format (Object message, Object[] args) { StringBuilder buf = new StringBuilder(); buf.append(message); if (args != null && args.length > 1) { buf.append(" ["); for (int ii = 0, nn = args.length/2; ii < nn; ii++) { if (ii > 0) { buf.append(", "); } buf.append(args[2*ii]).append("="); try { StringUtil.toString(buf, args[2*ii+1]); } catch (Throwable t) { buf.append("<toString() failure: " + t + ">"); } } buf.append("]"); } return buf.toString(); } /** * Extracts the exception from the message and arguments (if there is one). For use by logger * implementations. */ protected Throwable getException (Object message, Object[] args) { if (message instanceof Throwable) { return (Throwable)message; } else if (args.length % 2 == 1 && args[args.length-1] instanceof Throwable) { return (Throwable)args[args.length-1]; } else { return null; } } /** * Called at static initialization time. Selects and initializes our logging backend. */ protected static void initLogger () { // if a custom class was specified as a system property, use that Factory factory = createConfiguredFactory(); // create and a log4j logger if the log4j configuration system property is set try { if (factory == null && System.getProperty("log4j.configuration") != null) { factory = (Factory)Class.forName("com.samskivert.util.Log4JLogger").newInstance(); } } catch (SecurityException se) { // in a sandbox, no biggie } catch (Throwable t) { System.err.println("Unable to instantiate Log4JLogger: " + t); } // lastly, fall back to the Java logging system if (factory == null) { factory = new JDK14Logger(); } // and finally configure our factory setFactory(factory); } /** * A helper function for {@link #initLogger}. */ protected static Factory createConfiguredFactory () { String implClass; try { implClass = System.getProperty("com.samskivert.util.Log"); } catch (SecurityException se) { // in a sandbox return null; } if (!StringUtil.isBlank(implClass)) { try { return (Factory)Class.forName(implClass).newInstance(); } catch (Throwable t) { System.err.println("Unable to instantiate logging implementation: " + implClass); t.printStackTrace(System.err); } } return null; } protected static Factory _factory; static { initLogger(); } }
package org.apache.fop.apps; // FOP import org.apache.fop.area.AreaTree; import org.apache.fop.area.RenderPagesModel; import org.apache.fop.fo.ElementMapping; import org.apache.fop.fo.FOTreeBuilder; import org.apache.fop.fo.FOInputHandler; import org.apache.fop.fo.FOTreeHandler; import org.apache.fop.render.Renderer; import org.apache.fop.render.awt.AWTRenderer; import org.apache.fop.render.mif.MIFHandler; import org.apache.fop.render.rtf.RTFHandler; import org.apache.fop.tools.DocumentInputSource; import org.apache.fop.tools.DocumentReader; import org.apache.fop.layoutmgr.LayoutManagerLS; // Avalon import org.apache.avalon.framework.logger.ConsoleLogger; import org.apache.avalon.framework.logger.LogEnabled; import org.apache.avalon.framework.logger.Logger; // DOM /* org.w3c.dom.Document is not imported to reduce confusion with org.apache.fop.control.Document */ // SAX import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; // Java import java.io.IOException; import java.io.OutputStream; /** * Primary class that drives overall FOP process. * <P> * The simplest way to use this is to instantiate it with the * InputSource and OutputStream, then set the renderer desired, and * calling run(); * <P> * Here is an example use of Driver which outputs PDF: * * <PRE> * Driver driver = new Driver(new InputSource (args[0]), * new FileOutputStream(args[1])); * driver.enableLogging(myLogger); //optional * driver.setRenderer(RENDER_PDF); * driver.run(); * </PRE> * If neccessary, calling classes can call into the lower level * methods to setup and * render. Methods can be called to set the * Renderer to use, the (possibly multiple) ElementMapping(s) to * use and the OutputStream to use to output the results of the * rendering (where applicable). In the case of the Renderer and * ElementMapping(s), the Driver may be supplied either with the * object itself, or the name of the class, in which case Driver will * instantiate the class itself. The advantage of the latter is it * enables runtime determination of Renderer and ElementMapping(s). * <P> * Once the Driver is set up, the render method * is called. Depending on whether DOM or SAX is being used, the * invocation of the method is either render(Document) or * buildFOTree(Parser, InputSource) respectively. * <P> * A third possibility may be used to build the FO Tree, namely * calling getContentHandler() and firing the SAX events yourself. * <P> * Once the FO Tree is built, the format() and render() methods may be * called in that order. * <P> * Here is an example use of Driver which outputs to AWT: * * <PRE> * Driver driver = new Driver(); * driver.enableLogging(myLogger); //optional * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator)); * driver.render(parser, fileInputSource(args[0])); * </PRE> */ public class Driver implements LogEnabled { /** * private constant to indicate renderer was not defined. */ private static final int NOT_SET = 0; /** * Render to PDF. OutputStream must be set */ public static final int RENDER_PDF = 1; /** * Render to a GUI window. No OutputStream neccessary */ public static final int RENDER_AWT = 2; /** * Render to MIF. OutputStream must be set */ public static final int RENDER_MIF = 3; /** * Render to XML. OutputStream must be set */ public static final int RENDER_XML = 4; /** * Render to PRINT. No OutputStream neccessary */ public static final int RENDER_PRINT = 5; /** * Render to PCL. OutputStream must be set */ public static final int RENDER_PCL = 6; /** * Render to Postscript. OutputStream must be set */ public static final int RENDER_PS = 7; /** * Render to Text. OutputStream must be set */ public static final int RENDER_TXT = 8; /** * Render to SVG. OutputStream must be set */ public static final int RENDER_SVG = 9; /** * Render to RTF. OutputStream must be set */ public static final int RENDER_RTF = 10; /** * the FO tree builder */ private FOTreeBuilder treeBuilder; /** * the renderer type code given by setRenderer */ private int rendererType = NOT_SET; /** * the renderer to use to output the area tree */ private Renderer renderer; /** * the SAX ContentHandler */ private FOInputHandler foInputHandler; /** * the source of the FO file */ private InputSource source; /** * the stream to use to output the results of the renderer */ private OutputStream stream; /** * The XML parser to use when building the FO tree */ private XMLReader reader; /** * the system resources that FOP will use */ private Logger log = null; private FOUserAgent userAgent = null; private Document currentDocument = null; /** * Main constructor for the Driver class. */ public Driver() { stream = null; } /** * Convenience constructor for directly setting input and output. * @param source InputSource to take the XSL-FO input from * @param stream Target output stream */ public Driver(InputSource source, OutputStream stream) { this(); this.source = source; this.stream = stream; } private boolean isInitialized() { return (treeBuilder != null); } /** * Initializes the Driver object. */ public void initialize() { if (isInitialized()) { throw new IllegalStateException("Driver already initialized"); } treeBuilder = new FOTreeBuilder(); treeBuilder.setUserAgent(getUserAgent()); } /** * Optionally sets the FOUserAgent instance for FOP to use. The Driver * class sets up its own FOUserAgent if none is set through this method. * @param agent FOUserAgent to use */ public void setUserAgent(FOUserAgent agent) { userAgent = agent; } protected FOUserAgent getUserAgent() { if (userAgent == null) { userAgent = new FOUserAgent(); userAgent.enableLogging(getLogger()); userAgent.setBaseURL(""); } return userAgent; } public void enableLogging(Logger log) { if (this.log == null) { this.log = log; } else { getLogger().warn("Logger is already set! Won't use the new logger."); } } /** * Provide the Driver instance with a logger. * @param log the logger. Must not be <code>null</code>. * @deprecated Use #enableLogging(Logger) instead. */ public void setLogger(Logger log) { enableLogging(log); } /** * Returns the logger for use by FOP. * @return the logger * @see #enableLogging(Logger) */ public Logger getLogger() { if (this.log == null) { // use ConsoleLogger as default when logger not explicitly set this.log = new ConsoleLogger(ConsoleLogger.LEVEL_INFO); } return this.log; } /** * Resets the Driver so it can be reused. Property and element * mappings are reset to defaults. * The output stream is cleared. The renderer is cleared. */ public synchronized void reset() { source = null; stream = null; reader = null; if (treeBuilder != null) { treeBuilder.reset(); } } /** * Indicates whether FOP has already received input data. * @return true, if input data was received */ public boolean hasData() { return (treeBuilder.hasData()); } /** * Set the OutputStream to use to output the result of the Renderer * (if applicable) * @param stream the stream to output the result of rendering to */ public void setOutputStream(OutputStream stream) { this.stream = stream; } private void validateOutputStream() { if (this.stream == null) { throw new IllegalStateException("OutputStream has not been set"); } } /** * Set the source for the FO document. This can be a normal SAX * InputSource, or an DocumentInputSource containing a DOM document. * @see DocumentInputSource */ public void setInputSource(InputSource source) { this.source = source; } /** * Sets the reader used when reading in the source. If not set, * this defaults to a basic SAX parser. * @param reader the reader to use. */ public void setXMLReader(XMLReader reader) { this.reader = reader; } public void setRenderer(int renderer) throws IllegalArgumentException { rendererType = renderer; switch (renderer) { case RENDER_PDF: setRenderer("org.apache.fop.render.pdf.PDFRenderer"); break; case RENDER_AWT: throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT"); case RENDER_PRINT: setRenderer("org.apache.fop.render.awt.AWTPrintRenderer"); break; case RENDER_PCL: setRenderer("org.apache.fop.render.pcl.PCLRenderer"); break; case RENDER_PS: setRenderer("org.apache.fop.render.ps.PSRenderer"); break; case RENDER_TXT: setRenderer("org.apache.fop.render.txt.TXTRenderer()"); break; case RENDER_MIF: //foInputHandler will be set later break; case RENDER_XML: setRenderer("org.apache.fop.render.xml.XMLRenderer"); break; case RENDER_SVG: setRenderer("org.apache.fop.render.svg.SVGRenderer"); break; case RENDER_RTF: //foInputHandler will be set later break; default: rendererType = NOT_SET; throw new IllegalArgumentException("Unknown renderer type " + renderer); } } /** * Set the Renderer to use. * @param renderer the renderer instance to use (Note: Logger must be set at this point) */ public void setRenderer(Renderer renderer) { // AWTStarter calls this function directly if (renderer instanceof AWTRenderer) { rendererType = RENDER_AWT; } renderer.setProducer(Version.getVersion()); renderer.setUserAgent(getUserAgent()); this.renderer = renderer; } /** * Returns the currently active renderer. * @return the renderer */ public Renderer getRenderer() { return renderer; } public void setRenderer(String rendererClassName) throws IllegalArgumentException { try { renderer = (Renderer)Class.forName(rendererClassName).newInstance(); if (renderer instanceof LogEnabled) { ((LogEnabled)renderer).enableLogging(getLogger()); } renderer.setProducer(Version.getVersion()); renderer.setUserAgent(getUserAgent()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + rendererClassName); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + rendererClassName); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + rendererClassName); } catch (ClassCastException e) { throw new IllegalArgumentException(rendererClassName + " is not a renderer"); } } /** * Add the given element mapping. * An element mapping maps element names to Java classes. * * @param mapping the element mappingto add */ public void addElementMapping(ElementMapping mapping) { treeBuilder.addElementMapping(mapping); } /** * Add the element mapping with the given class name. * @param mappingClassName the class name representing the element mapping. */ public void addElementMapping(String mappingClassName) { treeBuilder.addElementMapping(mappingClassName); } /** * Determines which SAX ContentHandler is appropriate for the rendererType. * Structure renderers (e.g. MIF & RTF) each have a specialized * ContentHandler that directly place data into the output stream. Layout * renderers (e.g. PDF & PostScript) use a ContentHandler that builds an FO * Tree. * @return a SAX ContentHandler for handling the SAX events. */ public ContentHandler getContentHandler() { if (!isInitialized()) { initialize(); } if (rendererType != RENDER_PRINT && rendererType != RENDER_AWT) { validateOutputStream(); } /** Document creation is hard-wired for now, but needs to be made accessible through the API and/or configuration */ if (currentDocument == null) { currentDocument = new Document(this); } /** LayoutStrategy is hard-wired for now, but needs to be made accessible through the API and/or configuration */ if (foInputHandler instanceof FOTreeHandler) { if (currentDocument.getLayoutStrategy() == null) { currentDocument.setLayoutStrategy(new LayoutManagerLS(currentDocument)); } } // TODO: - do this stuff in a better way if (rendererType == RENDER_MIF) { foInputHandler = new MIFHandler(currentDocument, stream); } else if (rendererType == RENDER_RTF) { foInputHandler = new RTFHandler(currentDocument, stream); } else { if (renderer == null) { throw new IllegalStateException( "Renderer not set when using standard foInputHandler"); } foInputHandler = new FOTreeHandler(currentDocument, true); } currentDocument.foInputHandler = foInputHandler; foInputHandler.enableLogging(getLogger()); treeBuilder.setUserAgent(getUserAgent()); treeBuilder.setFOInputHandler(foInputHandler); treeBuilder.foTreeControl = currentDocument; return treeBuilder; } /** * Render the FO document read by a SAX Parser from an InputHandler * @param inputHandler the input handler containing the source and * parser information. * @throws FOPException if anything goes wrong. */ public synchronized void render(InputHandler inputHandler) throws FOPException { XMLReader parser = inputHandler.getParser(); render(parser, inputHandler.getInputSource()); } /** * This is the main render() method. The other render() methods are for * convenience, and normalize to this form, then run this. * Renders the FO document read by a SAX Parser from an InputSource. * @param parser the SAX parser. * @param source the input source the parser reads from. * @throws FOPException if anything goes wrong. */ public synchronized void render(XMLReader parser, InputSource source) throws FOPException { parser.setContentHandler(getContentHandler()); try { if (foInputHandler instanceof FOTreeHandler) { FOTreeHandler foTreeHandler = (FOTreeHandler)foInputHandler; foTreeHandler.addFOTreeListener(currentDocument); currentDocument.areaTree = new AreaTree(currentDocument); currentDocument.atModel = new RenderPagesModel(renderer); //this.atModel = new CachedRenderPagesModel(renderer); currentDocument.areaTree.setTreeModel(currentDocument.atModel); try { renderer.setupFontInfo(currentDocument); // check that the "any,normal,400" font exists if (!currentDocument.isSetupValid()) { throw new SAXException(new FOPException( "No default font defined by OutputConverter")); } renderer.startRenderer(stream); } catch (IOException e) { throw new SAXException(e); } } /** The following statement triggers virtually all of the processing for this document. The SAX parser fires events that are handled by the appropriate InputHandler object, which means that you will need to look in those objects to see where FOP picks up control of processing again. For Structure Renderers (e.g. MIF & RTF), the SAX events are handled directly. For Layout Renderers (e.g. PDF & PostScript), an FO Tree is built by the FOTreeHandler, which in turn fires events when a PageSequence object is complete. This allows higher-level control objects (such as this class) to work directly with PageSequence objects. See foPageSequenceComplete() where this level of control is implemented. */ parser.parse(source); if (foInputHandler instanceof FOTreeHandler) { FOTreeHandler foTreeHandler = (FOTreeHandler)foInputHandler; foTreeHandler.removeFOTreeListener(currentDocument); } } catch (SAXException e) { if (e.getException() instanceof FOPException) { // Undo exception tunneling. throw (FOPException)e.getException(); } else { throw new FOPException(e); } } catch (IOException e) { throw new FOPException(e); } } /** * This method overloads the main render() method, adding the convenience * of using a DOM Document as input. * @see #render(XMLReader, InputSource) * @param document the DOM document to read from * @throws FOPException if anything goes wrong. */ public synchronized void render(org.w3c.dom.Document document) throws FOPException { DocumentInputSource source = new DocumentInputSource(document); DocumentReader reader = new DocumentReader(); render(reader, source); } /** * Runs the formatting and renderering process using the previously set * parser, input source, renderer and output stream. * If the renderer was not set, default to PDF. * If no parser was set, and the input source is not a dom document, * get a default SAX parser. * @throws IOException in case of IO errors. * @throws FOPException if anything else goes wrong. */ public synchronized void run() throws IOException, FOPException { if (!isInitialized()) { initialize(); } if (renderer == null && rendererType != RENDER_RTF && rendererType != RENDER_MIF) { setRenderer(RENDER_PDF); } if (source == null) { throw new FOPException("InputSource is not set."); } if (reader == null) { if (!(source instanceof DocumentInputSource)) { reader = FOFileHandler.createParser(); } } if (source instanceof DocumentInputSource) { render(((DocumentInputSource)source).getDocument()); } else { render(reader, source); } } /** * Public accessor for setting the currentDocument to process. * @param document the Document object that should be processed. */ public void setCurrentDocument(Document document) { currentDocument = document; } /** * Public accessor for getting the currentDocument * @return the currentDocument */ public Document getCurrentDocument() { return currentDocument; } }
package edu.caravane.guitare.gitobejct; import java.util.HashMap; //18h19 -> 18h26 public class GitObjectsIndex { protected HashMap<String, GitObject> hashMap; public GitObjectsIndex() { hashMap = new HashMap<String, GitObject>(); } /** * This function retrieve a git object (already indexed) by his hash (sha1) * * @author VieVie31 * * @param sha1 the hash of the git object to retrieve * @return a git object */ public GitObject get(String sha1) { return hashMap.get(sha1); } /** * This function put (index) a git object by his hash value (sha1) * * @author VieVie31 * * @param sha1 the hash of the git object * @param gitObject the git object */ public void put(String sha1, GitObject gitObject) { hashMap.put(sha1, gitObject); } }
package jmetest.renderer; import java.nio.FloatBuffer; import com.jme.app.SimpleGame; import com.jme.bounding.BoundingSphere; import com.jme.image.Texture; import com.jme.input.InputSystem; import com.jme.input.KeyBindingManager; import com.jme.input.KeyInput; import com.jme.input.NodeHandler; import com.jme.light.DirectionalLight; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.Line; import com.jme.scene.Node; import com.jme.scene.Text; import com.jme.scene.shape.Box; import com.jme.scene.state.AlphaState; import com.jme.scene.state.CullState; import com.jme.scene.state.LightState; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; import com.jme.util.TextureManager; import com.jme.util.geom.BufferUtils; /** * <code>TestScenegraph</code> * * @author Mark Powell * @version $Id: TestScenegraph.java,v 1.27 2005-09-25 23:54:45 renanse Exp $ */ public class TestScenegraph extends SimpleGame { private Node scene; private NodeHandler nc1, nc2, nc3, nc4, nc5, nc6; private Box box1, box2, box3, box4, box5, box6; private Box selectionBox; private Node node1, node2, node3, node4, node5, node6; private Text text; private Node selectedNode; private TextureState ts, ts2, ts3; private KeyInput key; private Line line; /** * Entry point for the test, * * @param args */ public static void main(String[] args) { TestScenegraph app = new TestScenegraph(); app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG); app.start(); } protected void simpleUpdate() { input.update(timer.getTimePerFrame()); updateLines(); selectionBox.setLocalTranslation(selectedNode.getWorldTranslation()); selectionBox.setLocalRotation(selectedNode.getWorldRotation()); if (KeyBindingManager.getKeyBindingManager().isValidCommand("tex1", false)) { selectedNode.setRenderState(ts); selectedNode.updateRenderState(); } if (KeyBindingManager.getKeyBindingManager().isValidCommand("tex2", false)) { selectedNode.setRenderState(ts2); rootNode.updateRenderState(); } if (KeyBindingManager.getKeyBindingManager().isValidCommand("tex3", false)) { selectedNode.setRenderState(ts3); rootNode.updateRenderState(); } if (KeyBindingManager.getKeyBindingManager().isValidCommand("notex", false)) { selectedNode.clearRenderState(RenderState.RS_TEXTURE); rootNode.updateRenderState(); } } private void updateLines() { scene.updateGeometricState(0, true); FloatBuffer lineVerts = line.getVertexBuffer(); lineVerts.rewind(); BufferUtils.setInBuffer(node1.getWorldTranslation(), lineVerts, 0); BufferUtils.setInBuffer(node2.getWorldTranslation(), lineVerts, 1); BufferUtils.setInBuffer(node1.getWorldTranslation(), lineVerts, 2); BufferUtils.setInBuffer(node3.getWorldTranslation(), lineVerts, 3); BufferUtils.setInBuffer(node2.getWorldTranslation(), lineVerts, 4); BufferUtils.setInBuffer(node4.getWorldTranslation(), lineVerts, 5); BufferUtils.setInBuffer(node2.getWorldTranslation(), lineVerts, 6); BufferUtils.setInBuffer(node5.getWorldTranslation(), lineVerts, 7); BufferUtils.setInBuffer(node3.getWorldTranslation(), lineVerts, 8); BufferUtils.setInBuffer(node6.getWorldTranslation(), lineVerts, 9); } /** * builds the trimesh. * * @see com.jme.app.SimpleGame#initGame() */ protected void simpleInitGame() { rootNode.setRenderQueueMode(Renderer.QUEUE_OPAQUE); fpsNode.setRenderQueueMode(Renderer.QUEUE_OPAQUE); Vector3f loc = new Vector3f(0.0f, 0.0f, -100.0f); Vector3f left = new Vector3f(1.0f, 0.0f, 0.0f); Vector3f up = new Vector3f(0.0f, 1.0f, 0.0f); Vector3f dir = new Vector3f(0.0f, 0f, 1.0f); cam.setFrame(loc, left, up, dir); cam.update(); display.setTitle("Test Scene Graph"); lightState.setEnabled(false); key = InputSystem.getKeyInput(); KeyBindingManager.getKeyBindingManager().setKeyInput(key); KeyBindingManager.getKeyBindingManager().set("notex", KeyInput.KEY_7); KeyBindingManager.getKeyBindingManager().set("tex1", KeyInput.KEY_8); KeyBindingManager.getKeyBindingManager().set("tex2", KeyInput.KEY_9); KeyBindingManager.getKeyBindingManager().set("tex3", KeyInput.KEY_0); KeyBindingManager.getKeyBindingManager().set("tog_bounds", KeyInput.KEY_B); Vector3f min = new Vector3f(-5, -5, -5); Vector3f max = new Vector3f(5, 5, 5); AlphaState as1 = display.getRenderer().createAlphaState(); as1.setBlendEnabled(true); as1.setSrcFunction(AlphaState.SB_SRC_ALPHA); as1.setDstFunction(AlphaState.DB_ONE); as1.setTestEnabled(true); as1.setTestFunction(AlphaState.TF_GREATER); as1.setEnabled(true); DirectionalLight dr = new DirectionalLight(); dr.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f)); dr.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); dr.setDirection(new Vector3f(0, 0, 150)); dr.setEnabled(true); lightState.detachAll(); lightState.attach(dr); text = new Text("Selected Node", "Selected Node: Node 1"); text.setLocalTranslation(new Vector3f(0, 20, 0)); fpsNode.attachChild(text); scene = new Node("3D Scene Node"); CullState cs = display.getRenderer().createCullState(); cs.setCullMode(CullState.CS_BACK); cs.setEnabled(true); rootNode.setRenderState(cs); selectionBox = new Box("Selection", min.mult(1.25f), max.mult(1.25f)); selectionBox.setDefaultColor(new ColorRGBA(0, .6f, 0, 0.3f)); selectionBox.setRenderState(as1); selectionBox.setModelBound(new BoundingSphere()); selectionBox.updateModelBound(); selectionBox.setLightCombineMode(LightState.OFF); selectionBox.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT); node1 = new Node("Node 1"); box1 = new Box("Box 1", min, max); node1.attachChild(box1); node1.setLocalTranslation(new Vector3f(0, 30, 0)); selectedNode = node1; box1.setModelBound(new BoundingSphere()); box1.updateModelBound(); node2 = new Node("Node 2"); box2 = new Box("Box 2", min, max); node2.attachChild(box2); node1.attachChild(node2); node2.setLocalTranslation(new Vector3f(-20, -20, 0)); box2.setModelBound(new BoundingSphere()); box2.updateModelBound(); node3 = new Node("Node 3"); box3 = new Box("Box 3", min, max); node3.attachChild(box3); node1.attachChild(node3); node3.setLocalTranslation(new Vector3f(20, -20, 0)); box3.setModelBound(new BoundingSphere()); box3.updateModelBound(); node4 = new Node("Node 4"); box4 = new Box("Box 4", min, max); node4.attachChild(box4); node2.attachChild(node4); node4.setLocalTranslation(new Vector3f(-20, -20, 0)); box4.setModelBound(new BoundingSphere()); box4.updateModelBound(); node5 = new Node("Node 5"); box5 = new Box("Box 5", min, max); node5.attachChild(box5); node2.attachChild(node5); node5.setLocalTranslation(new Vector3f(20, -20, 0)); box5.setModelBound(new BoundingSphere()); box5.updateModelBound(); node6 = new Node("Node 6"); box6 = new Box("Box 6", min, max); node6.attachChild(box6); node3.attachChild(node6); node6.setLocalTranslation(new Vector3f(0, -20, 0)); box6.setModelBound(new BoundingSphere()); box6.updateModelBound(); FloatBuffer verts = BufferUtils.createVector3Buffer(10); // 5 lines, 2 endpoints each line = new Line("Connection", verts, null, null, null); line.setLightCombineMode(LightState.OFF); line.setLineWidth(2.5f); line.setStipplePattern((short)0xAAAA); line.setStippleFactor(5); ts = display.getRenderer().createTextureState(); ts.setEnabled(true); Texture t1 = TextureManager.loadTexture( TestScenegraph.class.getClassLoader().getResource( "jmetest/data/images/Monkey.jpg"), Texture.MM_LINEAR, Texture.FM_LINEAR); ts.setTexture(t1); ts2 = display.getRenderer().createTextureState(); ts2.setEnabled(true); Texture t2 = TextureManager.loadTexture(TestScenegraph.class .getClassLoader().getResource("jmetest/data/texture/dirt.jpg"), Texture.MM_LINEAR, Texture.FM_LINEAR); ts2.setTexture(t2); ts3 = display.getRenderer().createTextureState(); ts3.setEnabled(true); Texture t3 = TextureManager.loadTexture(TestScenegraph.class .getClassLoader().getResource( "jmetest/data/texture/snowflake.png"), Texture.MM_LINEAR, Texture.FM_LINEAR); ts3.setTexture(t3); node1.setRenderState(ts); scene.attachChild(node1); rootNode.attachChild(line); rootNode.attachChild(scene); scene.attachChild(selectionBox); nc1 = new NodeHandler(this, node1, "LWJGL"); nc2 = new NodeHandler(this, node2, "LWJGL"); nc3 = new NodeHandler(this, node3, "LWJGL"); nc4 = new NodeHandler(this, node4, "LWJGL"); nc5 = new NodeHandler(this, node5, "LWJGL"); nc6 = new NodeHandler(this, node6, "LWJGL"); nc1.setKeySpeed(5); nc1.setMouseSpeed(1); nc2.setKeySpeed(5); nc2.setMouseSpeed(1); nc3.setKeySpeed(5); nc3.setMouseSpeed(1); nc4.setKeySpeed(5); nc4.setMouseSpeed(1); nc5.setKeySpeed(5); nc5.setMouseSpeed(1); nc6.setKeySpeed(5); nc6.setMouseSpeed(1); input = nc1; KeyBindingManager keyboard = KeyBindingManager.getKeyBindingManager(); keyboard.set("node1", KeyInput.KEY_1); keyboard.set("node2", KeyInput.KEY_2); keyboard.set("node3", KeyInput.KEY_3); keyboard.set("node4", KeyInput.KEY_4); keyboard.set("node5", KeyInput.KEY_5); keyboard.set("node6", KeyInput.KEY_6); TestNodeSelectionAction s1 = new TestNodeSelectionAction(this, 1); s1.setKey("node1"); nc1.addAction(s1); nc2.addAction(s1); nc3.addAction(s1); nc4.addAction(s1); nc5.addAction(s1); nc6.addAction(s1); TestNodeSelectionAction s2 = new TestNodeSelectionAction(this, 2); s2.setKey("node2"); nc1.addAction(s2); nc2.addAction(s2); nc3.addAction(s2); nc4.addAction(s2); nc5.addAction(s2); nc6.addAction(s2); TestNodeSelectionAction s3 = new TestNodeSelectionAction(this, 3); s3.setKey("node3"); nc1.addAction(s3); nc2.addAction(s3); nc3.addAction(s3); nc4.addAction(s3); nc5.addAction(s3); nc6.addAction(s3); TestNodeSelectionAction s4 = new TestNodeSelectionAction(this, 4); s4.setKey("node4"); nc1.addAction(s4); nc2.addAction(s4); nc3.addAction(s4); nc4.addAction(s4); nc5.addAction(s4); nc6.addAction(s4); TestNodeSelectionAction s5 = new TestNodeSelectionAction(this, 5); s5.setKey("node5"); nc1.addAction(s5); nc2.addAction(s5); nc3.addAction(s5); nc4.addAction(s5); nc5.addAction(s5); nc6.addAction(s5); TestNodeSelectionAction s6 = new TestNodeSelectionAction(this, 6); s6.setKey("node6"); nc1.addAction(s6); nc2.addAction(s6); nc3.addAction(s6); nc4.addAction(s6); nc5.addAction(s6); nc6.addAction(s6); } public void setSelectedNode(int node) { switch (node) { case 1: input = nc1; text.print("Selected Node: Node 1"); selectedNode = node1; break; case 2: input = nc2; text.print("Selected Node: Node 2"); selectedNode = node2; break; case 3: input = nc3; text.print("Selected Node: Node 3"); selectedNode = node3; break; case 4: input = nc4; text.print("Selected Node: Node 4"); selectedNode = node4; break; case 5: input = nc5; text.print("Selected Node: Node 5"); selectedNode = node5; break; case 6: input = nc6; text.print("Selected Node: Node 6"); selectedNode = node6; break; } } }
package edu.chl.dat255.sofiase.readyforapet; import Model.Dog; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class SelectGame extends Activity { TextView warningMessage; Button yes, no; Runnable makeTextGone = new Runnable(){ @Override public void run(){//kolla om detta fungerar nr vi kan spara! yes.setVisibility(View.GONE); no.setVisibility(View.GONE); warningMessage.setVisibility(View.GONE); } }; /** * onCreate method * * @param savedInstanceState - Bundle */ @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView(R.layout.selectgame); Button yes = (Button) findViewById(R.id.yes); yes.setVisibility(View.GONE); Button no = (Button) findViewById(R.id.no); no.setVisibility(View.GONE); //The continue button reacts to a click and starts PetActivity Button continuePreviousGame = (Button) findViewById(R.id.continuegame); continuePreviousGame.setOnClickListener(new OnClickListener() { /** * Method onClick for the continue previous game button * * @param v - View */ public void onClick (View v){ if (CreatePet.getPet() != null){ startActivity(new Intent(SelectGame.this, PetActivity.class)); } else{ warningMessage = (TextView) findViewById(R.id.warningmessage); warningMessage.setText("Create a pet first!"); } } } ); //What happens when you button create new pet is pushed Button createNewPet = (Button) findViewById(R.id.createnewpet); createNewPet.setOnClickListener(new OnClickListener() { /** * Method onClick for the create new pet button * * @param v - View */ public void onClick (View v){ if (CreatePet.getPet() != null){ warningMessage = (TextView) findViewById(R.id.warningmessage); warningMessage.setText("Are you sure you want to create a new pet and delete your old one?"); Button yes = (Button) findViewById(R.id.yes); yes.setVisibility(View.VISIBLE); yes.setOnClickListener(new OnClickListener() { public void onClick (View v){ startActivity(new Intent(SelectGame.this, CreatePet.class)); //delete old pet from file here later } } ); Button no = (Button) findViewById(R.id.no); no.setVisibility(View.VISIBLE); no.setOnClickListener(new OnClickListener() { public void onClick (View v){ startActivity(new Intent(SelectGame.this, SelectGame.class));//kan man gra s? man kan inte no yes och no annars utan att def knapparna igen? } } ); } else{ startActivity(new Intent(SelectGame.this, CreatePet.class)); } } } ); } }
package joshua.decoder.ff; import java.util.List; import joshua.corpus.Vocabulary; import joshua.decoder.chart_parser.SourcePath; import joshua.decoder.ff.state_maintenance.DPState; import joshua.decoder.ff.tm.Rule; import joshua.decoder.hypergraph.HGNode; /** * This feature handles the list of features that are found with grammar rules in the grammar file. * dense features that may be associated with the rules in a grammar file. The feature names of * these dense rules are a function of the phrase model owner. When the feature is loaded, it * queries the weights for the set of features that are active for this grammar, storing them in an * array. * * @author Matt Post <post@cs.jhu.edu> * @author Zhifei Li <zhifei.work@gmail.com> */ public class PhraseModelFF extends StatelessFF { /* The owner of the grammar. */ private int ownerID; public PhraseModelFF(FeatureVector weights, String owner) { super(weights, "tm_" + owner, ""); /* * This is an efficiency hack; we cache the full dot product of the weights with the dense * features, storing them as a value under the name "tm_OWNER". There won't be a weight for * that, so we add a weight to the weights vector. This weight will never be output because when * the k-best list is retrieved and the actual feature values asked for, the accumulator will * fetch the fine-grained dense features. */ if (weights.containsKey(name)) { System.err.println(String.format( "* FATAL: Your weights file contains an entry for '%s', shouldn't", name)); System.exit(1); } weights.put(name, 1.0f); // Store the owner. this.ownerID = Vocabulary.id(owner); } @Override public float estimateCost(final Rule rule, int sentID) { return computeCost(rule, null, -1, -1, null, sentID); } /** * Just chain to computeFeatures(rule), since this feature doesn't use the sourcePath or sentID. * */ @Override public DPState compute(Rule rule, List<HGNode> tailNodes, int i, int j, SourcePath sourcePath, int sentID, Accumulator acc) { if (rule != null && rule.getOwner() == ownerID) { /* * Here, we peak at the Accumulator object. If it's asking for scores, then we don't bother to * add each feature, but rather compute the inner product and add *that*. This is totally * cheating; the Accumulator is supposed to be a generic object. But without this cheat */ if (acc instanceof ScoreAccumulator) { if (rule.getPrecomputableCost() <= Float.NEGATIVE_INFINITY) { float score = rule.getFeatureVector().innerProduct(weights); rule.setPrecomputableCost(score); } acc.add(name, rule.getPrecomputableCost()); } else { FeatureVector features = rule.getFeatureVector(); for (String key : features.keySet()) acc.add(key, features.get(key)); } } return null; } public String toString() { return name + " " + Vocabulary.word(ownerID); } }
package edu.mit.streamjit.api; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A WeightedRoundrobinJoiner joins its input by taking data items from its * children according to specified weights. A WeightedRoundrobinJoiner with * weights [1, 2, 1] will take one item from its first parent, two items from * its second parent, and one item from its third parent per iteration. * * TODO: see WeightedRoundrobinSplitter for details about this class' necessity * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 11/7/2012 */ public class WeightedRoundrobinJoiner<T> extends Joiner<T, T> { private final int[] weights; public WeightedRoundrobinJoiner(int... weights) { this.weights = weights; } @Override public void work() { for (int i = 0; i < inputs(); ++i) for (int j = 0; j < weights[i]; ++j) push(pop(i)); } @Override public int supportedInputs() { return weights.length; } @Override public List<Rate> getPeekRates() { //We don't peek. return Collections.nCopies(inputs(), Rate.create(0)); } @Override public List<Rate> getPopRates() { List<Rate> r = new ArrayList<>(); for (int w : weights) r.add(Rate.create(w)); return Collections.unmodifiableList(r); } @Override public List<Rate> getPushRates() { int sum = 0; for (int w : weights) sum += w; return Collections.singletonList(Rate.create(sum)); } }
package emergencylanding.k.library.lwjgl.tex; import java.awt.Color; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.image.Raster; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.WritableRaster; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL30; import emergencylanding.k.library.debug.Memory; import emergencylanding.k.library.exceptions.lwjgl.TextureBindException0; import emergencylanding.k.library.lwjgl.render.GLData; import emergencylanding.k.library.main.KMain; import emergencylanding.k.library.util.LUtils; public abstract class ELTexture { public static class DestTexture extends ELTexture { public DestTexture(ELTexture texture) { buf = ByteBuffer.allocateDirect(1); dim = new Dimension(1, 1); setConstructingOverrideId(texture.id); init(); ELTexture.texlist.remove(getID()); ELTexture.currentSpace -= buf.capacity(); ELTexture.removedIDs.add(getID()); GL11.glDeleteTextures(getID()); texture.destruction0(); } @Override public void setup() { } @Override protected BufferedImage toBufferedImageAbstract() { throw new UnsupportedOperationException("This texture is removed"); } @Override protected void onDestruction() { } } private int id = -1; private int useID = -1; static { System.gc(); } public static final long TOTAL_TEXTURE_SPACE = Runtime.getRuntime() .maxMemory() * 2 / 3; // private static IntBuffer ids = BufferUtils.createIntBuffer(1); private static HashMap<Integer, ELTexture> texlist = new HashMap<Integer, ELTexture>(); private static ArrayList<Integer> removedIDs = new ArrayList<Integer>(); public static long currentSpace = 0; public ByteBuffer buf = null; public Dimension dim = null; private static ArrayList<Runnable> glThreadQueue = new ArrayList<Runnable>(); static { System.gc(); Memory.printAll(); } // Define static Textures AFTER this comment public static final ELTexture invisible = new ColorTexture(new Color(0, 0, 0, 0), new Dimension(1, 1)); public ELTexture() { } private void bind0() { final ELTexture texObj = this; Runnable runnable = null; synchronized (glThreadQueue) { glThreadQueue.add(runnable = new Runnable() { @Override public void run() { if (buf == null || dim == null) { throw new TextureBindException0( "A required variable is null when creating textures!"); } else if (buf.capacity() < dim.height * dim.width * 4) { ByteBuffer tmp = ByteBuffer.allocateDirect(dim.height * dim.width * 4); tmp.put(buf); buf = tmp; buf.rewind(); } buf.rewind(); ELTexture lookAlike; if ((lookAlike = ELTexture.similar(texObj)) != null) { id = lookAlike.id; LUtils.print("Overrode id: " + id + " (obj=" + texObj + ", overridden=" + lookAlike + ")"); if (LUtils.debugLevel > 3) { new Throwable().printStackTrace(); } ELTexture.texlist.put(lookAlike.id, texObj); } else { boolean override = false; ELTexture.currentSpace += buf.capacity(); if (ELTexture.removedIDs.size() > 0 && useID == -1) { id = ELTexture.removedIDs.get(0); ELTexture.removedIDs.remove(0); } if (useID > -1) { override = true; id = useID; LUtils.print("Force-overrode id: " + id); if (ELTexture.texlist.get(id) != null) { ELTexture.currentSpace -= ELTexture.texlist .get(id).buf.capacity(); } else { LUtils.print("Interesting, it appears that id " + id + " is null. This shouldn't be happening, but we'll let it slide for now."); } } if (ELTexture.currentSpace < ELTexture.TOTAL_TEXTURE_SPACE && id == -1 && useID == -1) { id = GL11.glGenTextures(); } else if (id == -1 && useID == -1) { LUtils.print("WARNING! Texture limit reached, " + "not adding new textures! (" + TOTAL_TEXTURE_SPACE + " < " + currentSpace + ")"); return; } // Create a new texture object in memory and bind it GL13.glActiveTexture(GL13.GL_TEXTURE0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, id); // All RGB bytes are aligned to each other and each // component is 1 // byte GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); // Upload the texture data and generate mip maps (for // scaling) if (override) { GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, dim.width, dim.height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf); } else { GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, dim.width, dim.height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf); } GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); ELTexture.texlist.put(id, texObj); } } }); } if (Thread.currentThread() == KMain.getDisplayThread()) { runnable.run(); glThreadQueue.remove(runnable); } while (glThreadQueue.contains(runnable)) { try { Thread.sleep(1); } catch (Exception e) { } } } private static ELTexture similar(ELTexture texture) { ELTexture t1 = null; for (ELTexture t : ELTexture.texlist.values()) { if (t.isLookAlike(texture)) { t1 = t; break; } } return t1; } public static void doBindings() { synchronized (glThreadQueue) { for (Runnable r : glThreadQueue) { r.run(); } glThreadQueue.clear(); } } public boolean isLookAlike(ELTexture t) { return t.buf.equals(buf) && t.dim.equals(dim); } @Override public boolean equals(Object o) { return o instanceof ELTexture && isLookAlike((ELTexture) o); } public abstract void setup(); public int getID() { return id; } public void bind() { GL13.glActiveTexture(GL13.GL_TEXTURE0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, getID()); } public void unbind() { GL13.glActiveTexture(GL13.GL_TEXTURE0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, GLData.NONE); } public void glTextureVertex(float s, float t) { GL11.glTexCoord2f(s, t); } public int getWidth() { return dim.width; } public int getHeight() { return dim.height; } protected void init() { setup(); bind0(); } protected void setConstructingOverrideId(int id) { useID = id; } public BufferedImage toBufferedImage() { try { return toBufferedImageAbstract(); } catch (Exception e) { new IllegalStateException( "Didn't expect an error, running on backup", e) .printStackTrace(); return toBufferedImageBackup(); } } protected abstract BufferedImage toBufferedImageAbstract(); private BufferedImage toBufferedImageBackup() { int width = dim.width; int height = dim.height; int[] packedPixels = new int[width * height * 4]; buf.rewind(); // DisplayLayer.print("id " + id + " buf capacity " + buf.capacity()); int bufferInd = 0; for (int row = height - 1; row >= 0; row for (int col = 0; col < width; col++) { int R, G, B, A; R = buf.get(bufferInd++); G = buf.get(bufferInd++); B = buf.get(bufferInd++); A = buf.get(bufferInd++) & 0xff; int index = row * width + col; // DisplayLayer.print("recv " + R + "-" + G + "-" + B + "-" + packedPixels[index] = B + (G << 8) + (R << 16) + (A << 24); } } BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int bitMask[] = new int[] { 0xff0000, 0xff00, 0xff, 0xff000000 }; SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel( DataBuffer.TYPE_INT, width, height, bitMask); WritableRaster wr = Raster.createWritableRaster(sampleModel, null); wr.setPixels(0, 0, width, height, packedPixels); img.setData(wr); return img; } public void kill() { if (removedIDs.contains(this.id)) { return; } new DestTexture(this); System.gc(); } private void destruction0() { unbind(); onDestruction(); } protected abstract void onDestruction(); }
package am.app.mappingEngine; import java.util.EnumSet; import java.util.Enumeration; import java.util.Iterator; import am.app.feedback.FeedbackLoop; import am.app.feedback.InitialMatchers; import am.app.mapEngine.instance.BaseInstanceMatcher; import am.app.mappingEngine.Combination.CombinationMatcher; import am.app.mappingEngine.LexicalMatcherJAWS.LexicalMatcherJAWS; import am.app.mappingEngine.LexicalMatcherJWNL.LexicalMatcherJWNL; //import am.app.mappingEngine.LexicalMatcherUMLS.LexicalMatcherUMLS; import am.app.mappingEngine.PRAMatcher.OldPRAMatcher; import am.app.mappingEngine.PRAMatcher.PRAMatcher; import am.app.mappingEngine.PRAMatcher.PRAMatcher2; import am.app.mappingEngine.PRAintegration.PRAintegrationMatcher; import am.app.mappingEngine.baseSimilarity.BaseSimilarityMatcher; import am.app.mappingEngine.baseSimilarity.compoundWordSimilarity.CompoundWordSimilarityMatcher; import am.app.mappingEngine.basicStructureSelector.BasicStructuralSelectorMatcher; import am.app.mappingEngine.conceptMatcher.ConceptMatcher; import am.app.mappingEngine.dsi.DescendantsSimilarityInheritanceMatcher; import am.app.mappingEngine.dsi.OldDescendantsSimilarityInheritanceMatcher; import am.app.mappingEngine.manualMatcher.UserManualMatcher; import am.app.mappingEngine.multiWords.MultiWordsMatcher; import am.app.mappingEngine.oaei2009.OAEI2009matcher; import am.app.mappingEngine.parametricStringMatcher.ParametricStringMatcher; import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentMatcher; import am.app.mappingEngine.ssc.SiblingsSimilarityContributionMatcher; import am.app.mappingEngine.testMatchers.AllOneMatcher; import am.app.mappingEngine.testMatchers.AllZeroMatcher; import am.app.mappingEngine.testMatchers.CopyMatcher; import am.app.mappingEngine.testMatchers.EqualsMatcher; import am.app.mappingEngine.testMatchers.RandomMatcher; //import am.app.mappingEngine.LexicalMatcherUMLS.LexicalMatcherUMLS; /** * Enum for keeping the current list of matchers in the system, and their class references */ public enum MatchersRegistry { /** * This is where you add your own MATCHER. * * To add your matcher, add a definition to the enum, using this format * * EnumName ( "Short Name", MatcherClass.class ) * * For example, to add MySuperMatcher, you would add something like this (assuming the class name is MySuperMatcher): * * SuperMatcher ( "My Super Matcher", MySuperMatcher.class ), * * And so, if your matcher is has no code errors, it will be incorporated into the AgreementMaker. - Cosmin */ CompoundWordSim ( "Compound Word Similarity Matcher (CWSM)", CompoundWordSimilarityMatcher.class), //OFFICIAL MATCHERS LexicalJAWS ( "Lexical Matcher: JAWS", LexicalMatcherJAWS.class ), BaseSimilarity ( "Base Similarity Matcher (BSM)", BaseSimilarityMatcher.class ), ParametricString ( "Parametric String Matcher (PSM)", ParametricStringMatcher.class ), InstanceMatcher ("Base Instance-based Matcher (BIM)", BaseInstanceMatcher.class), MultiWords ("Vector-based Multi-Words Matcher (VMM)", MultiWordsMatcher.class), WordNetLexical ("Lexical Matcher: WordNet", LexicalMatcherJWNL.class), DSI ( "Descendant's Similarity Inheritance (DSI)", DescendantsSimilarityInheritanceMatcher.class ), BSS ( "Basic Structure Selector Matcher (BSS)", BasicStructuralSelectorMatcher.class ), SSC ( "Sibling's Similarity Contribution (SSC)", SiblingsSimilarityContributionMatcher.class ), Combination ( "Linear Weighted Combination (LWC)", CombinationMatcher.class ), ConceptSimilarity ( "Concept Similarity", ConceptMatcher.class, false), OAEI2009 ( "OAEI2009 Matcher", OAEI2009matcher.class), //UMLSKSLexical ("Lexical Matcher: UMLSKS", LexicalMatcherUMLS.class, false), //it requires internet connection and the IP to be registered //Auxiliary matchers created for specific purposes InitialMatcher ("Initial Matcher: LWC (PSM+VMM+BSM)", InitialMatchers.class, true), PRAintegration ( "PRA Integration", PRAintegrationMatcher.class, false), //this works fine PRAMatcher ("PRA Matcher", PRAMatcher.class, false), PRAMatcher2 ("PRA Matcher2", PRAMatcher2.class, false), OldPRAMAtcher ("Old PRA Matcher", OldPRAMatcher.class, false), //WORK IN PROGRESS InstanceBasedProp ("Instance-based Property Matcher (IPM)", BaseInstanceMatcher.class), //MATCHERS USED BY THE SYSTEM, usually not shown UserManual ( "User Manual Matching", UserManualMatcher.class, false), UniqueMatchings ( "Unique Matchings", ReferenceAlignmentMatcher.class, false), // this is used by the "Remove Duplicate Alignments" UIMenu entry ImportAlignment ( "Import Alignments", ReferenceAlignmentMatcher.class, true), //TEST MATCHERS Equals ( "Local Name Equivalence Comparison", EqualsMatcher.class , false), AllOne ( "(Test) All One Similarities", AllOneMatcher.class, true ), AllZero ( "(Test) All Zero Similarities", AllZeroMatcher.class, true ), Copy ( "Copy Matcher", CopyMatcher.class,false ), Random ( "(Test) Random Similarities", RandomMatcher.class, true ), DSI2 ( "OLD Descendant's Similarity Inheritance (DSI)", OldDescendantsSimilarityInheritanceMatcher.class, false ), UserFeedBackLoop ("User Feedback Loop", FeedbackLoop.class, false ); /* Don't change anything below this line .. unless you intend to. */ private boolean showInControlPanel; private String name; private String className; MatchersRegistry( String n, Class<?> matcherClass ) { name = n; className = matcherClass.getName(); showInControlPanel = true;} MatchersRegistry( String n, Class<?> matcherClass, boolean shown) { name = n; className = matcherClass.getName(); showInControlPanel = shown; } public String getMatcherName() { return name; } public String getMatcherClass() { return className; } public boolean isShown() { return showInControlPanel; } public String toString() { return name; } /** * Returns the matcher with the given name. * @param matcherName The name of the matcher. * @return The MatchersRegistry representation of the matcher (used with MatcherFactory). */ /* // This method duplicates MatcherFactory.getMatchersRegistryEntry( matcherName ) public static MatchersRegistry getMatcherByName( String matcherName ) { EnumSet<MatchersRegistry> matchers = EnumSet.allOf(MatchersRegistry.class); Iterator<MatchersRegistry> entryIter = matchers.iterator(); while( entryIter.hasNext() ) { MatchersRegistry currentEntry = entryIter.next(); if( currentEntry.getMatcherName().equals(matcherName) ) return currentEntry; } return null; } */ }
package org.elasticsearch.xpack.transform.integration.continuous; import org.apache.lucene.util.LuceneTestCase; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.client.transform.transforms.DestConfig; import org.elasticsearch.client.transform.transforms.SourceConfig; import org.elasticsearch.client.transform.transforms.TransformConfig; import org.elasticsearch.client.transform.transforms.pivot.GroupConfig; import org.elasticsearch.client.transform.transforms.pivot.PivotConfig; import org.elasticsearch.client.transform.transforms.pivot.TermsGroupSource; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.NumericMetricsAggregation.SingleValue; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.equalTo; @LuceneTestCase.AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/60781") public class TermsGroupByIT extends ContinuousTestCase { private static final String NAME = "continuous-terms-pivot-test"; private static final String MISSING_BUCKET_KEY = "~~NULL~~"; // ensure that this key is last after sorting private final boolean missing; public TermsGroupByIT() { missing = randomBoolean(); } @Override public TransformConfig createConfig() { TransformConfig.Builder transformConfigBuilder = new TransformConfig.Builder(); addCommonBuilderParameters(transformConfigBuilder); transformConfigBuilder.setSource(new SourceConfig(CONTINUOUS_EVENTS_SOURCE_INDEX)); transformConfigBuilder.setDest(new DestConfig(NAME, INGEST_PIPELINE)); transformConfigBuilder.setId(NAME); PivotConfig.Builder pivotConfigBuilder = new PivotConfig.Builder(); pivotConfigBuilder.setGroups( new GroupConfig.Builder().groupBy("event", new TermsGroupSource.Builder().setField("event").setMissingBucket(missing).build()) .build() ); AggregatorFactories.Builder aggregations = new AggregatorFactories.Builder(); addCommonAggregations(aggregations); aggregations.addAggregator(AggregationBuilders.max("metric.avg").field("metric")); pivotConfigBuilder.setAggregations(aggregations); transformConfigBuilder.setPivotConfig(pivotConfigBuilder.build()); return transformConfigBuilder.build(); } @Override public String getName() { return NAME; } @Override public void testIteration(int iteration) throws IOException { SearchRequest searchRequestSource = new SearchRequest(CONTINUOUS_EVENTS_SOURCE_INDEX).allowPartialSearchResults(false) .indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN); SearchSourceBuilder sourceBuilderSource = new SearchSourceBuilder().size(0); TermsAggregationBuilder terms = new TermsAggregationBuilder("event").size(1000).field("event").order(BucketOrder.key(true)); if (missing) { // missing_bucket produces `null`, we can't use `null` in aggs, so we have to use a magic value, see gh#60043 terms.missing(MISSING_BUCKET_KEY); } terms.subAggregation(AggregationBuilders.max("metric.avg").field("metric")); sourceBuilderSource.aggregation(terms); searchRequestSource.source(sourceBuilderSource); SearchResponse responseSource = search(searchRequestSource); SearchRequest searchRequestDest = new SearchRequest(NAME).allowPartialSearchResults(false) .indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN); SearchSourceBuilder sourceBuilderDest = new SearchSourceBuilder().size(1000).sort("event"); searchRequestDest.source(sourceBuilderDest); SearchResponse responseDest = search(searchRequestDest); List<? extends Bucket> buckets = ((Terms) responseSource.getAggregations().get("event")).getBuckets(); // the number of search hits should be equal to the number of buckets returned by the aggregation assertThat( "Number of buckets did not match, source: " + responseDest.getHits().getTotalHits().value + ", expected: " + Long.valueOf(buckets.size()) + ", iteration: " + iteration, responseDest.getHits().getTotalHits().value, equalTo(Long.valueOf(buckets.size())) ); Iterator<? extends Bucket> sourceIterator = buckets.iterator(); Iterator<SearchHit> destIterator = responseDest.getHits().iterator(); while (sourceIterator.hasNext() && destIterator.hasNext()) { Bucket bucket = sourceIterator.next(); SearchHit searchHit = destIterator.next(); Map<String, Object> source = searchHit.getSourceAsMap(); String transformBucketKey = (String) XContentMapValues.extractValue("event", source); if (transformBucketKey == null) { transformBucketKey = MISSING_BUCKET_KEY; } // test correctness, the results from the aggregation and the results from the transform should be the same assertThat( "Buckets did not match, source: " + source + ", expected: " + bucket.getKey() + ", iteration: " + iteration, transformBucketKey, equalTo(bucket.getKey()) ); assertThat( "Doc count did not match, source: " + source + ", expected: " + bucket.getDocCount() + ", iteration: " + iteration, XContentMapValues.extractValue("count", source), equalTo(Double.valueOf(bucket.getDocCount())) ); SingleValue avgAgg = (SingleValue) bucket.getAggregations().get("metric.avg"); assertThat( "Metric aggregation did not match, source: " + source + ", expected: " + avgAgg.value() + ", iteration: " + iteration, XContentMapValues.extractValue("metric.avg", source), equalTo(avgAgg.value()) ); // test optimization, transform should only rewrite documents that require it assertThat( "Ingest run: " + XContentMapValues.extractValue(INGEST_RUN_FIELD, source) + " did not match max run: " + XContentMapValues.extractValue(MAX_RUN_FIELD, source) + ", iteration: " + iteration, // TODO: aggs return double for MAX_RUN_FIELD, although it is an integer Double.valueOf((Integer) XContentMapValues.extractValue(INGEST_RUN_FIELD, source)), equalTo(XContentMapValues.extractValue(MAX_RUN_FIELD, source)) ); } assertFalse(sourceIterator.hasNext()); assertFalse(destIterator.hasNext()); } }
package eu.bcvsolutions.idm.core.model.event.processor.role; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Description; import org.springframework.stereotype.Component; import eu.bcvsolutions.idm.core.api.domain.OperationState; import eu.bcvsolutions.idm.core.api.domain.PriorityType; import eu.bcvsolutions.idm.core.api.dto.IdmRoleCompositionDto; import eu.bcvsolutions.idm.core.api.event.CoreEventProcessor; import eu.bcvsolutions.idm.core.api.event.DefaultEventResult; import eu.bcvsolutions.idm.core.api.event.EntityEvent; import eu.bcvsolutions.idm.core.api.event.EventResult; import eu.bcvsolutions.idm.core.api.event.processor.RoleCompositionProcessor; import eu.bcvsolutions.idm.core.api.utils.AutowireHelper; import eu.bcvsolutions.idm.core.model.event.RoleCompositionEvent.RoleCompositionEventType; import eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto; import eu.bcvsolutions.idm.core.scheduler.api.dto.filter.IdmLongRunningTaskFilter; import eu.bcvsolutions.idm.core.scheduler.api.service.LongRunningTaskManager; import eu.bcvsolutions.idm.core.scheduler.task.impl.RemoveRoleCompositionTaskExecutor; @Component(RoleCompositionDeleteProcessor.PROCESSOR_NAME) @Description("Deletes role composition from repository.") public class RoleCompositionDeleteProcessor extends CoreEventProcessor<IdmRoleCompositionDto> implements RoleCompositionProcessor { public static final String PROCESSOR_NAME = "core-role-composition-delete-processor"; @Autowired private LongRunningTaskManager longRunningTaskManager; public RoleCompositionDeleteProcessor() { super(RoleCompositionEventType.DELETE); } @Override public String getName() { return PROCESSOR_NAME; } @Override public boolean conditional(EntityEvent<IdmRoleCompositionDto> event) { IdmLongRunningTaskFilter filter = new IdmLongRunningTaskFilter(); filter.setOperationState(OperationState.RUNNING); filter.setTaskType(RemoveRoleCompositionTaskExecutor.class.getCanonicalName()); List<IdmLongRunningTaskDto> tasks = longRunningTaskManager.findLongRunningTasks(filter, null).getContent(); for (IdmLongRunningTaskDto task : tasks) { if (task.getTaskProperties() != null && task.getTaskProperties().get(RemoveRoleCompositionTaskExecutor.PARAMETER_ROLE_COMPOSITION_ID) != null && task.getTaskProperties().get(RemoveRoleCompositionTaskExecutor.PARAMETER_ROLE_COMPOSITION_ID).equals(event.getContent().getId())) { return false; } } return true; } @Override public EventResult<IdmRoleCompositionDto> process(EntityEvent<IdmRoleCompositionDto> event) { IdmRoleCompositionDto roleComposition = event.getContent(); if (roleComposition.getId() == null) { return new DefaultEventResult<>(event, this); } // delete all assigned roles gained by this automatic role by long running task RemoveRoleCompositionTaskExecutor roleCompositionTask = AutowireHelper.createBean(RemoveRoleCompositionTaskExecutor.class); roleCompositionTask.setRoleCompositionId(roleComposition.getId()); if (event.getPriority() == PriorityType.IMMEDIATE) { longRunningTaskManager.executeSync(roleCompositionTask); return new DefaultEventResult<>(event, this); } roleCompositionTask.setRequireNewTransaction(true); longRunningTaskManager.execute(roleCompositionTask); // TODO: new flag asynchronous? return new DefaultEventResult.Builder<>(event, this).setSuspended(true).build(); } }
package org.apereo.cas.configuration.model.core.authentication; import org.apereo.cas.configuration.model.support.cassandra.authentication.CassandraAuthenticationProperties; import org.apereo.cas.configuration.model.support.clouddirectory.CloudDirectoryProperties; import org.apereo.cas.configuration.model.support.couchbase.authentication.CouchbaseAuthenticationProperties; import org.apereo.cas.configuration.model.support.digest.DigestProperties; import org.apereo.cas.configuration.model.support.fortress.FortressAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.AcceptAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.FileAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.RejectAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.RemoteAddressAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.ShiroAuthenticationProperties; import org.apereo.cas.configuration.model.support.gua.GraphicalUserAuthenticationProperties; import org.apereo.cas.configuration.model.support.jaas.JaasAuthenticationProperties; import org.apereo.cas.configuration.model.support.jdbc.JdbcAuthenticationProperties; import org.apereo.cas.configuration.model.support.ldap.LdapAuthenticationProperties; import org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties; import org.apereo.cas.configuration.model.support.mongo.MongoAuthenticationProperties; import org.apereo.cas.configuration.model.support.ntlm.NtlmProperties; import org.apereo.cas.configuration.model.support.oauth.OAuthProperties; import org.apereo.cas.configuration.model.support.oidc.OidcProperties; import org.apereo.cas.configuration.model.support.openid.OpenIdProperties; import org.apereo.cas.configuration.model.support.pac4j.Pac4jProperties; import org.apereo.cas.configuration.model.support.pm.PasswordManagementProperties; import org.apereo.cas.configuration.model.support.radius.RadiusProperties; import org.apereo.cas.configuration.model.support.rest.RestAuthenticationProperties; import org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties; import org.apereo.cas.configuration.model.support.saml.shibboleth.ShibbolethIdPProperties; import org.apereo.cas.configuration.model.support.spnego.SpnegoProperties; import org.apereo.cas.configuration.model.support.surrogate.SurrogateAuthenticationProperties; import org.apereo.cas.configuration.model.support.throttle.ThrottleProperties; import org.apereo.cas.configuration.model.support.token.TokenAuthenticationProperties; import org.apereo.cas.configuration.model.support.trusted.TrustedAuthenticationProperties; import org.apereo.cas.configuration.model.support.wsfed.WsFederationDelegationProperties; import org.apereo.cas.configuration.model.support.wsfed.WsFederationProperties; import org.apereo.cas.configuration.model.support.x509.X509Properties; import org.apereo.cas.configuration.support.RequiresModule; import org.springframework.boot.context.properties.NestedConfigurationProperty; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * This is {@link AuthenticationProperties}. * * @author Misagh Moayyed * @since 5.0.0 */ @RequiresModule(name = "cas-server-core-authentication", automated = true) public class AuthenticationProperties implements Serializable { private static final long serialVersionUID = -1233126985007049516L; /** * Couchbase authentication settings. */ @NestedConfigurationProperty private CouchbaseAuthenticationProperties couchbase = new CouchbaseAuthenticationProperties(); /** * Cassandra authentication settings. */ @NestedConfigurationProperty private CassandraAuthenticationProperties cassandra = new CassandraAuthenticationProperties(); /** * Cloud Directory authentication settings. */ @NestedConfigurationProperty private CloudDirectoryProperties cloudDirectory = new CloudDirectoryProperties(); /** * Surrogate authentication settings. */ @NestedConfigurationProperty private SurrogateAuthenticationProperties surrogate = new SurrogateAuthenticationProperties(); /** * Graphical User authentication settings. */ @NestedConfigurationProperty private GraphicalUserAuthenticationProperties gua = new GraphicalUserAuthenticationProperties(); /** * Password management settings. */ @NestedConfigurationProperty private PasswordManagementProperties pm = new PasswordManagementProperties(); /** * Adaptive authentication settings. */ @NestedConfigurationProperty private AdaptiveAuthenticationProperties adaptive = new AdaptiveAuthenticationProperties(); /** * Attribute repository settings. */ @NestedConfigurationProperty private PrincipalAttributesProperties attributeRepository = new PrincipalAttributesProperties(); /** * Digest authentication settings. */ @NestedConfigurationProperty private DigestProperties digest = new DigestProperties(); /** * REST-based authentication settings. */ @NestedConfigurationProperty private RestAuthenticationProperties rest = new RestAuthenticationProperties(); /** * Collection of settings related to LDAP authentication. * These settings are required to be indexed (i.e. ldap[0].xyz). */ private List<LdapAuthenticationProperties> ldap = new ArrayList<>(); /** * Authentication throttling settings. */ @NestedConfigurationProperty private ThrottleProperties throttle = new ThrottleProperties(); /** * SAML identity provider settings. */ @NestedConfigurationProperty private SamlIdPProperties samlIdp = new SamlIdPProperties(); /** * Customization of authentication errors and exceptions. */ @NestedConfigurationProperty private AuthenticationExceptionsProperties exceptions = new AuthenticationExceptionsProperties(); /** * Authentication policy settings. */ @NestedConfigurationProperty private AuthenticationPolicyProperties policy = new AuthenticationPolicyProperties(); /** * Accepting authentication based on statically defined users. */ @NestedConfigurationProperty private AcceptAuthenticationProperties accept = new AcceptAuthenticationProperties(); /** * File-based authentication. */ @NestedConfigurationProperty private FileAuthenticationProperties file = new FileAuthenticationProperties(); /** * Blacklist-based authentication. */ @NestedConfigurationProperty private RejectAuthenticationProperties reject = new RejectAuthenticationProperties(); /** * Authentication based on a remote-address of a request. */ @NestedConfigurationProperty private RemoteAddressAuthenticationProperties remoteAddress = new RemoteAddressAuthenticationProperties(); /** * Authentication settings when integrating CAS with a shibboleth IdP. */ @NestedConfigurationProperty private ShibbolethIdPProperties shibIdp = new ShibbolethIdPProperties(); /** * Shiro-based authentication. */ @NestedConfigurationProperty private ShiroAuthenticationProperties shiro = new ShiroAuthenticationProperties(); /** * Trusted authentication. */ @NestedConfigurationProperty private TrustedAuthenticationProperties trusted = new TrustedAuthenticationProperties(); /** * Collection of settings related to JAAS authentication. * These settings are required to be indexed (i.e. jaas[0].xyz). */ private List<JaasAuthenticationProperties> jaas = new ArrayList<>(); /** * JDBC authentication settings. */ @NestedConfigurationProperty private JdbcAuthenticationProperties jdbc = new JdbcAuthenticationProperties(); /** * MFA settings. */ @NestedConfigurationProperty private MultifactorAuthenticationProperties mfa = new MultifactorAuthenticationProperties(); /** * MongoDb authentication settings. */ @NestedConfigurationProperty private MongoAuthenticationProperties mongo = new MongoAuthenticationProperties(); /** * NTLM authentication settings. */ @NestedConfigurationProperty private NtlmProperties ntlm = new NtlmProperties(); /** * OAuth authentication settings. */ @NestedConfigurationProperty private OAuthProperties oauth = new OAuthProperties(); /** * OpenID Connect authentication settings. */ @NestedConfigurationProperty private OidcProperties oidc = new OidcProperties(); /** * OpenID authentication settings. */ @NestedConfigurationProperty private OpenIdProperties openid = new OpenIdProperties(); /** * Pac4j delegated authentication settings. */ @NestedConfigurationProperty private Pac4jProperties pac4j = new Pac4jProperties(); /** * RADIUS authentication settings. */ @NestedConfigurationProperty private RadiusProperties radius = new RadiusProperties(); /** * SPNEGO authentication settings. */ @NestedConfigurationProperty private SpnegoProperties spnego = new SpnegoProperties(); /** * Collection of settings related to WsFed delegated authentication. * These settings are required to be indexed (i.e. wsfed[0].xyz). */ private List<WsFederationDelegationProperties> wsfed = new ArrayList<>(); /** * WS-FED IdP authentication settings. */ @NestedConfigurationProperty private WsFederationProperties wsfedIdp = new WsFederationProperties(); /** * X509 authentication settings. */ @NestedConfigurationProperty private X509Properties x509 = new X509Properties(); /** * Token/JWT authentication settings. */ @NestedConfigurationProperty private TokenAuthenticationProperties token = new TokenAuthenticationProperties(); /** * Apache Fortress authentication settings. */ @NestedConfigurationProperty private FortressAuthenticationProperties fortress = new FortressAuthenticationProperties(); /** * Authentication attribute release settings. */ @NestedConfigurationProperty private AuthenticationAttributeReleaseProperties authenticationAttributeRelease = new AuthenticationAttributeReleaseProperties(); /** * Whether CAS authentication/protocol attributes * should be released as part of ticket validation. */ private boolean releaseProtocolAttributes = true; public ShibbolethIdPProperties getShibIdp() { return shibIdp; } public void setShibIdp(final ShibbolethIdPProperties shibIdp) { this.shibIdp = shibIdp; } public SurrogateAuthenticationProperties getSurrogate() { return surrogate; } public void setSurrogate(final SurrogateAuthenticationProperties surrogate) { this.surrogate = surrogate; } public AuthenticationAttributeReleaseProperties getAuthenticationAttributeRelease() { return authenticationAttributeRelease; } public void setAuthenticationAttributeRelease(final AuthenticationAttributeReleaseProperties authenticationAttributeRelease) { this.authenticationAttributeRelease = authenticationAttributeRelease; } public boolean isReleaseProtocolAttributes() { return releaseProtocolAttributes; } public void setReleaseProtocolAttributes(final boolean releaseProtocolAttributes) { this.releaseProtocolAttributes = releaseProtocolAttributes; } public WsFederationProperties getWsfedIdp() { return wsfedIdp; } public void setWsfedIdp(final WsFederationProperties wsfedIdp) { this.wsfedIdp = wsfedIdp; } public TokenAuthenticationProperties getToken() { return token; } public void setToken(final TokenAuthenticationProperties token) { this.token = token; } public AuthenticationExceptionsProperties getExceptions() { return exceptions; } public void setExceptions(final AuthenticationExceptionsProperties exceptions) { this.exceptions = exceptions; } public AuthenticationPolicyProperties getPolicy() { return policy; } public AcceptAuthenticationProperties getAccept() { return accept; } public void setAccept(final AcceptAuthenticationProperties accept) { this.accept = accept; } public FileAuthenticationProperties getFile() { return file; } public void setFile(final FileAuthenticationProperties file) { this.file = file; } public RejectAuthenticationProperties getReject() { return reject; } public void setReject(final RejectAuthenticationProperties reject) { this.reject = reject; } public RemoteAddressAuthenticationProperties getRemoteAddress() { return remoteAddress; } public void setRemoteAddress(final RemoteAddressAuthenticationProperties remoteAddress) { this.remoteAddress = remoteAddress; } public ShiroAuthenticationProperties getShiro() { return shiro; } public void setShiro(final ShiroAuthenticationProperties shiro) { this.shiro = shiro; } public List<JaasAuthenticationProperties> getJaas() { return jaas; } public void setJaas(final List<JaasAuthenticationProperties> jaas) { this.jaas = jaas; } public JdbcAuthenticationProperties getJdbc() { return jdbc; } public void setJdbc(final JdbcAuthenticationProperties jdbc) { this.jdbc = jdbc; } public MultifactorAuthenticationProperties getMfa() { return mfa; } public void setMfa(final MultifactorAuthenticationProperties mfa) { this.mfa = mfa; } public MongoAuthenticationProperties getMongo() { return mongo; } public void setMongo(final MongoAuthenticationProperties mongo) { this.mongo = mongo; } public NtlmProperties getNtlm() { return ntlm; } public void setNtlm(final NtlmProperties ntlm) { this.ntlm = ntlm; } public OAuthProperties getOauth() { return oauth; } public void setOauth(final OAuthProperties oauth) { this.oauth = oauth; } public OidcProperties getOidc() { return oidc; } public void setOidc(final OidcProperties oidc) { this.oidc = oidc; } public OpenIdProperties getOpenid() { return openid; } public void setOpenid(final OpenIdProperties openid) { this.openid = openid; } public Pac4jProperties getPac4j() { return pac4j; } public void setPac4j(final Pac4jProperties pac4j) { this.pac4j = pac4j; } public RadiusProperties getRadius() { return radius; } public void setRadius(final RadiusProperties radius) { this.radius = radius; } public SpnegoProperties getSpnego() { return spnego; } public void setSpnego(final SpnegoProperties spnego) { this.spnego = spnego; } public List<WsFederationDelegationProperties> getWsfed() { return wsfed; } public void setWsfed(final List<WsFederationDelegationProperties> wsfed) { this.wsfed = wsfed; } public X509Properties getX509() { return x509; } public void setX509(final X509Properties x509) { this.x509 = x509; } public SamlIdPProperties getSamlIdp() { return samlIdp; } public void setSamlIdp(final SamlIdPProperties samlIdp) { this.samlIdp = samlIdp; } public ThrottleProperties getThrottle() { return throttle; } public void setThrottle(final ThrottleProperties throttle) { this.throttle = throttle; } public TrustedAuthenticationProperties getTrusted() { return trusted; } public void setTrusted(final TrustedAuthenticationProperties trusted) { this.trusted = trusted; } public List<LdapAuthenticationProperties> getLdap() { return ldap; } public void setLdap(final List<LdapAuthenticationProperties> ldap) { this.ldap = ldap; } public RestAuthenticationProperties getRest() { return rest; } public void setRest(final RestAuthenticationProperties rest) { this.rest = rest; } public DigestProperties getDigest() { return digest; } public void setDigest(final DigestProperties digest) { this.digest = digest; } public PrincipalAttributesProperties getAttributeRepository() { return attributeRepository; } public void setAttributeRepository(final PrincipalAttributesProperties attributeRepository) { this.attributeRepository = attributeRepository; } public AdaptiveAuthenticationProperties getAdaptive() { return adaptive; } public void setAdaptive(final AdaptiveAuthenticationProperties adaptive) { this.adaptive = adaptive; } public void setPolicy(final AuthenticationPolicyProperties policy) { this.policy = policy; } public PasswordManagementProperties getPm() { return pm; } public void setPm(final PasswordManagementProperties pm) { this.pm = pm; } public GraphicalUserAuthenticationProperties getGua() { return gua; } public void setGua(final GraphicalUserAuthenticationProperties gua) { this.gua = gua; } public CloudDirectoryProperties getCloudDirectory() { return cloudDirectory; } public void setCloudDirectory(final CloudDirectoryProperties cloudDirectory) { this.cloudDirectory = cloudDirectory; } public CassandraAuthenticationProperties getCassandra() { return cassandra; } public void setCassandra(final CassandraAuthenticationProperties cassandra) { this.cassandra = cassandra; } public CouchbaseAuthenticationProperties getCouchbase() { return couchbase; } public void setCouchbase(final CouchbaseAuthenticationProperties couchbase) { this.couchbase = couchbase; } public FortressAuthenticationProperties getFortress() { return fortress; } public void setFortress(final FortressAuthenticationProperties fortress) { this.fortress = fortress; } }
package org.intermine.web.results; import java.util.List; import java.util.Map; import java.util.Iterator; import java.util.ArrayList; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsInfo; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryHelper; import org.intermine.objectstore.query.QueryNode; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.FromElement; import org.intermine.metadata.Model; import org.intermine.metadata.FieldDescriptor; /** * A pageable and configurable table created from the Results object. * * @author Andrew Varley * @author Kim Rutherford */ public class PagedResults extends PagedTable { protected Results results; /** * Create a new PagedResults object from the given Results object. * * @param results the Results object */ public PagedResults(Results results, Model model) { this(QueryHelper.getColumnAliases(results.getQuery()), results, model); } /** * Create a new PagedResults object from the given Results object. * * @param results the Results object * @param columnNames the headings for the Results columns */ public PagedResults(List columnNames, Results results, Model model) { super(columnNames); this.results = results; setColumnTypes(model); updateRows(); } /** * @see PagedTable#getAllRows */ public List getAllRows() { return results; } /** * @see PagedTable#getSize */ public int getSize() { try { return results.getInfo().getRows(); } catch (ObjectStoreException e) { org.intermine.web.LogMe.log("i", e); throw new RuntimeException(e); } } /** * @see PagedTable#isSizeEstimate */ public boolean isSizeEstimate() { try { return results.getInfo().getStatus() != ResultsInfo.SIZE; } catch (ObjectStoreException e) { org.intermine.web.LogMe.log("i", e); throw new RuntimeException(e); } } /** * @see PagedTable#getExactSize */ protected int getExactSize() { return results.size(); } /** * @see PagedTable#updateRows */ protected void updateRows() { rows = new ArrayList(); try { for (int i = startRow; i < startRow + pageSize; i++) { rows.add(results.get(i)); } } catch (IndexOutOfBoundsException e) { } } /** * Return information about the results * @return the relevant ResultsInfo * @throws ObjectStoreException if an error occurs accessing the underlying ObjectStore */ public ResultsInfo getResultsInfo() throws ObjectStoreException { return results.getInfo(); } /** * Call setType() on each Column, setting it the type to a ClassDescriptor, a FieldDescriptor * or Object.class */ private void setColumnTypes(Model model) { Query q = results.getQuery(); Iterator columnIter = getColumns().iterator(); Iterator selectListIter = q.getSelect().iterator(); while (columnIter.hasNext()) { Column thisColumn = (Column) columnIter.next(); QueryNode thisQueryNode = (QueryNode) selectListIter.next(); if (thisQueryNode instanceof QueryClass) { Class thisQueryNodeClass = ((QueryClass) thisQueryNode).getType(); thisColumn.setType(model.getClassDescriptorByName(thisQueryNodeClass.getName())); } else { if (thisQueryNode instanceof QueryField) { QueryField queryField = (QueryField) thisQueryNode; FromElement fe = queryField.getFromElement(); if (fe instanceof QueryClass) { QueryClass queryClass = (QueryClass) fe; Map fieldMap = model.getFieldDescriptorsForClass(queryClass.getType()); FieldDescriptor fd = (FieldDescriptor) fieldMap.get(queryField.getFieldName()); thisColumn.setType(fd); } else { thisColumn.setType(Object.class); } } else { thisColumn.setType(Object.class); } } } } }
// Ship.java package de.htwg.battleship.objects; /** * Ship for Battleship. * @author Moritz Sauter (SauterMoritz@gmx.de) * @version 1.00 * @since 2014-10-29 */ public class Ship { /** * Correct size. */ private static final int CORRECT_FIELD_SIZE = 2; /** * Size of the ship. */ private int size; /** * Where the ship starts in the 2D-Field. */ private int[] positionStart; /** * If it is vertical or horizontal. * True if horizontal, False if vertical. */ private boolean orientation; /** * Public-Constructor with all parameters. * @param size of the ship. * @param orientation true if horizontal. * @param positionStart there the ship starts. */ public Ship(final int size, final boolean orientation, final int[] positionStart) { this.size = size; this.orientation = orientation; this.positionStart = positionStart; } /** * Getter for the Orientation of the ship. * @return true if horizontal, false if vertical. */ public boolean isOrientation() { return orientation; } /** * Setter for the Orientation of the ship. * @param orientation true if horizontal, false if vertical. */ public final void setOrientation(final boolean orientation) { this.orientation = orientation; } /** * Setter for the position where the ship starts. * @param positionStart array with the length = 2, * with a x- and a y-Coordinate. */ public final void setPositionStart(final int[] positionStart) { if (positionStart.length != CORRECT_FIELD_SIZE) { return; } if (positionStart[0] < 0 || positionStart[1] < 0) { return; } this.positionStart = new int[] {positionStart[0], positionStart[1]}; } /** * Getter for the position where the ship starts. * @return an array of a x- and a y-Coordinate. */ public final int[] getPositionStart() { return positionStart; } /** * Getter for the size of the ship. * @return size as an int. */ public final int getSize() { return size; } /** * Setter for the size of the ship. * @param size > 0 */ public final void setSize(final int size) { if (size <= 0) { return; } this.size = size; } }