answer
stringlengths
17
10.2M
package org.mapyrus.function; import java.util.HashMap; import org.mapyrus.MapyrusException; /** * Manages all available functions. Provides function name * lookup function. */ public class FunctionTable { static HashMap mFunctions = new HashMap(); /* * Load all internal functions and any additional functions defined by user. */ static { Function f; f = new Abs(); mFunctions.put(f.getName(), f); f = new Ceil(); mFunctions.put(f.getName(), f); f = new Cos(); mFunctions.put(f.getName(), f); f = new Dir(); mFunctions.put(f.getName(), f); f = new Floor(); mFunctions.put(f.getName(), f); f = new Format(); mFunctions.put(f.getName(), f); f = new Interpolate(); mFunctions.put(f.getName(), f); f = new Length(); mFunctions.put(f.getName(), f); f = new Lower(); mFunctions.put(f.getName(), f); f = new Lpad(); mFunctions.put(f.getName(), f); f = new Log10(); mFunctions.put(f.getName(), f); f = new Match(); mFunctions.put(f.getName(), f); f = new Max(); mFunctions.put(f.getName(), f); f = new Min(); mFunctions.put(f.getName(), f); f = new Parsegeo(); mFunctions.put(f.getName(), f); f = new Pow(); mFunctions.put(f.getName(), f); f = new Protected(); mFunctions.put(f.getName(), f); f = new Random(); mFunctions.put(f.getName(), f); f = new Readable(); mFunctions.put(f.getName(), f); f = new Replace(); mFunctions.put(f.getName(), f); f = new Roman(); mFunctions.put(f.getName(), f); f = new Round(); mFunctions.put(f.getName(), f); f = new Rpad(); mFunctions.put(f.getName(), f); f = new Sin(); mFunctions.put(f.getName(), f); f = new Split(); mFunctions.put(f.getName(), f); f = new Spool(); mFunctions.put(f.getName(), f); f = new Sqrt(); mFunctions.put(f.getName(), f); f = new Stringheight(); mFunctions.put(f.getName(), f); f = new Stringwidth(); mFunctions.put(f.getName(), f); f = new Substr(); mFunctions.put(f.getName(), f); f = new Sum(); mFunctions.put(f.getName(), f); f = new Tan(); mFunctions.put(f.getName(), f); f = new Tempname(); mFunctions.put(f.getName(), f); f = new Timestamp(); mFunctions.put(f.getName(), f); f = new Topage(); mFunctions.put(f.getName(), f); f = new Toworlds(); mFunctions.put(f.getName(), f); f = new Trim(); mFunctions.put(f.getName(), f); f = new Upper(); mFunctions.put(f.getName(), f); f = new Wordwrap(); mFunctions.put(f.getName(), f); try { /* * Java Topology Suite functions are only available if the * JTS JAR file is available in the classpath. */ f = new Buffer(); mFunctions.put(f.getName(), f); f = new Contains(); mFunctions.put(f.getName(), f); f = new ConvexHull(); mFunctions.put(f.getName(), f); f = new Difference(); mFunctions.put(f.getName(), f); f = new Intersection(); mFunctions.put(f.getName(), f); f = new Overlaps(); mFunctions.put(f.getName(), f); f = new Union(); mFunctions.put(f.getName(), f); } catch (NoClassDefFoundError e) { /* * Add dummy placeholder functions instead. * They'll fail if they are ever called though. */ mFunctions.put("buffer", new DummyFunction("buffer")); mFunctions.put("contains", new DummyFunction("contains")); mFunctions.put("convexhull", new DummyFunction("convexhull")); mFunctions.put("difference", new DummyFunction("difference")); mFunctions.put("intersection", new DummyFunction("intersection")); mFunctions.put("overlaps", new DummyFunction("overlaps")); mFunctions.put("union", new DummyFunction("union")); } } /** * Lookup function from name and return object * @param name name of function to lookup. * @return object for evaluating this function, or null if not found. */ public static Function getFunction(String funcName) throws MapyrusException { Function retval = (Function)(mFunctions.get(funcName)); return(retval); } }
package io.opentelemetry.sdk.extension.trace.jaeger.sampler; import static java.util.Objects.requireNonNull; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.opentelemetry.api.internal.Utils; import io.opentelemetry.sdk.trace.samplers.Sampler; import java.time.Duration; import java.util.concurrent.TimeUnit; /** A builder for {@link JaegerRemoteSampler}. */ public final class JaegerRemoteSamplerBuilder { private static final String DEFAULT_ENDPOINT = "localhost:14250"; private static final int DEFAULT_POLLING_INTERVAL_MILLIS = 60000; private static final Sampler INITIAL_SAMPLER = Sampler.parentBased(Sampler.traceIdRatioBased(0.001)); private String endpoint = DEFAULT_ENDPOINT; private ManagedChannel channel; private String serviceName; private Sampler initialSampler = INITIAL_SAMPLER; private int pollingIntervalMillis = DEFAULT_POLLING_INTERVAL_MILLIS; private boolean closeChannel = true; /** * Sets the service name to be used by this exporter. Required. * * @param serviceName the service name. * @return this. */ public JaegerRemoteSamplerBuilder setServiceName(String serviceName) { requireNonNull(serviceName, "serviceName"); this.serviceName = serviceName; return this; } /** Sets the Jaeger endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT}. */ public JaegerRemoteSamplerBuilder setEndpoint(String endpoint) { requireNonNull(endpoint, "endpoint"); this.endpoint = endpoint; return this; } /** * Sets the managed channel to use when communicating with the backend. Takes precedence over * {@link #setEndpoint(String)} if both are called. * * <p>Note: if you use this option, the provided channel will *not* be closed when {@code close()} * is called on the resulting {@link JaegerRemoteSampler}. */ public JaegerRemoteSamplerBuilder setChannel(ManagedChannel channel) { requireNonNull(channel, "channel"); this.channel = channel; closeChannel = false; return this; } /** * Sets the polling interval for configuration updates. If unset, defaults to {@value * DEFAULT_POLLING_INTERVAL_MILLIS}ms. Must be positive. */ public JaegerRemoteSamplerBuilder setPollingInterval(int interval, TimeUnit unit) { requireNonNull(unit, "unit"); Utils.checkArgument(interval > 0, "polling interval must be positive"); pollingIntervalMillis = (int) unit.toMillis(interval); return this; } /** * Sets the polling interval for configuration updates. If unset, defaults to {@value * DEFAULT_POLLING_INTERVAL_MILLIS}ms. */ public JaegerRemoteSamplerBuilder setPollingInterval(Duration interval) { requireNonNull(interval, "interval"); return setPollingInterval((int) interval.toMillis(), TimeUnit.MILLISECONDS); } /** * Sets the initial sampler that is used before sampling configuration is obtained. If unset, * defaults to a parent-based ratio-based sampler with a ratio of 0.001. */ public JaegerRemoteSamplerBuilder setInitialSampler(Sampler initialSampler) { requireNonNull(initialSampler, "initialSampler"); this.initialSampler = initialSampler; return this; } /** * Builds the {@link JaegerRemoteSampler}. * * @return the remote sampler instance. */ public JaegerRemoteSampler build() { if (channel == null) { channel = ManagedChannelBuilder.forTarget(endpoint).usePlaintext().build(); } return new JaegerRemoteSampler( serviceName, channel, pollingIntervalMillis, initialSampler, closeChannel); } JaegerRemoteSamplerBuilder() {} }
package jolie.runtime; import java.util.HashSet; import java.util.Set; import jolie.ExecutionThread; import jolie.process.TransformationReason; import jolie.runtime.expression.Expression; import jolie.util.Pair; /** * Represents a variable path, e.g. a.b[3], offering mechanisms * for referring to the object pointed by it. * @author Fabrizio Montesi */ public class VariablePath implements Expression { public static class EmptyPathLazyHolder { private EmptyPathLazyHolder() {} public static final Pair< Expression, Expression >[] EMPTY_PATH = new Pair[0]; } private final Pair< Expression, Expression >[] path; // Right Expression may be null public final Pair< Expression, Expression >[] path() { return path; } public boolean isGlobal() { return false; } protected static Pair< Expression, Expression >[] cloneExpressionHelper( Pair< Expression, Expression >[] path, TransformationReason reason ) { Pair< Expression, Expression >[] clonedPath = new Pair[ path.length ]; for( int i = 0; i < path.length; i++ ) { clonedPath[i] = new Pair<>( path[i].key().cloneExpression( reason ), ( path[i].value() == null ) ? null : path[i].value().cloneExpression( reason ) ); } return clonedPath; } public VariablePath copy() { return new VariablePath( path ); } @Override public Expression cloneExpression( TransformationReason reason ) { Pair< Expression, Expression >[] clonedPath = cloneExpressionHelper( path, reason ); return new VariablePath( clonedPath ); } public final VariablePath containedSubPath( VariablePath otherVarPath ) { if ( getRootValue() != otherVarPath.getRootValue() ) return null; // If the other path is shorter than this, it's not a subpath. if ( otherVarPath.path.length < path.length ) return null; int i, myIndex, otherIndex; Pair< Expression, Expression > pair, otherPair; Expression expr, otherExpr; for( i = 0; i < path.length; i++ ) { pair = path[i]; otherPair = otherVarPath.path[i]; // *.element_name is not a subpath of *.other_name if ( !pair.key().evaluate().strValue().equals( otherPair.key().evaluate().strValue() ) ) return null; // If element name is equal, check for the same index expr = pair.value(); otherExpr = otherPair.value(); myIndex = ( expr == null ) ? 0 : expr.evaluate().intValue(); otherIndex = ( otherExpr == null ) ? 0 : otherExpr.evaluate().intValue(); if ( myIndex != otherIndex ) return null; } // Now i represents the beginning of the subpath, we can just copy it from there Pair< Expression, Expression >[] subPath = new Pair[ otherVarPath.path.length - i ]; System.arraycopy( otherVarPath.path, i, subPath, 0, otherVarPath.path.length - i ); /*for( int k = 0; i < otherVarPath.path.length; i++ ) { subPath[k] = otherVarPath.path[i]; k++; }*/ return _createVariablePath( subPath ); } protected VariablePath _createVariablePath( Pair< Expression, Expression >[] path ) { return new VariablePath( path ); } public VariablePath( Pair< Expression, Expression >[] path ) { this.path = path; } protected Value getRootValue() { return ExecutionThread.currentThread().state().root(); } public final void undef() { Pair< Expression, Expression > pair; ValueVector currVector; Value currValue = getRootValue(); int index; String keyStr; for( int i = 0; i < path.length; i++ ) { pair = path[i]; keyStr = pair.key().evaluate().strValue(); currVector = currValue.children().get( keyStr ); if ( currVector == null ) { return; } else if ( currVector.size() < 1 ) { currValue.children().remove( keyStr ); return; } if ( pair.value() == null ) { if ( (i+1) < path.length ) { currValue = currVector.get( 0 ); } else { // We're finished currValue.children().remove( keyStr ); } } else { index = pair.value().evaluate().intValue(); if ( (i+1) < path.length ) { if ( currVector.size() <= index ) { return; } currValue = currVector.get( index ); } else { if ( currVector.size() > index ) { currVector.remove( index ); } } } } } public final Value getValue() { return getValue( getRootValue() ); } private final Set< ValueLink > fromValueLink = new HashSet<>(); public final Value getValue( ValueLink l ) { if ( fromValueLink.contains( l ) ) { throw buildAliasAccessException().toRuntimeFaultException(); } else { fromValueLink.add( l ); } Value v = getValue(); fromValueLink.remove( l ); return v; } public final Value getValue( Value currValue ) { for( Pair< Expression, Expression > pair : path ) { final String keyStr = pair.key().evaluate().strValue(); currValue = pair.value() == null ? currValue.getFirstChild( keyStr ) : currValue.getChildren( keyStr ).get( pair.value().evaluate().intValue() ); } return currValue; } public final void setValue( Value value ) { Pair< Expression, Expression > pair; ValueVector currVector; Value currValue = getRootValue(); int index; String keyStr; if ( path.length == 0 ) { currValue.refCopy( value ); } else { for( int i = 0; i < path.length; i++ ) { pair = path[i]; keyStr = pair.key().evaluate().strValue(); currVector = currValue.getChildren( keyStr ); if ( pair.value() == null ) { if ( (i+1) < path.length ) { currValue = currVector.get( 0 ); } else { // We're finished if ( currVector.get( 0 ).isUsedInCorrelation() ) { currVector.get( 0 ).refCopy( value ); } else { currVector.set( 0, value ); } } } else { index = pair.value().evaluate().intValue(); if ( (i+1) < path.length ) { currValue = currVector.get( index ); } else { if ( currVector.get( index ).isUsedInCorrelation() ) { currVector.get( index ).refCopy( value ); } else { currVector.set( index, value ); } } } } } } public final Value getValueOrNull() { return getValueOrNull( getRootValue() ); } public final Value getValueOrNull( Value currValue ) { for( int i = 0; i < path.length; i++ ) { final Pair< Expression, Expression > pair = path[i]; final ValueVector currVector = currValue.children().get( pair.key().evaluate().strValue() ); if ( currVector == null ) { return null; } if ( pair.value() == null ) { if ( (i+1) < path.length ) { if ( currVector.isEmpty() ) { return null; } currValue = currVector.get( 0 ); } else { // We're finished if ( currVector.isEmpty() ) { return null; } else { return currVector.get( 0 ); } } } else { final int index = pair.value().evaluate().intValue(); if ( currVector.size() <= index ) { return null; } currValue = currVector.get( index ); if ( (i+1) >= path.length ) { return currValue; } } } return currValue; } private final Set< ValueVectorLink > fromValueVectorLink = new HashSet<>(); public final ValueVector getValueVector( ValueVectorLink l ){ if( fromValueVectorLink.contains( l ) ){ throw buildAliasAccessException().toRuntimeFaultException(); } else { fromValueVectorLink.add( l ); } ValueVector v = getValueVector(); if( fromValueVectorLink.contains( v ) ){ throw buildAliasAccessException().toRuntimeFaultException(); } fromValueVectorLink.remove( l ); return v; } private final FaultException buildAliasAccessException(){ String alias = ""; boolean isRoot = true; for ( Pair< Expression, Expression > p : path ) { if( isRoot ){ alias += p.key().evaluate().strValue(); isRoot = false; } else { alias += "." + p.key().evaluate().strValue(); } } return new FaultException( "AliasAccessException", "Found a loop when accessing an alias pointing to path: " + alias ); } public final ValueVector getValueVector( Value currValue ) { ValueVector currVector = null; for( int i = 0; i < path.length; i++ ) { final Pair< Expression, Expression > pair = path[i]; currVector = currValue.getChildren( pair.key().evaluate().strValue() ); if ( (i+1) < path.length ) { if ( pair.value() == null ) { currValue = currVector.get( 0 ); } else { currValue = currVector.get( pair.value().evaluate().intValue() ); } } } return currVector; } public final ValueVector getValueVectorOrNull( Value currValue ) { ValueVector currVector = null; for( int i = 0; i < path.length; i++ ) { final Pair< Expression, Expression > pair = path[i]; currVector = currValue.children().get( pair.key().evaluate().strValue() ); if ( currVector == null ) { return null; } if ( (i+1) < path.length ) { if ( pair.value() == null ) { if ( currVector.isEmpty() ) { return null; } currValue = currVector.get( 0 ); } else { final int index = pair.value().evaluate().intValue(); if ( currVector.size() <= index ) { return null; } currValue = currVector.get( index ); } } } return currVector; } public final ValueVector getValueVectorOrNull() { return getValueVectorOrNull( getRootValue() ); } public final ValueVector getValueVector() { return getValueVector( getRootValue() ); } public final void makePointer( VariablePath rightPath ) { makePointer( getRootValue(), rightPath ); } public final void makePointer( Value currValue, VariablePath rightPath ) { Pair< Expression, Expression > pair; ValueVector currVector; int index; String keyStr; for( int i = 0; i < path.length; i++ ) { pair = path[i]; keyStr = pair.key().evaluate().strValue(); currVector = currValue.getChildren( keyStr ); if ( pair.value() == null ) { if ( (i+1) < path.length ) { currValue = currVector.get( 0 ); } else { // We're finished currValue.children().put( keyStr, ValueVector.createLink( rightPath ) ); } } else { index = pair.value().evaluate().intValue(); if ( (i+1) < path.length ) { currValue = currVector.get( index ); } else { currVector.set( index, Value.createLink( rightPath ) ); } } } } private Object getValueOrValueVector() { Pair< Expression, Expression > pair; ValueVector currVector; Value currValue = getRootValue(); int index; for( int i = 0; i < path.length; i++ ) { pair = path[i]; currVector = currValue.getChildren( pair.key().evaluate().strValue() ); if ( pair.value() == null ) { if ( (i+1) < path.length ) { currValue = currVector.get( 0 ); } else { // We're finished return currVector; } } else { index = pair.value().evaluate().intValue(); if ( (i+1) < path.length ) { currValue = currVector.get( index ); } else { return currVector.get( index ); } } } return currValue; } @SuppressWarnings("unchecked") public final void deepCopy( VariablePath rightPath ) { Object myObj = getValueOrValueVector(); if ( myObj instanceof Value ) { ((Value) myObj).deepCopy( rightPath.getValue() ); } else { ValueVector myVec = (ValueVector) myObj; ValueVector rightVec = rightPath.getValueVector(); for( int i = 0; i < rightVec.size(); i++ ) { myVec.get( i ).deepCopy( rightVec.get( i ) ); } } } @Override public final Value evaluate() { final Value v = getValueOrNull(); return ( v == null ) ? Value.UNDEFINED_VALUE : v; } }
package ca.sfu.client; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import ca.sfu.cmpt431.facility.Board; import ca.sfu.cmpt431.facility.BoardOperation; import ca.sfu.cmpt431.facility.Border; import ca.sfu.cmpt431.facility.Comrade; import ca.sfu.cmpt431.facility.Neighbour; import ca.sfu.cmpt431.facility.Outfits; import ca.sfu.cmpt431.message.Message; import ca.sfu.cmpt431.message.MessageCodeDictionary; import ca.sfu.cmpt431.message.join.JoinOutfitsMsg; import ca.sfu.cmpt431.message.join.JoinRequestMsg; import ca.sfu.cmpt431.message.join.JoinSplitMsg; import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg; import ca.sfu.cmpt431.message.regular.RegularBorderMsg; import ca.sfu.cmpt431.message.regular.RegularConfirmMsg; import ca.sfu.cmpt431.message.regular.RegularUpdateNeighbourMsg; import ca.sfu.network.MessageReceiver; import ca.sfu.network.MessageSender; public class Client { private static final int SERVER_PORT = 6560; private static final String SERVER_IP = "142.58.35.83"; private Comrade server; private int myPort; private String myIp = "142.58.35.122"; private MessageReceiver Receiver; private RegularConfirmMsg myConfirmMessage; private int status; private Outfits outfit; private int neiUpdCount; public boolean[] up ; public boolean[] down; public boolean[] left; public boolean[] right; public boolean upperLeft; public boolean upperRight; public boolean lowerLeft; public boolean lowerRight; private int borderCount = 0; public Client() { while(true){ Random r = new Random(); myPort = r.nextInt(55535)+10000; try{ System.out.println("trying port " + myPort); Receiver = new MessageReceiver(myPort); System.out.println("port " + myPort + "is ok"); break; } catch(Exception e){ System.out.println("port " + myPort + "is occupied"); } } } public void startClient() throws IOException, InterruptedException { MessageSender svsdr = new MessageSender(SERVER_IP, SERVER_PORT); server = new Comrade(MessageCodeDictionary.ID_SERVER, SERVER_PORT, SERVER_IP, svsdr); JoinRequestMsg Request = new JoinRequestMsg(myPort); server.sender.sendMsg(Request); status = 1; while(true){ if(!Receiver.isEmpty()){ System.out.println("status :" + status); Message msg = (Message) Receiver.getNextMessageWithIp().extracMessage(); switch(status) { // case 0: // server.sender.sendMsg(new RegularConfirmMsg(-1)); // status = 1; // break; case 1: repairOutfit((JoinOutfitsMsg) msg); sendNeiUpdMsg(); if(neiUpdCount > 0) status = 2; else { outfit.pair.sender.sendMsg(myConfirmMessage);//error System.out.println("!!!!!"); status = 3; } break; case 2: neiUpdCount if(neiUpdCount <= 0){ outfit.pair.sender.sendMsg(myConfirmMessage);//error System.out.println("!!!!!"); status = 3; } break; case 3: int msgType = msg.getMessageCode(); if(msgType == MessageCodeDictionary.REGULAR_NEXTCLOCK) { sendBorderToNeighbours(); if(isBorderMessageComplete()) computeAndReport(); else status = 4; } else if (msgType == MessageCodeDictionary.REGULAR_UPDATE_NEIGHBOUR) handleNeighbourUpdate((RegularUpdateNeighbourMsg)msg); else if (msgType == MessageCodeDictionary.JOIN_SPLIT) { System.out.println("!!!!!!!!!\nReceived split command\n!!!!!!!!!\n"); handleSplit((JoinSplitMsg) msg); status = 5; } else if (msgType == MessageCodeDictionary.REGULAR_BORDER_EXCHANGE) handleBorderMessage((RegularBorderMsg) msg); break; case 4: handleBorderMessage((RegularBorderMsg) msg); if(isBorderMessageComplete()) { computeAndReport(); status = 3; } break; case 5: if(msg.getMessageCode() != MessageCodeDictionary.REGULAR_CONFIRM){ System.out.println("type error, expect confirm message, received: " + msg.getMessageCode()); } else server.sender.sendMsg(myConfirmMessage); status = 3; break; default: System.out.println("Received unexpectd message."); break; } } } } private void repairOutfit(JoinOutfitsMsg msg) throws IOException { System.out.println("received outfit"); outfit = msg.yourOutfits; myConfirmMessage = new RegularConfirmMsg(outfit.myId); if(outfit.pair == null) outfit.pair = new Comrade(MessageCodeDictionary.ID_SERVER, SERVER_PORT, SERVER_IP, server.sender); else outfit.pair.sender = new MessageSender(outfit.pair.ip, outfit.pair.port); for(Neighbour nei: outfit.neighbour) { if(nei.comrade.id == outfit.pair.id) nei.comrade.sender = outfit.pair.sender; else { nei.comrade.sender = new MessageSender(nei.comrade.ip, nei.comrade.port); ArrayList<Integer> mypos = (ArrayList<Integer>) ClientHelper.ClientNeighbor(nei.position); nei.comrade.sender.sendMsg( new RegularUpdateNeighbourMsg(outfit.myId, mypos, myPort, myIp)); } } up = new boolean[outfit.myBoard.width]; down = new boolean[outfit.myBoard.width]; left = new boolean[outfit.myBoard.height]; right = new boolean[outfit.myBoard.height]; } private void sendNeiUpdMsg() throws IOException { neiUpdCount = 0; for(Neighbour nei: outfit.neighbour) if(nei.comrade.id != outfit.pair.id) { nei.comrade.sender.sendMsg(new RegularUpdateNeighbourMsg(outfit.myId, (ArrayList<Integer>) ClientHelper.ClientNeighbor(nei.position), myPort, myIp)); neiUpdCount++; } } private void sendBorderToNeighbours() throws IOException { int neighborCount = outfit.neighbour.size(); Border sendborder; for(int j = 0; j < neighborCount; j++) { sendborder = new Border(); sendborder.bits = getborder(outfit.neighbour.get(j).position); RegularBorderMsg sendbordermsg = new RegularBorderMsg(outfit.myId, sendborder); outfit.neighbour.get(j).comrade.sender.sendMsg(sendbordermsg); } } private void handleNeighbourUpdate(RegularUpdateNeighbourMsg msg) throws IOException { boolean isOldFriend = false; for(Neighbour nei: outfit.neighbour){ if(nei.comrade.id == msg.getClientId()) { nei.position.clear(); for(Integer q: msg.pos) nei.position.add(q); isOldFriend = true; } else { for (Integer p: nei.position){ for(Integer q: msg.pos) if(p == q) nei.position.remove(q); } if(nei.position.size() == 0){ nei.comrade.sender.close(); outfit.neighbour.remove(nei); } } } if(!isOldFriend) { Neighbour newnei = new Neighbour(msg.pos, new Comrade(msg.getClientId(), msg.port, msg.ip, new MessageSender(msg.ip, msg.port))); outfit.neighbour.add(newnei); } sendMsgToId(myConfirmMessage, msg.getClientId()); System.out.println("Neighbour after updating"); System.out.println("Neighbour size: " + outfit.neighbour.size()); int cnt = 1; for(Neighbour nei: outfit.neighbour) { System.out.println("Neighbour #" + cnt++ +" position:"); for(Integer in: nei.position) System.out.print(" " + in); System.out.println(""); } } private void handleSplit(JoinSplitMsg msg) throws IOException { List<Board> boards; Outfits pout = new Outfits(msg.newcomerId, outfit.nextClock, 0, 0, null); ArrayList<Neighbour> pnei = new ArrayList<Neighbour>(); for(Neighbour tn: outfit.neighbour) pnei.add(new Neighbour( new ArrayList<Integer>(tn.position), new Comrade(tn.comrade.id, tn.comrade.port, tn.comrade.ip, null))); pout.neighbour = pnei; Neighbour [] pn = new Neighbour[12]; for(int i = 0; i < 12; i++) pn[i] = findNeiWithPos(pout, i); Neighbour [] n = new Neighbour[12]; for(int i = 0; i < 12; i++) n[i] = findNeiWithPos(outfit, i); ArrayList<Integer> tmp = new ArrayList<Integer>(); outfit.pair = new Comrade(msg.newcomerId, msg.newcomerPort, msg.newcomerIp, new MessageSender(msg.newcomerIp, msg.newcomerPort)); if (msg.splitMode == MessageCodeDictionary.SPLIT_MODE_VERTICAL) { boards = BoardOperation.VerticalCut(outfit.myBoard); Board left, right; left = boards.get(0); right = boards.get(1); outfit.myBoard = left; pout.top = outfit.top; pout.left = outfit.left + left.width; pout.myBoard = right; pout.pair = new Comrade(outfit.myId, myPort, myIp, null); deletePos(pout, pn[10], 10); deletePos(pout, pn[11], 11); tmp = new ArrayList<Integer>(); tmp.add(10); tmp.add(11); pout.neighbour.add( new Neighbour(tmp, new Comrade(outfit.myId, myPort, myIp, null))); deletePos(outfit, n[4], 4); deletePos(outfit, n[5], 5); tmp = new ArrayList<Integer>(); tmp.add(4); tmp.add(5); outfit.neighbour.add( new Neighbour(tmp, outfit.pair)); if(n[1] == n[2]) { if(n[0] == n[1]) { addPos(n[1], 3, false); deletePos(outfit, n[3], 3); } else if(n[2] == n[3]) { addPos(pn[1], 0, true); deletePos(pout, pn[0], 0); }else { addPos(n[1], 3, false); deletePos(outfit, n[3], 3); addPos(pn[1], 0, true); deletePos(pout, pn[0], 0); } }else { addPos(n[1], 2, false); addPos(n[2], 3, false); deletePos(outfit, n[2], 2); deletePos(outfit, n[3], 3); addPos(pn[2], 1, true); addPos(pn[1], 0, true); deletePos(outfit, pn[1], 1); deletePos(outfit, pn[0], 0); } if(n[8] == n[7]) { if(n[9] == n[8]) { addPos(n[8], 6, true); deletePos(outfit, n[6], 6); } else if(n[7] == n[6]) { addPos(pn[8], 9, false); deletePos(pout, pn[9], 9); }else { addPos(n[8], 6, true); deletePos(outfit, n[6], 6); addPos(pn[8], 9, false); deletePos(pout, pn[9], 9); } }else { addPos(n[8], 7, true); addPos(n[7], 6, true); deletePos(outfit, n[7], 7); deletePos(outfit, n[6], 6); addPos(pn[7], 8, false); addPos(pn[8], 9, false); deletePos(outfit, pn[8], 8); deletePos(outfit, pn[9], 9); } } else { boards = BoardOperation.HorizontalCut(outfit.myBoard); Board top, bottom; top = boards.get(0); bottom = boards.get(1); outfit.myBoard = top; pout.top = outfit.top + top.height; pout.left = outfit.left; pout.myBoard = bottom; pout.pair = new Comrade(outfit.myId, myPort, myIp, null); deletePos(pout, pn[1], 1); deletePos(pout, pn[2], 2); tmp = new ArrayList<Integer>(); tmp.add(1); tmp.add(2); pout.neighbour.add( new Neighbour(tmp, new Comrade(outfit.myId, myPort, myIp, null))); deletePos(outfit, n[7], 7); deletePos(outfit, n[8], 8); tmp = new ArrayList<Integer>(); tmp.add(7); tmp.add(8); outfit.neighbour.add( new Neighbour(tmp, outfit.pair)); if(n[4] == n[5]) { if(n[3] == n[4]) { addPos(n[4], 6, false); deletePos(outfit, n[6], 6); } else if(n[5] == n[6]) { addPos(pn[4], 3, true); deletePos(pout, pn[3], 3); }else { addPos(n[4], 6, false); deletePos(outfit, n[6], 6); addPos(pn[4], 3, true); deletePos(pout, pn[3], 3); } }else { addPos(n[4], 5, false); addPos(n[5], 6, false); deletePos(outfit, n[5], 5); deletePos(outfit, n[6], 6); addPos(pn[5], 4, true); addPos(pn[4], 3, true); deletePos(outfit, pn[4], 4); deletePos(outfit, pn[3], 3); } if(n[11] == n[10]) { if(n[0] == n[11]) { addPos(n[11], 9, true); deletePos(outfit, n[9], 9); } else if(n[10] == n[9]) { addPos(pn[11], 0, false); deletePos(pout, pn[0], 0); }else { addPos(n[11], 9, true); deletePos(outfit, n[9], 9); addPos(pn[11], 0, false); deletePos(pout, pn[0], 0); } }else { addPos(n[11], 10, true); addPos(n[10], 9, true); deletePos(outfit, n[10], 10); deletePos(outfit, n[9], 9); addPos(pn[10], 11, false); addPos(pn[11], 0, false); deletePos(outfit, pn[11], 11); deletePos(outfit, pn[0], 0); } } System.out.println("My outfit after spliting:"); outiftInfo(outfit); System.out.println("Pair's outfit after spliting:"); outiftInfo(pout); outfit.pair.sender.sendMsg(new JoinOutfitsMsg(outfit.myId, myPort, pout)); } private void handleBorderMessage(RegularBorderMsg msg) { int cid = msg.getClientId(); int nei_id = -1; borderCount++; for(int i=0; i<outfit.neighbour.size(); i++){ if(outfit.neighbour.get(i).comrade.id == cid){ nei_id = i; break; } } //merge and update the global border array/variable // System.out.println(outfit.left); // for(Neighbour nei: outfit.neighbour){ // System.out.println("neighborID:" + nei.comrade.id); // System.out.println("border size:" + msg.boarder.bits.length); // for(Integer pos: nei.position) // System.out.print("neighborPos:" + pos + " "); // System.out.println(" " ); mergeBorder(msg.boarder.bits, outfit.neighbour.get(nei_id).position); } private boolean isBorderMessageComplete() { if(borderCount == outfit.neighbour.size()) return true; return false; } private void computeAndReport() throws IOException { BoardOperation.NextMoment(outfit.myBoard, null, null, null, null, false, false, false, false); server.sender.sendMsg(new RegularBoardReturnMsg(outfit.myId, outfit.top, outfit.left, outfit.myBoard)); borderCount = 0; } private void sendMsgToId(Message msg, int id) throws IOException { for(Neighbour nei: outfit.neighbour) if(nei.comrade.id == id) nei.comrade.sender.sendMsg(msg); } private void deletePos(Outfits out, Neighbour nei, Integer pos) { if(nei == null) return ; nei.position.remove(pos); if(nei.position.size() == 0) { if(nei.comrade.sender != null){ nei.comrade.sender.close(); out.neighbour.remove(nei); } } } private void addPos(Neighbour nei, Integer pos, boolean front) { if(nei == null) return; if(front) nei.position.add(0, pos); else nei.position.add(pos); } private void outiftInfo(Outfits out) { System.out.println("Id: " + out.myId); System.out.println("Clk: " + out.nextClock); System.out.println("Top: " + out.top); System.out.println("Left: " + out.left); System.out.println("Width:" + out.myBoard.width); System.out.println("Heig: " + out.myBoard.height); System.out.println("Neighbour size: " + out.neighbour.size()); int cnt = 1; for(Neighbour nei: out.neighbour){ System.out.print("Nei #" + cnt++ + " Id: " + nei.comrade.id +" Pos:"); for(Integer in: nei.position) System.out.print(" " + in); System.out.println(""); } System.out.println("Pair Id: " + out.pair.id); } private Neighbour findNeiWithPos(Outfits out, int pos) { for(Neighbour nei: out.neighbour) for(Integer i: nei.position) if(i == pos) return nei; return null; } protected boolean[] getborder(List<Integer> array){ Board b = outfit.myBoard; ArrayList<Boolean> al = new ArrayList<Boolean>(); int j; for(int i=0; i<array.size(); i++){ int a = array.get(i); switch(a+1){ case 1: if(al.size()!=0) break; al.add(b.bitmap[0][0]); break; case 2: j = 0; //if it is 1 already if(al.size() != 0) j = 1; for(; j<=b.width/2; j++) al.add(b.bitmap[0][j]); break; case 3: //if it is 2 already j = b.width/2-1; if(al.size() != 0) j=j+2; for(; j<b.width; j++) al.add(b.bitmap[0][j]); break; case 4: //if it is 3 already if(al.size() != 0) break; al.add(b.bitmap[0][b.width-1]); break; case 5: j = 0; //if it is 4 already if(al.size()!=0) j=1; for(; j<=b.height/2; j++) al.add(b.bitmap[j][b.width-1]); break; case 6: j = b.height/2-1; //if it is 5 already if(al.size()!=0) j=j+2; for(; j<b.height; j++) al.add(b.bitmap[j][b.width-1]); break; case 7: //if it is 6 already if(al.size()!=0) break; al.add(b.bitmap[b.height-1][b.width-1]); break; case 8: j = b.width - 1; //if it is 7 already if(al.size()!=0) j for(; j>=b.width/2-1; j al.add(b.bitmap[b.height-1][j]); break; case 9: j = b.width/2; if(al.size()!=0) j=j-2; for(; j>=0; j al.add(b.bitmap[b.height-1][j]); break; case 10: if(al.size()!=0) break; al.add(b.bitmap[b.height-1][0]); break; case 11: j = b.height-1; if(al.size()!=0) j for(; j>=b.height/2-1; j al.add(b.bitmap[j][0]); break; case 12: j = b.height/2; if(al.size()!=0) j=j-2; for(; j>=0; j al.add(b.bitmap[j][0]); break; } } boolean[] a = new boolean[al.size()]; for(int k=0; k<a.length; k++){ a[k]=(boolean)al.get(k); // System.out.print(al.get(k)); } return a; } //comment protected void mergeBorder(boolean[] aa, List<Integer> array1){ ArrayList<Boolean> tmp = new ArrayList<Boolean>(); for(int i=0; i<aa.length; i++){ tmp.add(aa[i]); } //error System.out.println("incoming size:"+tmp.size()); for(int i=0; i<array1.size(); i++){ System.out.print(array1.get(i)); } System.out.println(); Board b = outfit.myBoard; for(int i=0; i<array1.size(); i++){ if(tmp.size()==0) break; System.out.println("size"+tmp.size()); int num = array1.get(i); switch(num+1){ case 1: upperLeft = (boolean) tmp.get(0); tmp.remove(0); break; case 2: for(int p=0; p<b.width/2; p++){ up[p] = (boolean)tmp.get(0); tmp.remove(0); } break; case 3: for(int p=b.width/2; p<b.width; p++){ up[p] = (boolean)tmp.get(0); tmp.remove(0); } break; case 4: upperRight = (boolean)tmp.get(0); tmp.remove(0); break; case 5: for(int p=0; p<b.height/2; p++){ right[p] = (boolean)tmp.get(0); tmp.remove(0); } break; case 6: for(int p=b.height/2; p<b.height; p++){ right[p] = (boolean)tmp.get(0); tmp.remove(0); } break; case 7: lowerRight = (boolean)tmp.get(0); tmp.remove(0); break; case 8: for(int p=b.width-1; p>=b.width/2; p down[p] = (boolean)tmp.get(0); tmp.remove(0); } break; case 9: for(int p=b.width/2-1; p>=0; p down[p] = (boolean)tmp.get(0); tmp.remove(0); } break; case 10: lowerLeft = (boolean)tmp.get(0); tmp.remove(0); break; case 11: for(int p=b.height-1; p>=b.height/2; p System.out.println("11 board "+outfit.myBoard.height+" p "+p); left[p] = (boolean)tmp.get(0); tmp.remove(0); } break; case 12: for(int p=b.height/2-1; p>=0; p System.out.println("12 board "+outfit.myBoard.height+" p "+p); left[p] = (boolean)tmp.get(0); tmp.remove(0); } break; } } } }
package com.morihacky.android.rxjava; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import com.morihacky.android.rxjava.app.R; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnTextChanged; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.Subscription; import rx.android.observables.AndroidObservable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; import timber.log.Timber; public class SubjectDebounceSearchEmitterFragment extends Fragment { @InjectView(R.id.list_threading_log) ListView _logsList; private LogAdapter _adapter; private List<String> _logs; private Subscription _subscription; private PublishSubject<Observable<String>> _searchTextEmitterSubject; @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); _setupLogger(); _searchTextEmitterSubject = PublishSubject.create(); _subscription = AndroidObservable.bindFragment(SubjectDebounceSearchEmitterFragment.this, Observable.switchOnNext(_searchTextEmitterSubject)) // .debounce(400, TimeUnit.MILLISECONDS, Schedulers.io()) .throttleFirst(400, TimeUnit.MILLISECONDS, Schedulers.io()) .timeout(400, TimeUnit.MILLISECONDS, Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(_getSearchObserver()); } private Observer<String> _getSearchObserver() { return new Observer<String>() { @Override public void onCompleted() { Timber.d(" } @Override public void onError(Throwable e) { Timber.e(e, " _log(String.format("Dang error. check your logs")); } @Override public void onNext(String searchText) { _log(String.format("onNext You searched for %s", searchText)); onCompleted(); } }; } @OnTextChanged(R.id.input_txt_subject_debounce) public void onTextEntered(CharSequence charsEntered) { Timber.d(" _searchTextEmitterSubject.onNext(_getASearchObservableFor(charsEntered.toString())); } // Main Rx entities /** * @param searchText search text entered onTextChange * * @return a new observable which searches for text searchText, explicitly say you want subscription to be done on a a non-UI thread, otherwise it'll default to the main thread. */ private Observable<String> _getASearchObservableFor(final String searchText) { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { Timber.d(" subscriber.onNext(searchText); // subscriber.onCompleted(); This seems to have no effect. } }).subscribeOn(Schedulers.io()); } @Override public void onDestroy() { super.onDestroy(); _subscription.unsubscribe(); } // Method that help wiring up the example (irrelevant to RxJava) @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_subject_debounce, container, false); ButterKnife.inject(this, layout); return layout; } private void _setupLogger() { _logs = new ArrayList<String>(); _adapter = new LogAdapter(getActivity(), new ArrayList<String>()); _logsList.setAdapter(_adapter); } private void _log(String logMsg) { if (_isCurrentlyOnMainThread()) { _logs.add(0, logMsg + " (main thread) "); _adapter.clear(); _adapter.addAll(_logs); } else { _logs.add(0, logMsg + " (NOT main thread) "); // You can only do below stuff on main thread. new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { _adapter.clear(); _adapter.addAll(_logs); } }); } } private boolean _isCurrentlyOnMainThread() { return Looper.myLooper() == Looper.getMainLooper(); } private class LogAdapter extends ArrayAdapter<String> { public LogAdapter(Context context, List<String> logs) { super(context, R.layout.item_log, R.id.item_log, logs); } } }
package com.optimalorange.cooltechnologies.ui.fragment; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.etsy.android.grid.StaggeredGridView; import com.optimalorange.cooltechnologies.R; import com.optimalorange.cooltechnologies.entity.FavoriteBean; import com.optimalorange.cooltechnologies.entity.Video; import com.optimalorange.cooltechnologies.network.NetworkChecker; import com.optimalorange.cooltechnologies.network.VideosRequest; import com.optimalorange.cooltechnologies.network.VolleySingleton; import com.optimalorange.cooltechnologies.ui.PlayVideoActivity; import com.optimalorange.cooltechnologies.util.Utils; import com.umeng.analytics.MobclickAgent; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.SearchView; import android.widget.TextView; import java.util.LinkedList; import java.util.List; public class ListVideosFragment extends SwipeRefreshFragment { // Fragment /** * Videogenre<br/> * Type: String * * @see #newInstance(String genre) */ public static final String ARGUMENT_KEY_GENRE = ListVideosFragment.class.getName() + ".argument.KEY_GENRE"; private static final String CATEGORY_LABEL_OF_TECH = ""; private String mYoukuClientId; private NetworkChecker mNetworkChecker; private final RequestsManager mRequestsManager = new RequestsManager(); /** * truefalse */ private boolean mIsConnected = false; private BroadcastReceiver mNetworkReceiver; private View mNoConnectionView; private View mEmptyView; private View mMainContentView; private VolleySingleton mVolleySingleton; /** * VideogenrenullVideo * * @see #ARGUMENT_KEY_GENRE */ @Nullable private String mGenre; private int mPage = 1; private StaggeredGridView mGridView; private ItemsAdapter mItemsAdapter; private LinkedList<Video> mListVideos = new LinkedList<Video>(); /** * VideoentityVideo * * @return VideoRequest */ private VideosRequest buildQueryVideosRequest() { VideosRequest.Builder builder = new VideosRequest.Builder() .setClient_id(mYoukuClientId) .setCategory(CATEGORY_LABEL_OF_TECH) .setPage(mPage) .setPeriod(VideosRequest.Builder.PERIOD.WEEK) .setOrderby(VideosRequest.Builder.ORDER_BY.VIEW_COUNT) .setResponseListener(new Response.Listener<List<Video>>() { @Override public void onResponse(List<Video> videos) { for (Video mVideo : videos) { mListVideos.add(mVideo); } applyVideos(); mRequestsManager.addRequestRespondeds(); } }) .setErrorListener(new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); mRequestsManager.addRequestErrors(); } }); //Video mPage++; //mGenremGenreVideo if (mGenre != null) { builder.setGenre(mGenre); } return builder.build(); } /** * {@link ListVideosFragment} * * @param genre Videogenre * @return * @see #ARGUMENT_KEY_GENRE */ public static ListVideosFragment newInstance(String genre) { ListVideosFragment fragment = new ListVideosFragment(); Bundle arguments = new Bundle(); arguments.putString(ARGUMENT_KEY_GENRE, genre); fragment.setArguments(arguments); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Arguments if (getArguments() != null) { mGenre = getArguments().getString(ARGUMENT_KEY_GENRE); } mYoukuClientId = getString(R.string.youku_client_id); mVolleySingleton = VolleySingleton.getInstance(getActivity()); mNetworkChecker = NetworkChecker.newInstance(getActivity()); IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); mNetworkReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { setIsConnected(mNetworkChecker.isConnected()); } }; getActivity().registerReceiver(mNetworkReceiver, filter); //view setIsConnected(mNetworkChecker.isConnected()); applyIsConnected(); setHasOptionsMenu(true); } @Override public View onCreateChildView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_list_videos, container, false); mMainContentView = rootView.findViewById(R.id.main_content); mGridView = (StaggeredGridView) rootView.findViewById(R.id.grid_view); mEmptyView = rootView.findViewById(android.R.id.empty); mNoConnectionView = rootView.findViewById(R.id.no_connection); return rootView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mItemsAdapter = new ItemsAdapter(mListVideos, mVolleySingleton.getImageLoader()); mGridView.setAdapter(mItemsAdapter); mNoConnectionView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setConnection(); } }); applyVideos(); applyIsConnected(); if (mIsConnected && listVideosIsEmpty()) { setRefreshing(true); startLoad(); } //item mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent mIntent = new Intent(getActivity(), PlayVideoActivity.class); FavoriteBean favoriteBean = new FavoriteBean(mListVideos.get(i)); mIntent.putExtra(PlayVideoActivity.EXTRA_KEY_VIDEO, favoriteBean); startActivity(mIntent); } }); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(getClass().getSimpleName()); } @Override public void onPause() { MobclickAgent.onPageEnd(getClass().getSimpleName()); super.onPause(); } @Override public void onDestroyView() { mNoConnectionView = null; mEmptyView = null; mGridView.setAdapter(null); mGridView = null; mMainContentView = null; super.onDestroyView(); } @Override public void onDestroy() { cancelLoad(); mItemsAdapter = null; if (mNetworkReceiver != null) { getActivity().unregisterReceiver(mNetworkReceiver); } mNetworkReceiver = null; mNetworkChecker = null; super.onDestroy(); } @Override public void onRefresh() { //Video mListVideos.clear(); mPage = 1; mItemsAdapter.notifyDataSetChanged(); restartLoad(); } @Override protected boolean canChildScrollUp() { return mGridView.getVisibility() == View.VISIBLE && mGridView.canScrollVertically(-1); } private void startLoad() { if (mIsConnected) { mRequestsManager.addRequest(buildQueryVideosRequest()); } } private void restartLoad() { cancelLoad(); startLoad(); } private void cancelLoad() { mVolleySingleton.getRequestQueue().cancelAll(this); mRequestsManager.reset(); } private void onLoadFinished() { setRefreshing(false); } public void setIsConnected(boolean isConnected) { if (mIsConnected != isConnected) { mIsConnected = isConnected; applyIsConnected(); } } private void applyIsConnected() { if (mNoConnectionView != null) { mNoConnectionView.setVisibility(mIsConnected ? View.GONE : View.VISIBLE); } if (mMainContentView != null) { mMainContentView.setVisibility(mIsConnected ? View.VISIBLE : View.GONE); } setRefreshable(mIsConnected); } public boolean videosIsEmpty() { return mListVideos == null || mListVideos.size() == 0; } public boolean listVideosIsEmpty() { return mListVideos.size() == 0; } private void applyVideos() { if (mItemsAdapter != null) { mItemsAdapter.notifyDataSetChanged(); } final boolean isEmpty = videosIsEmpty(); if (mEmptyView != null) { mEmptyView.setVisibility(isEmpty ? View.VISIBLE : View.GONE); } } private boolean setConnection() { return NetworkChecker.openWirelessSettings(getActivity()); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_search, menu); // Associate searchable configuration with the SearchView SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setSearchableInfo( searchManager.getSearchableInfo(getActivity().getComponentName())); } /** * {@link com.android.volley.Request Requests}Requests */ private class RequestsManager { private int mRequests = 0; private int mRequestRespondeds = 0; private int mRequestErrors = 0; private int mRequestCancelleds = 0; /** * {@link com.android.volley.Request}0 */ private void reset() { mRequests = mRequestRespondeds = mRequestErrors = mRequestCancelleds = 0; } /** * {@link com.android.volley.Request} * * @return Request */ public int addRequest(Request request) { mVolleySingleton.addToRequestQueue(request); return mRequests++; } /** * {@link Request} * * @return Request */ public int addRequestRespondeds() { int result = mRequestRespondeds++; checkIsAllRequestsFinished(); return result; } /** * {@link Request} * * @return Request */ public int addRequestErrors() { int result = mRequestErrors++; checkIsAllRequestsFinished(); return result; } /** * {@link Request} * * @return Request */ public int addRequestCancelleds() { int result = mRequestCancelleds++; checkIsAllRequestsFinished(); return result; } public int getRequestFinisheds() { return mRequestRespondeds + mRequestErrors; } public boolean isAllRequestsFinished() { return mRequests == getRequestFinisheds() + mRequestCancelleds; } private void checkIsAllRequestsFinished() { if (isAllRequestsFinished()) { onLoadFinished(); } } } /** * * * @author Zhou Peican */ private class ItemsAdapter extends BaseAdapter { private LinkedList<Video> mVideos; private ImageLoader mImageLoader; public ItemsAdapter(LinkedList<Video> mVideos, ImageLoader mImageLoader) { super(); this.mVideos = mVideos; this.mImageLoader = mImageLoader; } @Override public int getCount() { return mVideos.size(); } @Override public Object getItem(int position) { return mVideos.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder vh; if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_video, parent, false); vh = new ViewHolder(); vh.thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail); vh.duration = (TextView) convertView.findViewById(R.id.duration); vh.title = (TextView) convertView.findViewById(R.id.title); vh.viewCount = (TextView) convertView.findViewById(R.id.view_count); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } mImageLoader.get(mVideos.get(position).getThumbnail_v2(), ImageLoader.getImageListener(vh.thumbnail, R.mipmap.ic_launcher, R.mipmap.ic_launcher)); vh.duration.setText(Utils.getDurationString(mVideos.get(position).getDuration())); vh.title.setText(mVideos.get(position).getTitle()); vh.viewCount.setText(String.format(getString(R.string.view_count), Utils.formatViewCount(mVideos.get(position).getView_count(), parent.getContext()))); //Video if (position == mListVideos.size() - 2) { mVolleySingleton.addToRequestQueue(buildQueryVideosRequest()); } return convertView; } private class ViewHolder { ImageView thumbnail; TextView duration; TextView title; TextView viewCount; } } }
package org.opencms.lock; import org.opencms.db.CmsDriverManager; import com.opencms.core.CmsException; import com.opencms.core.I_CmsConstants; import com.opencms.file.CmsProject; import com.opencms.file.CmsRequestContext; import com.opencms.file.CmsResource; import com.opencms.flex.util.CmsUUID; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public final class CmsLockDispatcher extends Object { /** The shared lock dispatcher instance */ private static CmsLockDispatcher sharedInstance; /** A map holding the exclusive CmsLocks */ private transient Map m_exclusiveLocks; /** * Default constructor.<p> */ private CmsLockDispatcher() { super(); m_exclusiveLocks = Collections.synchronizedMap(new HashMap()); } /** * Returns the shared instance of the lock dispatcher.<p> * * @return the shared instance of the lock dispatcher */ public static synchronized CmsLockDispatcher getInstance() { if (sharedInstance == null) { sharedInstance = new CmsLockDispatcher(); } return sharedInstance; } /** * Adds a resource to the lock dispatcher.<p> * * @param driverManager the driver manager * @param context the current request context * @param resourcename the full resource name including the site root * @param userId the ID of the user who locked the resource * @param projectId the ID of the project where the resource is locked * @param hierachy flag indicating how the resource is locked * @return the new CmsLock object for the added resource */ public void addResource(CmsDriverManager driverManager, CmsRequestContext context, String resourcename, CmsUUID userId, int projectId) throws CmsException { CmsLock lock = getLock(driverManager, context, resourcename); if (!lock.isNullLock() && !lock.getUserId().equals(context.currentUser().getId()) && lock.getProjectId() != context.currentProject().getId()) { throw new CmsLockException("Resource is already locked by another user", CmsLockException.C_RESOURCE_LOCKED_BY_OTHER_USER); } CmsLock newLock = new CmsLock(resourcename, userId, projectId, CmsLock.C_TYPE_EXCLUSIVE); m_exclusiveLocks.put(resourcename, newLock); // handle collisions with exclusive locked sub-resources in case of a folder if (resourcename.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) { Iterator i = m_exclusiveLocks.keySet().iterator(); String lockedPath = null; while (i.hasNext()) { lockedPath = (String) i.next(); if (lockedPath.startsWith(resourcename) && !lockedPath.equals(resourcename)) { i.remove(); } } } } /** * Counts the exclusive locked resources in a project.<p> * * @param project the project * @return the number of exclusive locked resources in the specified project */ public int countExclusiveLocksInProject(CmsProject project) { Iterator i = m_exclusiveLocks.values().iterator(); CmsLock lock = null; int count = 0; while (i.hasNext()) { lock = (CmsLock) i.next(); if (lock.getProjectId() == project.getId()) { count++; } } return count; } /** * @see java.lang.Object#finalize() */ protected void finalize() throws Throwable { if (m_exclusiveLocks != null) { m_exclusiveLocks.clear(); m_exclusiveLocks = null; sharedInstance = null; } } /** * Returns the lock for a resource name.<p> * * @param driverManager the driver manager * @param context the current request context * @param resourcename the full resource name including the site root * @return the CmsLock if the specified resource is locked, or the shared Null lock if the resource is not locked */ public CmsLock getLock(CmsDriverManager driverManager, CmsRequestContext context, String resourcename) throws CmsException { CmsLock parentFolderLock = null; CmsLock siblingLock = null; CmsResource sibling = null; CmsResource resource = null; // check some abort conditions first if (context.currentProject().getId() == I_CmsConstants.C_PROJECT_ONLINE_ID) { // resources are never locked in the online project return CmsLock.getNullLock(); } resource = internalReadFileHeader(driverManager, context, resourcename); if (resource == null || resource.getState() == I_CmsConstants.C_STATE_DELETED) { // deleted, removed or non-existent resources are never locked return CmsLock.getNullLock(); } // try to find an exclusive lock if (m_exclusiveLocks.containsKey(resourcename)) { // the resource is exclusive locked return (CmsLock) m_exclusiveLocks.get(resourcename); } // calculate the lock state // fetch all siblings of the resource to the same content record List siblings = driverManager.getAllSiblings(context, resourcename); if ((parentFolderLock = getParentFolderLock(resourcename)) == null) { // all parent folders are unlocked for (int i = 0; i < siblings.size(); i++) { sibling = (CmsResource) siblings.get(i); siblingLock = (CmsLock) m_exclusiveLocks.get(sibling.getFullResourceName()); if (siblingLock != null) { // a sibling is already exclusive locked return new CmsLock(resourcename, siblingLock.getUserId(), siblingLock.getProjectId(), CmsLock.C_TYPE_SHARED_EXCLUSIVE); } } // no locked siblings found return CmsLock.getNullLock(); } else { // a parent folder is locked for (int i = 0; i < siblings.size(); i++) { sibling = (CmsResource) siblings.get(i); if (m_exclusiveLocks.containsKey(sibling.getFullResourceName())) { // a sibling is already exclusive locked return new CmsLock(resourcename, parentFolderLock.getUserId(), parentFolderLock.getProjectId(), CmsLock.C_TYPE_SHARED_INHERITED); } } // no locked siblings found return new CmsLock(resourcename, parentFolderLock.getUserId(), parentFolderLock.getProjectId(), CmsLock.C_TYPE_INHERITED); } } /** * Returns the lock of the exclusive locked sibling pointing to the resource record of a * specified resource name.<p> * * @param driverManager the driver manager * @param context the current request context * @param resourcename the name of the specified resource * @return the lock of the exclusive locked sibling * @throws CmsException if somethong goes wrong */ public CmsLock getExclusiveLockedSibling(CmsDriverManager driverManager, CmsRequestContext context, String resourcename) throws CmsException { CmsResource sibling = null; // check first if the specified resource itself is already the exclusive locked sibling if (m_exclusiveLocks.containsKey(resourcename)) { // yup... return (CmsLock) m_exclusiveLocks.get(resourcename); } // nope, fetch all siblings of the resource to the same content record List siblings = driverManager.getAllSiblings(context, resourcename); for (int i = 0; i < siblings.size(); i++) { sibling = (CmsResource) siblings.get(i); if (m_exclusiveLocks.containsKey(sibling.getFullResourceName())) { return (CmsLock) m_exclusiveLocks.get(sibling.getFullResourceName()); } } return CmsLock.getNullLock(); } /** * Returns the lock of a possible locked parent folder of a resource.<p> * * @param resourcename the name of the resource * @return the lock of a parent folder, or null if no parent folders are locked */ private CmsLock getParentFolderLock(String resourcename) { String lockedPath = null; Iterator i = m_exclusiveLocks.keySet().iterator(); while (i.hasNext()) { lockedPath = (String) i.next(); if (resourcename.startsWith(lockedPath) && !resourcename.equals(lockedPath) && lockedPath.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) { return (CmsLock) m_exclusiveLocks.get(lockedPath); } } return null; } private CmsResource internalReadFileHeader(CmsDriverManager driverManager, CmsRequestContext context, String resourcename) throws CmsException { CmsResource resource = null; // reading a resource using readFileHeader while the lock state is checked would // inevitably result in an infinite loop... try { List path = driverManager.readPath(context, resourcename, false); resource = (CmsResource) path.get(path.size() - 1); } catch (CmsException e) { resource = null; } return resource; } /** * Proves if a resource is locked.<p> * * Use {@link org.opencms.lock.CmsLockDispatcher#getLock(CmsRequestContext, String)} * to obtain a CmsLock object for the specified resource to get further information * about how the resource is locked. * * @param driverManager the driver manager * @param context the current request context * @param resourcename the full resource name including the site root * @return true, if and only if the resource is currently locked */ public boolean isLocked(CmsDriverManager driverManager, CmsRequestContext context, String resourcename) throws CmsException { CmsLock lock = getLock(driverManager, context, resourcename); return !lock.isNullLock(); } /** * Removes a resource from the lock dispatcher.<p> * * @param driverManager the driver manager * @param context the current request context * @param resourcename the full resource name including the site root * @param forceUnlock true, if a resource is force to get unlocked, no matter by which user and in which project the resource is currently locked * @return the previous CmsLock object of the resource, or null if the resource was unlocked * @throws CmsLockException if the user tried to unlock a resource in a locked folder */ public CmsLock removeResource(CmsDriverManager driverManager, CmsRequestContext context, String resourcename, boolean forceUnlock) throws CmsException { CmsLock lock = getLock(driverManager, context, resourcename); CmsResource sibling = null; // check some abort conditions first if (lock.isNullLock()) { // the resource isn't locked return null; } if (!forceUnlock && (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId())) { // the resource is locked by another user throw new CmsLockException("Unable to unlock resource, resource is locked by another user and/or in another project", CmsLockException.C_RESOURCE_LOCKED_BY_OTHER_USER); } //if (!forceUnlock && (lock.getType() == CmsLock.C_TYPE_INHERITED || lock.getType() == CmsLock.C_TYPE_SHARED_INHERITED || (getParentFolderLock(resourcename) != null))) { if (lock.getType() == CmsLock.C_TYPE_INHERITED || lock.getType() == CmsLock.C_TYPE_SHARED_INHERITED || (getParentFolderLock(resourcename) != null)) { // sub-resources of a locked folder can't be unlocked throw new CmsLockException("Unable to unlock resource due to an inherited lock of a parent folder", CmsLockException.C_RESOURCE_LOCKED_INHERITED); } // remove the lock and clean-up stuff if (lock.getType() == CmsLock.C_TYPE_EXCLUSIVE) { if (resourcename.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) { // in case of a folder, remove any exclusive locks on sub-resources that probably have // been upgraded from an inherited lock when the user edited a resource Iterator i = m_exclusiveLocks.keySet().iterator(); String lockedPath = null; while (i.hasNext()) { lockedPath = (String) i.next(); if (lockedPath.startsWith(resourcename) && !lockedPath.equals(resourcename)) { // remove the exclusive locked sub-resource i.remove(); } } } return (CmsLock) m_exclusiveLocks.remove(resourcename); } if (lock.getType() == CmsLock.C_TYPE_SHARED_EXCLUSIVE) { // when a resource with a shared lock gets unlocked, fetch all siblings of the resource // to the same content record to identify the exclusive locked sibling List siblings = driverManager.getAllSiblings(context, resourcename); for (int i = 0; i < siblings.size(); i++) { sibling = (CmsResource) siblings.get(i); if (m_exclusiveLocks.containsKey(sibling.getFullResourceName())) { // remove the exclusive locked sibling m_exclusiveLocks.remove(sibling.getFullResourceName()); break; } } return lock; } return lock; } /** * Removes all resources that are exclusive locked in a project.<p> * * @param projectId the ID of the project where the resources have been locked */ public void removeResourcesInProject(int projectId) { Iterator i = m_exclusiveLocks.keySet().iterator(); CmsLock currentLock = null; while (i.hasNext()) { currentLock = (CmsLock) m_exclusiveLocks.get(i.next()); if (currentLock.getProjectId() == projectId) { // iterators are fail-fast! i.remove(); } } } /** * @see java.lang.Object#toString() */ public String toString() { // bring the list of locked resources into a human readable order first List lockedResources = (List) new ArrayList(m_exclusiveLocks.keySet()); Collections.sort(lockedResources); Iterator i = lockedResources.iterator(); StringBuffer buf = new StringBuffer(); String lockedPath = null; CmsLock currentLock = null; while (i.hasNext()) { lockedPath = (String) i.next(); currentLock = (CmsLock) m_exclusiveLocks.get(lockedPath); buf.append(currentLock.toString()).append("\n"); } return buf.toString(); } }
package jp.gr.java_conf.neko_daisuki.simplemediascanner; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Typeface; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; public class DirectoryFragment extends DialogFragment { public interface OnSelectedListener { public void onSelected(DirectoryFragment fragment, String path); } private static class FileComparator implements Comparator<File> { @Override public int compare(File lhs, File rhs) { if (lhs.isDirectory() && !rhs.isDirectory()) { return -1; } if (!lhs.isDirectory() && rhs.isDirectory()) { return 1; } return lhs.getName().compareTo(rhs.getName()); } } private class OnClickListener implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialog, int which) { mListener.onSelected(DirectoryFragment.this, mPath); } } private class Adapter extends BaseAdapter { private class OnClickListener implements View.OnClickListener { private int mPosition; public OnClickListener(int position) { mPosition = position; } @Override public void onClick(View v) { String path = String.format("%s/%s", mPath, getName(mPosition)); File file = new File(path); String canonicalPath; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); Context context = getActivity(); String message = e.getMessage(); Toast.makeText(context, message, Toast.LENGTH_LONG).show(); return; } setPath(canonicalPath.equals("") ? "/" : canonicalPath); mLabel.setText(mPath); mAdapter.notifyDataSetChanged(); } } @Override public int getCount() { return mFiles.length + 1; } @Override public Object getItem(int position) { return getName(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { return getView(position, makeView(position), parent); } TextView view = (TextView)convertView; view.setOnClickListener(getListener(position)); view.setTypeface(Typeface.DEFAULT, getStyle(position)); view.setText(getName(position)); return view; } private View makeView(int position) { return new TextView(getActivity()); } private View.OnClickListener getListener(int position) { if (position == 0) { return new OnClickListener(position); } boolean isDirectory = mFiles[position - 1].isDirectory(); return isDirectory ? new OnClickListener(position) : null; } private int getStyle(int position) { if (position == 0) { return Typeface.NORMAL; } return mFiles[position - 1].isDirectory() ? Typeface.NORMAL : Typeface.ITALIC; } private String getName(int position) { return position == 0 ? ".." : mFiles[position - 1].getName(); } } private static final String KEY_INITIAL_DIRECTORY = "initial_directory"; private static final Comparator<File> COMPARATOR = new FileComparator(); // documents private String mPath; private File[] mFiles; private OnSelectedListener mListener; // views private BaseAdapter mAdapter; private TextView mLabel; public static DialogFragment newInstance(String initialDirectory) { DialogFragment fragment = new DirectoryFragment(); Bundle args = new Bundle(); args.putString(KEY_INITIAL_DIRECTORY, initialDirectory); fragment.setArguments(args); return fragment; } @Override public void onAttach(Activity activity) { super.onAttach(activity); mListener = (OnSelectedListener)activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String path = getArguments().getString(KEY_INITIAL_DIRECTORY); setPath(new File(path).isDirectory() ? path : Environment.getExternalStorageDirectory().getAbsolutePath()); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Context context = getActivity(); String name = Context.LAYOUT_INFLATER_SERVICE; Object o = context.getSystemService(name); LayoutInflater inflater = (LayoutInflater)o; View view = inflater.inflate(R.layout.fragment_directory, null); mLabel = (TextView)view.findViewById(R.id.label); mLabel.setText(mPath); AbsListView list = (AbsListView)view.findViewById(R.id.list); mAdapter = new Adapter(); list.setAdapter(mAdapter); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setPositiveButton(R.string.positive, new OnClickListener()); builder.setNegativeButton(R.string.negative, null); builder.setTitle("Select a directory"); builder.setView(view); return builder.create(); } private void setPath(String path) { mPath = path; File[] files = new File(mPath).listFiles(); Arrays.sort(files, COMPARATOR); mFiles = files; } }
package org.eclipse.birt.report.designer.ui.lib.explorer.action; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; import org.eclipse.birt.report.designer.internal.ui.resourcelocator.ResourceEntry; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.lib.explorer.LibraryExplorerTreeViewPage; import org.eclipse.birt.report.designer.ui.lib.explorer.dialog.MoveResourceDialog; import org.eclipse.birt.report.designer.ui.util.ExceptionUtil; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.window.Window; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.dialogs.SelectionDialog; /** * The action class for moving resources in resource explorer. */ public class MoveResourceAction extends ResourceAction { /** * Constructs an action for moving resource. * * @param page * the resource explorer page */ public MoveResourceAction( LibraryExplorerTreeViewPage page ) { super( Messages.getString( "MoveLibraryAction.Text" ), page ); //$NON-NLS-1$ setId( ActionFactory.MOVE.getId( ) ); } @Override public boolean isEnabled( ) { return canModifySelectedResources( ); } @Override public void run( ) { Collection<File> files = null; try { files = getSelectedFiles( ); } catch ( IOException e ) { ExceptionUtil.handle( e ); } if ( files == null || files.isEmpty( ) ) { return; } SelectionDialog dialog = new MoveResourceDialog( files ); dialog.setHelpAvailable( true ); if ( dialog.open( ) == Window.OK ) { Object[] selected = dialog.getResult( ); if ( selected != null && selected.length == 1 ) { try { ResourceEntry entry = (ResourceEntry) selected[0]; IPath targetPath = new Path( convertToFile( entry.getURL( ) ).getAbsolutePath( ) ); for ( File file : files ) { moveFile( file, targetPath.append( file.getName( ) ) .toFile( ) ); } } catch ( IOException e ) { ExceptionUtil.handle( e ); } catch ( InvocationTargetException e ) { ExceptionUtil.handle( e ); } catch ( InterruptedException e ) { ExceptionUtil.handle( e ); } } } } /** * Moves the specified source file to the specified target file. * * @param srcFile * the source file. * @param targetFile * the target file * @exception InvocationTargetException * if the run method must propagate a checked exception, it * should wrap it inside an * <code>InvocationTargetException</code>; runtime exceptions * and errors are automatically wrapped in an * <code>InvocationTargetException</code> by this method * @exception InterruptedException * if the operation detects a request to cancel, using * <code>IProgressMonitor.isCanceled()</code>, it should exit * by throwing <code>InterruptedException</code>; this method * propagates the exception */ private void moveFile( File srcFile, File targetFile ) throws InvocationTargetException, InterruptedException { if ( targetFile.exists( ) ) { if ( !MessageDialog.openQuestion( getShell( ), Messages.getString( "MoveResourceAction.Dialog.Title" ), //$NON-NLS-1$ Messages.getString( "MoveResourceAction.Dialog.Message" ) ) ) //$NON-NLS-1$ { return; } new ProgressMonitorDialog( getShell( ) ).run( true, true, createDeleteRunnable( Arrays.asList( new File[]{ targetFile } ) ) ); } new ProgressMonitorDialog( getShell( ) ).run( true, true, createRenameFileRunnable( srcFile, targetFile ) ); } }
package aQute.bnd.ant; /** * The idea of this task is to read all the properties as if bnd has read them. * This makes it easier to use bnd standalone on the same data. */ import java.io.*; import java.util.*; import org.apache.tools.ant.*; import aQute.bnd.build.*; import aQute.bnd.build.Project; import aQute.bnd.osgi.*; public class PrepareTask extends BaseTask { File basedir; boolean print = false; String top; @Override public void execute() throws BuildException { try { if (basedir == null || !basedir.isDirectory()) throw new BuildException("The given base dir does not exist " + basedir); Workspace workspace = Workspace.getWorkspace(basedir.getParentFile()); workspace.addBasicPlugin(new ConsoleProgress()); Project project = workspace.getProject(basedir.getName()); if (project == null) throw new BuildException("Unable to find bnd project in directory: " + basedir); project.setProperty("in.ant", "true"); project.setProperty("environment", "ant"); // Check if we are in a sub build, in that case // top will be set to the target directory at the // top project. if (top != null && top.length() > 0 && !top.startsWith("$")) project.setProperty("top", top); project.setExceptions(true); Properties properties = project.getFlattenedProperties(); checkForTesting(project, properties); if (report() || report(workspace) || report(project)) throw new BuildException("Errors during preparing bnd"); copyProperties(properties); } catch (Exception e) { e.printStackTrace(); throw new BuildException(e); } } private void checkForTesting(Project project, Properties properties) throws Exception { // Only run junit when we have a junit dependency on the cp // with "junit" in it. boolean junit = project.getTestSrc().isDirectory() && !Processor.isTrue(project.getProperty(Constants.NOJUNIT)); boolean junitOsgi = project.getProperty("Test-Cases") != null && !Processor.isTrue(project.getProperty(Constants.NOJUNITOSGI)); if (junit) properties.setProperty("project.junit", "true"); if (junitOsgi) properties.setProperty("project.osgi.junit", "true"); } private void copyProperties(Properties flattened) { for (Enumeration< ? > k = flattened.propertyNames(); k.hasMoreElements();) { String key = (String) k.nextElement(); String value = flattened.getProperty(key); if (isPrint()) System.err.printf("%-20s = %s%n", key, value); // We override existing values. getProject().setProperty(key, value.trim()); } } public boolean isPrint() { return print; } /** * Print out the properties when they are set in sorted order * * @param print */ public void setPrint(boolean print) { this.print = print; } /** * Set the base directory of the project. This property MUST be set. * * @param basedir */ public void setBasedir(File basedir) { this.basedir = basedir; } /** * Set the base directory of the project. This property MUST be set. * * @param basedir */ public void setTop(String top) { this.top = top; } }
package com.nyaruka.sigtrac; import android.app.ActivityManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { checkService(context); } public static boolean checkService(Context context){ if(!isServiceRunning(context)){ startService(context); return false; } else { return true; } } private static void startService(Context context){ context.startService(new Intent(context, PingService.class)); } private static boolean isServiceRunning(Context context) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (PingService.class.getName().equals(service.service.getClassName())) { return true; } } return false; } }
package org.commcare.android.resource.installers; import org.commcare.CommCareApplication; import org.commcare.android.database.app.models.UserKeyRecord; import org.commcare.models.database.user.DatabaseUserOpenHelper; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceInitializationException; import org.commcare.resources.model.UnresolvedResourceException; import org.commcare.suite.model.OfflineUserRestore; import org.commcare.utils.AndroidCommCarePlatform; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.Reference; import org.javarosa.core.services.storage.EntityFilter; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.xmlpull.v1.XmlPullParserException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * @author Phillip Mates (pmates@dimagi.com) * @author Aliza Stone (astone@dimagi.com) */ public class OfflineUserRestoreAndroidInstaller extends FileSystemInstaller { @SuppressWarnings("unused") public OfflineUserRestoreAndroidInstaller() { // for externalization } public OfflineUserRestoreAndroidInstaller(String localDestination, String upgradeDestination) { super(localDestination, upgradeDestination); } @Override public boolean initialize(AndroidCommCarePlatform instance, boolean isUpgrade) throws ResourceInitializationException { instance.registerDemoUserRestore(initDemoUserRestore()); return true; } private OfflineUserRestore initDemoUserRestore() throws ResourceInitializationException { try { return new OfflineUserRestore(localLocation); } catch (UnfullfilledRequirementsException e) { throw new ResourceInitializationException(e.getMessage(), e); } catch (IOException | InvalidStructureException | XmlPullParserException e) { throw new ResourceInitializationException("Demo user restore file was malformed, " + "the following error occurred during parsing: " + e.getMessage(), e); } catch (InvalidReferenceException e) { throw new ResourceInitializationException( "Reference to demo user restore file was invalid: " + e.getMessage(), e); } } @Override protected int customInstall(Resource r, Reference local, boolean upgrade) throws IOException, UnresolvedResourceException { // To make sure that we won't fail on this later, after we have already committed to // the upgrade being good to go try { initDemoUserRestore(); } catch (ResourceInitializationException e) { throw new UnresolvedResourceException(r, e, e.getMessage(), true); } if (upgrade) { OfflineUserRestore currentOfflineUserRestore = CommCareApplication._().getCommCarePlatform().getDemoUserRestore(); if (currentOfflineUserRestore != null) { CommCareApplication._().wipeSandboxForUser(currentOfflineUserRestore.getUsername()); } return Resource.RESOURCE_STATUS_UPGRADE; } else { return Resource.RESOURCE_STATUS_INSTALLED; } } @Override public boolean requiresRuntimeInitialization() { return true; } }
package org.usfirst.frc.team2503; public class Constants { public static final int leftTalonPort = 0; public static final int rightTalonPort = 1; public static final int winchTalonPort = 2; public static final int upperLightsRelayPort = 0; public static final int underGlowLightsRelayPort = 1; public static int compressorPort = 0; public static final int winchLowerLimitSwitchChannel = 0; public static final int winchUpperLimitSwitchChannel = 1; public static final int driveBaseLeftSolenoidChannel = 1; public static final int driveBaseRightSolenoidChannel = 0; public static final double inputIndicationNullZone = 0.125; public static final double drivePrecisionMultiplier = 0.3; public static final double masterPowerMultiplier = 1.0; public static final String piBaseUrl = "http://192.168.1.103:5800"; public static final String piWebUrl = piBaseUrl + "/web"; public static final String piVisionUrl = piBaseUrl + "/vision"; public static final String piStatusUrl = piBaseUrl + "/status?k=robot"; public static final String piClientVersion = "0.0.0"; public static final boolean epilepsyMode = true; public static final boolean PERMISSION_COMPRESSOR_CONTROL = true; }
package org.eclipse.birt.report.designer.internal.lib.editparts; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import org.eclipse.birt.report.designer.core.model.LibraryHandleAdapt; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.model.schematic.HandleAdapterFactory; import org.eclipse.birt.report.designer.internal.lib.commands.SetCurrentEditModelCommand; import org.eclipse.birt.report.designer.internal.ui.editors.parts.DeferredGraphicalViewer; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.border.ReportDesignMarginBorder; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportDesignEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.figures.ReportRootFigure; import org.eclipse.birt.report.designer.internal.ui.layout.AbstractPageFlowLayout; import org.eclipse.birt.report.designer.internal.ui.layout.ReportDesignLayout; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.LibraryHandle; import org.eclipse.birt.report.model.api.activity.NotificationEvent; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.EditPartViewer; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Display; /** * This is the content edit part for Library. All other library elements puts on * to it */ public class LibraryReportDesignEditPart extends ReportDesignEditPart implements PropertyChangeListener { private static final Insets INSETS = new Insets( 30, 30, 30, 30 ); private static final Dimension DEFAULTSIZE = new Dimension( 800, 1000 ); /** * @param obj */ public LibraryReportDesignEditPart( Object obj ) { super( obj ); } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure() */ protected IFigure createFigure( ) { ReportRootFigure figure = new ReportRootFigure( ); figure.setOpaque( true ); figure.setShowMargin( showMargin ); ReportDesignLayout layout = new ReportDesignLayout( this ); Dimension size = DEFAULTSIZE; Rectangle bounds = new Rectangle( 0, 0, size.width - 1, size.height - 1 ); layout.setInitSize( bounds ); figure.setLayoutManager( layout ); figure.setBorder( new ReportDesignMarginBorder( INSETS ) ); figure.setBounds( bounds.getCopy( ) ); return figure; } /* * (non-Javadoc) * * @see org.eclipse.birt.designer.ui.editor.edit.ReportElementEditPart#getModelChildren() */ protected List getModelChildren( ) { return HandleAdapterFactory.getInstance( ).getLibraryHandleAdapter( getModel()) .getChildren( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.designer.internal.ui.editors.schematic.editparts.AbstractReportEditPart#refreshFigure() */ public void refreshFigure( ) { ReportRootFigure figure = (ReportRootFigure) getFigure( ); figure.setShowMargin( showMargin ); Dimension size = DEFAULTSIZE; Rectangle bounds = new Rectangle( 0, 0, size.width - 1, size.height - 1 ); ( (AbstractPageFlowLayout) getFigure( ).getLayoutManager( ) ) .setInitSize( bounds ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportDesignEditPart#activate() */ public void activate( ) { HandleAdapterFactory.getInstance( ).getLibraryHandleAdapter( (LibraryHandle) getModel( ) ).addPropertyChangeListener( this ); super.activate( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportDesignEditPart#deactivate() */ public void deactivate( ) { HandleAdapterFactory.getInstance( ).getLibraryHandleAdapter( (LibraryHandle) getModel( ) ).removePropertyChangeListener( this ); super.deactivate( ); } /* * (non-Javadoc) * * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) */ public void propertyChange( PropertyChangeEvent evt ) { if ( evt.getPropertyName( ).equals( LibraryHandleAdapt.CURRENTMODEL ) ) { refresh( ); Display.getCurrent( ).asyncExec( new Runnable( ) { public void run( ) { final List mediatorSelection = SessionHandleAdapter.getInstance( ) .getMediator( ).getCurrentState( ) .getSelectionObject( ); if ( mediatorSelection.size( ) == 1 && mediatorSelection.get( 0 ) instanceof LibraryHandle ) { return; } List list =getChildren( ); EditPartViewer viewer = getViewer( ); if ( viewer instanceof DeferredGraphicalViewer ) { ( (DeferredGraphicalViewer) viewer ).setSelection( new StructuredSelection( list ), false ); } //getViewer().setSelection(new StructuredSelection(list)); } } ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.core.Listener#elementChanged(org.eclipse.birt.report.model.api.DesignElementHandle, * org.eclipse.birt.report.model.api.activity.NotificationEvent) */ public void elementChanged( DesignElementHandle focus, NotificationEvent ev ) { if (!isModelInModuleHandle()) { SetCurrentEditModelCommand command = new SetCurrentEditModelCommand(null); command.execute(); } } private boolean isModelInModuleHandle() { List list = getModelChildren(); int size = list.size(); for (int i=0; i<size; i++) { Object obj = list.get(i); if (obj instanceof DesignElementHandle) { DesignElementHandle handle = (DesignElementHandle)obj; if (handle.getRoot() == null) { return false; } } } return true; } }
package org.eclipse.birt.report.designer.internal.ui.dialogs; import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.dialogs.ExpressionBuilder; import org.eclipse.birt.report.designer.ui.dialogs.IExpressionProvider; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DataSetParameterHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.structures.DataSetParameter; import org.eclipse.birt.report.model.api.metadata.IChoice; import org.eclipse.birt.report.model.api.metadata.IChoiceSet; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class DataSetParameterBindingInputDialog extends BaseDialog { private static final String LABEL_NAME = Messages.getString( "DataSetParameterBindingInputDialog.Label.Name" ); //$NON-NLS-1$ private static final String LABEL_DATA_TYPE = Messages.getString( "DataSetParameterBindingInputDialog.Label.DataType" ); //$NON-NLS-1$ private static final String LABEL_VALUE = Messages.getString( "DataSetParameterBindingInputDialog.Label.Value" ); //$NON-NLS-1$ private static final String DIALOG_TITLE = Messages.getString( "DataSetParameterBindingInputDialog.Title" ); //$NON-NLS-1$ private static final IChoiceSet DATA_TYPE_CHOICE_SET = DEUtil.getMetaDataDictionary( ) .getStructure( DataSetParameter.STRUCT_NAME ) .getMember( DataSetParameter.DATA_TYPE_MEMBER ) .getAllowedChoices( ); private Label nameLabel, typeLabel; private Text valueEditor; private Button expButton; private String value; private DataSetParameterHandle handle; private IExpressionProvider provider; public DataSetParameterBindingInputDialog( Shell parentShell, DataSetParameterHandle handle, IExpressionProvider provider ) { super( parentShell, DIALOG_TITLE ); this.handle = handle; this.provider = provider; } public DataSetParameterBindingInputDialog( DataSetParameterHandle handle, IExpressionProvider provider ) { this( UIUtil.getDefaultShell( ), handle, provider ); } protected boolean initDialog( ) { nameLabel.setText( handle.getName( ) ); typeLabel.setText( getParameterDataTypeDisplayName( handle.getParameterDataType( ) ) ); if ( value == null ) { value = ""; //$NON-NLS-1$ } valueEditor.setText( value ); return true; } private String getParameterDataTypeDisplayName( String type ) { IChoice choice = DATA_TYPE_CHOICE_SET.findChoice( type ); if ( choice != null ) return choice.getDisplayName( ); return DATA_TYPE_CHOICE_SET.findChoice( DesignChoiceConstants.COLUMN_DATA_TYPE_STRING ) .getDisplayName( ); } protected Control createDialogArea( Composite parent ) { Composite composite = (Composite) super.createDialogArea( parent ); composite.setLayout( new GridLayout( 2, false ) ); UIUtil.bindHelp( composite, IHelpContextIds.DATA_SET_PARAMETER_BINDING_DIALOG ); new Label( composite, SWT.NONE ).setText( LABEL_NAME ); nameLabel = new Label( composite, SWT.NONE ); nameLabel.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); new Label( composite, SWT.NONE ).setText( LABEL_DATA_TYPE ); typeLabel = new Label( composite, SWT.NONE ); typeLabel.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); new Label( composite, SWT.NONE ).setText( LABEL_VALUE ); Composite valueComposite = new Composite( composite, SWT.NONE ); valueComposite.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, false ) ); valueComposite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); valueEditor = new Text( valueComposite, SWT.BORDER | SWT.SINGLE ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.minimumWidth = 150; valueEditor.setLayoutData( gd ); expButton = new Button( valueComposite, SWT.PUSH ); UIUtil.setExpressionButtonImage( expButton ); expButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { ExpressionBuilder dialog = new ExpressionBuilder( valueEditor.getText( ) ); dialog.setExpressionProvier( provider ); if ( dialog.open( ) == OK ) { valueEditor.setText( dialog.getResult( ) ); } } } ); return composite; } protected void okPressed( ) { setResult( valueEditor.getText( ) ); super.okPressed( ); } public void setValue( String value ) { this.value = value; } }
package com.BV.LinearGradient; import com.facebook.react.bridge.ReadableArray; import android.content.Context; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.Shader; import android.view.View; public class LinearGradientView extends View { private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Path mPathForBorderRadius; private RectF mTempRectForBorderRadius; private LinearGradient mShader; private float[] mLocations; private float[] mStartPos = {0, 0}; private float[] mEndPos = {0, 1}; private int[] mColors; private int[] mSize = {0, 0}; private float mBorderRadius = 0f; public LinearGradientView(Context context) { super(context); } public void setStartPosition(ReadableArray startPos) { mStartPos = new float[]{(float) startPos.getDouble(0), (float) startPos.getDouble(1)}; drawGradient(); } public void setEndPosition(ReadableArray endPos) { mEndPos = new float[]{(float) endPos.getDouble(0), (float) endPos.getDouble(1)}; drawGradient(); } public void setColors(ReadableArray colors) { int[] _colors = new int[colors.size()]; for (int i=0; i < _colors.length; i++) { _colors[i] = colors.getInt(i); } mColors = _colors; drawGradient(); } public void setLocations(ReadableArray locations) { float[] _locations = new float[locations.size()]; for (int i=0; i < _locations.length; i++) { _locations[i] = (float) locations.getDouble(i); } mLocations = _locations; drawGradient(); } public void setBorderRadius(float borderRadius) { mBorderRadius = borderRadius; updatePath(); drawGradient(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mSize = new int[]{w, h}; updatePath(); drawGradient(); } private void drawGradient() { mShader = new LinearGradient( mStartPos[0] * mSize[0], mStartPos[1] * mSize[1], mEndPos[0] * mSize[0], mEndPos[1] * mSize[1], mColors, mLocations, Shader.TileMode.MIRROR); mPaint.setShader(mShader); invalidate(); } private void updatePath() { if (mPathForBorderRadius == null) { mPathForBorderRadius = new Path(); mTempRectForBorderRadius = new RectF(); } mPathForBorderRadius.reset(); mTempRectForBorderRadius.set(0f, 0f, (float) mSize[0], (float) mSize[1]); mPathForBorderRadius.addRoundRect( mTempRectForBorderRadius, mBorderRadius, mBorderRadius, Path.Direction.CW); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mPathForBorderRadius == null) { canvas.drawPaint(mPaint); } else { canvas.drawPath(mPathForBorderRadius, mPaint); } } }
package com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.restpoints; import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketChangesetPage; import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.RemoteRequestor; import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.ResponseCallback; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Matchers.*; import static org.mockito.Mockito.when; /** * TODO: Document this class / interface here * * @since v1.4.14 */ public class ChangesetRemoteRestpointTest { @Mock RemoteRequestor remoteRequestor; @Mock ResponseCallback<BitbucketChangesetPage> bitbucketChangesetPageResponseCallback; @BeforeClass public void initMocks() { MockitoAnnotations.initMocks(this); } @Test public void testGetNextChangesetsPageOnFirstPageHappyPath() throws Exception { ChangesetRemoteRestpoint changesetRemoteRestpoint = new ChangesetRemoteRestpoint(remoteRequestor,bitbucketChangesetPageResponseCallback); //Given final String orgName = "org"; final String slug = "slug"; List<String> includeNodes = new ArrayList<String>(); includeNodes.add("included"); List<String> excludeNodes = new ArrayList<String>(); excludeNodes.add("excluded"); Map<String,List<String>> parameters = new HashMap<String, List<String>>(); parameters.put("include",includeNodes); parameters.put("exclude", excludeNodes); final int changesetLimit = 2; BitbucketChangesetPage currentPage = null; BitbucketChangesetPage expected_result = new BitbucketChangesetPage(); //when when(remoteRequestor.post(eq("/api/2.0/repositories/" + orgName + "/" + slug + "/commits/?pagelen="+Integer.toString(changesetLimit)+"&page=1"), any(Map.class),eq(bitbucketChangesetPageResponseCallback))).thenReturn(expected_result); //expect Assert.assertEquals(changesetRemoteRestpoint.getNextChangesetsPage(orgName, slug, includeNodes, excludeNodes, changesetLimit, currentPage), expected_result, "didn't return expected changeset page because requestor got wrong parameters"); } }
package io.fullstack.oauth; import android.util.Log; import java.util.HashMap; import java.util.Random; import java.util.List; import android.support.annotation.Nullable; import java.net.URL; import java.net.MalformedURLException; import android.text.TextUtils; import java.util.Arrays; import com.github.scribejava.core.model.Verb; import com.github.scribejava.core.builder.api.BaseApi; import com.github.scribejava.core.oauth.OAuthService; import com.github.scribejava.core.oauth.OAuth10aService; import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.model.OAuth1AccessToken; import com.github.scribejava.core.model.OAuth1RequestToken; import com.github.scribejava.core.model.OAuthRequest; import com.github.scribejava.core.model.OAuthConfig; import com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.oauth.OAuth20Service; import com.github.scribejava.apis.TwitterApi; import com.github.scribejava.apis.FacebookApi; import com.github.scribejava.apis.GoogleApi20; import com.github.scribejava.apis.GitHubApi; import com.github.scribejava.apis.ConfigurableApi; import com.github.scribejava.apis.SlackApi; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.ReadableMapKeySetIterator; public class OAuthManagerProviders { private static final String TAG = "OAuthManagerProviders"; static public OAuth10aService getApiFor10aProvider( final String providerName, final HashMap params, @Nullable final ReadableMap opts, final String callbackUrl ) { if (providerName.equalsIgnoreCase("twitter")) { return OAuthManagerProviders.twitterService(params, opts, callbackUrl); } else { return null; } } static public OAuth20Service getApiFor20Provider( final String providerName, final HashMap params, @Nullable final ReadableMap opts, final String callbackUrl ) { if (providerName.equalsIgnoreCase("facebook")) { return OAuthManagerProviders.facebookService(params, opts, callbackUrl); } if (providerName.equalsIgnoreCase("google")) { return OAuthManagerProviders.googleService(params, opts, callbackUrl); } if (providerName.equalsIgnoreCase("github")) { return OAuthManagerProviders.githubService(params, opts, callbackUrl); } if (providerName.equalsIgnoreCase("slack")) { return OAuthManagerProviders.slackService(params, opts, callbackUrl); } if (params.containsKey("access_token_url") && params.containsKey("authorize_url")) { return OAuthManagerProviders.configurableService(params, opts, callbackUrl); } return null; } static public OAuthRequest getRequestForProvider( final String providerName, final Verb httpVerb, final OAuth1AccessToken oa1token, final URL url, final HashMap<String,Object> cfg, @Nullable final ReadableMap params ) { final OAuth10aService service = OAuthManagerProviders.getApiFor10aProvider(providerName, cfg, null, null); String token = oa1token.getToken(); OAuthConfig config = service.getConfig(); OAuthRequest request = new OAuthRequest(httpVerb, url.toString(), config); request = OAuthManagerProviders.addParametersToRequest(request, token, params); // Nothing special for Twitter return request; } static public OAuthRequest getRequestForProvider( final String providerName, final Verb httpVerb, final OAuth2AccessToken oa2token, final URL url, final HashMap<String,Object> cfg, @Nullable final ReadableMap params ) { final OAuth20Service service = OAuthManagerProviders.getApiFor20Provider(providerName, cfg, null, null); OAuthConfig config = service.getConfig(); OAuthRequest request = new OAuthRequest(httpVerb, url.toString(), config); String token = oa2token.getAccessToken(); request = OAuthManagerProviders.addParametersToRequest(request, token, params); Log.d(TAG, "Making request for " + providerName + " to add token " + token); // Need a way to standardize this, but for now if (providerName.equalsIgnoreCase("slack")) { request.addParameter("token", token); } return request; } // Helper to add parameters to the request static private OAuthRequest addParametersToRequest( OAuthRequest request, final String access_token, @Nullable final ReadableMap params ) { if (params != null && params.hasKey("params")) { ReadableMapKeySetIterator iterator = params.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); ReadableType readableType = params.getType(key); switch(readableType) { case String: String val = params.getString(key); // String escapedVal = Uri.encode(val); if (val.equals("access_token")) { val = access_token; } request.addParameter(key, val); break; default: throw new IllegalArgumentException("Could not read object with key: " + key); } } } return request; } private static OAuth10aService twitterService( final HashMap cfg, @Nullable final ReadableMap opts, final String callbackUrl) { String consumerKey = (String) cfg.get("consumer_key"); String consumerSecret = (String) cfg.get("consumer_secret"); ServiceBuilder builder = new ServiceBuilder() .apiKey(consumerKey) .apiSecret(consumerSecret) .debug(); String scopes = (String) cfg.get("scopes"); if (scopes != null) { // String scopeStr = OAuthManagerProviders.getScopeString(scopes, "+"); // Log.d(TAG, "scopeStr: " + scopeStr); // builder.scope(scopeStr); } if (callbackUrl != null) { builder.callback(callbackUrl); } return builder.build(TwitterApi.instance()); } private static OAuth20Service facebookService( final HashMap cfg, @Nullable final ReadableMap opts, final String callbackUrl) { ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl); return builder.build(FacebookApi.instance()); } private static OAuth20Service googleService( final HashMap cfg, @Nullable final ReadableMap opts, final String callbackUrl) { ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl); return builder.build(GoogleApi20.instance()); } private static OAuth20Service githubService( final HashMap cfg, @Nullable final ReadableMap opts, final String callbackUrl) { ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl); return builder.build(GitHubApi.instance()); } private static OAuth20Service configurableService( final HashMap cfg, @Nullable final ReadableMap opts, final String callbackUrl ) { ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl); Log.d(TAG, "Creating ConfigurableApi"); //Log.d(TAG, " authorize_url: " + cfg.get("authorize_url")); //Log.d(TAG, " access_token_url: " + cfg.get("access_token_url")); ConfigurableApi api = ConfigurableApi.instance() .setAccessTokenEndpoint((String) cfg.get("access_token_url")) .setAuthorizationBaseUrl((String) cfg.get("authorize_url")); if (cfg.containsKey("access_token_verb")) { //Log.d(TAG, " access_token_verb: " + cfg.get("access_token_verb")); api.setAccessTokenVerb((String) cfg.get("access_token_verb")); } return builder.build(api); } private static OAuth20Service slackService( final HashMap cfg, @Nullable final ReadableMap opts, final String callbackUrl ) { Log.d(TAG, "Make the builder: " + SlackApi.class); ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl); return builder.build(SlackApi.instance()); } private static ServiceBuilder _oauth2ServiceBuilder( final HashMap cfg, @Nullable final ReadableMap opts, final String callbackUrl ) { String clientKey = (String) cfg.get("client_id"); String clientSecret = (String) cfg.get("client_secret"); String state; if (cfg.containsKey("state")) { state = (String) cfg.get("state"); } else { state = TAG + new Random().nextInt(999_999); } // Builder ServiceBuilder builder = new ServiceBuilder() .apiKey(clientKey) .apiSecret(clientSecret) .state(state) .debug(); String scopes = ""; if (cfg.containsKey("scopes")) { scopes = (String) cfg.get("scopes"); String scopeStr = OAuthManagerProviders.getScopeString(scopes, ","); builder.scope(scopeStr); } boolean rawScopes = (cfg.containsKey("rawScopes") && ((String)cfg.get("rawScopes")).equalsIgnoreCase("true")); if (opts != null && opts.hasKey("scopes")) { scopes = (String) opts.getString("scopes"); String scopeStr = null; if (!rawScopes) scopeStr = OAuthManagerProviders.getScopeString(scopes, ","); else scopeStr = scopes; builder.scope(scopeStr); } if (callbackUrl != null) { builder.callback(callbackUrl); } return builder; } /** * Convert a list of scopes by space or string into an array */ private static String getScopeString( final String scopes, final String joinBy ) { List<String> array = Arrays.asList(scopes.replaceAll("\\s", "").split("[ ,]+")); Log.d(TAG, "array: " + array + " (" + array.size() + ") from " + scopes); return TextUtils.join(joinBy, array); } }
package org.biojava.nbio.structure.io; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.util.zip.GZIPInputStream; import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.EntityInfo; import org.biojava.nbio.structure.EntityType; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.mmcif.MMcifParser; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; import org.biojava.nbio.structure.xtal.CrystalCell; import org.junit.Test; /** * Tests for non-deposited PDB/mmCIF files, i.e. any kind of "raw" file * lacking significant parts of the headers. * * Some things tested: * - heuristics to guess isNMR, isCrystallographic * * @author Jose Duarte * */ public class TestNonDepositedFiles { @Test public void test1B8GnoSeqresPdb() throws IOException, StructureException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/1b8g_raw.pdb.gz")); assertNotNull(inStream); PDBFileParser pdbpars = new PDBFileParser(); FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); pdbpars.setFileParsingParameters(params); Structure s = pdbpars.parsePDBFile(inStream) ; assertNotNull(s); assertTrue(s.isCrystallographic()); assertFalse(s.isNmr()); assertTrue(s.nrModels()==1); assertNull(s.getPDBHeader().getExperimentalTechniques()); assertNotNull(s.getCrystallographicInfo().getCrystalCell()); assertNotNull(s.getCrystallographicInfo().getSpaceGroup()); assertEquals(s.getCrystallographicInfo().getSpaceGroup().getShortSymbol(),"P 1 21 1"); CrystalCell cell = s.getCrystallographicInfo().getCrystalCell(); assertTrue(cell.isCellReasonable()); // TODO get the scale matrix from the PDB file and check it against the calculated one: //cell.checkScaleMatrixConsistency(scaleMatrix); //cell.checkScaleMatrix(scaleMatrix); // 2 protein chanis, 2 nonpoly PLP chains, 2 water chains assertEquals(6,s.getChains().size()); // checking that heuristics in CompoundFinder work. We should have 1 polymer entity (protein) + 1 nonpoly entity (PLP) + 1 water entity assertEquals(3, s.getEntityInfos().size()); assertEquals(EntityType.POLYMER, s.getEntityById(1).getType()); //System.out.println("Chains from incomplete header file: "); //checkChains(s); // trying without seqAlignSeqRes params.setAlignSeqRes(false); inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/1b8g_raw.pdb.gz")); s = pdbpars.parsePDBFile(inStream); assertNotNull(s); assertEquals(6,s.getChains().size()); assertEquals(3, s.getEntityInfos().size()); assertEquals(EntityType.POLYMER, s.getEntityById(1).getType()); } //@Test public void test1B8G() throws IOException, StructureException { AtomCache cache = new AtomCache(); StructureIO.setAtomCache(cache); cache.setUseMmCif(true); Structure s = StructureIO.getStructure("1B8G"); System.out.println("Chains from full deposited file: "); checkChains(s); } @Test public void test3C5F() throws IOException, StructureException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/3c5f_raw.pdb.gz")); assertNotNull(inStream); PDBFileParser pdbpars = new PDBFileParser(); FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); pdbpars.setFileParsingParameters(params); Structure s = pdbpars.parsePDBFile(inStream) ; // multi-model X-ray diffraction entry, thus: assertFalse(s.isNmr()); assertTrue(s.isCrystallographic()); assertTrue(s.nrModels()>1); assertNull(s.getPDBHeader().getExperimentalTechniques()); } @Test public void test4B19() throws IOException, StructureException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/4b19_raw.pdb.gz")); assertNotNull(inStream); PDBFileParser pdbpars = new PDBFileParser(); FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); pdbpars.setFileParsingParameters(params); Structure s = pdbpars.parsePDBFile(inStream) ; // multi-model NMR entry, thus: assertTrue(s.isNmr()); assertFalse(s.isCrystallographic()); assertTrue(s.nrModels()>1); assertNull(s.getPDBHeader().getExperimentalTechniques()); } @Test public void test2M7Y() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/2m7y_raw.pdb.gz")); assertNotNull(inStream); PDBFileParser pdbpars = new PDBFileParser(); FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); pdbpars.setFileParsingParameters(params); Structure s = pdbpars.parsePDBFile(inStream) ; // single-model NMR entry, thus: //assertTrue(s.isNmr()); // we can't detect it properly, because it's single model! assertFalse(s.isCrystallographic()); // at least this we can detect from the unreasonable crystal cell assertTrue(s.nrModels()==1); assertNull(s.getPDBHeader().getExperimentalTechniques()); } private void checkChains(Structure s) { for (Chain chain:s.getChains()) { int seqResLength = chain.getSeqResLength(); int atomLength = chain.getAtomLength(); System.out.println("chain "+chain.getId()+", atomLength: "+atomLength+", seqResLength: "+seqResLength); //assertTrue("atom length ("+atomLength+") should be smaller than seqResLength ("+seqResLength+")",atomLength<=seqResLength); System.out.println("seq res groups size: "+chain.getSeqResGroups().size()); } } /** * A test for reading a phenix-produced (ver 1.9_1692) mmCIF file. * This is the file submitted to the PDB for deposition of entry 4lup * See github issue #234 * @throws IOException */ @Test public void testPhenixCifFile() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/4lup_phenix_output.cif.gz")); MMcifParser parser = new SimpleMMcifParser(); SimpleMMcifConsumer consumer = new SimpleMMcifConsumer(); FileParsingParameters fileParsingParams = new FileParsingParameters(); fileParsingParams.setAlignSeqRes(true); consumer.setFileParsingParameters(fileParsingParams); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(inStream))); Structure s = consumer.getStructure(); assertNotNull(s); assertTrue(s.isCrystallographic()); // all ligands are into their own chains, so we have 2 proteins, 2 nucleotide chains, 1 ligand chain and 1 purely water chain assertEquals(6, s.getChains().size()); // 4 entities: 1 protein, 1 nucleotide, 1 water, 1 ligand (EDO) assertEquals(4, s.getEntityInfos().size()); int[] counts = countEntityTypes(s.getEntityInfos()); assertEquals(2, counts[0]); assertEquals(1, counts[1]); assertEquals(1, counts[2]); } @Test public void testPhenixPdbFile() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/4lup_phenix_output.pdb.gz")); PDBFileParser pdbpars = new PDBFileParser(); FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); pdbpars.setFileParsingParameters(params); Structure s = pdbpars.parsePDBFile(inStream) ; assertNotNull(s); assertTrue(s.isCrystallographic()); // all ligands are into their own chains, so we have 2 proteins, 2 nucleotide chains, 1 ligand chain and 1 purely water chain assertEquals(6, s.getChains().size()); // 4 entities: 1 protein, 1 nucleotide, 1 water, 1 ligand (EDO) assertEquals(4, s.getEntityInfos().size()); int[] counts = countEntityTypes(s.getEntityInfos()); assertEquals(2, counts[0]); assertEquals(1, counts[1]); assertEquals(1, counts[2]); } @Test public void testPhaserPdbFile() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/4lup_phaser_output.pdb.gz")); PDBFileParser pdbpars = new PDBFileParser(); FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); pdbpars.setFileParsingParameters(params); Structure s = pdbpars.parsePDBFile(inStream) ; assertNotNull(s); assertTrue(s.isCrystallographic()); assertEquals(2, s.getChains().size()); assertEquals(1, s.getEntityInfos().size()); } @Test public void testRefmacPdbFile() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/rnase_refmac_output.pdb.gz")); PDBFileParser pdbpars = new PDBFileParser(); FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); pdbpars.setFileParsingParameters(params); Structure s = pdbpars.parsePDBFile(inStream) ; assertNotNull(s); assertTrue(s.isCrystallographic()); // 2 polymer chains with 1 ligand per chain, 1 purely water chain = 5 chains assertEquals(5, s.getChains().size()); // 1 polymer entity, 1 nonpoly entity, 1 water entity assertEquals(3, s.getEntityInfos().size()); int[] counts = countEntityTypes(s.getEntityInfos()); assertEquals(1, counts[0]); assertEquals(1, counts[1]); assertEquals(1, counts[2]); } /** * This test represents a common situation for a non-deposited structure. * When building with common crystallography software, the user often adds new * ligands (or solvent) molecules as new chains. Only prior to deposition * then relabel them so that they belong to the same chain as the polymeric residues. * * In this case, the ligands represent valuable information and should not be discarded. */ @Test public void testNewLigandChain() throws IOException { // Test the file parsing speed when the files are already downloaded. InputStream pdbStream = new GZIPInputStream(this.getClass().getResourceAsStream("/ligandTest.pdb.gz")); InputStream cifStream = new GZIPInputStream(this.getClass().getResourceAsStream("/ligandTest.cif.gz")); assertNotNull(cifStream); assertNotNull(pdbStream); FileParsingParameters params = new FileParsingParameters(); PDBFileParser pdbpars = new PDBFileParser(); pdbpars.setFileParsingParameters(params); Structure s1 = pdbpars.parsePDBFile(pdbStream) ; // The chain B should be present with 1 ligand HEM Chain c1 = s1.getNonPolyChainsByPDB("B").get(0); assertNotNull(c1); int expectedNumLigands = 1; assertEquals(expectedNumLigands, c1.getAtomGroups().size()); MMcifParser mmcifpars = new SimpleMMcifParser(); SimpleMMcifConsumer consumer = new SimpleMMcifConsumer(); consumer.setFileParsingParameters(params); mmcifpars.addMMcifConsumer(consumer); mmcifpars.parse(cifStream) ; Structure s2 = consumer.getStructure(); // The chain B should be present with 1 ligand HEM Chain c2 = s2.getNonPolyChainsByPDB("B").get(0); assertNotNull(c2); assertEquals(expectedNumLigands, c2.getAtomGroups().size()); // pdb and mmcif should have same number of chains assertEquals(s1.getChains().size(), s2.getChains().size()); } @Test public void testWaterOnlyChainPdb() throws IOException { // following file is cut-down version of 4a10 InputStream pdbStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/4a10_short.pdb.gz")); PDBFileParser pdbpars = new PDBFileParser(); Structure s1 = pdbpars.parsePDBFile(pdbStream) ; assertEquals(2, s1.getChains().size()); Chain c1 = s1.getWaterChainByPDB("F"); assertNotNull("Got null when looking for water-only chain with author id F", c1); // checking that compounds are linked assertNotNull(c1.getEntityInfo()); // checking that the water molecule was assigned an ad-hoc compound assertEquals(2,s1.getEntityInfos().size()); } @Test public void testWaterOnlyChainCif() throws IOException { // following file is cut-down versions of 4a10 InputStream cifStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/4a10_short.cif.gz")); MMcifParser mmcifpars = new SimpleMMcifParser(); SimpleMMcifConsumer consumer = new SimpleMMcifConsumer(); mmcifpars.addMMcifConsumer(consumer); mmcifpars.parse(cifStream) ; Structure s2 = consumer.getStructure(); assertEquals(2, s2.getChains().size()); Chain c = s2.getWaterChainByPDB("F"); assertNotNull("Got null when looking for water-only chain with author id F", c); // checking that compounds are linked assertNotNull(c.getEntityInfo()); // checking that the water molecule was assigned an ad-hoc compound assertEquals(2,s2.getEntityInfos().size()); Chain cAsymId = s2.getWaterChain("E"); assertNotNull("Got null when looking for water-only chain with asym id E", cAsymId); assertSame(c, cAsymId); } /** * Some PDB files coming from phenix or other software can have a CRYST1 line without z and not padded with white-spaces * for the space group column. * @throws IOException * @since 5.0.0 */ @Test public void testCryst1Parsing() throws IOException { String cryst1Line = "CRYST1 11.111 11.111 111.111 70.00 80.00 60.00 P 1"; Structure s; PDBFileParser pdbPars = new PDBFileParser(); try(InputStream is = new ByteArrayInputStream(cryst1Line.getBytes()) ) { s = pdbPars.parsePDBFile(is); } assertEquals("P 1", s.getPDBHeader().getCrystallographicInfo().getSpaceGroup().getShortSymbol()); } private static int[] countEntityTypes(List<EntityInfo> entities) { int countPoly = 0; int countNonPoly = 0; int countWater = 0; for (EntityInfo e:entities) { if (e.getType()==EntityType.POLYMER) countPoly++; if (e.getType()==EntityType.NONPOLYMER) countNonPoly++; if (e.getType()==EntityType.WATER) countWater++; } int[] counts = {countPoly, countNonPoly, countWater}; return counts; } }
package org.biojava.bio.structure.domain; import java.io.InputStream; import java.net.URL; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.StructureTools; import org.biojava.bio.structure.align.ce.AbstractUserArgumentProcessor; import org.biojava.bio.structure.align.client.JFatCatClient; import org.biojava.bio.structure.align.client.StructureName; import org.biojava.bio.structure.align.util.AtomCache; import org.biojava.bio.structure.align.util.HTTPConnectionTools; import org.biojava.bio.structure.scop.server.XMLUtil; /** A class that provided PDP assignments that are loaded from a remote web server * * @author Andreas Prlic * */ public class RemotePDPProvider extends SerializableCache<String,SortedSet<String>> { public static final String DEFAULT_SERVER = "http://source.rcsb.org/jfatcatserver/domains/"; String server = DEFAULT_SERVER; private static String CACHE_FILE_NAME = "remotepdpdomaindefs.ser"; public static void main(String[] args){ System.setProperty(AbstractUserArgumentProcessor.PDB_DIR,"/Users/andreas/WORK/PDB"); RemotePDPProvider me = new RemotePDPProvider(true); //System.out.println(scop.getByCategory(ScopCategory.Superfamily)); SortedSet<String> pdpdomains = me.getPDPDomainNamesForPDB("4HHB"); System.out.println(pdpdomains); AtomCache cache = new AtomCache(); Structure s = me.getDomain(pdpdomains.first(), cache); System.out.println(s); me.flushCache(); } public RemotePDPProvider(){ this(false); } public RemotePDPProvider(boolean useCache) { super(CACHE_FILE_NAME); if ( ! useCache) { disableCache(); //else if ( serializedCache.keySet().size() < 10000){ } else { // make sure we always have the latest assignments... loadRepresentativeDomains(); } } /** get the ranges of representative domains from the centralized server * */ private void loadRepresentativeDomains() { AssignmentXMLSerializer results = null; try { URL u = new URL(server + "getRepresentativePDPDomains"); System.out.println(u); InputStream response = HTTPConnectionTools.getInputStream(u); String xml = JFatCatClient.convertStreamToString(response); //System.out.println(xml); results = AssignmentXMLSerializer.fromXML(xml); Map<String,String> data = results.getAssignments(); System.out.println("got " + data.size() + " domain ranges for PDP domains from server."); for (String key: data.keySet()){ String range = data.get(key); // work around list in results; String[] spl = range.split(","); SortedSet<String> value = new TreeSet<String>(); for (String s : spl){ value.add(s); } serializedCache.put(key, value); } } catch (Exception e){ e.printStackTrace(); } return ; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public Structure getDomain(String pdbDomainName, AtomCache cache){ SortedSet<String> domainRanges = null; if ( serializedCache != null){ if ( serializedCache.containsKey(pdbDomainName)){ domainRanges= serializedCache.get(pdbDomainName); } } Structure s = null; try { boolean shouldRequestDomainRanges = checkDomainRanges(domainRanges); if (shouldRequestDomainRanges){ URL u = new URL(server + "getPDPDomain?pdpId="+pdbDomainName); System.out.println(u); InputStream response = HTTPConnectionTools.getInputStream(u); String xml = JFatCatClient.convertStreamToString(response); //System.out.println(xml); domainRanges = XMLUtil.getDomainRangesFromXML(xml); if ( domainRanges != null) cache(pdbDomainName,domainRanges); } int i =0 ; StringBuffer r = new StringBuffer(); for (String domainRange : domainRanges){ if ( ! domainRange.contains(".")) r.append(domainRange); else { String[] spl = domainRange.split("\\."); if ( spl.length>1) r.append(spl[1]); else { System.out.println("not sure what to do with " + domainRange); } } i++; if ( i < domainRanges.size()) { r.append(","); } } String ranges = r.toString(); StructureName sname = new StructureName(pdbDomainName); Structure tmp = cache.getStructure(sname.getPdbId()); s = StructureTools.getSubRanges(tmp, ranges); s.setName(pdbDomainName); } catch (Exception e){ e.printStackTrace(); } return s; } /** returns true if client should fetch domain definitions from server * * @param domainRanges * @return */ private boolean checkDomainRanges(SortedSet<String> domainRanges) { if ( (domainRanges == null) || (domainRanges.size() == 0)){ return true; } for ( String d : domainRanges){ //System.out.println("domainRange: >" + d +"< " + d.length()); if ( (d != null) && (d.length() >0)){ return false; } } return true; } public SortedSet<String> getPDPDomainNamesForPDB(String pdbId){ SortedSet<String> results = null; try { URL u = new URL(server + "getPDPDomainNamesForPDB?pdbId="+pdbId); System.out.println(u); InputStream response = HTTPConnectionTools.getInputStream(u); String xml = JFatCatClient.convertStreamToString(response); //System.out.println(xml); results = XMLUtil.getDomainRangesFromXML(xml); } catch (Exception e){ e.printStackTrace(); } return results; } }
package org.deviceconnect.android.event; import android.content.ComponentName; import android.content.Intent; import org.deviceconnect.android.event.cache.EventCacheController; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.message.DConnectMessage; import java.util.List; /** * . * * * @author NTT DOCOMO, INC. */ public enum EventManager { /** * EventManager. */ INSTANCE; private EventCacheController mController; /** * . * * * @param controller */ public void setController(final EventCacheController controller) { mController = controller; } private void checkState() { if (mController == null) { throw new IllegalStateException("CacheController is not set."); } } /** * IntentEvent. * * @param request * @return */ private Event createEvent(final Intent request) { if (request == null) { throw new IllegalArgumentException("Request is null."); } checkState(); String serviceId = request.getStringExtra(DConnectMessage.EXTRA_SERVICE_ID); String profile = request.getStringExtra(DConnectMessage.EXTRA_PROFILE); String inter = request.getStringExtra(DConnectMessage.EXTRA_INTERFACE); String attribute = request.getStringExtra(DConnectMessage.EXTRA_ATTRIBUTE); String accessToken = request.getStringExtra(DConnectMessage.EXTRA_ACCESS_TOKEN); String sessionKey = request.getStringExtra(DConnectMessage.EXTRA_SESSION_KEY); ComponentName name = request.getParcelableExtra(DConnectMessage.EXTRA_RECEIVER); Event event = new Event(); event.setSessionKey(sessionKey); event.setAccessToken(accessToken); // XXXX event.setProfile(profile != null ? profile.toLowerCase() : null); event.setInterface(inter != null ? inter.toLowerCase() : null); event.setAttribute(attribute != null ? attribute.toLowerCase() : null); event.setServiceId(serviceId); if (name != null) { event.setReceiverName(name.flattenToString()); } return event; } /** * . * * @param request * @return */ public EventError addEvent(final Intent request) { Event event = createEvent(request); return mController.addEvent(event); } public Event getEvent(final Intent request) { checkState(); ComponentName receiver = request.getParcelableExtra(DConnectMessage.EXTRA_RECEIVER); String receiverName = receiver != null ? receiver.flattenToString() : null; String profile = request.getStringExtra(DConnectMessage.EXTRA_PROFILE); String inter = request.getStringExtra(DConnectMessage.EXTRA_INTERFACE); String attribute = request.getStringExtra(DConnectMessage.EXTRA_ATTRIBUTE); // XXXX return mController.getEvent(request.getStringExtra(DConnectMessage.EXTRA_SERVICE_ID), profile != null ? profile.toLowerCase() : null, inter != null ? inter.toLowerCase() : null, attribute != null ? attribute.toLowerCase() : null, request.getStringExtra(DConnectMessage.EXTRA_SESSION_KEY), receiverName); } /** * . * * @param request * @return */ public EventError removeEvent(final Intent request) { return removeEvent(createEvent(request)); } public EventError removeEvent(final Event event) { checkState(); if (event == null) { throw new IllegalArgumentException("Event is null."); } return mController.removeEvent(event); } /** * . * * @param sessionKey * @return truefalse */ public boolean removeEvents(final String sessionKey) { checkState(); return mController.removeEvents(sessionKey); } /** * . * * @return truefalse */ public boolean removeAll() { checkState(); return mController.removeAll(); } public void flush() { checkState(); mController.flush(); } /** * . * * @param request * @return */ public List<Event> getEventList(final Intent request) { return getEventList( request.getStringExtra(DConnectMessage.EXTRA_SERVICE_ID), request.getStringExtra(DConnectMessage.EXTRA_PROFILE), request.getStringExtra(DConnectMessage.EXTRA_INTERFACE), request.getStringExtra(DConnectMessage.EXTRA_ATTRIBUTE)); } /** * IDAPI. * * @param serviceId ID * @param profile * @param inter * @param attribute * @return */ public List<Event> getEventList(final String serviceId, final String profile, final String inter, final String attribute) { checkState(); // XXXX return mController.getEvents(serviceId, profile != null ? profile.toLowerCase() : null, inter != null ? inter.toLowerCase() : null, attribute != null ? attribute.toLowerCase() : null); } /** * API. * * @param profile * @param inter * @param attribute * @return */ public List<Event> getEventList(final String profile, final String inter, final String attribute) { checkState(); return getEventList(null, profile, inter, attribute); } /** * API. * * @param profile * @param attribute * @return */ public List<Event> getEventList(final String profile, final String attribute) { checkState(); return getEventList(profile, null, attribute); } /** * API. * * @param sessionKey * @return */ public List<Event> getEventList(final String sessionKey) { checkState(); return mController.getEvents(sessionKey); } /** * Intent. * Intent * * @param event * @return Intent */ public static Intent createEventMessage(final Event event) { Intent message = MessageUtils.createEventIntent(); message.putExtra(DConnectMessage.EXTRA_SERVICE_ID, event.getServiceId()); message.putExtra(DConnectMessage.EXTRA_PROFILE, event.getProfile()); message.putExtra(DConnectMessage.EXTRA_INTERFACE, event.getInterface()); message.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, event.getAttribute()); message.putExtra(DConnectMessage.EXTRA_SESSION_KEY, event.getSessionKey()); ComponentName cn = ComponentName.unflattenFromString(event.getReceiverName()); message.setComponent(cn); return message; } }
package org.eclipse.smarthome.binding.sonos.handler; import static org.eclipse.smarthome.binding.sonos.SonosBindingConstants.*; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.eclipse.smarthome.binding.sonos.SonosBindingConstants; import org.eclipse.smarthome.binding.sonos.config.ZonePlayerConfiguration; import org.eclipse.smarthome.binding.sonos.internal.SonosAlarm; import org.eclipse.smarthome.binding.sonos.internal.SonosEntry; import org.eclipse.smarthome.binding.sonos.internal.SonosMetaData; import org.eclipse.smarthome.binding.sonos.internal.SonosXMLParser; import org.eclipse.smarthome.binding.sonos.internal.SonosZoneGroup; import org.eclipse.smarthome.binding.sonos.internal.SonosZonePlayerState; import org.eclipse.smarthome.config.discovery.DiscoveryServiceRegistry; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.NextPreviousType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.OpenClosedType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.library.types.PlayPauseType; import org.eclipse.smarthome.core.library.types.RawType; import org.eclipse.smarthome.core.library.types.RewindFastforwardType; import org.eclipse.smarthome.core.library.types.StringType; import org.eclipse.smarthome.core.library.types.UpDownType; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; import org.eclipse.smarthome.core.thing.binding.ThingHandler; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.UnDefType; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.eclipse.smarthome.io.transport.upnp.UpnpIOParticipant; import org.eclipse.smarthome.io.transport.upnp.UpnpIOService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; /** * The {@link ZonePlayerHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Karel Goderis - Initial contribution * */ public class ZonePlayerHandler extends BaseThingHandler implements UpnpIOParticipant { private Logger logger = LoggerFactory.getLogger(ZonePlayerHandler.class); private final static String ANALOG_LINE_IN_URI = "x-rincon-stream:"; private final static String OPTICAL_LINE_IN_URI = "x-sonos-htastream:"; private final static String QUEUE_URI = "x-rincon-queue:"; private final static String GROUP_URI = "x-rincon:"; private final static String STREAM_URI = "x-sonosapi-stream:"; private final static String FILE_URI = "x-file-cifs:"; private final static String SPDIF = ":spdif"; private UpnpIOService service; private DiscoveryServiceRegistry discoveryServiceRegistry; private ScheduledFuture<?> pollingJob; private SonosZonePlayerState savedState = null; private final static Collection<String> SERVICE_SUBSCRIPTIONS = Lists.newArrayList("DeviceProperties", "AVTransport", "ZoneGroupTopology", "GroupManagement", "RenderingControl", "AudioIn", "HTControl"); private Map<String, Boolean> subscriptionState = new HashMap<String, Boolean>(); protected final static int SUBSCRIPTION_DURATION = 1800; private static final int SOCKET_TIMEOUT = 5000; /** * Default notification timeout */ private static final int NOTIFICATION_TIMEOUT = 20000; /** * Intrinsic lock used to synchronize the execution of notification sounds */ private final Object notificationLock = new Object(); /** * Separate sound volume used for the notification */ private String notificationSoundVolume = null; /** * {@link ThingHandler} instance of the coordinator speaker used for control delegation */ private ZonePlayerHandler coordinatorHandler; /** * The default refresh interval when not specified in channel configuration. */ private static final int DEFAULT_REFRESH_INTERVAL = 60; private Map<String, String> stateMap = Collections.synchronizedMap(new HashMap<String, String>()); private final Object upnpLock = new Object(); private final Object stateLock = new Object(); private Runnable pollingRunnable = new Runnable() { @Override public void run() { try { logger.debug("Polling job"); // First check if the Sonos zone is set in the UPnP service registry // If not, set the thing state to OFFLINE and wait for the next poll if (!isUpnpDeviceRegistered()) { logger.debug("UPnP device {} not yet registered", getUDN()); updateStatus(ThingStatus.OFFLINE); synchronized (upnpLock) { subscriptionState = new HashMap<String, Boolean>(); } return; } // Check if the Sonos zone can be joined // If not, set the thing state to OFFLINE and do nothing else updatePlayerState(); if (getThing().getStatus() != ThingStatus.ONLINE) { return; } addSubscription(); updateZoneInfo(); updateRunningAlarmProperties(); updateLed(); updateSleepTimerDuration(); } catch (Exception e) { logger.debug("Exception during poll : {}", e); } } }; private String opmlUrl; public ZonePlayerHandler(Thing thing, UpnpIOService upnpIOService, DiscoveryServiceRegistry discoveryServiceRegistry, String opmlUrl) { super(thing); this.opmlUrl = opmlUrl; logger.debug("Creating a ZonePlayerHandler for thing '{}'", getThing().getUID()); if (upnpIOService != null) { this.service = upnpIOService; } if (discoveryServiceRegistry != null) { this.discoveryServiceRegistry = discoveryServiceRegistry; } } @Override public void dispose() { logger.debug("Handler disposed for thing {}", getThing().getUID()); if (pollingJob != null && !pollingJob.isCancelled()) { pollingJob.cancel(true); pollingJob = null; } removeSubscription(); } @Override public void initialize() { logger.debug("initializing handler for thing {}", getThing().getUID()); if (migrateThingType()) { // we change the type, so we might need a different handler -> let's finish return; } if (getUDN() != null) { updateStatus(ThingStatus.ONLINE); onUpdate(); super.initialize(); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR); logger.warn("Cannot initalize the zoneplayer. UDN not set."); } } @Override public void handleCommand(ChannelUID channelUID, Command command) { if (command instanceof RefreshType) { updateChannel(channelUID.getId()); } else { switch (channelUID.getId()) { case LED: setLed(command); break; case MUTE: setMute(command); break; case NOTIFICATIONSOUND: scheduleNotificationSound(command); break; case NOTIFICATIONVOLUME: setNotificationSoundVolume(command); break; case STOP: try { getCoordinatorHandler().stop(); } catch (IllegalStateException e) { logger.warn("Cannot handle stop command ({})", e.getMessage()); } break; case VOLUME: setVolumeForGroup(command); break; case ADD: addMember(command); break; case REMOVE: removeMember(command); break; case STANDALONE: becomeStandAlonePlayer(); break; case PUBLICADDRESS: publicAddress(); break; case RADIO: playRadio(command); break; case FAVORITE: playFavorite(command); break; case ALARM: setAlarm(command); break; case SNOOZE: snoozeAlarm(command); break; case SAVEALL: saveAllPlayerState(); break; case RESTOREALL: restoreAllPlayerState(); break; case SAVE: saveState(); break; case RESTORE: restoreState(); break; case PLAYLIST: playPlayList(command); break; case PLAYQUEUE: playQueue(); break; case PLAYTRACK: playTrack(command); break; case PLAYURI: playURI(command); break; case PLAYLINEIN: playLineIn(command); break; case CONTROL: try { if (command instanceof PlayPauseType) { if (command == PlayPauseType.PLAY) { getCoordinatorHandler().play(); } else if (command == PlayPauseType.PAUSE) { getCoordinatorHandler().pause(); } } if (command instanceof NextPreviousType) { if (command == NextPreviousType.NEXT) { getCoordinatorHandler().next(); } else if (command == NextPreviousType.PREVIOUS) { getCoordinatorHandler().previous(); } } if (command instanceof RewindFastforwardType) { // Rewind and Fast Forward are currently not implemented by the binding } } catch (IllegalStateException e) { logger.warn("Cannot handle control command ({})", e.getMessage()); } break; case SLEEPTIMER: setSleepTimer(command); break; case SHUFFLE: setShuffle(command); break; case REPEAT: setRepeat(command); break; default: break; } } } private void restoreAllPlayerState() { Collection<Thing> allThings = thingRegistry.getAll(); for (Thing aThing : allThings) { if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())) { ZonePlayerHandler handler = (ZonePlayerHandler) aThing.getHandler(); handler.restoreState(); } } } private void saveAllPlayerState() { Collection<Thing> allThings = thingRegistry.getAll(); for (Thing aThing : allThings) { if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())) { ZonePlayerHandler handler = (ZonePlayerHandler) aThing.getHandler(); handler.saveState(); } } } @Override public void onValueReceived(String variable, String value, String service) { if (getThing().getStatus() == ThingStatus.ONLINE) { logger.trace("Received pair '{}':'{}' (service '{}') for thing '{}'", new Object[] { variable, value, service, this.getThing().getUID() }); String oldValue = this.stateMap.get(variable); if (shouldIgnoreVariableUpdate(variable, value, oldValue)) { return; } this.stateMap.put(variable, value); // pre-process some variables, eg XML processing if (service.equals("AVTransport") && variable.equals("LastChange")) { Map<String, String> parsedValues = SonosXMLParser.getAVTransportFromXML(value); for (String parsedValue : parsedValues.keySet()) { // Update the transport state after the update of the media information // to not break the notification mechanism if (!parsedValue.equals("TransportState")) { onValueReceived(parsedValue, parsedValues.get(parsedValue), "AVTransport"); } // Translate AVTransportURI/AVTransportURIMetaData to CurrentURI/CurrentURIMetaData // for a compatibility with the result of the action GetMediaInfo if (parsedValue.equals("AVTransportURI")) { onValueReceived("CurrentURI", parsedValues.get(parsedValue), service); } else if (parsedValue.equals("AVTransportURIMetaData")) { onValueReceived("CurrentURIMetaData", parsedValues.get(parsedValue), service); } } updateMediaInformation(); if (parsedValues.get("TransportState") != null) { onValueReceived("TransportState", parsedValues.get("TransportState"), "AVTransport"); } } if (service.equals("RenderingControl") && variable.equals("LastChange")) { Map<String, String> parsedValues = SonosXMLParser.getRenderingControlFromXML(value); for (String parsedValue : parsedValues.keySet()) { onValueReceived(parsedValue, parsedValues.get(parsedValue), "RenderingControl"); } } // update the appropriate channel switch (variable) { case "TransportState": updateChannel(STATE); updateChannel(CONTROL); dispatchOnAllGroupMembers(variable, value, service); break; case "CurrentPlayMode": updateChannel(SHUFFLE); updateChannel(REPEAT); dispatchOnAllGroupMembers(variable, value, service); break; case "CurrentLEDState": updateChannel(LED); break; case "ZoneName": updateState(ZONENAME, (stateMap.get("ZoneName") != null) ? new StringType(stateMap.get("ZoneName")) : UnDefType.UNDEF); break; case "CurrentZoneName": updateChannel(ZONENAME); break; case "ZoneGroupState": updateChannel(ZONEGROUP); updateChannel(COORDINATOR); // Update coordinator after a change is made to the grouping of Sonos players updateGroupCoordinator(); updateMediaInformation(); // Update state and control channels for the group members with the coordinator values if (stateMap.get("TransportState") != null) { dispatchOnAllGroupMembers("TransportState", stateMap.get("TransportState"), "AVTransport"); } // Update shuffle and repeat channels for the group members with the coordinator values if (stateMap.get("CurrentPlayMode") != null) { dispatchOnAllGroupMembers("CurrentPlayMode", stateMap.get("CurrentPlayMode"), "AVTransport"); } break; case "LocalGroupUUID": updateChannel(ZONEGROUPID); break; case "GroupCoordinatorIsLocal": updateChannel(LOCALCOORDINATOR); break; case "VolumeMaster": updateChannel(VOLUME); break; case "MuteMaster": updateChannel(MUTE); break; case "LineInConnected": case "TOSLinkConnected": updateChannel(LINEIN); break; case "AlarmRunning": updateChannel(ALARMRUNNING); break; case "RunningAlarmProperties": updateChannel(ALARMPROPERTIES); break; case "CurrentURIFormatted": updateChannel(CURRENTTRACK); break; case "CurrentTitle": updateChannel(CURRENTTITLE); break; case "CurrentArtist": updateChannel(CURRENTARTIST); break; case "CurrentAlbum": updateChannel(CURRENTALBUM); break; case "CurrentURI": updateChannel(CURRENTTRANSPORTURI); break; case "CurrentTrackURI": updateChannel(CURRENTTRACKURI); break; case "CurrentAlbumArtURI": updateChannel(CURRENTALBUMART); updateChannel(CURRENTALBUMARTURL); break; case "CurrentSleepTimerGeneration": if (value.equals("0")) { updateState(SLEEPTIMER, new DecimalType(0)); } break; case "SleepTimerGeneration": if (value.equals("0")) { updateState(SLEEPTIMER, new DecimalType(0)); } else { updateSleepTimerDuration(); } break; case "RemainingSleepTimerDuration": updateState(SLEEPTIMER, (stateMap.get("RemainingSleepTimerDuration") != null) ? new DecimalType( sleepStrTimeToSeconds(stateMap.get("RemainingSleepTimerDuration"))) : UnDefType.UNDEF); break; default: break; } } } private void dispatchOnAllGroupMembers(String variable, String value, String service) { if (isCoordinator()) { for (String member : getOtherZoneGroupMembers()) { try { ZonePlayerHandler memberHandler = getHandlerByName(member); if (memberHandler != null && memberHandler.getThing() != null && ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())) { memberHandler.onValueReceived(variable, value, service); } } catch (IllegalStateException e) { logger.warn("Cannot update channel for group member ({})", e.getMessage()); } } } } private URL getAlbumArtUrl() { URL url = null; String albumArtURI = stateMap.get("CurrentAlbumArtURI"); if (albumArtURI != null) { try { if (albumArtURI.startsWith("http")) { url = new URL(albumArtURI); } else if (albumArtURI.startsWith("/")) { URL serviceDescrUrl = service.getDescriptorURL(this); if (serviceDescrUrl != null) { url = new URL(serviceDescrUrl.getProtocol(), serviceDescrUrl.getHost(), serviceDescrUrl.getPort(), albumArtURI); } } } catch (MalformedURLException e) { logger.debug("Failed to build a valid album art URL from {}: {}", albumArtURI, e.getMessage()); url = null; } } return url; } private String getContentTypeFromUrl(URL url) { if (url == null) { return null; } String contentType; InputStream input = null; try { URLConnection connection = url.openConnection(); contentType = connection.getContentType(); logger.debug("Content type from headers: {}", contentType); if (contentType == null) { input = connection.getInputStream(); contentType = URLConnection.guessContentTypeFromStream(input); logger.debug("Content type from data: {}", contentType); if (contentType == null) { contentType = RawType.DEFAULT_MIME_TYPE; } } } catch (IOException e) { logger.debug("Failed to identify content type from URL: {}", e.getMessage()); contentType = RawType.DEFAULT_MIME_TYPE; } finally { IOUtils.closeQuietly(input); } return contentType; } protected void updateChannel(String channeldD) { if (!isLinked(channeldD)) { return; } URL url; State newState = UnDefType.UNDEF; switch (channeldD) { case STATE: if (stateMap.get("TransportState") != null) { newState = new StringType(stateMap.get("TransportState")); } break; case CONTROL: if (stateMap.get("TransportState") != null) { if (stateMap.get("TransportState").equals("PLAYING")) { newState = PlayPauseType.PLAY; } else if (stateMap.get("TransportState").equals("STOPPED")) { newState = PlayPauseType.PAUSE; } else if (stateMap.get("TransportState").equals("PAUSED_PLAYBACK")) { newState = PlayPauseType.PAUSE; } } break; case SHUFFLE: if (stateMap.get("CurrentPlayMode") != null) { newState = isShuffleActive() ? OnOffType.ON : OnOffType.OFF; } break; case REPEAT: if (stateMap.get("CurrentPlayMode") != null) { newState = new StringType(getRepeatMode()); } break; case LED: if (stateMap.get("CurrentLEDState") != null) { newState = stateMap.get("CurrentLEDState").equals("On") ? OnOffType.ON : OnOffType.OFF; } break; case ZONENAME: if (stateMap.get("CurrentZoneName") != null) { newState = new StringType(stateMap.get("CurrentZoneName")); } break; case ZONEGROUP: if (stateMap.get("ZoneGroupState") != null) { newState = new StringType(stateMap.get("ZoneGroupState")); } break; case ZONEGROUPID: if (stateMap.get("LocalGroupUUID") != null) { newState = new StringType(stateMap.get("LocalGroupUUID")); } break; case COORDINATOR: newState = new StringType(getCoordinator()); break; case LOCALCOORDINATOR: if (stateMap.get("GroupCoordinatorIsLocal") != null) { newState = stateMap.get("GroupCoordinatorIsLocal").equals("true") ? OnOffType.ON : OnOffType.OFF; } break; case VOLUME: if (stateMap.get("VolumeMaster") != null) { newState = new PercentType(stateMap.get("VolumeMaster")); } break; case MUTE: if (stateMap.get("MuteMaster") != null) { newState = stateMap.get("MuteMaster").equals("1") ? OnOffType.ON : OnOffType.OFF; } break; case LINEIN: if (stateMap.get("LineInConnected") != null) { newState = stateMap.get("LineInConnected").equals("true") ? OnOffType.ON : OnOffType.OFF; } else if (stateMap.get("TOSLinkConnected") != null) { newState = stateMap.get("TOSLinkConnected").equals("true") ? OnOffType.ON : OnOffType.OFF; } break; case ALARMRUNNING: if (stateMap.get("AlarmRunning") != null) { newState = stateMap.get("AlarmRunning").equals("1") ? OnOffType.ON : OnOffType.OFF; } break; case ALARMPROPERTIES: if (stateMap.get("RunningAlarmProperties") != null) { newState = new StringType(stateMap.get("RunningAlarmProperties")); } break; case CURRENTTRACK: if (stateMap.get("CurrentURIFormatted") != null) { newState = new StringType(stateMap.get("CurrentURIFormatted")); } break; case CURRENTTITLE: if (stateMap.get("CurrentTitle") != null) { newState = new StringType(stateMap.get("CurrentTitle")); } break; case CURRENTARTIST: if (stateMap.get("CurrentArtist") != null) { newState = new StringType(stateMap.get("CurrentArtist")); } break; case CURRENTALBUM: if (stateMap.get("CurrentAlbum") != null) { newState = new StringType(stateMap.get("CurrentAlbum")); } break; case CURRENTALBUMART: url = getAlbumArtUrl(); if (url != null) { String contentType = getContentTypeFromUrl(url); InputStream input = null; try { input = url.openStream(); newState = new RawType(IOUtils.toByteArray(input), contentType); } catch (IOException e) { logger.debug("Failed to download the album cover art: {}", e.getMessage()); newState = UnDefType.UNDEF; } finally { IOUtils.closeQuietly(input); } } break; case CURRENTALBUMARTURL: url = getAlbumArtUrl(); if (url != null) { newState = new StringType(url.toExternalForm()); } break; case CURRENTTRANSPORTURI: if (stateMap.get("CurrentURI") != null) { newState = new StringType(stateMap.get("CurrentURI")); } break; case CURRENTTRACKURI: if (stateMap.get("CurrentTrackURI") != null) { newState = new StringType(stateMap.get("CurrentTrackURI")); } break; default: newState = null; break; } if (newState != null) { updateState(channeldD, newState); } } /** * CurrentURI will not change, but will trigger change of CurrentURIFormated * CurrentTrackMetaData will not change, but will trigger change of Title, Artist, Album */ private boolean shouldIgnoreVariableUpdate(String variable, String value, String oldValue) { return !hasValueChanged(value, oldValue) && !isQueueEvent(variable); } private boolean hasValueChanged(String value, String oldValue) { return oldValue != null ? !oldValue.equals(value) : value != null; } /** * Similar to the AVTransport eventing, the Queue events its state variables * as sub values within a synthesized LastChange state variable. */ private boolean isQueueEvent(String variable) { return "LastChange".equals(variable); } private void updateGroupCoordinator() { try { coordinatorHandler = getHandlerByName(getCoordinator()); } catch (IllegalStateException e) { logger.warn("Cannot update the group coordinator ({})", e.getMessage()); coordinatorHandler = null; } } private boolean isUpnpDeviceRegistered() { return service.isRegistered(this); } private void addSubscription() { synchronized (upnpLock) { // Set up GENA Subscriptions if (service.isRegistered(this)) { for (String subscription : SERVICE_SUBSCRIPTIONS) { if ((subscriptionState.get(subscription) == null) || !subscriptionState.get(subscription).booleanValue()) { logger.debug("{}: Subscribing to service {}...", getUDN(), subscription); service.addSubscription(this, subscription, SUBSCRIPTION_DURATION); subscriptionState.put(subscription, true); } } } } } private void removeSubscription() { synchronized (upnpLock) { // Set up GENA Subscriptions if (service.isRegistered(this)) { for (String subscription : SERVICE_SUBSCRIPTIONS) { if ((subscriptionState.get(subscription) != null) && subscriptionState.get(subscription).booleanValue()) { logger.debug("{}: Unsubscribing from service {}...", getUDN(), subscription); service.removeSubscription(this, subscription); } } } subscriptionState = new HashMap<String, Boolean>(); service.unregisterParticipant(this); } } @Override public void onServiceSubscribed(String service, boolean succeeded) { synchronized (upnpLock) { logger.debug("{}: Subscription to service {} {}", getUDN(), service, succeeded ? "succeeded" : "failed"); subscriptionState.put(service, succeeded); } } private void onUpdate() { if (pollingJob == null || pollingJob.isCancelled()) { ZonePlayerConfiguration config = getConfigAs(ZonePlayerConfiguration.class); // use default if not specified int refreshInterval = DEFAULT_REFRESH_INTERVAL; if (config.refresh != null) { refreshInterval = config.refresh.intValue(); } pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0, refreshInterval, TimeUnit.SECONDS); } } private void updatePlayerState() { Map<String, String> result = service.invokeAction(this, "DeviceProperties", "GetZoneInfo", null); if (result.isEmpty()) { if (!ThingStatus.OFFLINE.equals(getThing().getStatus())) { logger.debug("Sonos player {} is not available in local network", getUDN()); updateStatus(ThingStatus.OFFLINE); synchronized (upnpLock) { subscriptionState = new HashMap<String, Boolean>(); } } } else if (!ThingStatus.ONLINE.equals(getThing().getStatus())) { logger.debug("Sonos player {} has been found in local network", getUDN()); updateStatus(ThingStatus.ONLINE); } } protected void updateMediaInfo() { Map<String, String> inputs = new HashMap<String, String>(); inputs.put("InstanceID", "0"); Map<String, String> result = service.invokeAction(this, "AVTransport", "GetMediaInfo", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } updateMediaInformation(); } protected void updateCurrentZoneName() { Map<String, String> result = service.invokeAction(this, "DeviceProperties", "GetZoneAttributes", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "DeviceProperties"); } } protected void updateLed() { Map<String, String> result = service.invokeAction(this, "DeviceProperties", "GetLEDState", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "DeviceProperties"); } } protected void updateTime() { Map<String, String> result = service.invokeAction(this, "AlarmClock", "GetTimeNow", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AlarmClock"); } } protected void updatePosition() { Map<String, String> result = service.invokeAction(this, "AVTransport", "GetPositionInfo", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } protected void updateRunningAlarmProperties() { Map<String, String> result = service.invokeAction(this, "AVTransport", "GetRunningAlarmProperties", null); String alarmID = result.get("AlarmID"); String loggedStartTime = result.get("LoggedStartTime"); String newStringValue = null; if (alarmID != null && loggedStartTime != null) { newStringValue = alarmID + " - " + loggedStartTime; } else { newStringValue = "No running alarm"; } result.put("RunningAlarmProperties", newStringValue); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } protected void updateZoneInfo() { Map<String, String> result = service.invokeAction(this, "DeviceProperties", "GetZoneInfo", null); Map<String, String> result2 = service.invokeAction(this, "DeviceProperties", "GetZoneAttributes", null); result.putAll(result2); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "DeviceProperties"); } } public String getCoordinator() { if (stateMap.get("ZoneGroupState") != null) { Collection<SonosZoneGroup> zoneGroups = SonosXMLParser.getZoneGroupFromXML(stateMap.get("ZoneGroupState")); for (SonosZoneGroup zg : zoneGroups) { if (zg.getMembers().contains(getUDN())) { return zg.getCoordinator(); } } } return getUDN(); } public boolean isCoordinator() { return getUDN().equals(getCoordinator()); } protected void updateMediaInformation() { String currentURI = getCurrentURI(); SonosMetaData currentTrack = getTrackMetadata(); SonosMetaData currentUriMetaData = getCurrentURIMetadata(); String artist = null; String album = null; String title = null; String resultString = null; boolean needsUpdating = false; if (currentURI == null) { // Do nothing } else if (currentURI.isEmpty()) { // Reset data needsUpdating = true; } else if (currentURI.contains(GROUP_URI)) { // The Sonos is a slave member of a group, we do nothing // The media information will be updated by the coordinator // Notification of group change occurs later, so we just check the URI } else if (isPlayingStream(currentURI)) { // Radio stream (tune-in) boolean opmlUrlSucceeded = false; if (opmlUrl != null) { String stationID = StringUtils.substringBetween(currentURI, ":s", "?sid"); String mac = getMACAddress(); if (stationID != null && !stationID.isEmpty() && mac != null && !mac.isEmpty()) { String url = opmlUrl; url = StringUtils.replace(url, "%id", stationID); url = StringUtils.replace(url, "%serial", mac); String response = null; try { response = HttpUtil.executeUrl("GET", url, SOCKET_TIMEOUT); } catch (IOException e) { logger.debug("Request to device failed: {}", e); } if (response != null) { List<String> fields = SonosXMLParser.getRadioTimeFromXML(response); if (fields != null && fields.size() > 0) { opmlUrlSucceeded = true; resultString = new String(); // radio name should be first field title = fields.get(0); Iterator<String> listIterator = fields.listIterator(); while (listIterator.hasNext()) { String field = listIterator.next(); resultString = resultString + field; if (listIterator.hasNext()) { resultString = resultString + " - "; } } needsUpdating = true; } } } } if (!opmlUrlSucceeded) { if (currentUriMetaData != null) { title = currentUriMetaData.getTitle(); if ((currentTrack == null) || (currentTrack.getStreamContent() == null) || currentTrack.getStreamContent().isEmpty()) { resultString = title; } else { resultString = title + " - " + currentTrack.getStreamContent(); } needsUpdating = true; } } } else if (isPlayingLineIn(currentURI)) { if (currentTrack != null) { title = currentTrack.getTitle(); resultString = title; needsUpdating = true; } } else if (!currentURI.contains("x-rincon-mp3") && !currentURI.contains("x-sonosapi")) { if (currentTrack != null) { artist = !currentTrack.getAlbumArtist().isEmpty() ? currentTrack.getAlbumArtist() : currentTrack.getCreator(); album = currentTrack.getAlbum(); title = currentTrack.getTitle(); resultString = artist + " - " + album + " - " + title; needsUpdating = true; } } if (needsUpdating) { String albumArtURI = (currentTrack != null && currentTrack.getAlbumArtUri() != null && !currentTrack.getAlbumArtUri().isEmpty()) ? currentTrack.getAlbumArtUri() : ""; for (String member : getZoneGroupMembers()) { try { ZonePlayerHandler memberHandler = getHandlerByName(member); if (memberHandler != null && memberHandler.getThing() != null && ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())) { memberHandler.onValueReceived("CurrentArtist", (artist != null) ? artist : "", "AVTransport"); memberHandler.onValueReceived("CurrentAlbum", (album != null) ? album : "", "AVTransport"); memberHandler.onValueReceived("CurrentTitle", (title != null) ? title : "", "AVTransport"); memberHandler.onValueReceived("CurrentURIFormatted", (resultString != null) ? resultString : "", "AVTransport"); memberHandler.onValueReceived("CurrentAlbumArtURI", albumArtURI, "AVTransport"); } } catch (IllegalStateException e) { logger.warn("Cannot update media data for group member ({})", e.getMessage()); } } } } public boolean isGroupCoordinator() { String value = stateMap.get("GroupCoordinatorIsLocal"); if (value != null) { return value.equals("true") ? true : false; } return false; } @Override public String getUDN() { return getConfigAs(ZonePlayerConfiguration.class).udn; } public String getCurrentURI() { return stateMap.get("CurrentURI"); } public SonosMetaData getCurrentURIMetadata() { if (stateMap.get("CurrentURIMetaData") != null && !stateMap.get("CurrentURIMetaData").isEmpty()) { return SonosXMLParser.getMetaDataFromXML(stateMap.get("CurrentURIMetaData")); } else { return null; } } public SonosMetaData getTrackMetadata() { if (stateMap.get("CurrentTrackMetaData") != null && !stateMap.get("CurrentTrackMetaData").isEmpty()) { return SonosXMLParser.getMetaDataFromXML(stateMap.get("CurrentTrackMetaData")); } else { return null; } } public SonosMetaData getEnqueuedTransportURIMetaData() { if (stateMap.get("EnqueuedTransportURIMetaData") != null && !stateMap.get("EnqueuedTransportURIMetaData").isEmpty()) { return SonosXMLParser.getMetaDataFromXML(stateMap.get("EnqueuedTransportURIMetaData")); } else { return null; } } public String getMACAddress() { updateZoneInfo(); return stateMap.get("MACAddress"); } public String getPosition() { updatePosition(); return stateMap.get("RelTime"); } public long getCurrenTrackNr() { updatePosition(); String value = stateMap.get("Track"); if (value != null) { return Long.valueOf(value); } else { return -1; } } public String getVolume() { return stateMap.get("VolumeMaster"); } public String getTransportState() { return stateMap.get("TransportState"); } public List<SonosEntry> getArtists(String filter) { return getEntries("A:", filter); } public List<SonosEntry> getArtists() { return getEntries("A:", "dc:title,res,dc:creator,upnp:artist,upnp:album"); } public List<SonosEntry> getAlbums(String filter) { return getEntries("A:ALBUM", filter); } public List<SonosEntry> getAlbums() { return getEntries("A:ALBUM", "dc:title,res,dc:creator,upnp:artist,upnp:album"); } public List<SonosEntry> getTracks(String filter) { return getEntries("A:TRACKS", filter); } public List<SonosEntry> getTracks() { return getEntries("A:TRACKS", "dc:title,res,dc:creator,upnp:artist,upnp:album"); } public List<SonosEntry> getQueue(String filter) { return getEntries("Q:0", filter); } public List<SonosEntry> getQueue() { return getEntries("Q:0", "dc:title,res,dc:creator,upnp:artist,upnp:album"); } public long getQueueSize() { return getNbEntries("Q:0"); } public List<SonosEntry> getPlayLists(String filter) { return getEntries("SQ:", filter); } public List<SonosEntry> getPlayLists() { return getEntries("SQ:", "dc:title,res,dc:creator,upnp:artist,upnp:album"); } public List<SonosEntry> getFavoriteRadios(String filter) { return getEntries("R:0/0", filter); } public List<SonosEntry> getFavoriteRadios() { return getEntries("R:0/0", "dc:title,res,dc:creator,upnp:artist,upnp:album"); } /** * Searches for entries in the 'favorites' list on a sonos account * * @return */ public List<SonosEntry> getFavorites() { return getEntries("FV:2", "dc:title,res,dc:creator,upnp:artist,upnp:album"); } protected List<SonosEntry> getEntries(String type, String filter) { long startAt = 0; Map<String, String> inputs = new HashMap<String, String>(); inputs.put("ObjectID", type); inputs.put("BrowseFlag", "BrowseDirectChildren"); inputs.put("Filter", filter); inputs.put("StartingIndex", Long.toString(startAt)); inputs.put("RequestedCount", Integer.toString(200)); inputs.put("SortCriteria", ""); List<SonosEntry> resultList = null; Map<String, String> result = service.invokeAction(this, "ContentDirectory", "Browse", inputs); long totalMatches = getResultEntry(result, "TotalMatches", type, filter); long initialNumberReturned = getResultEntry(result, "NumberReturned", type, filter); String initialResult = result.get("Result"); resultList = SonosXMLParser.getEntriesFromString(initialResult); startAt = startAt + initialNumberReturned; while (startAt < totalMatches) { inputs.put("StartingIndex", Long.toString(startAt)); result = service.invokeAction(this, "ContentDirectory", "Browse", inputs); // Execute this action synchronously String nextResult = result.get("Result"); long numberReturned = getResultEntry(result, "NumberReturned", type, filter); resultList.addAll(SonosXMLParser.getEntriesFromString(nextResult)); startAt = startAt + numberReturned; } return resultList; } protected long getNbEntries(String type) { Map<String, String> inputs = new HashMap<String, String>(); inputs.put("ObjectID", type); inputs.put("BrowseFlag", "BrowseDirectChildren"); inputs.put("Filter", "dc:title"); inputs.put("StartingIndex", "0"); inputs.put("RequestedCount", "1"); inputs.put("SortCriteria", ""); Map<String, String> result = service.invokeAction(this, "ContentDirectory", "Browse", inputs); return getResultEntry(result, "TotalMatches", type, "dc:title"); } /** * Handles value searching in a SONOS result map (called by {@link #getEntries(String, String)}) * * @param resultInput - the map to be examined for the requestedKey * @param requestedKey - the key to be sought in the resultInput map * @param entriesType - the 'type' argument of {@link #getEntries(String, String)} method used for logging * @param entriesFilter - the 'filter' argument of {@link #getEntries(String, String)} method used for logging * * @return 0 as long or the value corresponding to the requiredKey if found */ private Long getResultEntry(Map<String, String> resultInput, String requestedKey, String entriesType, String entriesFilter) { long result = 0; if (resultInput.isEmpty()) { return result; } try { result = Long.valueOf(resultInput.get(requestedKey)); } catch (NumberFormatException ex) { logger.warn("Could not fetch " + requestedKey + " result for type: " + entriesType + " and filter: " + entriesFilter + ". Using default value '0': " + ex.getMessage(), ex); } return result; } /** * Save the state (track, position etc) of the Sonos Zone player. * * @return true if no error occurred. */ protected void saveState() { synchronized (stateLock) { savedState = new SonosZonePlayerState(); String currentURI = getCurrentURI(); savedState.transportState = getTransportState(); savedState.volume = getVolume(); if (currentURI != null) { if (isPlayingStream(currentURI)) { // we are streaming music SonosMetaData track = getTrackMetadata(); SonosMetaData current = getCurrentURIMetadata(); if (track != null && current != null) { savedState.entry = new SonosEntry("", current.getTitle(), "", "", track.getAlbumArtUri(), "", current.getUpnpClass(), currentURI); } } else if (currentURI.contains(GROUP_URI)) { // we are a slave to some coordinator savedState.entry = new SonosEntry("", "", "", "", "", "", "", currentURI); } else if (isPlayingLineIn(currentURI)) { // we are streaming from the Line In connection savedState.entry = new SonosEntry("", "", "", "", "", "", "", currentURI); } else if (isPlayingQueue(currentURI)) { // we are playing something that sits in the queue SonosMetaData queued = getEnqueuedTransportURIMetaData(); if (queued != null) { savedState.track = getCurrenTrackNr(); if (queued.getUpnpClass().contains("object.container.playlistContainer")) { // we are playing a real 'saved' playlist List<SonosEntry> playLists = getPlayLists(); for (SonosEntry someList : playLists) { if (someList.getTitle().equals(queued.getTitle())) { savedState.entry = new SonosEntry(someList.getId(), someList.getTitle(), someList.getParentId(), "", "", "", someList.getUpnpClass(), someList.getRes()); break; } } } else if (queued.getUpnpClass().contains("object.container")) { // we are playing some other sort of // 'container' - we will save that to a // playlist for our convenience logger.debug("Save State for a container of type {}", queued.getUpnpClass()); // save the playlist String existingList = ""; List<SonosEntry> playLists = getPlayLists(); for (SonosEntry someList : playLists) { if (someList.getTitle().equals(ESH_PREFIX + getUDN())) { existingList = someList.getId(); break; } } saveQueue(ESH_PREFIX + getUDN(), existingList); // get all the playlists and a ref to our // saved list playLists = getPlayLists(); for (SonosEntry someList : playLists) { if (someList.getTitle().equals(ESH_PREFIX + getUDN())) { savedState.entry = new SonosEntry(someList.getId(), someList.getTitle(), someList.getParentId(), "", "", "", someList.getUpnpClass(), someList.getRes()); break; } } } } else { savedState.entry = new SonosEntry("", "", "", "", "", "", "", QUEUE_URI + getUDN() + " } } savedState.relTime = getPosition(); } else { savedState.entry = null; } } } /** * Restore the state (track, position etc) of the Sonos Zone player. * * @return true if no error occurred. */ protected void restoreState() { synchronized (stateLock) { if (savedState != null) { // put settings back if (savedState.volume != null) { setVolume(DecimalType.valueOf(savedState.volume)); } if (isCoordinator()) { if (savedState.entry != null) { // check if we have a playlist to deal with if (savedState.entry.getUpnpClass().contains("object.container.playlistContainer")) { addURIToQueue(savedState.entry.getRes(), SonosXMLParser.compileMetadataString(savedState.entry), 0, true); SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", QUEUE_URI + getUDN() + " setCurrentURI(entry); setPositionTrack(savedState.track); } else { setCurrentURI(savedState.entry); setPosition(savedState.relTime); } } if (savedState.transportState != null) { if (savedState.transportState.equals("PLAYING")) { play(); } else if (savedState.transportState.equals("STOPPED")) { stop(); } else if (savedState.transportState.equals("PAUSED_PLAYBACK")) { pause(); } } } } } } public void saveQueue(String name, String queueID) { if (name != null && queueID != null) { Map<String, String> inputs = new HashMap<String, String>(); inputs.put("Title", name); inputs.put("ObjectID", queueID); Map<String, String> result = service.invokeAction(this, "AVTransport", "SaveQueue", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } } public void setVolume(Command command) { if (command != null) { if (command instanceof OnOffType || command instanceof IncreaseDecreaseType || command instanceof DecimalType || command instanceof PercentType) { Map<String, String> inputs = new HashMap<String, String>(); String newValue = null; if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.INCREASE) { int i = Integer.valueOf(this.getVolume()); newValue = String.valueOf(Math.min(100, i + 1)); } else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) { int i = Integer.valueOf(this.getVolume()); newValue = String.valueOf(Math.max(0, i - 1)); } else if (command instanceof OnOffType && command == OnOffType.ON) { newValue = "100"; } else if (command instanceof OnOffType && command == OnOffType.OFF) { newValue = "0"; } else if (command instanceof DecimalType) { newValue = command.toString(); } else { return; } inputs.put("Channel", "Master"); inputs.put("DesiredVolume", newValue); Map<String, String> result = service.invokeAction(this, "RenderingControl", "SetVolume", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "RenderingControl"); } } } } /** * Set the VOLUME command specific to the current grouping according to the Sonos behaviour. * AdHoc groups handles the volume specifically for each player. * Bonded groups delegate the volume to the coordinator which applies the same level to all group members. */ public void setVolumeForGroup(Command command) { if (isAdHocGroup() || isStandalonePlayer()) { setVolume(command); } else { try { getCoordinatorHandler().setVolume(command); } catch (IllegalStateException e) { logger.warn("Cannot set group volume ({})", e.getMessage()); } } } /** * Checks if the player receiving the command is part of a group that * consists of randomly added players or contains bonded players * * @return boolean */ private boolean isAdHocGroup() { SonosZoneGroup currentZoneGroup = getCurrentZoneGroup(); if (currentZoneGroup != null) { List<String> zoneGroupMemberNames = currentZoneGroup.getMemberZoneNames(); if (zoneGroupMemberNames != null) { for (String zoneName : zoneGroupMemberNames) { if (!zoneName.equals(zoneGroupMemberNames.get(0))) { // At least one "ZoneName" differs so we have an AdHoc group return true; } } } } return false; } /** * Checks if the player receiving the command is a standalone player * * @return boolean */ private boolean isStandalonePlayer() { return getCurrentZoneGroup() != null ? getCurrentZoneGroup().getMembers().size() == 1 : true; } /** * Returns the current zone group * (of which the player receiving the command is part) * * @return {@link SonosZoneGroup} */ private SonosZoneGroup getCurrentZoneGroup() { String zoneGroupState = stateMap.get("ZoneGroupState"); if (zoneGroupState != null) { Collection<SonosZoneGroup> zoneGroups = SonosXMLParser.getZoneGroupFromXML(zoneGroupState); for (SonosZoneGroup zoneGroup : zoneGroups) { if (zoneGroup.getMembers().contains(getUDN())) { return zoneGroup; } } } logger.warn("Could not fetch Sonos group state information"); return null; } /** * Sets the volume level for a notification sound * (initializes {@link #notificationSoundVolume}) * * @param command */ public void setNotificationSoundVolume(Command command) { if (command != null) { notificationSoundVolume = command.toString(); } } /** * Gets the volume level for a notification sound */ public PercentType getNotificationSoundVolume() { if (notificationSoundVolume == null) { // we need to initialize the value for the first time notificationSoundVolume = getVolume(); if (notificationSoundVolume != null) { updateState(SonosBindingConstants.NOTIFICATIONVOLUME, new PercentType(new BigDecimal(notificationSoundVolume))); } } if (notificationSoundVolume != null) { return new PercentType(new BigDecimal(notificationSoundVolume)); } else { return null; } } public void addURIToQueue(String URI, String meta, long desiredFirstTrack, boolean enqueueAsNext) { if (URI != null && meta != null) { Map<String, String> inputs = new HashMap<String, String>(); try { inputs.put("InstanceID", "0"); inputs.put("EnqueuedURI", URI); inputs.put("EnqueuedURIMetaData", meta); inputs.put("DesiredFirstTrackNumberEnqueued", Long.toString(desiredFirstTrack)); inputs.put("EnqueueAsNext", Boolean.toString(enqueueAsNext)); } catch (NumberFormatException ex) { logger.error("Action Invalid Value Format Exception {}", ex.getMessage()); } Map<String, String> result = service.invokeAction(this, "AVTransport", "AddURIToQueue", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } } public void setCurrentURI(SonosEntry newEntry) { setCurrentURI(newEntry.getRes(), SonosXMLParser.compileMetadataString(newEntry)); } public void setCurrentURI(String URI, String URIMetaData) { if (URI != null && URIMetaData != null) { Map<String, String> inputs = new HashMap<String, String>(); try { inputs.put("InstanceID", "0"); inputs.put("CurrentURI", URI); inputs.put("CurrentURIMetaData", URIMetaData); } catch (NumberFormatException ex) { logger.error("Action Invalid Value Format Exception {}", ex.getMessage()); } Map<String, String> result = service.invokeAction(this, "AVTransport", "SetAVTransportURI", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } } public void setPosition(String relTime) { seek("REL_TIME", relTime); } public void setPositionTrack(long tracknr) { seek("TRACK_NR", Long.toString(tracknr)); } public void setPositionTrack(String tracknr) { seek("TRACK_NR", tracknr); } protected void seek(String unit, String target) { if (unit != null && target != null) { Map<String, String> inputs = new HashMap<String, String>(); try { inputs.put("InstanceID", "0"); inputs.put("Unit", unit); inputs.put("Target", target); } catch (NumberFormatException ex) { logger.error("Action Invalid Value Format Exception {}", ex.getMessage()); } Map<String, String> result = service.invokeAction(this, "AVTransport", "Seek", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } } public void play() { Map<String, String> inputs = new HashMap<String, String>(); inputs.put("Speed", "1"); Map<String, String> result = service.invokeAction(this, "AVTransport", "Play", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } public void stop() { Map<String, String> result = service.invokeAction(this, "AVTransport", "Stop", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } public void pause() { Map<String, String> result = service.invokeAction(this, "AVTransport", "Pause", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } public void setShuffle(Command command) { if ((command != null) && (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType)) { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP) || command.equals(OpenClosedType.OPEN)) { switch (coordinator.getRepeatMode()) { case "ALL": coordinator.updatePlayMode("SHUFFLE"); break; case "ONE": coordinator.updatePlayMode("SHUFFLE_REPEAT_ONE"); break; case "OFF": coordinator.updatePlayMode("SHUFFLE_NOREPEAT"); break; } } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN) || command.equals(OpenClosedType.CLOSED)) { switch (coordinator.getRepeatMode()) { case "ALL": coordinator.updatePlayMode("REPEAT_ALL"); break; case "ONE": coordinator.updatePlayMode("REPEAT_ONE"); break; case "OFF": coordinator.updatePlayMode("NORMAL"); break; } } } catch (IllegalStateException e) { logger.warn("Cannot handle shuffle command ({})", e.getMessage()); } } } public void setRepeat(Command command) { if ((command != null) && (command instanceof StringType)) { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); switch (command.toString()) { case "ALL": coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE" : "REPEAT_ALL"); break; case "ONE": coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE_REPEAT_ONE" : "REPEAT_ONE"); break; case "OFF": coordinator.updatePlayMode(coordinator.isShuffleActive() ? "SHUFFLE_NOREPEAT" : "NORMAL"); break; default: logger.warn("{}: unexpected repeat command; accepted values are ALL, ONE and OFF", command.toString()); break; } } catch (IllegalStateException e) { logger.warn("Cannot handle repeat command ({})", e.getMessage()); } } } public Boolean isShuffleActive() { return ((stateMap.get("CurrentPlayMode") != null) && stateMap.get("CurrentPlayMode").startsWith("SHUFFLE")) ? true : false; } public String getRepeatMode() { String mode = "OFF"; if (stateMap.get("CurrentPlayMode") != null) { switch (stateMap.get("CurrentPlayMode")) { case "REPEAT_ALL": case "SHUFFLE": mode = "ALL"; break; case "REPEAT_ONE": case "SHUFFLE_REPEAT_ONE": mode = "ONE"; break; case "NORMAL": case "SHUFFLE_NOREPEAT": default: mode = "OFF"; break; } } return mode; } protected void updatePlayMode(String playMode) { Map<String, String> inputs = new HashMap<String, String>(); inputs.put("InstanceID", "0"); inputs.put("NewPlayMode", playMode); Map<String, String> result = service.invokeAction(this, "AVTransport", "SetPlayMode", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } /** * Clear all scheduled music from the current queue. * */ public void removeAllTracksFromQueue() { Map<String, String> inputs = new HashMap<String, String>(); inputs.put("InstanceID", "0"); Map<String, String> result = service.invokeAction(this, "AVTransport", "RemoveAllTracksFromQueue", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } /** * Play music from the line-in of the given Player referenced by the given UDN or name * * @param udn or name */ public void playLineIn(Command command) { if (command != null && command instanceof StringType) { try { String remotePlayerName = command.toString(); ZonePlayerHandler coordinatorHandler = getCoordinatorHandler(); ZonePlayerHandler remoteHandler = getHandlerByName(remotePlayerName); // check if player has a line-in connected if (remoteHandler.isAnalogLineInConnected() || remoteHandler.isOpticalLineInConnected()) { // stop whatever is currently playing coordinatorHandler.stop(); // set the URI if (remoteHandler.isAnalogLineInConnected()) { coordinatorHandler.setCurrentURI(ANALOG_LINE_IN_URI + remoteHandler.getUDN(), ""); } else { coordinatorHandler.setCurrentURI(OPTICAL_LINE_IN_URI + remoteHandler.getUDN() + SPDIF, ""); } // take the system off mute coordinatorHandler.setMute(OnOffType.OFF); // start jammin' coordinatorHandler.play(); } else { logger.warn("Line-in of {} is not connected", remoteHandler.getUDN()); } } catch (IllegalStateException e) { logger.warn("Cannot play line-in ({})", e.getMessage()); } } } private ZonePlayerHandler getCoordinatorHandler() throws IllegalStateException { if (coordinatorHandler == null) { try { coordinatorHandler = getHandlerByName(getCoordinator()); } catch (IllegalStateException e) { coordinatorHandler = null; throw new IllegalStateException("Missing group coordinator " + getCoordinator()); } } return coordinatorHandler; } /** * Returns a list of all zone group members this particular player is member of * Or empty list if the players is not assigned to any group * * @return a list of Strings containing the UDNs of other group members */ protected List<String> getZoneGroupMembers() { List<String> result = new ArrayList<>(); if (stateMap.get("ZoneGroupState") != null) { Collection<SonosZoneGroup> zoneGroups = SonosXMLParser.getZoneGroupFromXML(stateMap.get("ZoneGroupState")); for (SonosZoneGroup zg : zoneGroups) { if (zg.getMembers().contains(getUDN())) { result.addAll(zg.getMembers()); break; } } } else { // If the group topology was not yet received, return at least the current Sonos zone result.add(getUDN()); } return result; } /** * Returns a list of other zone group members this particular player is member of * Or empty list if the players is not assigned to any group * * @return a list of Strings containing the UDNs of other group members */ protected List<String> getOtherZoneGroupMembers() { List<String> zoneGroupMembers = getZoneGroupMembers(); zoneGroupMembers.remove(getUDN()); return zoneGroupMembers; } protected ZonePlayerHandler getHandlerByName(String remotePlayerName) throws IllegalStateException { if (thingRegistry != null) { for (ThingTypeUID supportedThingType : SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS) { Thing thing = thingRegistry.get(new ThingUID(supportedThingType, remotePlayerName)); if (thing != null) { return (ZonePlayerHandler) thing.getHandler(); } } Collection<Thing> allThings = thingRegistry.getAll(); for (Thing aThing : allThings) { if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID()) && aThing.getConfiguration().get(ZonePlayerConfiguration.UDN).equals(remotePlayerName)) { return (ZonePlayerHandler) aThing.getHandler(); } } } throw new IllegalStateException("Could not find handler for " + remotePlayerName); } public void setMute(Command command) { if (command != null) { if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) { Map<String, String> inputs = new HashMap<String, String>(); inputs.put("Channel", "Master"); if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP) || command.equals(OpenClosedType.OPEN)) { inputs.put("DesiredMute", "True"); } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN) || command.equals(OpenClosedType.CLOSED)) { inputs.put("DesiredMute", "False"); } Map<String, String> result = service.invokeAction(this, "RenderingControl", "SetMute", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "RenderingControl"); } } } } public List<SonosAlarm> getCurrentAlarmList() { Map<String, String> result = service.invokeAction(this, "AlarmClock", "ListAlarms", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AlarmClock"); } return SonosXMLParser.getAlarmsFromStringResult(result.get("CurrentAlarmList")); } public void updateAlarm(SonosAlarm alarm) { if (alarm != null) { Map<String, String> inputs = new HashMap<String, String>(); try { inputs.put("ID", Integer.toString(alarm.getID())); inputs.put("StartLocalTime", alarm.getStartTime()); inputs.put("Duration", alarm.getDuration()); inputs.put("Recurrence", alarm.getRecurrence()); inputs.put("RoomUUID", alarm.getRoomUUID()); inputs.put("ProgramURI", alarm.getProgramURI()); inputs.put("ProgramMetaData", alarm.getProgramMetaData()); inputs.put("PlayMode", alarm.getPlayMode()); inputs.put("Volume", Integer.toString(alarm.getVolume())); if (alarm.getIncludeLinkedZones()) { inputs.put("IncludeLinkedZones", "1"); } else { inputs.put("IncludeLinkedZones", "0"); } if (alarm.getEnabled()) { inputs.put("Enabled", "1"); } else { inputs.put("Enabled", "0"); } } catch (NumberFormatException ex) { logger.error("Action Invalid Value Format Exception {}", ex.getMessage()); } Map<String, String> result = service.invokeAction(this, "AlarmClock", "UpdateAlarm", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AlarmClock"); } } } public void setAlarm(Command command) { if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) { if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP) || command.equals(OpenClosedType.OPEN)) { setAlarm(true); } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN) || command.equals(OpenClosedType.CLOSED)) { setAlarm(false); } } } public void setAlarm(boolean alarmSwitch) { List<SonosAlarm> sonosAlarms = getCurrentAlarmList(); // find the nearest alarm - take the current time from the Sonos system, // not the system where we are running SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); fmt.setTimeZone(TimeZone.getTimeZone("GMT")); String currentLocalTime = getTime(); Date currentDateTime = null; try { currentDateTime = fmt.parse(currentLocalTime); } catch (ParseException e) { logger.error("An exception occurred while formatting a date"); e.printStackTrace(); } if (currentDateTime != null) { Calendar currentDateTimeCalendar = Calendar.getInstance(); currentDateTimeCalendar.setTimeZone(TimeZone.getTimeZone("GMT")); currentDateTimeCalendar.setTime(currentDateTime); currentDateTimeCalendar.add(Calendar.DAY_OF_YEAR, 10); long shortestDuration = currentDateTimeCalendar.getTimeInMillis() - currentDateTime.getTime(); SonosAlarm firstAlarm = null; for (SonosAlarm anAlarm : sonosAlarms) { SimpleDateFormat durationFormat = new SimpleDateFormat("HH:mm:ss"); durationFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date durationDate; try { durationDate = durationFormat.parse(anAlarm.getDuration()); } catch (ParseException e) { logger.error("An exception occurred while parsing a date : '{}'", e.getMessage()); continue; } long duration = durationDate.getTime(); if (duration < shortestDuration && anAlarm.getRoomUUID().equals(getUDN())) { shortestDuration = duration; firstAlarm = anAlarm; } } // Set the Alarm if (firstAlarm != null) { if (alarmSwitch) { firstAlarm.setEnabled(true); } else { firstAlarm.setEnabled(false); } updateAlarm(firstAlarm); } } } public String getTime() { updateTime(); return stateMap.get("CurrentLocalTime"); } public Boolean isAlarmRunning() { return ((stateMap.get("AlarmRunning") != null) && stateMap.get("AlarmRunning").equals("1")) ? true : false; } public void snoozeAlarm(Command command) { if (isAlarmRunning() && command instanceof DecimalType) { int minutes = ((DecimalType) command).intValue(); Map<String, String> inputs = new HashMap<String, String>(); Calendar snoozePeriod = Calendar.getInstance(); snoozePeriod.setTimeZone(TimeZone.getTimeZone("GMT")); snoozePeriod.setTimeInMillis(0); snoozePeriod.add(Calendar.MINUTE, minutes); SimpleDateFormat pFormatter = new SimpleDateFormat("HH:mm:ss"); pFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); try { inputs.put("Duration", pFormatter.format(snoozePeriod.getTime())); } catch (NumberFormatException ex) { logger.error("Action Invalid Value Format Exception {}", ex.getMessage()); } Map<String, String> result = service.invokeAction(this, "AVTransport", "SnoozeAlarm", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } else { logger.warn("There is no alarm running on {}", getUDN()); } } public Boolean isAnalogLineInConnected() { return ((stateMap.get("LineInConnected") != null) && stateMap.get("LineInConnected").equals("true")) ? true : false; } public Boolean isOpticalLineInConnected() { return ((stateMap.get("TOSLinkConnected") != null) && stateMap.get("TOSLinkConnected").equals("true")) ? true : false; } public void becomeStandAlonePlayer() { Map<String, String> result = service.invokeAction(this, "AVTransport", "BecomeCoordinatorOfStandaloneGroup", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } public void addMember(Command command) { if (command != null && command instanceof StringType) { SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", GROUP_URI + getUDN()); try { getHandlerByName(command.toString()).setCurrentURI(entry); } catch (IllegalStateException e) { logger.warn("Cannot add group member ({})", e.getMessage()); } } } public boolean publicAddress() { // check if sourcePlayer has a line-in connected if (isAnalogLineInConnected() || isOpticalLineInConnected()) { // first remove this player from its own group if any becomeStandAlonePlayer(); List<SonosZoneGroup> currentSonosZoneGroups = new ArrayList<SonosZoneGroup>(); for (SonosZoneGroup grp : SonosXMLParser.getZoneGroupFromXML(stateMap.get("ZoneGroupState"))) { currentSonosZoneGroups.add((SonosZoneGroup) grp.clone()); } // add all other players to this new group for (SonosZoneGroup group : currentSonosZoneGroups) { for (String player : group.getMembers()) { try { ZonePlayerHandler somePlayer = getHandlerByName(player); if (somePlayer != this) { somePlayer.becomeStandAlonePlayer(); somePlayer.stop(); addMember(StringType.valueOf(somePlayer.getUDN())); } } catch (IllegalStateException e) { logger.warn("Cannot add to group ({})", e.getMessage()); } } } try { ZonePlayerHandler coordinator = getCoordinatorHandler(); // set the URI of the group to the line-in SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", ANALOG_LINE_IN_URI + getUDN()); if (isOpticalLineInConnected()) { entry = new SonosEntry("", "", "", "", "", "", "", OPTICAL_LINE_IN_URI + getUDN() + SPDIF); } coordinator.setCurrentURI(entry); coordinator.play(); return true; } catch (IllegalStateException e) { logger.warn("Cannot handle command ({})", e.getMessage()); return false; } } else { logger.warn("Line-in of {} is not connected", getUDN()); return false; } } /** * Play a given url to music in one of the music libraries. * * @param url * in the format of //host/folder/filename.mp3 */ public void playURI(Command command) { if (command != null && command instanceof StringType) { try { String url = command.toString(); ZonePlayerHandler coordinator = getCoordinatorHandler(); // stop whatever is currently playing coordinator.stop(); coordinator.waitForNotTransportState("PLAYING"); // clear any tracks which are pending in the queue coordinator.removeAllTracksFromQueue(); // add the new track we want to play to the queue // The url will be prefixed with x-file-cifs if it is NOT a http URL if (!url.startsWith("x-") && (!url.startsWith("http"))) { // default to file based url url = FILE_URI + url; } coordinator.addURIToQueue(url, "", 0, true); // set the current playlist to our new queue coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + " // take the system off mute coordinator.setMute(OnOffType.OFF); // start jammin' coordinator.play(); } catch (IllegalStateException e) { logger.warn("Cannot play URI ({})", e.getMessage()); } } } private void scheduleNotificationSound(final Command command) { scheduler.schedule(new Runnable() { @Override public void run() { synchronized (notificationLock) { playNotificationSoundURI(command); } } }, 0, TimeUnit.MILLISECONDS); } /** * Play a given notification sound * * @param url in the format of //host/folder/filename.mp3 */ public void playNotificationSoundURI(Command notificationURL) { if (notificationURL != null && notificationURL instanceof StringType) { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); String currentURI = coordinator.getCurrentURI(); if (isPlayingStream(currentURI)) { handleRadioStream(currentURI, notificationURL, coordinator); } else if (isPlayingLineIn(currentURI)) { handleLineIn(currentURI, notificationURL, coordinator); } else if (isPlayingQueue(currentURI)) { handleSharedQueue(notificationURL, coordinator); } else if (isPlaylistEmpty(coordinator)) { handleEmptyQueue(notificationURL, coordinator); } synchronized (notificationLock) { notificationLock.notify(); } } catch (IllegalStateException e) { logger.warn("Cannot play sound ({})", e.getMessage()); } } } private boolean isPlaylistEmpty(ZonePlayerHandler coordinator) { return coordinator.getQueueSize() == 0; } private boolean isPlayingQueue(String currentURI) { if (currentURI == null) { return false; } return currentURI.contains(QUEUE_URI); } private boolean isPlayingStream(String currentURI) { if (currentURI == null) { return false; } return currentURI.contains(STREAM_URI); } private boolean isPlayingLineIn(String currentURI) { if (currentURI == null) { return false; } return currentURI.contains(ANALOG_LINE_IN_URI) || (currentURI.startsWith(OPTICAL_LINE_IN_URI) && currentURI.endsWith(SPDIF)); } /** * Does a chain of predefined actions when a Notification sound is played by * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case * radio streaming is currently loaded * * @param currentStreamURI - the currently loaded stream's URI * @param notificationURL - the notification url in the format of //host/folder/filename.mp3 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s) */ private void handleRadioStream(String currentStreamURI, Command notificationURL, ZonePlayerHandler coordinator) { String nextAction = coordinator.getTransportState(); SonosMetaData track = coordinator.getTrackMetadata(); SonosMetaData currentURI = coordinator.getCurrentURIMetadata(); if (track != null && currentURI != null) { handleNotificationSound(notificationURL, coordinator); coordinator.setCurrentURI(new SonosEntry("", currentURI.getTitle(), "", "", track.getAlbumArtUri(), "", currentURI.getUpnpClass(), currentStreamURI)); restoreLastTransportState(coordinator, nextAction); } } /** * Does a chain of predefined actions when a Notification sound is played by * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case * line in is currently loaded * * @param currentLineInURI - the currently loaded line-in URI * @param notificationURL - the notification url in the format of //host/folder/filename.mp3 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s) */ private void handleLineIn(String currentLineInURI, Command notificationURL, ZonePlayerHandler coordinator) { String nextAction = coordinator.getTransportState(); handleNotificationSound(notificationURL, coordinator); coordinator.setCurrentURI(currentLineInURI, ""); restoreLastTransportState(coordinator, nextAction); } /** * Does a chain of predefined actions when a Notification sound is played by * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case * shared queue is currently loaded * * @param notificationURL - the notification url in the format of //host/folder/filename.mp3 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s) */ private void handleSharedQueue(Command notificationURL, ZonePlayerHandler coordinator) { String nextAction = coordinator.getTransportState(); String trackPosition = coordinator.getPosition(); long currentTrackNumber = coordinator.getCurrenTrackNr(); handleNotificationSound(notificationURL, coordinator); coordinator.setPositionTrack(currentTrackNumber); coordinator.setPosition(trackPosition); restoreLastTransportState(coordinator, nextAction); } /** * Handle the execution of the notification sound by sequentially executing the required steps. * * @param notificationURL - the notification url in the format of //host/folder/filename.mp3 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s) */ private void handleNotificationSound(Command notificationURL, ZonePlayerHandler coordinator) { String originalVolume = (isAdHocGroup() || isStandalonePlayer()) ? getVolume() : coordinator.getVolume(); coordinator.stop(); coordinator.waitForNotTransportState("PLAYING"); applyNotificationSoundVolume(); long notificationPosition = coordinator.getQueueSize() + 1; coordinator.addURIToQueue(notificationURL.toString(), "", notificationPosition, false); coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + " coordinator.setPositionTrack(notificationPosition); coordinator.play(); coordinator.waitForFinishedNotification(); if (originalVolume != null) { setVolumeForGroup(DecimalType.valueOf(originalVolume)); } coordinator.removeRangeOfTracksFromQueue(new StringType(Long.toString(notificationPosition) + ",1")); } private void restoreLastTransportState(ZonePlayerHandler coordinator, String nextAction) { if (nextAction != null) { switch (nextAction) { case "PLAYING": coordinator.play(); coordinator.waitForTransportState("PLAYING"); break; case "PAUSED_PLAYBACK": coordinator.pause(); break; } } } /** * Does a chain of predefined actions when a Notification sound is played by * {@link ZonePlayerHandler#playNotificationSoundURI(Command)} in case * empty queue is currently loaded * * @param notificationURL - the notification url in the format of //host/folder/filename.mp3 * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s) */ private void handleEmptyQueue(Command notificationURL, ZonePlayerHandler coordinator) { String originalVolume = coordinator.getVolume(); coordinator.applyNotificationSoundVolume(); coordinator.playURI(notificationURL); coordinator.waitForFinishedNotification(); coordinator.removeAllTracksFromQueue(); coordinator.setVolume(DecimalType.valueOf(originalVolume)); } /** * Applies the notification sound volume level to the group (if not null) * * @param coordinator - {@link ZonePlayerHandler} coordinator for the SONOS device(s) */ private void applyNotificationSoundVolume() { PercentType volume = getNotificationSoundVolume(); if (volume != null) { setVolumeForGroup(volume); } } private void waitForFinishedNotification() { waitForTransportState("PLAYING"); // check Sonos state events to determine the end of the notification sound String notificationTitle = stateMap.get("CurrentTitle"); long playstart = System.currentTimeMillis(); while (System.currentTimeMillis() - playstart < NOTIFICATION_TIMEOUT) { try { Thread.sleep(50); if (!notificationTitle.equals(stateMap.get("CurrentTitle")) || !"PLAYING".equals(stateMap.get("TransportState"))) { break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } } private void waitForTransportState(String state) { if (stateMap.get("TransportState") != null) { long start = System.currentTimeMillis(); while (!stateMap.get("TransportState").equals(state)) { try { Thread.sleep(50); if (System.currentTimeMillis() - start > NOTIFICATION_TIMEOUT) { break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } } } private void waitForNotTransportState(String state) { if (stateMap.get("TransportState") != null) { long start = System.currentTimeMillis(); while (stateMap.get("TransportState").equals(state)) { try { Thread.sleep(50); if (System.currentTimeMillis() - start > NOTIFICATION_TIMEOUT) { break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } } } /** * Removes a range of tracks from the queue. * (<x,y> will remove y songs started by the song number x) * * @param command - must be in the format <startIndex, numberOfSongs> */ public void removeRangeOfTracksFromQueue(Command command) { if (command != null && command instanceof StringType) { Map<String, String> inputs = new HashMap<String, String>(); String[] rangeInputSplit = command.toString().split(","); // If range input is incorrect, remove the first song by default String startIndex = rangeInputSplit[0] != null ? rangeInputSplit[0] : "1"; String numberOfTracks = rangeInputSplit[1] != null ? rangeInputSplit[1] : "1"; inputs.put("InstanceID", "0"); inputs.put("StartingIndex", startIndex); inputs.put("NumberOfTracks", numberOfTracks); Map<String, String> result = service.invokeAction(this, "AVTransport", "RemoveTrackRangeFromQueue", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } } public void playQueue() { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); // set the current playlist to our new queue coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + " // take the system off mute coordinator.setMute(OnOffType.OFF); // start jammin' coordinator.play(); } catch (IllegalStateException e) { logger.warn("Cannot play queue ({})", e.getMessage()); } } public void setLed(Command command) { if (command != null) { if (command instanceof OnOffType || command instanceof OpenClosedType || command instanceof UpDownType) { Map<String, String> inputs = new HashMap<String, String>(); if (command.equals(OnOffType.ON) || command.equals(UpDownType.UP) || command.equals(OpenClosedType.OPEN)) { inputs.put("DesiredLEDState", "On"); } else if (command.equals(OnOffType.OFF) || command.equals(UpDownType.DOWN) || command.equals(OpenClosedType.CLOSED)) { inputs.put("DesiredLEDState", "Off"); } Map<String, String> result = service.invokeAction(this, "DeviceProperties", "SetLEDState", inputs); Map<String, String> result2 = service.invokeAction(this, "DeviceProperties", "GetLEDState", null); result.putAll(result2); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "DeviceProperties"); } } } } public void removeMember(Command command) { if (command != null && command instanceof StringType) { try { ZonePlayerHandler oldmemberHandler = getHandlerByName(command.toString()); oldmemberHandler.becomeStandAlonePlayer(); SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", QUEUE_URI + oldmemberHandler.getUDN() + " oldmemberHandler.setCurrentURI(entry); } catch (IllegalStateException e) { logger.warn("Cannot remove group member ({})", e.getMessage()); } } } public void previous() { Map<String, String> result = service.invokeAction(this, "AVTransport", "Previous", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } public void next() { Map<String, String> result = service.invokeAction(this, "AVTransport", "Next", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } public void playRadio(Command command) { if (command instanceof StringType) { String station = command.toString(); List<SonosEntry> stations = getFavoriteRadios(); SonosEntry theEntry = null; // search for the appropriate radio based on its name (title) for (SonosEntry someStation : stations) { if (someStation.getTitle().equals(station)) { theEntry = someStation; break; } } // set the URI of the group coordinator if (theEntry != null) { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); coordinator.setCurrentURI(theEntry); coordinator.play(); } catch (IllegalStateException e) { logger.warn("Cannot play radio ({})", e.getMessage()); } } else { logger.warn("Radio station '{}' not found", station); } } } /** * This will attempt to match the station string with a entry in the * favorites list, this supports both single entries and playlists * * @param favorite to match * @return true if a match was found and played. */ public void playFavorite(Command command) { if (command instanceof StringType) { String favorite = command.toString(); List<SonosEntry> favorites = getFavorites(); SonosEntry theEntry = null; // search for the appropriate favorite based on its name (title) for (SonosEntry entry : favorites) { if (entry.getTitle().equals(favorite)) { theEntry = entry; break; } } // set the URI of the group coordinator if (theEntry != null) { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); /** * If this is a playlist we need to treat it as such */ if (theEntry.getResourceMetaData() != null && theEntry.getResourceMetaData().getUpnpClass().startsWith("object.container")) { coordinator.removeAllTracksFromQueue(); coordinator.addURIToQueue(theEntry); coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + " String firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued"); if (firstTrackNumberEnqueued != null) { coordinator.seek("TRACK_NR", firstTrackNumberEnqueued); } } else { coordinator.setCurrentURI(theEntry); } coordinator.play(); } catch (IllegalStateException e) { logger.warn("Cannot paly favorite ({})", e.getMessage()); } } else { logger.warn("Favorite '{}' not found", favorite); } } } public void playTrack(Command command) { if (command != null && command instanceof DecimalType) { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); String trackNumber = command.toString(); coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + " // seek the track - warning, we do not check if the tracknumber falls in the boundary of the queue coordinator.setPositionTrack(trackNumber); // take the system off mute coordinator.setMute(OnOffType.OFF); // start jammin' coordinator.play(); } catch (IllegalStateException e) { logger.warn("Cannot play track ({})", e.getMessage()); } } } public void playPlayList(Command command) { if (command != null && command instanceof StringType) { String playlist = command.toString(); List<SonosEntry> playlists = getPlayLists(); SonosEntry theEntry = null; // search for the appropriate play list based on its name (title) for (SonosEntry somePlaylist : playlists) { if (somePlaylist.getTitle().equals(playlist)) { theEntry = somePlaylist; break; } } // set the URI of the group coordinator if (theEntry != null) { try { ZonePlayerHandler coordinator = getCoordinatorHandler(); coordinator.addURIToQueue(theEntry); coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + " String firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued"); if (firstTrackNumberEnqueued != null) { coordinator.seek("TRACK_NR", firstTrackNumberEnqueued); } coordinator.play(); } catch (IllegalStateException e) { logger.warn("Cannot play playlist ({})", e.getMessage()); } } else { logger.warn("Playlist '{}' not found", playlist); } } } public void addURIToQueue(SonosEntry newEntry) { addURIToQueue(newEntry.getRes(), SonosXMLParser.compileMetadataString(newEntry), 1, true); } public String getZoneName() { return stateMap.get("ZoneName"); } public String getZoneGroupID() { return stateMap.get("LocalGroupUUID"); } public String getRunningAlarmProperties() { updateRunningAlarmProperties(); return stateMap.get("RunningAlarmProperties"); } public String getMute() { return stateMap.get("MuteMaster"); } public boolean getLed() { return ((stateMap.get("CurrentLEDState") != null) && stateMap.get("CurrentLEDState").equals("On")) ? true : false; } public String getCurrentZoneName() { updateCurrentZoneName(); return stateMap.get("CurrentZoneName"); } @Override public void onStatusChanged(boolean status) { // TODO Auto-generated method stub } private String getModelNameFromDescriptor() { URL descriptor = service.getDescriptorURL(this); if (descriptor != null) { String sonosModelDescription = SonosXMLParser.parseModelDescription(service.getDescriptorURL(this)); return SonosXMLParser.extractModelName(sonosModelDescription); } else { return null; } } private boolean migrateThingType() { if (getThing().getThingTypeUID().equals(ZONEPLAYER_THING_TYPE_UID)) { String modelName = getModelNameFromDescriptor(); if (isSupportedModel(modelName)) { updateSonosThingType(modelName); return true; } } return false; } private boolean isSupportedModel(String modelName) { for (ThingTypeUID thingTypeUID : SUPPORTED_KNOWN_THING_TYPES_UIDS) { if (thingTypeUID.getId().equalsIgnoreCase(modelName)) { return true; } } return false; } private void updateSonosThingType(String newThingTypeID) { changeThingType(new ThingTypeUID(SonosBindingConstants.BINDING_ID, newThingTypeID), getConfig()); } /* * Set the sleeptimer duration * Use String command of format "HH:MM:SS" to set the timer to the desired duration * Use empty String "" to switch the sleep timer off */ public void setSleepTimer(Command command) { if (command != null) { if (command instanceof DecimalType) { Map<String, String> inputs = new HashMap<String, String>(); inputs.put("InstanceID", "0"); inputs.put("NewSleepTimerDuration", sleepSecondsToTimeStr(Integer.parseInt(command.toString()))); this.service.invokeAction(this, "AVTransport", "ConfigureSleepTimer", inputs); } } } protected void updateSleepTimerDuration() { Map<String, String> result = service.invokeAction(this, "AVTransport", "GetRemainingSleepTimerDuration", null); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } private String sleepSecondsToTimeStr(long sleepSeconds) { if (sleepSeconds == 0) { return ""; } else if (sleepSeconds < 68400) { long hours = TimeUnit.SECONDS.toHours(sleepSeconds); sleepSeconds -= TimeUnit.HOURS.toSeconds(hours); long minutes = TimeUnit.SECONDS.toMinutes(sleepSeconds); sleepSeconds -= TimeUnit.MINUTES.toSeconds(minutes); long seconds = TimeUnit.SECONDS.toSeconds(sleepSeconds); return String.format("%02d:%02d:%02d", hours, minutes, seconds); } else { logger.error("Sonos SleepTimer: Invalid sleep time set. sleep time must be >=0 and < 68400s (24h)"); return "ERR"; } } private long sleepStrTimeToSeconds(String sleepTime) { String[] units = sleepTime.split(":"); int hours = Integer.parseInt(units[0]); int minutes = Integer.parseInt(units[1]); int seconds = Integer.parseInt(units[2]); return 3600 * hours + 60 * minutes + seconds; } }
package imj2.tools; import static java.lang.Math.min; import static java.lang.Math.pow; import static java.lang.Math.round; import static java.lang.Math.sqrt; import static net.sourceforge.aprog.swing.SwingTools.horizontalBox; import static net.sourceforge.aprog.swing.SwingTools.show; import static net.sourceforge.aprog.tools.Tools.array; import imj2.tools.Image2DComponent.Painter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.TreeMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import net.sourceforge.aprog.swing.SwingTools; import net.sourceforge.aprog.tools.MathTools.Statistics; import net.sourceforge.aprog.tools.Tools; import org.junit.Test; /** * @author codistmonk (creation 2014-04-09) */ @SuppressWarnings("unchecked") public final class BitwiseQuantizationTest { // @Test public final void test1() { final TreeMap<double[], String> lines = new TreeMap<double[], String>(DoubleArrayComparator.INSTANCE); for (int qR0 = 0; qR0 <= 7; ++qR0) { final int qR = qR0; for (int qG0 = 0; qG0 <= 7; ++qG0) { final int qG = qG0; for (int qB0 = 0; qB0 <= 7; ++qB0) { final int qB = qB0; MultiThreadTools.getExecutor().submit(new Runnable() { @Override public final void run() { final int[] rgb = new int[3]; final int[] qRGB = rgb.clone(); final float[] xyz = new float[3]; final float[] cielab = new float[3]; final float[] qCIELAB = cielab.clone(); final Statistics error = new Statistics(); for (int color = 0; color <= 0x00FFFFFF; ++color) { rgbToRGB(color, rgb); rgbToXYZ(rgb, xyz); xyzToCIELAB(xyz, cielab); quantize(rgb, qR, qG, qB, qRGB); rgbToXYZ(qRGB, xyz); xyzToCIELAB(xyz, qCIELAB); error.addValue(distance2(cielab, qCIELAB)); } final double[] key = { qR + qG + qB, error.getMean() }; final String line = "qRGB: " + qR + " " + qG + " " + qB + " " + ((qR + qG + qB)) + " error: " + error.getMinimum() + " <= " + error.getMean() + " ( " + sqrt(error.getVariance()) + " ) <= " + error.getMaximum(); synchronized (lines) { lines.put(key, line); System.out.println(line); } } }); } } } for (int qH0 = 0; qH0 <= 7; ++qH0) { final int qH = qH0; for (int qS0 = 0; qS0 <= 7; ++qS0) { final int qS = qS0; for (int qV0 = 0; qV0 <= 7; ++qV0) { final int qV = qV0; MultiThreadTools.getExecutor().submit(new Runnable() { @Override public final void run() { final int[] rgb = new int[3]; final int[] qRGB = rgb.clone(); final float[] xyz = new float[3]; final float[] cielab = new float[3]; final float[] qCIELAB = cielab.clone(); final int[] hsv = new int[3]; final int[] qHSV = hsv.clone(); final Statistics error = new Statistics(); for (int color = 0; color <= 0x00FFFFFF; ++color) { rgbToRGB(color, rgb); rgbToXYZ(rgb, xyz); xyzToCIELAB(xyz, cielab); rgbToHSV(rgb, hsv); quantize(hsv, qH, qS, qV, qHSV); hsvToRGB(qHSV, qRGB); rgbToXYZ(qRGB, xyz); xyzToCIELAB(xyz, qCIELAB); error.addValue(distance2(cielab, qCIELAB)); } final double[] key = { qH + qS + qV, error.getMean() }; final String line = "qHSV: " + qH + " " + qS + " " + qV + " " + ((qH + qS + qV)) + " error: " + error.getMinimum() + " <= " + error.getMean() + " ( " + sqrt(error.getVariance()) + " ) <= " + error.getMaximum(); synchronized (lines) { lines.put(key, line); System.out.println(line); } } }); } } } shutdownAndWait(MultiThreadTools.getExecutor(), Long.MAX_VALUE); System.out.println(); for (final String line : lines.values()) { System.out.println(line); } } @Test public final void test2() { Tools.debugPrint(quantizers); final SimpleImageView imageView = new SimpleImageView(); final JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, quantizers.size() - 1, 1)); imageView.getPainters().add(new Painter<SimpleImageView>() { @Override public final void paint(final Graphics2D g, final SimpleImageView component, final int width, final int height) { final ColorQuantizer quantizer = quantizers.get(((Number) spinner.getValue()).intValue()); final BufferedImage image = imageView.getImage(); final BufferedImage buffer = imageView.getBufferImage(); final int w = buffer.getWidth(); final int h = buffer.getHeight(); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { int north = 0; int west = 0; int east = 0; int south = 0; if (0 < y) { north = quantizer.quantize(image.getRGB(x, y - 1)); } if (0 < x) { west = quantizer.quantize(image.getRGB(x - 1, y)); } if (x + 1 < w) { east = quantizer.quantize(image.getRGB(x + 1, y)); } if (y + 1 < h) { south = quantizer.quantize(image.getRGB(x, y + 1)); } final int center = quantizer.quantize(image.getRGB(x, y)); // if (min(north, west, east, south) < center) { if (north != center || west != center || east != center || south != center) { buffer.setRGB(x, y, Color.YELLOW.getRGB()); } } } } /** * {@value}. */ private static final long serialVersionUID = 8306989611117085093L; }); final JPanel panel = new JPanel(new BorderLayout()); SwingTools.setCheckAWT(false); spinner.addChangeListener(new ChangeListener() { @Override public final void stateChanged(final ChangeEvent event) { imageView.refreshBuffer(); } }); panel.add(horizontalBox(spinner), BorderLayout.NORTH); panel.add(imageView, BorderLayout.CENTER); show(panel, this.getClass().getSimpleName(), true); } private static final List<Object[]> table = new ArrayList<Object[]>(); static final List<ColorQuantizer> quantizers = new ArrayList<ColorQuantizer>(); static { table.add(array("qRGB", 0, 0, 0, 0.0)); table.add(array("qHSV", 0, 0, 0, 0.6955260904279362)); table.add(array("qRGB", 1, 0, 0, 0.32641454294213)); table.add(array("qRGB", 0, 0, 1, 0.6240309742241252)); table.add(array("qRGB", 0, 1, 0, 0.7514458393503941)); table.add(array("qHSV", 0, 0, 1, 0.8751917410004951)); table.add(array("qHSV", 0, 1, 0, 1.126961289651885)); table.add(array("qHSV", 1, 0, 0, 1.7813204349626734)); table.add(array("qRGB", 1, 0, 1, 0.8583117538819247)); table.add(array("qRGB", 1, 1, 0, 0.8692188281204635)); table.add(array("qRGB", 2, 0, 0, 0.9808307435374101)); table.add(array("qRGB", 0, 1, 1, 1.0380778379038296)); table.add(array("qHSV", 0, 0, 2, 1.1659382941554577)); table.add(array("qHSV", 0, 1, 1, 1.2559919477363735)); table.add(array("qHSV", 1, 0, 1, 1.8951245566432926)); table.add(array("qRGB", 0, 0, 2, 1.8980446031157745)); table.add(array("qHSV", 1, 1, 0, 2.092400382244634)); table.add(array("qHSV", 0, 2, 0, 2.115374741291907)); table.add(array("qRGB", 0, 2, 0, 2.265005588909907)); table.add(array("qHSV", 2, 0, 0, 4.528551120210534)); table.add(array("qRGB", 1, 1, 1, 1.1180287803753424)); table.add(array("qRGB", 2, 1, 0, 1.2748883526552783)); table.add(array("qRGB", 2, 0, 1, 1.4067111100652796)); table.add(array("qHSV", 0, 1, 2, 1.5203314800623147)); table.add(array("qHSV", 0, 0, 3, 1.809747264609731)); table.add(array("qRGB", 0, 1, 2, 1.9618195348396559)); table.add(array("qRGB", 1, 0, 2, 2.064893103362241)); table.add(array("qHSV", 1, 0, 2, 2.1016815466827374)); table.add(array("qHSV", 1, 1, 1, 2.177229033053775)); table.add(array("qHSV", 0, 2, 1, 2.2173938408647693)); table.add(array("qRGB", 1, 2, 0, 2.2504013406529717)); table.add(array("qRGB", 0, 2, 1, 2.2932977370369603)); table.add(array("qRGB", 3, 0, 0, 2.2959598157696686)); table.add(array("qHSV", 1, 2, 0, 2.8907950047008057)); table.add(array("qHSV", 0, 3, 0, 4.270360710208371)); table.add(array("qRGB", 0, 0, 3, 4.52553090293637)); table.add(array("qHSV", 2, 0, 1, 4.592369919131593)); table.add(array("qHSV", 2, 1, 0, 4.722213766837409)); table.add(array("qRGB", 0, 3, 0, 5.333067162914784)); table.add(array("qHSV", 3, 0, 0, 10.133061431545565)); table.add(array("qRGB", 2, 1, 1, 1.4880175209433724)); table.add(array("qRGB", 1, 1, 2, 2.0282165668025764)); table.add(array("qHSV", 0, 1, 3, 2.152929318600153)); table.add(array("qRGB", 1, 2, 1, 2.2559129235446513)); table.add(array("qRGB", 3, 1, 0, 2.370351273948446)); table.add(array("qHSV", 1, 1, 2, 2.3731733681910288)); table.add(array("qRGB", 2, 2, 0, 2.389170595189107)); table.add(array("qHSV", 0, 2, 2, 2.450676449335271)); table.add(array("qRGB", 2, 0, 2, 2.4962070471616475)); table.add(array("qHSV", 1, 0, 3, 2.614980863199656)); table.add(array("qRGB", 3, 0, 1, 2.61968019557456)); table.add(array("qRGB", 0, 2, 2, 2.775659263227969)); table.add(array("qHSV", 1, 2, 1, 2.9645149300940132)); table.add(array("qHSV", 0, 0, 4, 3.308055191838597)); table.add(array("qRGB", 0, 1, 3, 4.3145002832409265)); table.add(array("qHSV", 0, 3, 1, 4.356094355535418)); table.add(array("qRGB", 1, 0, 3, 4.6480678384750584)); table.add(array("qHSV", 2, 0, 2, 4.720369162242616)); table.add(array("qHSV", 2, 1, 1, 4.771642243384687)); table.add(array("qHSV", 1, 3, 0, 4.820816066888919)); table.add(array("qRGB", 4, 0, 0, 4.951001286754124)); table.add(array("qRGB", 0, 3, 1, 5.179776824191323)); table.add(array("qRGB", 1, 3, 0, 5.245476477957572)); table.add(array("qHSV", 2, 2, 0, 5.275040700873244)); table.add(array("qHSV", 0, 4, 0, 8.608606861303441)); table.add(array("qRGB", 0, 0, 4, 10.005984804008115)); table.add(array("qHSV", 3, 0, 1, 10.16591826453798)); table.add(array("qHSV", 3, 1, 0, 10.246741129698233)); table.add(array("qRGB", 0, 4, 0, 11.621132862924227)); table.add(array("qHSV", 4, 0, 0, 21.441441059860917)); table.add(array("qRGB", 2, 1, 2, 2.345664153459157)); table.add(array("qRGB", 2, 2, 1, 2.3803760800798126)); table.add(array("qRGB", 3, 1, 1, 2.548324173801728)); table.add(array("qRGB", 1, 2, 2, 2.7386225128738215)); table.add(array("qHSV", 1, 1, 3, 2.890959844279944)); table.add(array("qHSV", 0, 2, 3, 3.039789316612684)); table.add(array("qRGB", 3, 2, 0, 3.0876627555063707)); table.add(array("qHSV", 1, 2, 2, 3.149855857626206)); table.add(array("qRGB", 3, 0, 2, 3.5456082043397177)); table.add(array("qHSV", 0, 1, 4, 3.6408406868479344)); table.add(array("qHSV", 1, 0, 4, 3.9301965018206424)); table.add(array("qRGB", 1, 1, 3, 4.377510140614242)); table.add(array("qRGB", 0, 2, 3, 4.55417176057843)); table.add(array("qHSV", 0, 3, 2, 4.558363544642229)); table.add(array("qRGB", 4, 1, 0, 4.866263779024119)); table.add(array("qHSV", 1, 3, 1, 4.890021661874276)); table.add(array("qHSV", 2, 1, 2, 4.896690972204208)); table.add(array("qRGB", 2, 0, 3, 4.975510162691538)); table.add(array("qHSV", 2, 0, 3, 5.073700328823798)); table.add(array("qRGB", 1, 3, 1, 5.076416388035941)); table.add(array("qRGB", 2, 3, 0, 5.186407432321236)); table.add(array("qRGB", 4, 0, 1, 5.18922966136709)); table.add(array("qRGB", 0, 3, 2, 5.253668905846729)); table.add(array("qHSV", 2, 2, 1, 5.321301853278064)); table.add(array("qHSV", 2, 3, 0, 6.78099035432321)); table.add(array("qHSV", 0, 0, 5, 6.8001379002246205)); table.add(array("qHSV", 0, 4, 1, 8.6804212735382)); table.add(array("qHSV", 1, 4, 0, 8.96150522653321)); table.add(array("qRGB", 0, 1, 4, 9.621269654573805)); table.add(array("qRGB", 1, 0, 4, 10.10082618502018)); table.add(array("qHSV", 3, 0, 2, 10.239604490826345)); table.add(array("qHSV", 3, 1, 1, 10.273738901017087)); table.add(array("qRGB", 5, 0, 0, 10.357214019008278)); table.add(array("qHSV", 3, 2, 0, 10.595095232353103)); table.add(array("qRGB", 0, 4, 1, 11.345079146799256)); table.add(array("qRGB", 1, 4, 0, 11.499694035514397)); table.add(array("qHSV", 0, 5, 0, 16.979860091230222)); table.add(array("qHSV", 4, 0, 1, 21.447935998355156)); table.add(array("qHSV", 4, 1, 0, 21.462964882808116)); table.add(array("qRGB", 0, 0, 5, 21.56144319342579)); table.add(array("qRGB", 0, 5, 0, 24.732918303318232)); table.add(array("qHSV", 5, 0, 0, 43.77691374160295)); table.add(array("qRGB", 2, 2, 2, 2.852922516764376)); table.add(array("qRGB", 3, 2, 1, 3.0828291421052723)); table.add(array("qRGB", 3, 1, 2, 3.3041165241821764)); table.add(array("qHSV", 1, 2, 3, 3.6541400074569506)); table.add(array("qHSV", 1, 1, 4, 4.215862457035969)); table.add(array("qHSV", 0, 2, 4, 4.460470627495945)); table.add(array("qRGB", 1, 2, 3, 4.539080994752359)); table.add(array("qRGB", 2, 1, 3, 4.6363242231465)); table.add(array("qRGB", 2, 3, 1, 5.004329263328033)); table.add(array("qRGB", 4, 1, 1, 5.011027074098335)); table.add(array("qHSV", 0, 3, 3, 5.062496531035296)); table.add(array("qHSV", 1, 3, 2, 5.063458476675465)); table.add(array("qRGB", 1, 3, 2, 5.147515511354933)); table.add(array("qRGB", 4, 2, 0, 5.167587135912787)); table.add(array("qHSV", 2, 1, 3, 5.260392593892533)); table.add(array("qRGB", 3, 3, 0, 5.432007270000069)); table.add(array("qHSV", 2, 2, 2, 5.446669044137193)); table.add(array("qRGB", 3, 0, 3, 5.825331577595821)); table.add(array("qRGB", 4, 0, 2, 5.931000598479003)); table.add(array("qHSV", 2, 0, 4, 6.082311495314012)); table.add(array("qRGB", 0, 3, 3, 6.254886430030773)); table.add(array("qHSV", 2, 3, 1, 6.830073389040216)); table.add(array("qHSV", 0, 1, 5, 7.122838491638112)); table.add(array("qHSV", 1, 0, 5, 7.218793962972602)); table.add(array("qHSV", 0, 4, 2, 8.848843990753025)); table.add(array("qHSV", 1, 4, 1, 9.024514418743152)); table.add(array("qRGB", 0, 2, 4, 9.322599398655775)); table.add(array("qRGB", 1, 1, 4, 9.682368743150985)); table.add(array("qRGB", 5, 1, 0, 10.172020644792356)); table.add(array("qHSV", 3, 1, 2, 10.346634555923645)); table.add(array("qRGB", 2, 0, 4, 10.349131860405612)); table.add(array("qHSV", 2, 4, 0, 10.378143392591879)); table.add(array("qHSV", 3, 0, 3, 10.46174533248007)); table.add(array("qRGB", 5, 0, 1, 10.533497144893856)); table.add(array("qHSV", 3, 2, 1, 10.62143108459401)); table.add(array("qRGB", 0, 4, 2, 11.08684873356561)); table.add(array("qRGB", 1, 4, 1, 11.212816854561149)); table.add(array("qRGB", 2, 4, 0, 11.32752806549405)); table.add(array("qHSV", 3, 3, 0, 11.635117350399002)); table.add(array("qHSV", 0, 0, 6, 15.668032586962413)); table.add(array("qHSV", 0, 5, 1, 17.04482075137555)); table.add(array("qHSV", 1, 5, 0, 17.187108424535914)); table.add(array("qRGB", 0, 1, 5, 21.08512918203094)); table.add(array("qHSV", 4, 1, 1, 21.469367174690095)); table.add(array("qHSV", 4, 0, 2, 21.473931969823585)); table.add(array("qRGB", 6, 0, 0, 21.532049376223195)); table.add(array("qHSV", 4, 2, 0, 21.59445165396762)); table.add(array("qRGB", 1, 0, 5, 21.638632549717023)); table.add(array("qRGB", 0, 5, 1, 24.37721172994415)); table.add(array("qRGB", 1, 5, 0, 24.60734851909329)); table.add(array("qHSV", 0, 6, 0, 32.73574351446413)); table.add(array("qHSV", 5, 1, 0, 43.751204156283656)); table.add(array("qHSV", 5, 0, 1, 43.76416717883281)); table.add(array("qRGB", 0, 0, 6, 46.13239365025457)); table.add(array("qRGB", 0, 6, 0, 52.70802175522528)); table.add(array("qHSV", 6, 0, 0, 83.81508873246744)); table.add(array("qRGB", 3, 2, 2, 3.527362691503131)); table.add(array("qRGB", 2, 2, 3, 4.653057616366176)); table.add(array("qHSV", 1, 2, 4, 4.950383818907108)); table.add(array("qRGB", 2, 3, 2, 5.068365988414407)); table.add(array("qRGB", 4, 2, 1, 5.178832026758057)); table.add(array("qRGB", 3, 3, 1, 5.253549057030269)); table.add(array("qRGB", 3, 1, 3, 5.433232494141032)); table.add(array("qHSV", 1, 3, 3, 5.516563492291423)); table.add(array("qRGB", 4, 1, 2, 5.635111396603524)); table.add(array("qHSV", 2, 2, 3, 5.816758192084616)); table.add(array("qRGB", 1, 3, 3, 6.166399561123543)); table.add(array("qHSV", 2, 1, 4, 6.289879138851597)); table.add(array("qHSV", 0, 3, 4, 6.345495263856095)); table.add(array("qRGB", 4, 3, 0, 6.783776610747946)); table.add(array("qHSV", 2, 3, 2, 6.958393497024418)); table.add(array("qHSV", 1, 1, 5, 7.514279390344463)); table.add(array("qHSV", 0, 2, 5, 7.850523125363171)); table.add(array("qRGB", 4, 0, 3, 7.909364447767676)); table.add(array("qHSV", 2, 0, 5, 8.893228803404542)); table.add(array("qHSV", 1, 4, 2, 9.177754256712644)); table.add(array("qHSV", 0, 4, 3, 9.270509807166043)); table.add(array("qRGB", 1, 2, 4, 9.33366729062409)); table.add(array("qRGB", 2, 1, 4, 9.890118915323102)); table.add(array("qRGB", 0, 3, 4, 9.929929778266683)); table.add(array("qRGB", 5, 2, 0, 10.138080062468157)); table.add(array("qRGB", 5, 1, 1, 10.29114858366)); table.add(array("qHSV", 2, 4, 1, 10.428669001108311)); table.add(array("qHSV", 3, 1, 3, 10.577000076352872)); table.add(array("qHSV", 3, 2, 2, 10.69795588995799)); table.add(array("qRGB", 1, 4, 2, 10.949224161393213)); table.add(array("qRGB", 3, 0, 4, 11.00602110019438)); table.add(array("qRGB", 2, 4, 1, 11.02877492642026)); table.add(array("qRGB", 5, 0, 2, 11.102983007881091)); table.add(array("qHSV", 3, 0, 4, 11.158505372879214)); table.add(array("qRGB", 3, 4, 0, 11.227760965671465)); table.add(array("qRGB", 0, 4, 3, 11.309405765689151)); table.add(array("qHSV", 3, 3, 1, 11.664870489106614)); table.add(array("qHSV", 3, 4, 0, 14.395372498170593)); table.add(array("qHSV", 1, 0, 6, 15.901936420764862)); table.add(array("qHSV", 0, 1, 6, 15.991471787000199)); table.add(array("qHSV", 0, 5, 2, 17.176936549609696)); table.add(array("qHSV", 1, 5, 1, 17.247695065696494)); table.add(array("qHSV", 2, 5, 0, 18.082575505826718)); table.add(array("qRGB", 0, 2, 5, 20.405035493287702)); table.add(array("qRGB", 1, 1, 5, 21.14347635507767)); table.add(array("qRGB", 6, 1, 0, 21.293096999751032)); table.add(array("qHSV", 4, 1, 2, 21.496241062179358)); table.add(array("qHSV", 4, 0, 3, 21.580207287110984)); table.add(array("qHSV", 4, 2, 1, 21.602329841806487)); table.add(array("qRGB", 6, 0, 1, 21.67462497600947)); table.add(array("qRGB", 2, 0, 5, 21.830723642418008)); table.add(array("qHSV", 4, 3, 0, 22.133768474410587)); table.add(array("qRGB", 0, 5, 2, 23.86359478382961)); table.add(array("qRGB", 1, 5, 1, 24.244431205525952)); table.add(array("qRGB", 2, 5, 0, 24.39691267076655)); table.add(array("qHSV", 0, 6, 1, 32.80316538441022)); table.add(array("qHSV", 1, 6, 0, 32.842233350233535)); table.add(array("qHSV", 5, 2, 0, 43.74076975658067)); table.add(array("qHSV", 5, 1, 1, 43.742010947423)); table.add(array("qHSV", 5, 0, 2, 43.7562916943628)); table.add(array("qHSV", 0, 0, 7, 44.92160259247629)); table.add(array("qRGB", 7, 0, 0, 45.176087377745176)); table.add(array("qRGB", 0, 1, 6, 45.62356017773505)); table.add(array("qRGB", 1, 0, 6, 46.196411417482125)); table.add(array("qRGB", 0, 6, 1, 52.301160399275815)); table.add(array("qRGB", 1, 6, 0, 52.61193218654751)); table.add(array("qHSV", 0, 7, 0, 61.80730533010471)); table.add(array("qHSV", 6, 1, 0, 83.63587197808127)); table.add(array("qHSV", 6, 0, 1, 83.76551042010584)); table.add(array("qRGB", 0, 0, 7, 98.58169362835481)); table.add(array("qRGB", 0, 7, 0, 113.80279045303948)); table.add(array("qHSV", 7, 0, 0, 156.02265105719644)); table.add(array("qRGB", 3, 2, 3, 5.253916642742753)); table.add(array("qRGB", 3, 3, 2, 5.313590650823462)); table.add(array("qRGB", 4, 2, 2, 5.575899042570833)); table.add(array("qRGB", 2, 3, 3, 6.102583333976196)); table.add(array("qRGB", 4, 3, 1, 6.637861657250586)); table.add(array("qHSV", 1, 3, 4, 6.720167065205978)); table.add(array("qHSV", 2, 2, 4, 6.853957182198859)); table.add(array("qHSV", 2, 3, 3, 7.313034588867101)); table.add(array("qRGB", 4, 1, 3, 7.4952032204868)); table.add(array("qHSV", 1, 2, 5, 8.19464651896803)); table.add(array("qHSV", 2, 1, 5, 9.128864210622176)); table.add(array("qRGB", 2, 2, 4, 9.45054024064088)); table.add(array("qHSV", 0, 3, 5, 9.50272830656282)); table.add(array("qHSV", 1, 4, 3, 9.57225682172096)); table.add(array("qRGB", 1, 3, 4, 9.878300576656232)); table.add(array("qRGB", 5, 2, 1, 10.168317697289462)); table.add(array("qHSV", 0, 4, 4, 10.325282646966802)); table.add(array("qRGB", 3, 1, 4, 10.513446996566712)); table.add(array("qHSV", 2, 4, 2, 10.553962637282169)); table.add(array("qRGB", 2, 4, 2, 10.754583231629907)); table.add(array("qRGB", 5, 1, 2, 10.78334660852396)); table.add(array("qRGB", 3, 4, 1, 10.923400572688765)); table.add(array("qHSV", 3, 2, 3, 10.940245342238159)); table.add(array("qRGB", 5, 3, 0, 10.948747935514554)); table.add(array("qRGB", 1, 4, 3, 11.177647318386894)); table.add(array("qHSV", 3, 1, 4, 11.292017176980279)); table.add(array("qHSV", 3, 3, 2, 11.749442609095881)); table.add(array("qRGB", 4, 4, 0, 11.754305664224468)); table.add(array("qRGB", 4, 0, 4, 12.707821916090875)); table.add(array("qRGB", 5, 0, 3, 12.721094610289231)); table.add(array("qHSV", 3, 0, 5, 13.321914762530062)); table.add(array("qRGB", 0, 4, 4, 13.462907410406403)); table.add(array("qHSV", 3, 4, 1, 14.428941545444602)); table.add(array("qHSV", 1, 1, 6, 16.213530849741776)); table.add(array("qHSV", 0, 2, 6, 16.595732776692728)); table.add(array("qHSV", 2, 0, 6, 16.990247872051476)); table.add(array("qHSV", 1, 5, 2, 17.37262548192689)); table.add(array("qHSV", 0, 5, 3, 17.50097970500494)); table.add(array("qHSV", 2, 5, 1, 18.135576856216254)); table.add(array("qRGB", 0, 3, 5, 19.920991125299423)); table.add(array("qRGB", 1, 2, 5, 20.43422559355158)); table.add(array("qHSV", 3, 5, 0, 20.953539337715004)); table.add(array("qRGB", 6, 2, 0, 21.039614618747564)); table.add(array("qRGB", 2, 1, 5, 21.311634080572432)); table.add(array("qRGB", 6, 1, 1, 21.402040306383505)); table.add(array("qHSV", 4, 1, 3, 21.607639767259705)); table.add(array("qHSV", 4, 2, 2, 21.635546199656854)); table.add(array("qHSV", 4, 0, 4, 21.980255130529887)); table.add(array("qRGB", 6, 0, 2, 22.113679071750695)); table.add(array("qHSV", 4, 3, 1, 22.144316336683882)); table.add(array("qRGB", 3, 0, 5, 22.328417765460777)); table.add(array("qRGB", 0, 5, 3, 23.401054294240303)); table.add(array("qRGB", 1, 5, 2, 23.725014384855967)); table.add(array("qHSV", 4, 4, 0, 23.862897375364486)); table.add(array("qRGB", 2, 5, 1, 24.024643580435026)); table.add(array("qRGB", 3, 5, 0, 24.123412933265822)); table.add(array("qHSV", 0, 6, 2, 32.89667758007501)); table.add(array("qHSV", 1, 6, 1, 32.90781890164448)); table.add(array("qHSV", 2, 6, 0, 33.32236993216267)); table.add(array("qHSV", 5, 2, 1, 43.73216585611982)); table.add(array("qHSV", 5, 1, 2, 43.73285247357186)); table.add(array("qHSV", 5, 0, 3, 43.773924275773595)); table.add(array("qHSV", 5, 3, 0, 43.87212842657174)); table.add(array("qRGB", 0, 2, 6, 44.73957191563254)); table.add(array("qRGB", 7, 1, 0, 44.91994210785489)); table.add(array("qHSV", 1, 0, 7, 45.012075852208746)); table.add(array("qRGB", 7, 0, 1, 45.321510970753366)); table.add(array("qHSV", 0, 1, 7, 45.3975990469012)); table.add(array("qRGB", 1, 1, 6, 45.67720247527094)); table.add(array("qRGB", 2, 0, 6, 46.3468570278201)); table.add(array("qRGB", 0, 6, 2, 51.60143636551707)); table.add(array("qRGB", 1, 6, 1, 52.200354051560105)); table.add(array("qRGB", 2, 6, 0, 52.442942082617805)); table.add(array("qHSV", 1, 7, 0, 61.84624110147413)); table.add(array("qHSV", 0, 7, 1, 61.98559575821476)); table.add(array("qHSV", 6, 2, 0, 83.31021735981916)); table.add(array("qHSV", 6, 1, 1, 83.59644325622138)); table.add(array("qHSV", 6, 0, 2, 83.70003079189063)); table.add(array("qRGB", 0, 1, 7, 98.09175375687065)); table.add(array("qRGB", 1, 0, 7, 98.63222463427425)); table.add(array("qRGB", 0, 7, 1, 113.35848060108387)); table.add(array("qRGB", 1, 7, 0, 113.79100745068551)); table.add(array("qHSV", 7, 1, 0, 155.76875083166007)); table.add(array("qHSV", 7, 0, 1, 155.9388815899415)); table.add(array("qRGB", 3, 3, 3, 6.340866483189372)); table.add(array("qRGB", 4, 3, 2, 6.709653006265603)); table.add(array("qRGB", 4, 2, 3, 7.129963963236756)); table.add(array("qHSV", 2, 3, 4, 8.320823808478119)); table.add(array("qHSV", 2, 2, 5, 9.692344955617365)); table.add(array("qHSV", 1, 3, 5, 9.779610923631795)); table.add(array("qRGB", 2, 3, 4, 9.857522392338288)); table.add(array("qRGB", 3, 2, 4, 9.950763892439424)); table.add(array("qRGB", 5, 2, 2, 10.507557830242826)); table.add(array("qHSV", 1, 4, 4, 10.584318858953525)); table.add(array("qRGB", 3, 4, 2, 10.638399022749269)); table.add(array("qRGB", 5, 3, 1, 10.85649017076917)); table.add(array("qHSV", 2, 4, 3, 10.886674213271974)); table.add(array("qRGB", 2, 4, 3, 10.986209294528791)); table.add(array("qRGB", 4, 4, 1, 11.46652530930045)); table.add(array("qHSV", 3, 2, 4, 11.673906598335554)); table.add(array("qHSV", 3, 3, 3, 11.994609999866599)); table.add(array("qRGB", 4, 1, 4, 12.20218340832902)); table.add(array("qRGB", 5, 1, 3, 12.312975745853725)); table.add(array("qHSV", 0, 4, 5, 13.149357181796196)); table.add(array("qRGB", 1, 4, 4, 13.35518595291978)); table.add(array("qHSV", 3, 1, 5, 13.487052808959266)); table.add(array("qHSV", 3, 4, 2, 14.518904965426142)); table.add(array("qRGB", 5, 4, 0, 14.556491367623703)); table.add(array("qHSV", 1, 2, 6, 16.799177364455836)); table.add(array("qRGB", 5, 0, 4, 16.923951577513773)); table.add(array("qHSV", 2, 1, 6, 17.266229614644402)); table.add(array("qHSV", 1, 5, 3, 17.683854172496947)); table.add(array("qHSV", 0, 3, 6, 18.027459361336454)); table.add(array("qHSV", 2, 5, 2, 18.246274714415243)); table.add(array("qHSV", 0, 5, 4, 18.349046936514938)); table.add(array("qRGB", 1, 3, 5, 19.907650136450783)); table.add(array("qHSV", 3, 0, 6, 20.31449096221656)); table.add(array("qRGB", 2, 2, 5, 20.549489748044554)); table.add(array("qHSV", 3, 5, 1, 20.994690069622262)); table.add(array("qRGB", 6, 2, 1, 21.093244874228947)); table.add(array("qRGB", 6, 3, 0, 21.19254912139334)); table.add(array("qRGB", 0, 4, 5, 21.246600560116846)); table.add(array("qHSV", 4, 2, 3, 21.75875632193585)); table.add(array("qRGB", 3, 1, 5, 21.78644893297665)); table.add(array("qRGB", 6, 1, 2, 21.79250600681563)); table.add(array("qHSV", 4, 1, 4, 22.02443261543551)); table.add(array("qHSV", 4, 3, 2, 22.186876867524546)); table.add(array("qRGB", 1, 5, 3, 23.260883706223176)); table.add(array("qRGB", 6, 0, 3, 23.386703338692957)); table.add(array("qHSV", 4, 0, 5, 23.427093643965375)); table.add(array("qRGB", 2, 5, 2, 23.493924375351092)); table.add(array("qRGB", 4, 0, 5, 23.642266327011406)); table.add(array("qRGB", 3, 5, 1, 23.741972884777905)); table.add(array("qHSV", 4, 4, 1, 23.879017394229695)); table.add(array("qRGB", 0, 5, 4, 23.943637893089022)); table.add(array("qRGB", 4, 5, 0, 24.063262335361493)); table.add(array("qHSV", 4, 5, 0, 28.615899360492723)); table.add(array("qHSV", 1, 6, 2, 32.99827811369083)); table.add(array("qHSV", 0, 6, 3, 33.1286253581266)); table.add(array("qHSV", 2, 6, 1, 33.3839421900219)); table.add(array("qHSV", 3, 6, 0, 35.009802069537756)); table.add(array("qRGB", 0, 3, 6, 43.460896182311956)); table.add(array("qHSV", 5, 2, 2, 43.73202855891318)); table.add(array("qHSV", 5, 1, 3, 43.7535637956447)); table.add(array("qHSV", 5, 3, 1, 43.86640260615535)); table.add(array("qHSV", 5, 0, 4, 43.92909101484812)); table.add(array("qHSV", 5, 4, 0, 44.55571124845371)); table.add(array("qRGB", 7, 2, 0, 44.55833251204558)); table.add(array("qRGB", 1, 2, 6, 44.776897391602574)); table.add(array("qRGB", 7, 1, 1, 45.04637978612198)); table.add(array("qHSV", 1, 1, 7, 45.482246920674726)); table.add(array("qHSV", 2, 0, 7, 45.51365112224777)); table.add(array("qRGB", 7, 0, 2, 45.70512868979869)); table.add(array("qRGB", 2, 1, 6, 45.813611637632384)); table.add(array("qHSV", 0, 2, 7, 45.89436224260916)); table.add(array("qRGB", 3, 0, 6, 46.720243380629405)); table.add(array("qRGB", 0, 6, 3, 50.56913459912434)); table.add(array("qRGB", 1, 6, 2, 51.495507349823036)); table.add(array("qRGB", 2, 6, 1, 52.024598427168634)); table.add(array("qRGB", 3, 6, 0, 52.19106917882459)); table.add(array("qHSV", 0, 7, 2, 62.01143653140464)); table.add(array("qHSV", 1, 7, 1, 62.023247577307245)); table.add(array("qHSV", 2, 7, 0, 62.02579926667945)); table.add(array("qHSV", 6, 3, 0, 82.76435853485751)); table.add(array("qHSV", 6, 2, 1, 83.27401911307462)); table.add(array("qHSV", 6, 1, 2, 83.53199900326042)); table.add(array("qHSV", 6, 0, 3, 83.58759338540732)); table.add(array("qRGB", 0, 2, 7, 97.16239083873536)); table.add(array("qRGB", 1, 1, 7, 98.13677798324206)); table.add(array("qRGB", 2, 0, 7, 98.74559245319055)); table.add(array("qRGB", 0, 7, 2, 112.52326535326874)); table.add(array("qRGB", 1, 7, 1, 113.34355286396212)); table.add(array("qRGB", 2, 7, 0, 113.78207678079858)); table.add(array("qHSV", 7, 2, 0, 155.26271089738088)); table.add(array("qHSV", 7, 1, 1, 155.69921989766797)); table.add(array("qHSV", 7, 0, 2, 155.81640234578813)); table.add(array("qRGB", 4, 3, 3, 7.688442546008208)); table.add(array("qRGB", 3, 3, 4, 10.095141022638085)); table.add(array("qRGB", 3, 4, 3, 10.864897114402869)); table.add(array("qRGB", 5, 3, 2, 10.951615663240458)); table.add(array("qHSV", 2, 3, 5, 11.070154272260991)); table.add(array("qRGB", 4, 4, 2, 11.191632862199885)); table.add(array("qRGB", 4, 2, 4, 11.52598396241005)); table.add(array("qHSV", 2, 4, 4, 11.782463229695244)); table.add(array("qRGB", 5, 2, 3, 11.819634155213707)); table.add(array("qHSV", 3, 3, 4, 12.734447695338403)); table.add(array("qRGB", 2, 4, 4, 13.198005564072307)); table.add(array("qHSV", 1, 4, 5, 13.349700851194054)); table.add(array("qHSV", 3, 2, 5, 13.89682265182176)); table.add(array("qRGB", 5, 4, 1, 14.322611845014073)); table.add(array("qHSV", 3, 4, 3, 14.765915006914788)); table.add(array("qRGB", 5, 1, 4, 16.431998213672987)); table.add(array("qHSV", 2, 2, 6, 17.794743002263)); table.add(array("qHSV", 1, 3, 6, 18.19966125131184)); table.add(array("qHSV", 1, 5, 4, 18.509866614595577)); table.add(array("qHSV", 2, 5, 3, 18.52725317113241)); table.add(array("qRGB", 2, 3, 5, 19.933533714232336)); table.add(array("qHSV", 3, 1, 6, 20.533316034673383)); table.add(array("qHSV", 0, 5, 5, 20.662238654155118)); table.add(array("qRGB", 3, 2, 5, 20.95052655636009)); table.add(array("qHSV", 3, 5, 2, 21.083018105884644)); table.add(array("qHSV", 0, 4, 6, 21.110219649964062)); table.add(array("qRGB", 6, 3, 1, 21.161371921806357)); table.add(array("qRGB", 1, 4, 5, 21.18027776782719)); table.add(array("qRGB", 6, 2, 2, 21.38663005776269)); table.add(array("qHSV", 4, 2, 4, 22.196381149547953)); table.add(array("qHSV", 4, 3, 3, 22.32389197746879)); table.add(array("qRGB", 6, 1, 3, 23.0029729164763)); table.add(array("qRGB", 2, 5, 3, 23.022684799085344)); table.add(array("qRGB", 4, 1, 5, 23.086305798726343)); table.add(array("qRGB", 3, 5, 2, 23.194828446980296)); table.add(array("qRGB", 6, 4, 0, 23.288580709898017)); table.add(array("qHSV", 4, 1, 5, 23.501867553611202)); table.add(array("qRGB", 4, 5, 1, 23.68088624329254)); table.add(array("qRGB", 1, 5, 4, 23.811048702797404)); table.add(array("qHSV", 4, 4, 2, 23.930560280338014)); table.add(array("qRGB", 5, 5, 0, 25.402895483675284)); table.add(array("qRGB", 6, 0, 4, 26.864638036544115)); table.add(array("qRGB", 5, 0, 5, 27.081377578441117)); table.add(array("qRGB", 0, 5, 5, 28.54063915420294)); table.add(array("qHSV", 4, 5, 1, 28.641730651838913)); table.add(array("qHSV", 4, 0, 6, 28.854331775352687)); table.add(array("qHSV", 1, 6, 3, 33.22460294147693)); table.add(array("qHSV", 2, 6, 2, 33.46921764781381)); table.add(array("qHSV", 0, 6, 4, 33.702579763034635)); table.add(array("qHSV", 3, 6, 1, 35.06389034413055)); table.add(array("qHSV", 4, 6, 0, 40.137731481784115)); table.add(array("qRGB", 0, 4, 6, 42.525753512691516)); table.add(array("qRGB", 1, 3, 6, 43.47286860289719)); table.add(array("qHSV", 5, 2, 3, 43.75703255179147)); table.add(array("qHSV", 5, 3, 2, 43.86973635535911)); table.add(array("qHSV", 5, 1, 4, 43.9193503618413)); table.add(array("qRGB", 7, 3, 0, 44.309567106007385)); table.add(array("qHSV", 5, 4, 1, 44.55595283640167)); table.add(array("qRGB", 7, 2, 1, 44.652283598962846)); table.add(array("qHSV", 5, 0, 5, 44.70057087412785)); table.add(array("qRGB", 2, 2, 6, 44.88342483911719)); table.add(array("qRGB", 7, 1, 2, 45.40073048149536)); table.add(array("qHSV", 2, 1, 7, 45.957826377522295)); table.add(array("qHSV", 1, 2, 7, 45.97438884520198)); table.add(array("qRGB", 3, 1, 6, 46.171046220192245)); table.add(array("qRGB", 7, 0, 3, 46.74410786531797)); table.add(array("qHSV", 0, 3, 7, 46.94047509487422)); table.add(array("qHSV", 5, 5, 0, 46.98065616162865)); table.add(array("qHSV", 3, 0, 7, 47.31084724651443)); table.add(array("qRGB", 4, 0, 6, 47.69348627992129)); table.add(array("qRGB", 0, 6, 4, 49.58886169746684)); table.add(array("qRGB", 1, 6, 3, 50.45815908106512)); table.add(array("qRGB", 2, 6, 2, 51.30975863355777)); table.add(array("qRGB", 3, 6, 1, 51.76398032287591)); table.add(array("qRGB", 4, 6, 0, 51.98456631116456)); table.add(array("qHSV", 1, 7, 2, 62.0476400938254)); table.add(array("qHSV", 0, 7, 3, 62.08910702114573)); table.add(array("qHSV", 2, 7, 1, 62.19923587229031)); table.add(array("qHSV", 3, 7, 0, 62.71396179748241)); table.add(array("qHSV", 6, 4, 0, 82.01003193662558)); table.add(array("qHSV", 6, 3, 1, 82.73396479269887)); table.add(array("qHSV", 6, 2, 2, 83.2140183000991)); table.add(array("qHSV", 6, 1, 3, 83.4241302922701)); table.add(array("qHSV", 6, 0, 4, 83.43394427208376)); table.add(array("qRGB", 0, 3, 7, 95.5024295094967)); table.add(array("qRGB", 1, 2, 7, 97.19867684302076)); table.add(array("qRGB", 2, 1, 7, 98.2421679833705)); table.add(array("qRGB", 3, 0, 7, 99.01508349160125)); table.add(array("qRGB", 0, 7, 3, 111.04199670996694)); table.add(array("qRGB", 1, 7, 2, 112.50410102149714)); table.add(array("qRGB", 2, 7, 1, 113.32974893931791)); table.add(array("qRGB", 3, 7, 0, 113.8193934779908)); table.add(array("qHSV", 7, 3, 0, 154.25179097350306)); table.add(array("qHSV", 7, 2, 1, 155.19759088118153)); table.add(array("qHSV", 7, 0, 3, 155.5731316317515)); table.add(array("qHSV", 7, 1, 2, 155.57639462650135)); table.add(array("qRGB", 4, 3, 4, 11.300385291883343)); table.add(array("qRGB", 4, 4, 3, 11.413287765007333)); table.add(array("qRGB", 5, 3, 3, 11.835590580277925)); table.add(array("qRGB", 3, 4, 4, 13.105170302239044)); table.add(array("qRGB", 5, 4, 2, 14.102725593278263)); table.add(array("qHSV", 2, 4, 5, 14.342172542032769)); table.add(array("qHSV", 3, 3, 5, 14.946261925820883)); table.add(array("qHSV", 3, 4, 4, 15.46518525367638)); table.add(array("qRGB", 5, 2, 4, 15.6937208294619)); table.add(array("qHSV", 2, 3, 6, 19.079145485722293)); table.add(array("qHSV", 2, 5, 4, 19.290435137212366)); table.add(array("qRGB", 3, 3, 5, 20.16864052990391)); table.add(array("qHSV", 1, 5, 5, 20.791984112466153)); table.add(array("qHSV", 3, 2, 6, 20.96089276744169)); table.add(array("qRGB", 2, 4, 5, 21.08938909810169)); table.add(array("qHSV", 1, 4, 6, 21.243770468351563)); table.add(array("qRGB", 6, 3, 2, 21.288110810768334)); table.add(array("qHSV", 3, 5, 3, 21.312307819388156)); table.add(array("qRGB", 4, 2, 5, 22.178404640544578)); table.add(array("qRGB", 6, 2, 3, 22.45089367092038)); table.add(array("qRGB", 3, 5, 3, 22.70561761512323)); table.add(array("qHSV", 4, 3, 4, 22.783387113717136)); table.add(array("qRGB", 4, 5, 2, 23.12311052644533)); table.add(array("qRGB", 6, 4, 1, 23.13965229796283)); table.add(array("qRGB", 2, 5, 4, 23.581710343484367)); table.add(array("qHSV", 4, 2, 5, 23.712242409809047)); table.add(array("qHSV", 4, 4, 3, 24.08132103092352)); table.add(array("qRGB", 5, 5, 1, 25.045878832584336)); table.add(array("qRGB", 6, 1, 4, 26.409192843237044)); table.add(array("qRGB", 5, 1, 5, 26.529047924439634)); table.add(array("qHSV", 0, 5, 6, 27.63065202910769)); table.add(array("qRGB", 1, 5, 5, 28.431190265339374)); table.add(array("qHSV", 4, 5, 2, 28.6992567436543)); table.add(array("qHSV", 4, 1, 6, 28.982662338530055)); table.add(array("qRGB", 6, 5, 0, 31.698950614604737)); table.add(array("qHSV", 2, 6, 3, 33.68213058054486)); table.add(array("qHSV", 1, 6, 4, 33.78916238071692)); table.add(array("qHSV", 3, 6, 2, 35.137672403014726)); table.add(array("qHSV", 0, 6, 5, 35.38285901058025)); table.add(array("qRGB", 6, 0, 5, 35.798088797723715)); table.add(array("qHSV", 4, 6, 1, 40.17942007592115)); table.add(array("qRGB", 1, 4, 6, 42.499987755993985)); table.add(array("qRGB", 2, 3, 6, 43.52716203099239)); table.add(array("qHSV", 5, 3, 3, 43.906895816832254)); table.add(array("qHSV", 5, 2, 4, 43.935627297756106)); table.add(array("qRGB", 7, 3, 1, 44.349719267806194)); table.add(array("qHSV", 5, 4, 2, 44.56590570376091)); table.add(array("qHSV", 5, 1, 5, 44.70977685547477)); table.add(array("qRGB", 7, 2, 2, 44.94814474219706)); table.add(array("qRGB", 0, 5, 6, 45.098262849514896)); table.add(array("qRGB", 3, 2, 6, 45.19680023082748)); table.add(array("qRGB", 7, 4, 0, 45.24050897140638)); table.add(array("qRGB", 7, 1, 3, 46.397617749593216)); table.add(array("qHSV", 2, 2, 7, 46.42892542288154)); table.add(array("qHSV", 5, 5, 1, 46.98756966975928)); table.add(array("qHSV", 1, 3, 7, 47.01472807679523)); table.add(array("qRGB", 4, 1, 6, 47.12882395174464)); table.add(array("qHSV", 3, 1, 7, 47.69825145609503)); table.add(array("qHSV", 5, 0, 6, 48.30892314902963)); table.add(array("qHSV", 0, 4, 7, 49.13722160795946)); table.add(array("qRGB", 1, 6, 4, 49.47449215886267)); table.add(array("qRGB", 7, 0, 4, 49.56445112803157)); table.add(array("qRGB", 2, 6, 3, 50.26044398911863)); table.add(array("qRGB", 5, 0, 6, 50.31137045369451)); table.add(array("qRGB", 0, 6, 5, 50.568076039984064)); table.add(array("qRGB", 3, 6, 2, 51.032435381608266)); table.add(array("qRGB", 4, 6, 1, 51.548862763853826)); table.add(array("qRGB", 5, 6, 0, 52.552285583869214)); table.add(array("qHSV", 4, 0, 7, 52.8129511776001)); table.add(array("qHSV", 5, 6, 0, 54.13995592279949)); table.add(array("qHSV", 1, 7, 3, 62.123968137878016)); table.add(array("qHSV", 2, 7, 2, 62.221939996879684)); table.add(array("qHSV", 0, 7, 4, 62.31871516714029)); table.add(array("qHSV", 3, 7, 1, 62.87714478304283)); table.add(array("qHSV", 4, 7, 0, 65.07473789181662)); table.add(array("qHSV", 6, 5, 0, 81.4408397301875)); table.add(array("qHSV", 6, 4, 1, 81.98400997685754)); table.add(array("qHSV", 6, 3, 2, 82.67858543292775)); table.add(array("qHSV", 6, 2, 3, 83.11171679692882)); table.add(array("qHSV", 6, 1, 4, 83.27724778864844)); table.add(array("qHSV", 6, 0, 5, 83.41585847422323)); table.add(array("qRGB", 0, 4, 7, 92.95641588673492)); table.add(array("qRGB", 1, 3, 7, 95.52435465074312)); table.add(array("qRGB", 2, 2, 7, 97.28774943440655)); table.add(array("qRGB", 3, 1, 7, 98.50079273033025)); table.add(array("qRGB", 4, 0, 7, 99.70123907935444)); table.add(array("qRGB", 0, 7, 4, 108.70942567609441)); table.add(array("qRGB", 1, 7, 3, 111.01652069235655)); table.add(array("qRGB", 2, 7, 2, 112.48198468055303)); table.add(array("qRGB", 3, 7, 1, 113.35964114383401)); table.add(array("qRGB", 4, 7, 0, 114.08455335800612)); table.add(array("qHSV", 7, 4, 0, 152.26767295140053)); table.add(array("qHSV", 7, 3, 1, 154.18872685701697)); table.add(array("qHSV", 7, 2, 2, 155.07487080911943)); table.add(array("qHSV", 7, 0, 4, 155.09750765195514)); table.add(array("qHSV", 7, 1, 3, 155.33090566219985)); table.add(array("qRGB", 4, 4, 4, 13.635492369684071)); table.add(array("qRGB", 5, 4, 3, 14.339651153267729)); table.add(array("qRGB", 5, 3, 4, 15.105009711688462)); table.add(array("qHSV", 3, 4, 5, 17.613021066244166)); table.add(array("qRGB", 3, 4, 5, 21.06899986017425)); table.add(array("qRGB", 4, 3, 5, 21.163357953208294)); table.add(array("qHSV", 2, 5, 5, 21.459022937564324)); table.add(array("qHSV", 3, 5, 4, 21.953548327784002)); table.add(array("qHSV", 2, 4, 6, 21.953794391617667)); table.add(array("qHSV", 3, 3, 6, 22.015191420102827)); table.add(array("qRGB", 6, 3, 3, 22.057818941088346)); table.add(array("qRGB", 4, 5, 3, 22.611345132538872)); table.add(array("qRGB", 6, 4, 2, 23.01722632330868)); table.add(array("qRGB", 3, 5, 4, 23.26583544312819)); table.add(array("qHSV", 4, 3, 5, 24.334741391416884)); table.add(array("qRGB", 5, 5, 2, 24.513149100441726)); table.add(array("qHSV", 4, 4, 4, 24.54206993455648)); table.add(array("qRGB", 5, 2, 5, 25.583221839197073)); table.add(array("qRGB", 6, 2, 4, 25.672319962794653)); table.add(array("qHSV", 1, 5, 6, 27.723584486538304)); table.add(array("qRGB", 2, 5, 5, 28.24066686271142)); table.add(array("qHSV", 4, 5, 3, 28.858335408264463)); table.add(array("qHSV", 4, 2, 6, 29.245750524384043)); table.add(array("qRGB", 6, 5, 1, 31.41318872510949)); table.add(array("qHSV", 2, 6, 4, 34.22040714241764)); table.add(array("qRGB", 6, 1, 5, 35.27323810665261)); table.add(array("qHSV", 3, 6, 3, 35.32334270831286)); table.add(array("qHSV", 1, 6, 5, 35.45535791369207)); table.add(array("qHSV", 4, 6, 2, 40.23476684721952)); table.add(array("qHSV", 0, 6, 6, 40.75582097662498)); table.add(array("qRGB", 2, 4, 6, 42.47457324801316)); table.add(array("qRGB", 3, 3, 6, 43.743810942045144)); table.add(array("qHSV", 5, 3, 4, 44.10013792348927)); table.add(array("qRGB", 7, 3, 2, 44.5399115043061)); table.add(array("qHSV", 5, 4, 3, 44.61240036097907)); table.add(array("qHSV", 5, 2, 5, 44.75074825138069)); table.add(array("qRGB", 1, 5, 6, 45.02628653090765)); table.add(array("qRGB", 7, 4, 1, 45.19548827530423)); table.add(array("qRGB", 7, 2, 3, 45.85128412568048)); table.add(array("qRGB", 4, 2, 6, 46.104706678281275)); table.add(array("qHSV", 5, 5, 2, 47.00216719845255)); table.add(array("qHSV", 2, 3, 7, 47.434430403929944)); table.add(array("qHSV", 3, 2, 7, 48.113864245075504)); table.add(array("qHSV", 5, 1, 6, 48.35414705431072)); table.add(array("qRGB", 7, 1, 4, 49.16085177151545)); table.add(array("qHSV", 1, 4, 7, 49.200744348108195)); table.add(array("qRGB", 2, 6, 4, 49.26688031984588)); table.add(array("qRGB", 5, 1, 6, 49.736293373767865)); table.add(array("qRGB", 3, 6, 3, 49.95796953990217)); table.add(array("qRGB", 1, 6, 5, 50.455210971385455)); table.add(array("qRGB", 4, 6, 2, 50.79571129684579)); table.add(array("qRGB", 7, 5, 0, 51.06486999908676)); table.add(array("qRGB", 5, 6, 1, 52.116365829212135)); table.add(array("qHSV", 4, 1, 7, 53.10463249735915)); table.add(array("qHSV", 0, 5, 7, 53.78015545839082)); table.add(array("qHSV", 5, 6, 1, 54.159747593732384)); table.add(array("qRGB", 6, 6, 0, 56.65347676334426)); table.add(array("qRGB", 7, 0, 5, 57.05088417395533)); table.add(array("qRGB", 6, 0, 6, 57.387399296171345)); table.add(array("qRGB", 0, 6, 6, 59.83107919981765)); table.add(array("qHSV", 2, 7, 3, 62.295216190063)); table.add(array("qHSV", 1, 7, 4, 62.35076210418596)); table.add(array("qHSV", 3, 7, 2, 62.89298902640965)); table.add(array("qHSV", 0, 7, 5, 63.112997894458175)); table.add(array("qHSV", 4, 7, 1, 65.22501380465377)); table.add(array("qHSV", 5, 0, 7, 67.35803299473069)); table.add(array("qHSV", 5, 7, 0, 72.5529842358517)); table.add(array("qHSV", 6, 5, 1, 81.41961158006531)); table.add(array("qHSV", 6, 4, 2, 81.93752641201267)); table.add(array("qHSV", 6, 3, 3, 82.59066390393983)); table.add(array("qHSV", 6, 6, 0, 82.68591896276428)); table.add(array("qHSV", 6, 2, 4, 82.97878839973524)); table.add(array("qHSV", 6, 1, 5, 83.27251053606977)); table.add(array("qHSV", 6, 0, 6, 84.8281185595414)); table.add(array("qRGB", 0, 5, 7, 90.63206534182964)); table.add(array("qRGB", 1, 4, 7, 92.95451501587132)); table.add(array("qRGB", 2, 3, 7, 95.58421617689663)); table.add(array("qRGB", 3, 2, 7, 97.52004006544156)); table.add(array("qRGB", 4, 1, 7, 99.1720497524499)); table.add(array("qRGB", 5, 0, 7, 101.56712234851004)); table.add(array("qRGB", 0, 7, 5, 105.99908554244503)); table.add(array("qRGB", 1, 7, 4, 108.67401118003978)); table.add(array("qRGB", 2, 7, 3, 110.9808282044467)); table.add(array("qRGB", 3, 7, 2, 112.49699129233186)); table.add(array("qRGB", 4, 7, 1, 113.61400042659453)); table.add(array("qRGB", 5, 7, 0, 115.24588503540951)); table.add(array("qHSV", 7, 5, 0, 148.4866525222472)); table.add(array("qHSV", 7, 4, 1, 152.20702004897882)); table.add(array("qHSV", 7, 3, 2, 154.06650658928004)); table.add(array("qHSV", 7, 0, 5, 154.22820386668872)); table.add(array("qHSV", 7, 2, 3, 154.8302458267778)); table.add(array("qHSV", 7, 1, 4, 154.85496721006646)); table.add(array("qRGB", 5, 4, 4, 16.452327018216238)); table.add(array("qRGB", 4, 4, 5, 21.576691496711987)); table.add(array("qRGB", 4, 5, 4, 23.151504858179628)); table.add(array("qRGB", 6, 4, 3, 23.29238320073896)); table.add(array("qHSV", 3, 5, 5, 23.855937179825872)); table.add(array("qRGB", 5, 5, 3, 24.010895759787857)); table.add(array("qRGB", 5, 3, 5, 24.345372151173603)); table.add(array("qHSV", 3, 4, 6, 24.483664759259558)); table.add(array("qRGB", 6, 3, 4, 24.84121606806918)); table.add(array("qHSV", 4, 4, 5, 26.121861030618177)); table.add(array("qRGB", 3, 5, 5, 27.975681776202745)); table.add(array("qHSV", 2, 5, 6, 28.22285519819319)); table.add(array("qHSV", 4, 5, 4, 29.326939071136668)); table.add(array("qHSV", 4, 3, 6, 29.941881324210264)); table.add(array("qRGB", 6, 5, 2, 30.97884589500067)); table.add(array("qRGB", 6, 2, 5, 34.346490652277055)); table.add(array("qHSV", 3, 6, 4, 35.80586465661823)); table.add(array("qHSV", 2, 6, 5, 35.831301740769405)); table.add(array("qHSV", 4, 6, 3, 40.37922211577201)); table.add(array("qHSV", 1, 6, 6, 40.81321272585543)); table.add(array("qRGB", 3, 4, 6, 42.525019656531576)); table.add(array("qRGB", 4, 3, 6, 44.51060848937224)); table.add(array("qHSV", 5, 4, 4, 44.81908847853915)); table.add(array("qRGB", 2, 5, 6, 44.902350932273606)); table.add(array("qHSV", 5, 3, 5, 44.954338178029914)); table.add(array("qRGB", 7, 4, 2, 45.209654110379404)); table.add(array("qRGB", 7, 3, 3, 45.25226318990082)); table.add(array("qHSV", 5, 5, 3, 47.067622456344374)); table.add(array("qHSV", 5, 2, 6, 48.43284417039696)); table.add(array("qRGB", 7, 2, 4, 48.48082801682692)); table.add(array("qRGB", 5, 2, 6, 48.67260126855884)); table.add(array("qRGB", 3, 6, 4, 48.93754909302421)); table.add(array("qHSV", 3, 3, 7, 49.02681684469041)); table.add(array("qHSV", 2, 4, 7, 49.56029119812139)); table.add(array("qRGB", 4, 6, 3, 49.67978878365301)); table.add(array("qRGB", 2, 6, 5, 50.2467901034742)); table.add(array("qRGB", 7, 5, 1, 50.89632581346104)); table.add(array("qRGB", 5, 6, 2, 51.349978241781436)); table.add(array("qHSV", 4, 2, 7, 53.40986543747504)); table.add(array("qHSV", 1, 5, 7, 53.832715409307504)); table.add(array("qHSV", 5, 6, 2, 54.17452931216259)); table.add(array("qRGB", 6, 6, 1, 56.24604742164139)); table.add(array("qRGB", 7, 1, 5, 56.576264479355444)); table.add(array("qRGB", 6, 1, 6, 56.814909591996674)); table.add(array("qRGB", 1, 6, 6, 59.72839648703533)); table.add(array("qHSV", 2, 7, 4, 62.51176621430742)); table.add(array("qHSV", 3, 7, 3, 62.96174689694058)); table.add(array("qHSV", 1, 7, 5, 63.14358049455555)); table.add(array("qHSV", 0, 6, 7, 63.465936946588535)); table.add(array("qHSV", 4, 7, 2, 65.23155454626794)); table.add(array("qHSV", 0, 7, 6, 66.36369767041624)); table.add(array("qHSV", 5, 1, 7, 67.49295507997199)); table.add(array("qRGB", 7, 6, 0, 72.32032989402973)); table.add(array("qHSV", 5, 7, 1, 72.6504972897907)); table.add(array("qRGB", 7, 0, 6, 76.11764832983383)); table.add(array("qHSV", 6, 5, 2, 81.38302809602966)); table.add(array("qHSV", 6, 4, 3, 81.86192037913459)); table.add(array("qHSV", 6, 3, 4, 82.47611149206824)); table.add(array("qHSV", 6, 6, 1, 82.67225695734406)); table.add(array("qHSV", 6, 2, 5, 83.00311321520888)); table.add(array("qHSV", 6, 1, 6, 84.70426204696611)); table.add(array("qHSV", 6, 7, 0, 90.32392117480995)); table.add(array("qRGB", 1, 5, 7, 90.59284659085877)); table.add(array("qRGB", 2, 4, 7, 92.96533250892645)); table.add(array("qRGB", 0, 6, 7, 94.23816148736213)); table.add(array("qRGB", 3, 3, 7, 95.76126172444539)); table.add(array("qHSV", 6, 0, 7, 96.77929387101405)); table.add(array("qRGB", 4, 2, 7, 98.15417423649613)); table.add(array("qRGB", 5, 1, 7, 101.01783865813661)); table.add(array("qRGB", 1, 7, 5, 105.9478151508339)); table.add(array("qRGB", 0, 7, 6, 106.2108223866618)); table.add(array("qRGB", 6, 0, 7, 106.88184436821574)); table.add(array("qRGB", 2, 7, 4, 108.61661495825513)); table.add(array("qRGB", 3, 7, 3, 110.9684674837774)); table.add(array("qRGB", 4, 7, 2, 112.72714747788302)); table.add(array("qRGB", 5, 7, 1, 114.76166638761399)); table.add(array("qRGB", 6, 7, 0, 119.55559324301412)); table.add(array("qHSV", 7, 6, 0, 141.64444052630054)); table.add(array("qHSV", 7, 5, 1, 148.4251492515059)); table.add(array("qHSV", 7, 4, 2, 152.0899192589707)); table.add(array("qHSV", 7, 0, 6, 153.00264635518943)); table.add(array("qHSV", 7, 3, 3, 153.83156011108096)); table.add(array("qHSV", 7, 1, 5, 153.98670951089673)); table.add(array("qHSV", 7, 2, 4, 154.36075363667933)); table.add(array("qRGB", 5, 4, 5, 24.071811935682792)); table.add(array("qRGB", 5, 5, 4, 24.519064488681344)); table.add(array("qRGB", 6, 4, 4, 25.197573119249448)); table.add(array("qRGB", 4, 5, 5, 27.88679667800512)); table.add(array("qHSV", 3, 5, 6, 30.125155623703037)); table.add(array("qRGB", 6, 5, 3, 30.57235916304928)); table.add(array("qHSV", 4, 5, 5, 30.80517648683717)); table.add(array("qHSV", 4, 4, 6, 31.699842078117207)); table.add(array("qRGB", 6, 3, 5, 32.99240577170763)); table.add(array("qHSV", 3, 6, 5, 37.271137072988665)); table.add(array("qHSV", 4, 6, 4, 40.75410626562716)); table.add(array("qHSV", 2, 6, 6, 41.107826122575894)); table.add(array("qRGB", 4, 4, 6, 42.983901487038864)); table.add(array("qRGB", 3, 5, 6, 44.73696740093618)); table.add(array("qRGB", 7, 4, 3, 45.575935181665926)); table.add(array("qHSV", 5, 4, 5, 45.73706665815075)); table.add(array("qRGB", 5, 3, 6, 46.93140066470426)); table.add(array("qHSV", 5, 5, 4, 47.31457765402981)); table.add(array("qRGB", 7, 3, 4, 47.57904720235397)); table.add(array("qRGB", 4, 6, 4, 48.59959709126427)); table.add(array("qHSV", 5, 3, 6, 48.70967709693754)); table.add(array("qRGB", 3, 6, 5, 49.90415093680079)); table.add(array("qRGB", 5, 6, 3, 50.19162493994238)); table.add(array("qRGB", 7, 5, 2, 50.64474510643907)); table.add(array("qHSV", 3, 4, 7, 50.97542315094293)); table.add(array("qHSV", 2, 5, 7, 54.10765028158217)); table.add(array("qHSV", 4, 3, 7, 54.119314448377594)); table.add(array("qHSV", 5, 6, 3, 54.240483810016585)); table.add(array("qRGB", 6, 6, 2, 55.51362394958891)); table.add(array("qRGB", 7, 2, 5, 55.72738548239443)); table.add(array("qRGB", 6, 2, 6, 55.74309141050442)); table.add(array("qRGB", 2, 6, 6, 59.53589671516055)); table.add(array("qHSV", 3, 7, 4, 63.157139098842364)); table.add(array("qHSV", 2, 7, 5, 63.28833907338459)); table.add(array("qHSV", 1, 6, 7, 63.50457128922028)); table.add(array("qHSV", 4, 7, 3, 65.29115018166584)); table.add(array("qHSV", 1, 7, 6, 66.39194736243954)); table.add(array("qHSV", 5, 2, 7, 67.61437384583752)); table.add(array("qRGB", 7, 6, 1, 71.99761869066867)); table.add(array("qHSV", 5, 7, 2, 72.62668860926118)); table.add(array("qRGB", 7, 1, 6, 75.56911192801118)); table.add(array("qHSV", 6, 5, 3, 81.33113264372975)); table.add(array("qHSV", 6, 4, 4, 81.78259962534494)); table.add(array("qHSV", 6, 3, 5, 82.54804950625551)); table.add(array("qHSV", 6, 6, 2, 82.64653580433713)); table.add(array("qHSV", 0, 7, 7, 82.98009795855553)); table.add(array("qHSV", 6, 2, 6, 84.49086288438515)); table.add(array("qHSV", 6, 7, 1, 90.3539481096517)); table.add(array("qRGB", 2, 5, 7, 90.52673250324939)); table.add(array("qRGB", 3, 4, 7, 93.04225296123272)); table.add(array("qRGB", 1, 6, 7, 94.15118331333835)); table.add(array("qRGB", 4, 3, 7, 96.30652031331188)); table.add(array("qHSV", 6, 1, 7, 96.66311028783815)); table.add(array("qRGB", 5, 2, 7, 99.9525311596843)); table.add(array("qRGB", 2, 7, 5, 105.85586615081006)); table.add(array("qRGB", 1, 7, 6, 106.13379451983877)); table.add(array("qRGB", 6, 1, 7, 106.30844111204077)); table.add(array("qRGB", 3, 7, 4, 108.55788479941238)); table.add(array("qRGB", 4, 7, 3, 111.1485560507927)); table.add(array("qRGB", 5, 7, 2, 113.84057827200076)); table.add(array("qRGB", 6, 7, 1, 119.0611377850553)); table.add(array("qRGB", 0, 7, 7, 121.61122326525965)); table.add(array("qRGB", 7, 0, 7, 122.22938888033444)); table.add(array("qHSV", 7, 7, 0, 130.39792724870412)); table.add(array("qRGB", 7, 7, 0, 133.93140854155877)); table.add(array("qHSV", 7, 6, 1, 141.57678709847553)); table.add(array("qHSV", 7, 5, 2, 148.3157517124646)); table.add(array("qHSV", 7, 4, 3, 151.85812919582494)); table.add(array("qHSV", 7, 1, 6, 152.75698339389902)); table.add(array("qHSV", 7, 3, 4, 153.36844533228413)); table.add(array("qHSV", 7, 2, 5, 153.50798443432024)); table.add(array("qHSV", 7, 0, 7, 154.42826003900322)); table.add(array("qRGB", 5, 5, 5, 29.16035761415699)); table.add(array("qRGB", 6, 5, 4, 31.076711561370868)); table.add(array("qRGB", 6, 4, 5, 32.067109009705945)); table.add(array("qHSV", 4, 5, 6, 36.083595936249296)); table.add(array("qHSV", 4, 6, 5, 41.964190211364595)); table.add(array("qHSV", 3, 6, 6, 42.29930100726572)); table.add(array("qRGB", 4, 5, 6, 44.727040748103285)); table.add(array("qRGB", 5, 4, 6, 44.968623478214795)); table.add(array("qRGB", 7, 4, 4, 47.278835169696876)); table.add(array("qHSV", 5, 5, 5, 48.217951512529)); table.add(array("qRGB", 5, 6, 4, 49.01993078520322)); table.add(array("qRGB", 4, 6, 5, 49.51021618599725)); table.add(array("qHSV", 5, 4, 6, 49.547304173959944)); table.add(array("qRGB", 7, 5, 3, 50.45381424547857)); table.add(array("qRGB", 6, 3, 6, 53.916454183431405)); table.add(array("qRGB", 6, 6, 3, 54.37236041600201)); table.add(array("qRGB", 7, 3, 5, 54.41183262515647)); table.add(array("qHSV", 5, 6, 4, 54.45350302726497)); table.add(array("qHSV", 3, 5, 7, 55.244904587366044)); table.add(array("qHSV", 4, 4, 7, 55.64610512093585)); table.add(array("qRGB", 3, 6, 6, 59.209737174708884)); table.add(array("qHSV", 2, 6, 7, 63.6751728390727)); table.add(array("qHSV", 3, 7, 5, 63.88987040305082)); table.add(array("qHSV", 4, 7, 4, 65.43916877735103)); table.add(array("qHSV", 2, 7, 6, 66.50671872962488)); table.add(array("qHSV", 5, 3, 7, 67.9918424704696)); table.add(array("qRGB", 7, 6, 2, 71.40548869524387)); table.add(array("qHSV", 5, 7, 3, 72.65552942805532)); table.add(array("qRGB", 7, 2, 6, 74.539198911411)); table.add(array("qHSV", 6, 5, 4, 81.28294078298102)); table.add(array("qHSV", 6, 4, 5, 81.90954861718659)); table.add(array("qHSV", 6, 6, 3, 82.60810662817708)); table.add(array("qHSV", 1, 7, 7, 83.01474461331952)); table.add(array("qHSV", 6, 3, 6, 84.12128748832396)); table.add(array("qHSV", 6, 7, 2, 90.30191795302524)); table.add(array("qRGB", 3, 5, 7, 90.44343880501384)); table.add(array("qRGB", 4, 4, 7, 93.39992710387831)); table.add(array("qRGB", 2, 6, 7, 93.98542612049617)); table.add(array("qHSV", 6, 2, 7, 96.531808332587)); table.add(array("qRGB", 5, 3, 7, 97.98623863661277)); table.add(array("qRGB", 6, 2, 7, 105.18986761294468)); table.add(array("qRGB", 3, 7, 5, 105.72241391531153)); table.add(array("qRGB", 2, 7, 6, 105.9861999725296)); table.add(array("qRGB", 4, 7, 4, 108.64397196690527)); table.add(array("qRGB", 5, 7, 3, 112.1823057298339)); table.add(array("qRGB", 6, 7, 2, 118.1068250687499)); table.add(array("qRGB", 1, 7, 7, 121.49344484417644)); table.add(array("qRGB", 7, 1, 7, 121.63454416537526)); table.add(array("qHSV", 7, 7, 1, 130.27815752171145)); table.add(array("qRGB", 7, 7, 1, 133.45192537538827)); table.add(array("qHSV", 7, 6, 2, 141.4759110619432)); table.add(array("qHSV", 7, 5, 3, 148.09813296839445)); table.add(array("qHSV", 7, 4, 4, 151.41705304769513)); table.add(array("qHSV", 7, 2, 6, 152.30122027302545)); table.add(array("qHSV", 7, 3, 5, 152.53646872834864)); table.add(array("qHSV", 7, 1, 7, 154.0768707620358)); table.add(array("qRGB", 6, 5, 5, 35.400137435029016)); table.add(array("qRGB", 5, 5, 6, 45.8233771590495)); table.add(array("qHSV", 4, 6, 6, 46.40245579086771)); table.add(array("qRGB", 5, 6, 5, 49.782515993143186)); table.add(array("qRGB", 7, 5, 4, 51.041409413692236)); table.add(array("qRGB", 6, 4, 6, 51.54216148099061)); table.add(array("qHSV", 5, 5, 6, 51.940531483076605)); table.add(array("qRGB", 7, 4, 5, 53.137756535881834)); table.add(array("qRGB", 6, 6, 4, 53.14396294559098)); table.add(array("qHSV", 5, 6, 5, 55.228715876666485)); table.add(array("qRGB", 4, 6, 6, 58.79585620026274)); table.add(array("qHSV", 4, 5, 7, 59.203972102699964)); table.add(array("qHSV", 3, 6, 7, 64.44018880057266)); table.add(array("qHSV", 4, 7, 5, 66.07804953551427)); table.add(array("qHSV", 3, 7, 6, 67.02198891573136)); table.add(array("qHSV", 5, 4, 7, 68.82377873985625)); table.add(array("qRGB", 7, 6, 3, 70.45097650807729)); table.add(array("qHSV", 5, 7, 4, 72.72379724972508)); table.add(array("qRGB", 7, 3, 6, 72.7496334594355)); table.add(array("qHSV", 6, 5, 5, 81.45839848659669)); table.add(array("qHSV", 6, 6, 4, 82.57432023168315)); table.add(array("qHSV", 2, 7, 7, 83.09689252187526)); table.add(array("qHSV", 6, 4, 6, 83.60367097668954)); table.add(array("qHSV", 6, 7, 3, 90.24254703335666)); table.add(array("qRGB", 4, 5, 7, 90.47157622213018)); table.add(array("qRGB", 3, 6, 7, 93.69327279840577)); table.add(array("qRGB", 5, 4, 7, 94.78848826316275)); table.add(array("qHSV", 6, 3, 7, 96.34074236006498)); table.add(array("qRGB", 6, 3, 7, 103.09409877318586)); table.add(array("qRGB", 4, 7, 5, 105.64751778991774)); table.add(array("qRGB", 3, 7, 6, 105.73289902046317)); table.add(array("qRGB", 5, 7, 4, 109.50856313511423)); table.add(array("qRGB", 6, 7, 3, 116.35263661572063)); table.add(array("qRGB", 7, 2, 7, 120.47091510995996)); table.add(array("qRGB", 2, 7, 7, 121.25909325650642)); table.add(array("qHSV", 7, 7, 2, 130.189412070187)); table.add(array("qRGB", 7, 7, 2, 132.51054904265393)); table.add(array("qHSV", 7, 6, 3, 141.2750518038755)); table.add(array("qHSV", 7, 5, 4, 147.68593530869273)); table.add(array("qHSV", 7, 4, 5, 150.63169725118138)); table.add(array("qHSV", 7, 3, 6, 151.39341368885468)); table.add(array("qHSV", 7, 2, 7, 153.7261405181208)); table.add(array("qRGB", 6, 5, 6, 51.16588678216485)); table.add(array("qRGB", 6, 6, 5, 53.65792546587413)); table.add(array("qRGB", 7, 5, 5, 54.86314628308258)); table.add(array("qHSV", 5, 6, 6, 58.5541643813996)); table.add(array("qRGB", 5, 6, 6, 58.88231069937044)); table.add(array("qHSV", 4, 6, 7, 67.29232843725568)); table.add(array("qHSV", 4, 7, 6, 68.98398547192)); table.add(array("qRGB", 7, 6, 4, 69.35909510351173)); table.add(array("qRGB", 7, 4, 6, 70.20612999951547)); table.add(array("qHSV", 5, 5, 7, 70.9522982391356)); table.add(array("qHSV", 5, 7, 5, 73.15155535858463)); table.add(array("qHSV", 6, 6, 5, 82.78120697495775)); table.add(array("qHSV", 6, 5, 6, 83.28443665149418)); table.add(array("qHSV", 3, 7, 7, 83.45320638949539)); table.add(array("qHSV", 6, 7, 4, 90.172638730084)); table.add(array("qRGB", 5, 5, 7, 91.24646560431594)); table.add(array("qRGB", 4, 6, 7, 93.2732797260707)); table.add(array("qHSV", 6, 4, 7, 96.09723782084295)); table.add(array("qRGB", 6, 4, 7, 99.54726990857749)); table.add(array("qRGB", 4, 7, 6, 105.39366045848752)); table.add(array("qRGB", 5, 7, 5, 106.18657681840735)); table.add(array("qRGB", 6, 7, 4, 113.434492479518)); table.add(array("qRGB", 7, 3, 7, 118.27215956840143)); table.add(array("qRGB", 3, 7, 7, 120.8193361510788)); table.add(array("qHSV", 7, 7, 3, 130.01513071046674)); table.add(array("qRGB", 7, 7, 3, 130.72885419357505)); table.add(array("qHSV", 7, 6, 4, 140.9012578035098)); table.add(array("qHSV", 7, 5, 5, 146.95565866567614)); table.add(array("qHSV", 7, 4, 6, 149.59413316853056)); table.add(array("qHSV", 7, 3, 7, 153.00106824868672)); table.add(array("qRGB", 6, 6, 6, 62.13342555613777)); table.add(array("qRGB", 7, 5, 6, 68.76461465385874)); table.add(array("qRGB", 7, 6, 5, 69.64939924785347)); table.add(array("qHSV", 5, 7, 6, 75.49661507284307)); table.add(array("qHSV", 5, 6, 7, 76.37570829713836)); table.add(array("qHSV", 6, 6, 6, 84.60279131029957)); table.add(array("qHSV", 4, 7, 7, 84.87036525141197)); table.add(array("qHSV", 6, 7, 5, 90.25307437485817)); table.add(array("qRGB", 5, 6, 7, 93.09297348388682)); table.add(array("qRGB", 6, 5, 7, 95.09765215140195)); table.add(array("qHSV", 6, 5, 7, 96.05791272541956)); table.add(array("qRGB", 5, 7, 6, 105.35293816829977)); table.add(array("qRGB", 6, 7, 5, 109.55213823708338)); table.add(array("qRGB", 7, 4, 7, 114.43406884005788)); table.add(array("qRGB", 4, 7, 7, 120.06463886098378)); table.add(array("qRGB", 7, 7, 4, 127.61800680953633)); table.add(array("qHSV", 7, 7, 4, 129.69888897137199)); table.add(array("qHSV", 7, 6, 5, 140.26914343765014)); table.add(array("qHSV", 7, 5, 6, 146.10742102345884)); table.add(array("qHSV", 7, 4, 7, 151.5596422793711)); table.add(array("qRGB", 7, 6, 6, 76.82768387008761)); table.add(array("qHSV", 5, 7, 7, 89.91254983728324)); table.add(array("qHSV", 6, 7, 6, 91.6934546217888)); table.add(array("qRGB", 6, 6, 7, 95.13524389792414)); table.add(array("qHSV", 6, 6, 7, 97.3143392560389)); table.add(array("qRGB", 6, 7, 6, 107.54519533200947)); table.add(array("qRGB", 7, 5, 7, 109.04192747205848)); table.add(array("qRGB", 5, 7, 7, 119.07036843710114)); table.add(array("qRGB", 7, 7, 5, 123.04945636715787)); table.add(array("qHSV", 7, 7, 5, 129.19031913082105)); table.add(array("qHSV", 7, 6, 6, 139.72383239068853)); table.add(array("qHSV", 7, 5, 7, 148.72214401655344)); table.add(array("qHSV", 6, 7, 7, 103.02970911320593)); table.add(array("qRGB", 7, 6, 7, 106.51658523554815)); table.add(array("qRGB", 6, 7, 7, 119.09765442358427)); table.add(array("qRGB", 7, 7, 6, 119.10670119292193)); table.add(array("qHSV", 7, 7, 6, 129.00909805599323)); table.add(array("qHSV", 7, 6, 7, 143.4394848729931)); table.add(array("qRGB", 7, 7, 7, 126.23189633081189)); table.add(array("qHSV", 7, 7, 7, 134.22861938161395)); for (final Object[] row : table) { final String type = (String) row[0]; /*if ("qHSV".equals(type))*/ { final int qA = ((Number) row[1]).intValue(); final int qB = ((Number) row[2]).intValue(); final int qC = ((Number) row[3]).intValue(); final int q = qA + qB + qC; if (quantizers.size() <= q) { quantizers.add(ColorQuantizer.newQuantizer(type, qA, qB, qC)); } } } } /** * @author codistmonk (creation 2014-04-10) */ public static abstract class ColorQuantizer implements Serializable { private final int qA; private final int qB; private final int qC; protected ColorQuantizer(final int qA, final int qB, final int qC) { this.qA = qA; this.qB = qB; this.qC = qC; } public final int quantize(final int rgb) { final int[] abc = new int[3]; this.rgbToABC(rgb, abc); final int a = (abc[0] & 0xFF) >> this.qA; final int b = (abc[1] & 0xFF) >> this.qB; final int c = (abc[2] & 0xFF) >> this.qC; return (a << (16 - this.qB - this.qC)) | (b << (8 - this.qC)) | (c << 0); } public final String getType() { if (this instanceof RGBQuantizer) { return "qRGB"; } if (this instanceof HSVQuantizer) { return "qHSV"; } return this.getClass().getSimpleName(); } @Override public final String toString() { return this.getType() + this.qA + "" + this.qB + "" + this.qC; } protected abstract void rgbToABC(final int rgb, final int[] abc); /** * {@value}. */ private static final long serialVersionUID = -5601399591176973099L; public static final ColorQuantizer newQuantizer(final String type, final int qA, final int qB, final int qC) { if ("qRGB".equals(type)) { return new RGBQuantizer(qA, qC, qB); } if ("qHSV".equals(type)) { return new HSVQuantizer(qA, qC, qB); } throw new IllegalArgumentException(); } } /** * @author codistmonk (creation 2014-04-10) */ public static final class RGBQuantizer extends ColorQuantizer { public RGBQuantizer(final int qR, final int qG, final int qB) { super(qR, qG, qB); } @Override protected final void rgbToABC(final int rgb, final int[] abc) { rgbToRGB(rgb, abc); } /** * {@value}. */ private static final long serialVersionUID = -739890245396913487L; } /** * @author codistmonk (creation 2014-04-10) */ public static final class HSVQuantizer extends ColorQuantizer { public HSVQuantizer(final int qH, final int qS, final int qV) { super(qH, qS, qV); } @Override protected final void rgbToABC(final int rgb, final int[] abc) { rgbToRGB(rgb, abc); rgbToHSV(abc, abc); } /** * {@value}. */ private static final long serialVersionUID = -739890245396913487L; } public static final void shutdownAndWait(final ExecutorService executor, final long milliseconds) { executor.shutdown(); try { executor.awaitTermination(milliseconds, TimeUnit.MILLISECONDS); } catch (final InterruptedException exception) { exception.printStackTrace(); } } public static final int[] rgbToRGB(final int rgb, final int[] result) { result[0] = (rgb >> 16) & 0xFF; result[1] = (rgb >> 8) & 0xFF; result[2] = (rgb >> 0) & 0xFF; return result; } public static final int[] rgbToHSV(final int[] rgb, final int[] result) { final float[] hsv = new float[3]; Color.RGBtoHSB(rgb[0], rgb[1], rgb[2], hsv); result[0] = round(hsv[0] * 255F); result[1] = round(hsv[1] * 255F); result[2] = round(hsv[2] * 255F); return result; } public static final int[] hsvToRGB(final int[] hsv, final int[] result) { return rgbToRGB(Color.HSBtoRGB(hsv[0] / 255F, hsv[1] / 255F, hsv[2] / 255F), result); } public static final float[] rgbToXYZ(final int[] rgb, final float[] result) { final float r = rgb[0] / 255F; final float g = rgb[1] / 255F; final float b = rgb[2] / 255F; final float b21 = 0.17697F; result[0] = (0.49F * r + 0.31F * g + 0.20F * b) / b21; result[1] = (b21 * r + 0.81240F * g + 0.01063F * b) / b21; result[2] = (0.00F * r + 0.01F * g + 0.99F * b) / b21; return result; } public static final int[] xyzToRGB(final float[] xyz, final int[] result) { final float x = xyz[0]; final float y = xyz[1]; final float z = xyz[2]; result[0] = round(255F * (0.41847F * x - 0.15866F * y - 0.082835F * z)); result[1] = round(255F * (-0.091169F * x + 0.25243F * y + 0.015708F * z)); result[2] = round(255F * (0.00092090F * x - 0.0025498F * y + 0.17860F * z)); return result; } public static final float[] xyzToCIELAB(final float[] xyz, final float[] result) { final float d65X = 0.95047F; final float d65Y = 1.0000F; final float d65Z = 1.08883F; final float fX = f(xyz[0] / d65X); final float fY = f(xyz[1] / d65Y); final float fZ = f(xyz[2] / d65Z); result[0] = 116F * fY - 16F; result[1] = 500F * (fX - fY); result[2] = 200F * (fY - fZ); return result; } public static final float[] cielabToXYZ(final float[] cielab, final float[] result) { final float d65X = 0.95047F; final float d65Y = 1.0000F; final float d65Z = 1.08883F; final float lStar = cielab[0]; final float aStar = cielab[1]; final float bStar = cielab[2]; final float c = (lStar + 16F) / 116F; result[0] = d65X * fInv(c + aStar / 500F); result[1] = d65Y * fInv(c); result[2] = d65Z * fInv(c - bStar / 200F); return result; } public static final float f(final float t) { return cube(6F / 29F) < t ? (float) pow(t, 1.0 / 3.0) : square(29F / 6F) * t / 3F + 4F / 29F; } public static final float fInv(final float t) { return 6F / 29F < t ? cube(t) : 3F * square(6F / 29F) * (t - 4F / 29F); } public static final float square(final float value) { return value * value; } public static final float cube(final float value) { return value * value * value; } public static final int[] quantize(final int[] abc, final int q, final int[] result) { return quantize(abc, q, q, q, result); } public static final int[] quantize(final int[] abc, final int qA, final int qB, final int qC, final int[] result) { result[0] = abc[0] & ((~0) << qA); result[1] = abc[1] & ((~0) << qB); result[2] = abc[2] & ((~0) << qC); return result; } public static final double distance2(final float[] abc1, final float[] abc2) { final int n = abc1.length; double sum = 0.0; for (int i = 0; i < n; ++i) { sum += square(abc1[i] - abc2[i]); } return sqrt(sum); } public static final int min(final int... values) { int result = Integer.MAX_VALUE; for (final int value : values) { if (value < result) { result = value; } } return result; } public static final int max(final int... values) { int result = Integer.MIN_VALUE; for (final int value : values) { if (result < value) { result = value; } } return result; } /** * @author codistmonk (creation 2014-04-10) */ public static final class DoubleArrayComparator implements Serializable, Comparator<double[]> { @Override public final int compare(final double[] array1, final double[] array2) { final int n1 = array1.length; final int n2 = array2.length; final int n = Math.min(n1, n2); for (int i = 0; i < n; ++i) { final int comparison = Double.compare(array1[i], array2[i]); if (comparison != 0) { return comparison; } } return n1 - n2; } /** * {@value}. */ private static final long serialVersionUID = -88586465954519984L; public static final DoubleArrayComparator INSTANCE = new DoubleArrayComparator(); } }
package org.safehaus.kiskis.mgmt.impl.taskrunner; import com.jayway.awaitility.Awaitility; import static com.jayway.awaitility.Awaitility.to; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.core.Is.is; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.safehaus.kiskis.mgmt.api.commandrunner.CommandRunner; import org.safehaus.kiskis.mgmt.impl.commandrunner.CommandRunnerImpl; import org.junit.Test; import static org.mockito.Mockito.*; import org.safehaus.kiskis.mgmt.api.commandrunner.AgentResult; import org.safehaus.kiskis.mgmt.api.commandrunner.Command; import org.safehaus.kiskis.mgmt.api.commandrunner.CommandCallback; import org.safehaus.kiskis.mgmt.api.commandrunner.CommandStatus; import org.safehaus.kiskis.mgmt.api.commandrunner.RequestBuilder; import org.safehaus.kiskis.mgmt.api.communicationmanager.CommunicationManager; import org.safehaus.kiskis.mgmt.impl.commandrunner.CommandImpl; import org.safehaus.kiskis.mgmt.shared.protocol.Agent; import org.safehaus.kiskis.mgmt.shared.protocol.Request; import org.safehaus.kiskis.mgmt.shared.protocol.Response; /** * * @author dilshat */ public class CommandRunnerTest { private static ExecutorService exec; @BeforeClass public static void setupClass() { exec = Executors.newCachedThreadPool(); } @AfterClass public static void afterClass() { exec.shutdown(); } @Test public void shouldRunCommand() { CommandRunner commandRunner = mock(CommandRunnerImpl.class); Command command = mock(Command.class); CommandCallback callback = mock(CommandCallback.class); commandRunner.runCommand(command, callback); verify(commandRunner).runCommand(command, callback); } @Test public void shouldAddListenerToCommManager() { CommunicationManager communicationManager = mock(CommunicationManager.class); CommandRunnerImpl commandRunnerImpl = new CommandRunnerImpl(communicationManager); commandRunnerImpl.init(); verify(communicationManager).addListener(commandRunnerImpl); } @Test public void shouldRemoveListenerFromCommManager() { CommunicationManager communicationManager = mock(CommunicationManager.class); CommandRunnerImpl commandRunnerImpl = new CommandRunnerImpl(communicationManager); commandRunnerImpl.init(); commandRunnerImpl.destroy(); verify(communicationManager).removeListener(commandRunnerImpl); } @Test public void shouldSendRequestToCommManager() { CommunicationManager communicationManager = mock(CommunicationManager.class); CommandRunnerImpl commandRunnerImpl = new CommandRunnerImpl(communicationManager); commandRunnerImpl.init(); UUID uuid = UUID.randomUUID(); CommandImpl commandImpl = mock(CommandImpl.class); when(commandImpl.getCommandUUID()).thenReturn(uuid); when(commandImpl.getTimeout()).thenReturn(1); Request request = mock(Request.class); Set<Request> requests = new HashSet<Request>(); requests.add(request); when(commandImpl.getRequests()).thenReturn(requests); commandRunnerImpl.runCommand(commandImpl); verify(communicationManager).sendRequest(any(Request.class)); } @Test public void commandShouldTimeout() { CommunicationManager communicationManager = mock(CommunicationManager.class); CommandRunnerImpl commandRunnerImpl = new CommandRunnerImpl(communicationManager); Agent agent = mock(Agent.class); Set<Agent> agents = new HashSet<Agent>(); agents.add(agent); RequestBuilder builder = mock(RequestBuilder.class); when(builder.getTimeout()).thenReturn(1); Command command = commandRunnerImpl.createCommand(builder, agents); commandRunnerImpl.init(); commandRunnerImpl.runCommand(command); assertEquals(CommandStatus.TIMEDOUT, command.getCommandStatus()); } @Test public void commandShouldTimeoutAsync() { CommunicationManager communicationManager = mock(CommunicationManager.class); CommandRunnerImpl commandRunnerImpl = new CommandRunnerImpl(communicationManager); Agent agent = mock(Agent.class); Set<Agent> agents = new HashSet<Agent>(); agents.add(agent); RequestBuilder builder = mock(RequestBuilder.class); when(builder.getTimeout()).thenReturn(1); commandRunnerImpl.init(); final Command command = commandRunnerImpl.createCommand(builder, agents); commandRunnerImpl.runCommandAsync(command); Awaitility.await().atMost(1050, TimeUnit.MILLISECONDS).with().pollInterval(10, TimeUnit.MILLISECONDS) .untilCall(to(command).getCommandStatus(), is(CommandStatus.TIMEDOUT)); } @Test public void commandShouldSucceed() throws InterruptedException { CommunicationManager communicationManager = mock(CommunicationManager.class); final CommandRunnerImpl commandRunnerImpl = new CommandRunnerImpl(communicationManager); commandRunnerImpl.init(); Agent agent = mock(Agent.class); Set<Agent> agents = new HashSet<Agent>(); agents.add(agent); UUID agentUUID = UUID.randomUUID(); when(agent.getUuid()).thenReturn(agentUUID); RequestBuilder builder = mock(RequestBuilder.class); when(builder.getTimeout()).thenReturn(1); final Command command = commandRunnerImpl.createCommand(builder, agents); UUID commandUUID = ((CommandImpl) command).getCommandUUID(); final Response response = mock(Response.class); when(response.getUuid()).thenReturn(agentUUID); when(response.getTaskUuid()).thenReturn(commandUUID); when(response.isFinal()).thenReturn(true); when(response.hasSucceeded()).thenReturn(true); commandRunnerImpl.runCommandAsync(command); exec.execute(new Runnable() { public void run() { commandRunnerImpl.onResponse(response); } }); Awaitility.await().atMost(1, TimeUnit.SECONDS).with().pollInterval(100, TimeUnit.MILLISECONDS) .untilCall(to(command).getCommandStatus(), is(CommandStatus.SUCCEEDED)); } @Test public void commandShouldStop() throws InterruptedException { CommunicationManager communicationManager = mock(CommunicationManager.class); final CommandRunnerImpl commandRunnerImpl = new CommandRunnerImpl(communicationManager); commandRunnerImpl.init(); Agent agent = mock(Agent.class); Set<Agent> agents = new HashSet<Agent>(); agents.add(agent); UUID agentUUID = UUID.randomUUID(); when(agent.getUuid()).thenReturn(agentUUID); RequestBuilder builder = mock(RequestBuilder.class); when(builder.getTimeout()).thenReturn(1); final Command command = commandRunnerImpl.createCommand(builder, agents); UUID commandUUID = ((CommandImpl) command).getCommandUUID(); final Response response = mock(Response.class); when(response.getUuid()).thenReturn(agentUUID); when(response.getTaskUuid()).thenReturn(commandUUID); when(response.isFinal()).thenReturn(false); when(response.hasSucceeded()).thenReturn(false); final AtomicInteger atomicInteger = new AtomicInteger(); commandRunnerImpl.runCommandAsync(command, new CommandCallback() { @Override public void onResponse(Response response, AgentResult agentResult, Command command) { atomicInteger.incrementAndGet(); stop(); } }); exec.execute(new Runnable() { public void run() { commandRunnerImpl.onResponse(response); commandRunnerImpl.onResponse(response); } }); Awaitility.await().atMost(1, TimeUnit.SECONDS).with().pollInterval(50, TimeUnit.MILLISECONDS) .and().pollDelay(100, TimeUnit.MILLISECONDS).until(new Callable<Boolean>() { public Boolean call() throws Exception { return atomicInteger.get() == 1; } }); } }
package mondrian.rolap; import mondrian.olap.*; import mondrian.util.MemoryMonitor; import mondrian.util.MemoryMonitorFactory; import org.apache.commons.dbcp.ConnectionFactory; import org.apache.commons.dbcp.DataSourceConnectionFactory; import org.apache.commons.dbcp.DriverManagerConnectionFactory; import org.apache.log4j.Logger; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.Connection; import java.sql.SQLException; import java.util.*; /** * A <code>RolapConnection</code> is a connection to a Mondrian OLAP Server. * * <p>Typically, you create a connection via * {@link DriverManager#getConnection(String, mondrian.spi.CatalogLocator, boolean)}. * {@link RolapConnectionProperties} describes allowable keywords.</p> * * @see RolapSchema * @see DriverManager * @author jhyde * @since 2 October, 2002 * @version $Id$ */ public class RolapConnection extends ConnectionBase { private static final Logger LOGGER = Logger.getLogger(RolapConnection.class); private final Util.PropertyList connectInfo; /** * Factory for JDBC connections to talk to the RDBMS. This factory will * usually use a connection pool. */ private final DataSource dataSource; private final String catalogName; private final RolapSchema schema; private SchemaReader schemaReader; protected Role role; private Locale locale = Locale.US; /** * Creates a connection. * * @param connectInfo Connection properties; keywords are described in * {@link RolapConnectionProperties}. */ public RolapConnection(Util.PropertyList connectInfo) { this(connectInfo, null, null); } /** * Creates a connection. * * @param connectInfo Connection properties; keywords are described in * {@link RolapConnectionProperties}. */ public RolapConnection(Util.PropertyList connectInfo, DataSource datasource) { this(connectInfo, null, datasource); } /** * Creates a RolapConnection. * * <p>Only {@link mondrian.rolap.RolapSchema.Pool#get} calls this with schema != null (to * create a schema's internal connection). Other uses retrieve a schema * from the cache based upon the <code>Catalog</code> property. * * @param connectInfo Connection properties; keywords are described in * {@link RolapConnectionProperties}. * @param schema Schema for the connection. Must be null unless this is to * be an internal connection. * @pre connectInfo != null */ RolapConnection(Util.PropertyList connectInfo, RolapSchema schema) { this(connectInfo, schema, null); } /** * Creates a RolapConnection. * * <p>Only {@link mondrian.rolap.RolapSchema.Pool#get} calls this with * schema != null (to create a schema's internal connection). * Other uses retrieve a schema from the cache based upon * the <code>Catalog</code> property. * * @param connectInfo Connection properties; keywords are described in * {@link RolapConnectionProperties}. * @param schema Schema for the connection. Must be null unless this is to * be an internal connection. * @param dataSource If not null an external DataSource to be used * by Mondrian * @pre connectInfo != null */ RolapConnection( Util.PropertyList connectInfo, RolapSchema schema, DataSource dataSource) { super(); String provider = connectInfo.get( RolapConnectionProperties.Provider.name(), "mondrian"); Util.assertTrue(provider.equalsIgnoreCase("mondrian")); this.connectInfo = connectInfo; this.catalogName = connectInfo.get(RolapConnectionProperties.Catalog.name()); this.dataSource = (dataSource != null) ? dataSource : createDataSource(connectInfo); Role role = null; if (schema == null) { // If RolapSchema.Pool.get were to call this with schema == null, // we would loop. if (dataSource == null) { // If there is no external data source is passed in, // we expect the following properties to be set, // as they are used to generate the schema cache key. final String jdbcConnectString = connectInfo.get(RolapConnectionProperties.Jdbc.name()); final String jdbcUser = connectInfo.get(RolapConnectionProperties.JdbcUser.name()); final String strDataSource = connectInfo.get(RolapConnectionProperties.DataSource.name()); final String connectionKey = jdbcConnectString + getJDBCProperties(connectInfo).toString(); schema = RolapSchema.Pool.instance().get( catalogName, connectionKey, jdbcUser, strDataSource, connectInfo); } else { schema = RolapSchema.Pool.instance().get( catalogName, dataSource, connectInfo); } String roleName = connectInfo.get(RolapConnectionProperties.Role.name()); if (roleName != null) { role = schema.lookupRole(roleName); if (role == null) { throw Util.newError("Role '" + roleName + "' not found"); } } } if (role == null) { role = schema.getDefaultRole(); } // Set the locale. String localeString = connectInfo.get(RolapConnectionProperties.Locale.name()); if (localeString != null) { String[] strings = localeString.split("_"); switch (strings.length) { case 1: this.locale = new Locale(strings[0]); break; case 2: this.locale = new Locale(strings[0], strings[1]); break; case 3: this.locale = new Locale(strings[0], strings[1], strings[2]); break; default: throw Util.newInternal("bad locale string '" + localeString + "'"); } } this.schema = schema; setRole(role); } protected Logger getLogger() { return LOGGER; } // This is package-level in order for the RolapConnectionTest class to have // access. static DataSource createDataSource(Util.PropertyList connectInfo) { final String jdbcConnectString = connectInfo.get(RolapConnectionProperties.Jdbc.name()); final String poolNeededString = connectInfo.get(RolapConnectionProperties.PoolNeeded.name()); Properties jdbcProperties = getJDBCProperties(connectInfo); String propertyString = jdbcProperties.toString(); if (jdbcConnectString != null) { // Get connection through own pooling datasource String jdbcDrivers = connectInfo.get(RolapConnectionProperties.JdbcDrivers.name()); if (jdbcDrivers != null) { RolapUtil.loadDrivers(jdbcDrivers); } final String jdbcDriversProp = MondrianProperties.instance().JdbcDrivers.get(); RolapUtil.loadDrivers(jdbcDriversProp); final boolean poolNeeded = (poolNeededString == null) // JDBC connections are dumb beasts, so we assume they're not // pooled. ? true : poolNeededString.equalsIgnoreCase("true"); final String jdbcUser = connectInfo.get(RolapConnectionProperties.JdbcUser.name()); final String jdbcPassword = connectInfo.get(RolapConnectionProperties.JdbcPassword.name()); if (jdbcUser != null) { jdbcProperties.put("user", jdbcUser); } if (jdbcPassword != null) { jdbcProperties.put("password", jdbcPassword); } if (!poolNeeded) { // Connection is already pooled; don't pool it again. return new DriverManagerDataSource(jdbcConnectString, jdbcProperties); } if (jdbcConnectString.toLowerCase().indexOf("mysql") > -1) { // mysql driver needs this autoReconnect parameter jdbcProperties.setProperty("autoReconnect", "true"); } // use the DriverManagerConnectionFactory to create connections ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcConnectString , jdbcProperties); try { return RolapConnectionPool.instance().getPoolingDataSource( jdbcConnectString + propertyString, connectionFactory); } catch (Throwable e) { throw Util.newInternal(e, "Error while creating connection pool (with URI " + jdbcConnectString + ")"); } } else { final String dataSourceName = connectInfo.get(RolapConnectionProperties.DataSource.name()); if (dataSourceName == null) { throw Util.newInternal( "Connect string '" + connectInfo.toString() + "' must contain either '" + RolapConnectionProperties.Jdbc + "' or '" + RolapConnectionProperties.DataSource + "'"); } final boolean poolNeeded = (poolNeededString == null) // Data sources are fairly smart, so we assume they look after // their own pooling. ? false : poolNeededString.equalsIgnoreCase("true"); // Get connection from datasource. final DataSource dataSource; try { dataSource = (DataSource) new InitialContext().lookup(dataSourceName); } catch (NamingException e) { throw Util.newInternal(e, "Error while looking up data source (" + dataSourceName + ")"); } if (!poolNeeded) { return dataSource; } ConnectionFactory connectionFactory = new DataSourceConnectionFactory(dataSource); try { return RolapConnectionPool.instance().getPoolingDataSource( dataSourceName, connectionFactory); } catch (Exception e) { throw Util.newInternal(e, "Error while creating connection pool (with URI " + dataSourceName + ")"); } } } /** * Creates a {@link Properties} object containing all of the JDBC * connection properties present in the * {@link Util.PropertyList connectInfo}. * * @param connectInfo * @return The JDBC connection properties. */ private static Properties getJDBCProperties(Util.PropertyList connectInfo) { Properties jdbcProperties = new Properties(); Iterator<String[]> iterator = connectInfo.iterator(); while (iterator.hasNext()) { String[] entry = iterator.next(); if (entry[0].startsWith(RolapConnectionProperties.JdbcPropertyPrefix)) { jdbcProperties.put(entry[0].substring(RolapConnectionProperties.JdbcPropertyPrefix.length()), entry[1]); } } return jdbcProperties; } public Util.PropertyList getConnectInfo() { return connectInfo; } public void close() { } public Schema getSchema() { return schema; } public String getConnectString() { return connectInfo.toString(); } public String getCatalogName() { return catalogName; } public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } public SchemaReader getSchemaReader() { return schemaReader; } public Object getProperty(String name) { // Mask out the values of certain properties. if (name.equals(RolapConnectionProperties.JdbcPassword.name()) || name.equals(RolapConnectionProperties.CatalogContent.name())) { return ""; } return connectInfo.get(name); } /** * @throws ResourceLimitExceededException if some resource limit specified in the * property file was exceeded * @throws QueryCanceledException if query was canceled in the middle of * execution * @throws QueryTimeoutException if query exceeded timeout specified in * the property file */ public Result execute(Query query) { class Listener implements MemoryMonitor.Listener { private final Query query; Listener(final Query query) { this.query = query; } public void memoryUsageNotification(long used, long max) { StringBuilder buf = new StringBuilder(200); buf.append("OutOfMemory used="); buf.append(used); buf.append(", max="); buf.append(max); buf.append(" for connection: "); buf.append(getConnectString()); // Call ConnectionBase method which has access to // Query methods. RolapConnection.memoryUsageNotification(query, buf.toString()); } } Listener listener = new Listener(query); MemoryMonitor mm = MemoryMonitorFactory.instance().getObject(); try { mm.addListener(listener); // Check to see if we must punt query.checkCancelOrTimeout(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(Util.unparse(query)); } query.setQueryStartTime(); Result result = new RolapResult(query, true); for (int i = 0; i < query.axes.length; i++) { QueryAxis axis = query.axes[i]; if (axis.isNonEmpty()) { result = new NonEmptyResult(result, query, i); } } if (LOGGER.isDebugEnabled()) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); result.print(pw); pw.flush(); LOGGER.debug(sw.toString()); } query.setQueryEndExecution(); return result; } catch (ResultLimitExceededException e) { // query has been punted throw e; } catch (Exception e) { String queryString; query.setQueryEndExecution(); try { queryString = Util.unparse(query); } catch (Exception e1) { queryString = "?"; } throw Util.newError(e, "Error while executing query [" + queryString + "]"); } finally { mm.removeListener(listener); } } public void setRole(Role role) { assert role != null; assert !role.isMutable(); this.role = role; this.schemaReader = new RolapSchemaReader(role, schema) { public Cube getCube() { throw new UnsupportedOperationException(); } }; } public Role getRole() { Util.assertPostcondition(role != null, "role != null"); Util.assertPostcondition(!role.isMutable(), "!role.isMutable()"); return role; } /** * Implementation of {@link DataSource} which calls the good ol' * {@link java.sql.DriverManager}. */ private static class DriverManagerDataSource implements DataSource { private final String jdbcConnectString; private PrintWriter logWriter; private int loginTimeout; private Properties jdbcProperties; public DriverManagerDataSource(String jdbcConnectString, Properties properties) { this.jdbcConnectString = jdbcConnectString; this.jdbcProperties = properties; } public Connection getConnection() throws SQLException { return new org.apache.commons.dbcp.DelegatingConnection( java.sql.DriverManager.getConnection( jdbcConnectString, jdbcProperties)); } public Connection getConnection(String username, String password) throws SQLException { if (jdbcProperties == null) { return java.sql.DriverManager.getConnection(jdbcConnectString, username, password); } else { Properties temp = (Properties)jdbcProperties.clone(); temp.put("user", username); temp.put("password", password); return java.sql.DriverManager.getConnection(jdbcConnectString, temp); } } public PrintWriter getLogWriter() throws SQLException { return logWriter; } public void setLogWriter(PrintWriter out) throws SQLException { logWriter = out; } public void setLoginTimeout(int seconds) throws SQLException { loginTimeout = seconds; } public int getLoginTimeout() throws SQLException { return loginTimeout; } public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("not a wrapper"); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } } public DataSource getDataSource() { return dataSource; } /** * A <code>NonEmptyResult</code> filters a result by removing empty rows * on a particular axis. */ class NonEmptyResult extends ResultBase { final Result underlying; private final int axis; private final Map<Integer, Integer> map; /** workspace. Synchronized access only. */ private final int[] pos; NonEmptyResult(Result result, Query query, int axis) { super(query, result.getAxes().clone()); this.underlying = result; this.axis = axis; this.map = new HashMap<Integer, Integer>(); int axisCount = underlying.getAxes().length; this.pos = new int[axisCount]; this.slicerAxis = underlying.getSlicerAxis(); List<Position> positions = underlying.getAxes()[axis].getPositions(); List<Position> positionsList = new ArrayList<Position>(); int i = 0; for (Position position: positions) { if (! isEmpty(i, axis)) { map.put(positionsList.size(), i); positionsList.add(position); } i++; } this.axes[axis] = new RolapAxis.PositionList(positionsList); } protected Logger getLogger() { return LOGGER; } /** * Returns true if all cells at a given offset on a given axis are * empty. For example, in a 2x2x2 dataset, <code>isEmpty(1,0)</code> * returns true if cells <code>{(1,0,0), (1,0,1), (1,1,0), * (1,1,1)}</code> are all empty. As you can see, we hold the 0th * coordinate fixed at 1, and vary all other coordinates over all * possible values. */ private boolean isEmpty(int offset, int fixedAxis) { int axisCount = getAxes().length; pos[fixedAxis] = offset; return isEmptyRecurse(fixedAxis, axisCount - 1); } private boolean isEmptyRecurse(int fixedAxis, int axis) { if (axis < 0) { RolapCell cell = (RolapCell) underlying.getCell(pos); return cell.isNull(); } else if (axis == fixedAxis) { return isEmptyRecurse(fixedAxis, axis - 1); } else { List<Position> positions = getAxes()[axis].getPositions(); int i = 0; for (Position position: positions) { pos[axis] = i; if (!isEmptyRecurse(fixedAxis, axis - 1)) { return false; } i++; } return true; } } // synchronized because we use 'pos' public synchronized Cell getCell(int[] externalPos) { System.arraycopy(externalPos, 0, this.pos, 0, externalPos.length); int offset = externalPos[axis]; int mappedOffset = mapOffsetToUnderlying(offset); this.pos[axis] = mappedOffset; return underlying.getCell(this.pos); } private int mapOffsetToUnderlying(int offset) { return map.get(offset); } public void close() { underlying.close(); } } } // End RolapConnection.java
package java7; import com.sandwich.koan.Koan; import static com.sandwich.koan.constant.KoanConstants.__; import static com.sandwich.util.Assert.assertEquals; public class AboutJava7LiteralsEnhancements { @Koan public void binaryLiterals() { //binary literals are marked with 0b prefix short binaryLiteral = 0b1111; assertEquals(binaryLiteral, (short)15); } @Koan public void binaryLiteralsWithUnderscores() { //literals can use underscores for improved readability short binaryLiteral = 0b1111_1111; assertEquals(binaryLiteral, (short)255); } @Koan public void numericLiteralsWithUnderscores() { long literal = 111_111_111L; //notice capital "B" - a valid binary literal prefix short multiplier = 0B1_000; assertEquals(literal * multiplier, 888888888l); } @Koan public void negativeBinaryLiteral() { int negativeBinaryLiteral = 0b1111_1111_1111_1111_1111_1111_1111_1100 / 4; assertEquals(negativeBinaryLiteral, -1); } @Koan public void binaryLiteralsWithBitwiseOperator() { int binaryLiteral = ~0b1111_1111; assertEquals(binaryLiteral, -256); } }
package org.eclipse.che.plugin.docker.machine.cleaner; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.environment.server.CheEnvironmentEngine; import org.eclipse.che.commons.schedule.ScheduleRate; import org.eclipse.che.plugin.docker.client.DockerConnector; import org.eclipse.che.plugin.docker.client.json.ContainerListEntry; import org.eclipse.che.plugin.docker.machine.DockerContainerNameGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import static java.lang.String.format; import static org.eclipse.che.plugin.docker.client.params.RemoveContainerParams.create; import static org.eclipse.che.plugin.docker.machine.DockerContainerNameGenerator.ContainerNameInfo; /** * Job for periodically clean up inactive docker containers and log list active containers. * * @author Alexander Andrienko */ @Singleton public class DockerContainerCleaner implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(DockerContainerCleaner.class); // TODO replace with WorkspaceManager private final CheEnvironmentEngine environmentEngine; private final DockerConnector dockerConnector; private final DockerContainerNameGenerator nameGenerator; @Inject public DockerContainerCleaner(CheEnvironmentEngine environmentEngine, DockerConnector dockerConnector, DockerContainerNameGenerator nameGenerator) { this.environmentEngine = environmentEngine; this.dockerConnector = dockerConnector; this.nameGenerator = nameGenerator; } @ScheduleRate(periodParameterName = "che.docker.unused_containers_cleanup_min", initialDelayParameterName = "che.docker.unused_containers_cleanup_min", unit = TimeUnit.MINUTES) @Override public void run() { List<String> activeContainers = new ArrayList<>(); try { for (ContainerListEntry container : dockerConnector.listContainers()) { String containerName = container.getNames()[0]; Optional<ContainerNameInfo> optional = nameGenerator.parse(containerName); if (optional.isPresent()) { try { // container is orphaned if not found exception is thrown environmentEngine.getMachine(optional.get().getWorkspaceId(), optional.get().getMachineId()); activeContainers.add(containerName); } catch (NotFoundException e) { cleanUp(container); } catch (Exception e) { LOG.error(format("Failed to check activity for container with name '%s'. Cause: %s", containerName, e.getLocalizedMessage()), e); } } } } catch (IOException e) { LOG.error("Failed to get list docker containers", e); } catch (Exception e) { LOG.error("Failed to clean up inactive containers", e); } LOG.info("List containers registered in the api: " + activeContainers); } private void cleanUp(ContainerListEntry container) { String containerId = container.getId(); String containerName = container.getNames()[0]; killContainer(containerId, containerName, container.getStatus()); removeContainer(containerId, containerName); } private void killContainer(String containerId, String containerName, String containerStatus) { try { if (containerStatus.startsWith("Up")) { dockerConnector.killContainer(containerId); LOG.warn("Unused container with 'id': '{}' and 'name': '{}' was killed ", containerId, containerName); } } catch (IOException e) { LOG.error(format("Failed to kill unused container with 'id': '%s' and 'name': '%s'", containerId, containerName), e); } } private void removeContainer(String containerId, String containerName) { try { dockerConnector.removeContainer(create(containerId).withForce(true).withRemoveVolumes(true)); LOG.warn("Unused container with 'id': '{}' and 'name': '{}' was removed", containerId, containerName); } catch (IOException e) { LOG.error(format("Failed to delete unused container with 'id': '%s' and 'name': '%s'", containerId, containerName), e); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gov.hhs.fha.nhinc.mpi.adapter.component; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.saml.extraction.SamlTokenExtractor; import javax.xml.ws.WebServiceContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hl7.v3.PRPAIN201306UV02; import org.hl7.v3.PRPAIN201305UV02; import org.hl7.v3.RespondingGatewayPRPAIN201305UV02RequestType; import javax.xml.ws.BindingProvider; import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerCache; /** * This class is the implementation of the AdapterComponentMpi. It performs any * web service specific stuff necessary and then calls the underlying java * implementation for this service. * * @author Les Westberg */ public class AdapterComponentMpiImpl { private static Log log = LogFactory.getLog(AdapterComponentMpiImpl.class); /** * Perform a look up on the MPI. * * @param bIsSecure TRUE if this is being called from a secure web service. * @param findCandidatesRequest The information about the patient that is being used for the lookup. * @param context The web service context information. * @return The results of the lookup. */ public PRPAIN201306UV02 query(boolean bIsSecure, org.hl7.v3.PRPAIN201305UV02 findCandidatesRequest, WebServiceContext context) { log.debug("Entering AdapterComponentMpiImpl.query - secured"); AssertionType assertion = null; if ((bIsSecure) && (context != null)) { assertion = SamlTokenExtractor.GetAssertion(context); } else { assertion = new AssertionType(); } AdapterComponentMpiOrchImpl oOrchestrator = new AdapterComponentMpiOrchImpl(); PRPAIN201306UV02 response = oOrchestrator.findCandidates(findCandidatesRequest, assertion); // Send response back to the initiating Gateway log.debug("Exiting AdapterComponentMpiImpl.query - secured"); return response; } public PRPAIN201306UV02 query(PRPAIN201305UV02 findCandidatesRequest, AssertionType assertionFromBody) { log.debug("Entering AdapterComponentMpiImpl.query - unsecured"); AssertionType assertion = null; if(assertionFromBody != null) { assertion = assertionFromBody; } else { assertion = new AssertionType(); } AdapterComponentMpiOrchImpl oOrchestrator = new AdapterComponentMpiOrchImpl(); PRPAIN201306UV02 response = oOrchestrator.findCandidates(findCandidatesRequest, assertion); // Send response back to the initiating Gateway log.debug("Exiting AdapterComponentMpiImpl.query - unsecured"); return response; } }
package org.apereo.cas.configuration.support; import org.apereo.cas.util.crypto.CipherExecutor; import lombok.Getter; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.iv.IvGenerator; import org.jasypt.iv.NoIvGenerator; import org.jasypt.iv.RandomIvGenerator; import org.springframework.core.env.Environment; import java.security.Security; import java.util.function.Function; import java.util.regex.Pattern; /** * This is {@link CasConfigurationJasyptCipherExecutor}. * * @author Misagh Moayyed * @since 5.1.0 */ public class CasConfigurationJasyptCipherExecutor implements CipherExecutor<String, String> { /** * Prefix inserted at the beginning of a value to indicate it's encrypted. */ public static final String ENCRYPTED_VALUE_PREFIX = "{cas-cipher}"; private static final Pattern ALGS_THAT_REQUIRE_IV_PATTERN = Pattern.compile("PBEWITHHMACSHA\\d+ANDAES_.*(?<!-BC)$"); /** * The Jasypt instance. */ private final StandardPBEStringEncryptor jasyptInstance; public CasConfigurationJasyptCipherExecutor(final String algorithm, final String password) { Security.addProvider(new BouncyCastleProvider()); jasyptInstance = new StandardPBEStringEncryptor(); setIvGenerator(new RandomIvGenerator()); setAlgorithm(algorithm); setPassword(password); } public CasConfigurationJasyptCipherExecutor(final Environment environment) { this(getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ALGORITHM), getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PASSWORD)); val pName = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PROVIDER); setProviderName(pName); val iter = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ITERATIONS); setKeyObtentionIterations(iter); val required = Boolean.parseBoolean(getJasyptParamFromEnv(environment, JasyptEncryptionParameters.INITIALIZATION_VECTOR)); setIvGenerator(required ? new RandomIvGenerator() : new NoIvGenerator()); } /** * Gets jasypt param from env. * * @param environment the environment * @param param the param * @return the jasypt param from env */ private static String getJasyptParamFromEnv(final Environment environment, final JasyptEncryptionParameters param) { return environment.getProperty(param.getPropertyName(), param.getDefaultValue()); } /** * Sets algorithm. * * @param alg the alg */ public void setAlgorithm(final String alg) { if (StringUtils.isNotBlank(alg)) { LOGGER.debug("Configured Jasypt algorithm [{}]", alg); jasyptInstance.setAlgorithm(alg); val required = isVectorInitializationRequiredFor(alg); setIvGenerator(required ? new RandomIvGenerator() : new NoIvGenerator()); } } /** * Sets iv generator. * * @param iv the iv */ public void setIvGenerator(final IvGenerator iv) { jasyptInstance.setIvGenerator(iv); } /** * Return true if the algorithm requires initialization vector. * {@code PBEWithDigestAndAES} algorithms (from the JCE Provider of JAVA 8) require an initialization vector. * Other algorithms may also use an initialization vector and it will increase the encrypted text's length. * * @param algorithm the algorithm to check * @return true if algorithm requires initialization vector */ private static boolean isVectorInitializationRequiredFor(final String algorithm) { return StringUtils.isNotBlank(algorithm) && ALGS_THAT_REQUIRE_IV_PATTERN.matcher(algorithm).matches(); } /** * Sets password. * * @param psw the psw */ public void setPassword(final String psw) { if (StringUtils.isNotBlank(psw)) { LOGGER.debug("Configured Jasypt password"); jasyptInstance.setPassword(psw); } } /** * Sets key obtention iterations. * * @param iter the iter */ public void setKeyObtentionIterations(final String iter) { if (StringUtils.isNotBlank(iter) && NumberUtils.isCreatable(iter)) { LOGGER.debug("Configured Jasypt iterations"); jasyptInstance.setKeyObtentionIterations(Integer.parseInt(iter)); } } /** * Sets provider name. * * @param pName the p name */ public void setProviderName(final String pName) { if (StringUtils.isNotBlank(pName)) { LOGGER.debug("Configured Jasypt provider"); jasyptInstance.setProviderName(pName); } } @Override public String encode(final String value, final Object[] parameters) { return encryptValue(value); } @Override public String decode(final String value, final Object[] parameters) { return decryptValue(value); } @Override public String getName() { return "CAS Configuration Jasypt Encryption"; } /** * Encrypt value string. * * @param value the value * @param handler the handler * @return the string */ public String encryptValue(final String value, final Function<Exception, String> handler) { try { return encryptValueAndThrow(value); } catch (final Exception e) { return handler.apply(e); } } /** * Encrypt value as string. * * @param value the value * @return the string */ public String encryptValue(final String value) { return encryptValue(value, e -> { LOGGER.warn("Could not encrypt value [{}]", value, e); return null; }); } /** * Encrypt value string (but don't log error, for use in shell). * * @param value the value * @return the string */ private String encryptValueAndThrow(final String value) { initializeJasyptInstanceIfNecessary(); return ENCRYPTED_VALUE_PREFIX + jasyptInstance.encrypt(value); } /** * Decrypt value string. * * @param value the value * @return the string */ public String decryptValue(final String value) { try { return decryptValueAndThrow(value); } catch (final Exception e) { LOGGER.warn("Could not decrypt value [{}]", value, e); } return null; } /** * Decrypt value directly, regardless of prefixes, etc. * * @param value the value * @return the decrypted value, or parameter value as was passed. */ private String decryptValueDirect(final String value) { initializeJasyptInstanceIfNecessary(); LOGGER.trace("Decrypting value [{}]...", value); val result = jasyptInstance.decrypt(value); if (StringUtils.isNotBlank(result)) { LOGGER.debug("Decrypted value [{}] successfully.", value); return result; } LOGGER.warn("Encrypted value [{}] has no values.", value); return value; } /** * Is value encrypted, and does it start with the required prefix. * * @param value the value * @return true/false */ public static boolean isValueEncrypted(final String value) { return StringUtils.isNotBlank(value) && value.startsWith(ENCRYPTED_VALUE_PREFIX); } /** * Extract encrypted value as string to decode later. * * @param value the value * @return the string */ public static String extractEncryptedValue(final String value) { return isValueEncrypted(value) ? value.substring(ENCRYPTED_VALUE_PREFIX.length()) : value; } /** * Decrypt value string. (but don't log error, for use in shell). * * @param value the value * @return the string */ private String decryptValueAndThrow(final String value) { if (isValueEncrypted(value)) { val encValue = extractEncryptedValue(value); return decryptValueDirect(encValue); } return value; } /** * Initialize jasypt instance if necessary. */ private void initializeJasyptInstanceIfNecessary() { if (!jasyptInstance.isInitialized()) { LOGGER.trace("Initializing Jasypt..."); jasyptInstance.initialize(); } } /** * The Jasypt encryption parameters. */ public enum JasyptEncryptionParameters { /** * Jasypt algorithm name to use. */ ALGORITHM("cas.standalone.configuration-security.alg", "PBEWithMD5AndTripleDES"), /** * Jasypt provider name to use. None for Java, {@code BC} for BouncyCastle. */ PROVIDER("cas.standalone.configuration-security.provider", null), /** * Jasypt number of iterations to use. */ ITERATIONS("cas.standalone.configuration-security.iterations", null), /** * Jasypt password to use for encryption and decryption. */ PASSWORD("cas.standalone.configuration-security.psw", null), /** * Use (or not) a Jasypt Initialization Vector. */ INITIALIZATION_VECTOR("cas.standalone.configuration-security.initialization-vector", "false"); /** * The Name. */ @Getter private final String propertyName; /** * The Default value. */ @Getter private final String defaultValue; JasyptEncryptionParameters(final String name, final String defaultValue) { this.propertyName = name; this.defaultValue = defaultValue; } } }
package com.dw.algorithmlib; import java.math.BigInteger; public class MathHelper { // find gcd algorithm static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int findGCDInArray(int arr[], int n) { int result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result); return result; } public boolean isSquare(int n) { int t = (int)Math.sqrt(n); return t*t == n; } public static int charToInt(char c) { return c - '0'; } public boolean isPrime(int n) { boolean result = true; for(int i=2;i<=Math.sqrt(n);i++) { if(n%i == 0) { result = false; break; } } return result; } // @todo: add two large number using String // num1 = 12345678 // num2 = 34567890 public String add(String num1, String num2) { int first = charToInt(num1.charAt(num1.length() - 1)); int second = charToInt(num2.charAt(num2.length() - 1)); ListNode num1Head = new ListNode(first); ListNode num2Head = new ListNode(second); ListNode p1 = num1Head; for (int i = num1.length() - 2; i >= 0; i ListNode t = new ListNode(charToInt(num1.charAt(i))); p1.next = t; p1 = t; } ListNode p2 = num2Head; for (int i = num2.length() - 2; i >= 0; i ListNode t = new ListNode(charToInt(num2.charAt(i))); p2.next = t; p2 = t; } p1 = num1Head; p2 = num2Head; ListNode target = num1.length() > num2.length()? p1 : p2; ListNode targetHead = target; ListNode prevTarget = target; int carry = 0; while (p1 != null & p2 != null) { target.val = p1.val + p2.val + carry; carry = target.val/10; target.val = target.val % 10; p1 = p1.next; p2 = p2.next; prevTarget = target; target = num1.length() > num2.length()? p1 : p2; } if(carry != 0) { if(target != null) { target.val = target.val + carry; } else if(target == null) { ListNode newNode = new ListNode(carry); prevTarget.next = newNode; } } StringBuilder sb = new StringBuilder(); p1 = targetHead; while(p1 != null) { sb.append(p1.val); p1 = p1.next; } return sb.reverse().toString(); } // @todo: multiply two large number using String public String Multiple(String num1, String num2) { String result = ""; return result; } // @todo: multiply two large number using String public String divide(String num1, String num2) { String result = ""; return result; } /** * Transfer number * @param N * @return */ public String NumToMin2(int N) { if (N == 0) return "0"; StringBuilder result = new StringBuilder(); int temp; while (N != 0) { temp = N % (-2); N = (N - Math.abs(temp))/(-2); if (temp == 1) { result.append('1'); } else result.append(temp == 0 ? '0' : '1'); } return result.reverse().toString(); } public static void main(String[] args) { // TODO Auto-generated method stub BigInteger bi1, bi2, bi3; bi1 = new BigInteger("1200000000000000000000000000000000000000000"); bi2 = new BigInteger("50"); // perform add operation on bi1 using bi2 bi3 = bi1.gcd(bi2); String str = "Result of addition is " +bi3;; // print bi3 value System.out.println( str ); } }
package integrationTests; import java.lang.reflect.*; import java.util.*; import org.junit.*; import mockit.coverage.*; import mockit.coverage.paths.*; public class CoverageTest extends Assert { static final Map<String, FileCoverageData> data = CoverageData.instance().getFileToFileDataMap(); protected FileCoverageData fileData; protected MethodCoverageData methodData; private int currentPathIndex = -1; @Before public void findCoverageData() throws Exception { Field testedField = getClass().getDeclaredField("tested"); Class<?> testedClass = testedField.getType(); String classFilePath = testedClass.getName().replace('.', '/') + ".java"; fileData = data.get(classFilePath); assertNotNull("FileCoverageData not found for " + classFilePath); } protected final void assertLines(int startingLine, int endingLine, int expectedLinesExecuted) { SortedMap<Integer, LineCoverageData> lineToLineData = fileData.lineToLineData; assertTrue("Starting line not found", lineToLineData.containsKey(startingLine)); assertTrue("Ending line not found", lineToLineData.containsKey(endingLine)); int linesExecuted = 0; for (int line = startingLine; line <= endingLine; line++) { LineCoverageData lineData = lineToLineData.get(line); if (lineData != null && lineData.getExecutionCount() > 0) { linesExecuted++; } } assertEquals("Unexpected number of lines executed:", expectedLinesExecuted, linesExecuted); } protected final void assertLine( int line, int expectedSegments, int expectedCoveredSegments, int expectedExecutionCount) { LineCoverageData lineData = fileData.lineToLineData.get(line); assertNotNull("Not an executable line", lineData); assertEquals("Segments:", expectedSegments, lineData.getNumberOfSegments()); assertEquals("Covered segments:", expectedCoveredSegments, lineData.getNumberOfCoveredSegments()); assertEquals("Execution count:", expectedExecutionCount, lineData.getExecutionCount()); } protected final void findMethodData(int firstLineOfMethodBody, String methodName) { methodData = fileData.firstLineToMethodData.get(firstLineOfMethodBody); assertNotNull("Method not found with first line " + firstLineOfMethodBody, methodData); assertEquals( "No method with name \"" + methodName + "\" found with first line at " + firstLineOfMethodBody, methodName, methodData.methodName); } protected final void assertPaths( int expectedPaths, int expectedCoveredPaths, int expectedExecutionCount) { assertEquals("Number of paths:", expectedPaths, methodData.paths.size()); assertEquals("Number of covered paths:", expectedCoveredPaths, methodData.getCoveredPaths()); assertEquals( "Execution count for all paths:", expectedExecutionCount, methodData.getExecutionCount()); } protected final void assertMethodLines(int startingLine, int endingLine) { assertEquals(startingLine, methodData.getFirstLineOfImplementationBody()); assertEquals(endingLine, methodData.getLastLineOfImplementationBody()); } protected final void assertPath(int expectedNodeCount, int expectedExecutionCount) { int i = currentPathIndex + 1; currentPathIndex = -1; Path path = methodData.paths.get(i); assertEquals("Path node count:", expectedNodeCount, path.getNodes().size()); assertEquals("Path execution count:", expectedExecutionCount, path.getExecutionCount()); currentPathIndex = i; } @After public final void verifyThatAllPathsWereAccountedFor() { int nextPathIndex = currentPathIndex + 1; if (methodData != null && nextPathIndex > 0) { assertEquals( "Path " + nextPathIndex + " was not verified;", nextPathIndex, methodData.paths.size()); } } }
package org.terasology.world.chunks.localChunkProvider; import com.google.common.collect.Maps; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent; import org.terasology.entitySystem.entity.lifecycleEvents.OnActivatedComponent; import org.terasology.entitySystem.entity.lifecycleEvents.OnChangedComponent; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.UpdateSubscriberSystem; import org.terasology.logic.location.LocationComponent; import org.terasology.math.JomlUtil; import org.terasology.math.geom.Vector3i; import org.terasology.monitoring.Activity; import org.terasology.monitoring.PerformanceMonitor; import org.terasology.world.RelevanceRegionComponent; import org.terasology.world.WorldComponent; import org.terasology.world.chunks.Chunk; import org.terasology.world.chunks.ChunkRegionListener; import org.terasology.world.chunks.event.BeforeChunkUnload; import org.terasology.world.chunks.event.OnChunkLoaded; import org.terasology.world.chunks.internal.ChunkRelevanceRegion; import org.terasology.world.chunks.pipeline.PositionFuture; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.StreamSupport; /** * RelevanceSystem loads, holds and unloads chunks around "players" (entity with {@link RelevanceRegionComponent} and * {@link LocationComponent}). * <p> * Uses in singleplayer or multiplayer on server-side. * <p> * Client side multiplayer downloads and displays the chunks sent by the server. * <p> * It is uses {@link RelevanceRegionComponent} for determinate "view distance". */ public class RelevanceSystem implements UpdateSubscriberSystem { private static final Vector3i UNLOAD_LEEWAY = Vector3i.one(); private final ReadWriteLock regionLock = new ReentrantReadWriteLock(); private final Map<EntityRef, ChunkRelevanceRegion> regions = Maps.newHashMap(); private final LocalChunkProvider chunkProvider; public RelevanceSystem(LocalChunkProvider chunkProvider) { this.chunkProvider = chunkProvider; } @ReceiveEvent(components = {RelevanceRegionComponent.class, LocationComponent.class}) public void onNewRelevanceRegion(OnActivatedComponent event, EntityRef entity) { addRelevanceEntity(entity, entity.getComponent(RelevanceRegionComponent.class).distance, null); } public Collection<ChunkRelevanceRegion> getRegions() { return regions.values(); } @ReceiveEvent(components = RelevanceRegionComponent.class) public void onRelevanceRegionChanged(OnChangedComponent event, EntityRef entity) { updateRelevanceEntityDistance(entity, entity.getComponent(RelevanceRegionComponent.class).distance); } @ReceiveEvent(components = {RelevanceRegionComponent.class, LocationComponent.class}) public void onLostRelevanceRegion(BeforeDeactivateComponent event, EntityRef entity) { removeRelevanceEntity(entity); } @ReceiveEvent(components = WorldComponent.class) public void onNewChunk(OnChunkLoaded chunkAvailable, EntityRef worldEntity) { for (ChunkRelevanceRegion region : regions.values()) { region.checkIfChunkIsRelevant(chunkProvider.getChunk(chunkAvailable.getChunkPos())); } } @ReceiveEvent(components = WorldComponent.class) public void onRemoveChunk(BeforeChunkUnload chunkUnloadEvent, EntityRef worldEntity) { for (ChunkRelevanceRegion region : regions.values()) { region.chunkUnloaded(chunkUnloadEvent.getChunkPos()); } } /** * Update distance of relative entity, if exists. * * @param entity entity for update distance. * @param distance new distance for setting to entity's region. */ public void updateRelevanceEntityDistance(EntityRef entity, Vector3i distance) { regionLock.readLock().lock(); try { ChunkRelevanceRegion region = regions.get(entity); if (region != null) { region.setRelevanceDistance(distance); } } finally { regionLock.readLock().unlock(); } } /** * Remove Entity from relevance system. * * @param entity entity for remove. */ public void removeRelevanceEntity(EntityRef entity) { regionLock.writeLock().lock(); try { regions.remove(entity); } finally { regionLock.writeLock().unlock(); } } /** * Synchronize region center to entity's position and create/load chunks in that region. */ private void updateRelevance() { try (Activity activity = PerformanceMonitor.startActivity("Update relevance")) { for (ChunkRelevanceRegion chunkRelevanceRegion : regions.values()) { chunkRelevanceRegion.update(); if (chunkRelevanceRegion.isDirty()) { for (Vector3i pos : chunkRelevanceRegion.getNeededChunks()) { Chunk chunk = chunkProvider.getChunk(pos); if (chunk != null) { chunkRelevanceRegion.checkIfChunkIsRelevant(chunk); } else { chunkProvider.createOrLoadChunk(pos); } } chunkRelevanceRegion.setUpToDate(); } } } } /** * Add entity to relevance system. create region for it. Update distance if region exists already. Create/Load * chunks for region. * * @param entity entity to add. * @param distance region's distance. * @param listener chunk relevance listener. */ public void addRelevanceEntity(EntityRef entity, Vector3i distance, ChunkRegionListener listener) { if (!entity.exists()) { return; } regionLock.readLock().lock(); try { ChunkRelevanceRegion region = regions.get(entity); if (region != null) { region.setRelevanceDistance(distance); return; } } finally { regionLock.readLock().unlock(); } ChunkRelevanceRegion region = new ChunkRelevanceRegion(entity, distance); if (listener != null) { region.setListener(listener); } regionLock.writeLock().lock(); try { regions.put(entity, region); } finally { regionLock.writeLock().unlock(); } StreamSupport.stream(region.getCurrentRegion().spliterator(), false) .sorted(new PositionRelevanceComparator()) //<-- this is n^2 cost. not sure why this needs to be sorted like this. .forEach( pos -> { Chunk chunk = chunkProvider.getChunk(pos); if (chunk != null) { region.checkIfChunkIsRelevant(chunk); } else { chunkProvider.createOrLoadChunk(pos); } } ); } /** * Check that chunk contains in any regions. * * @param pos chunk's position * @return {@code true} if chunk in regions, otherwise {@code false} */ public boolean isChunkInRegions(Vector3i pos) { for (ChunkRelevanceRegion region : regions.values()) { if (region.getCurrentRegion().expand(UNLOAD_LEEWAY).encompasses(pos)) { return true; } } return false; } /** * Create comporator for ChunkTasks, which compare by distance from region centers * * @return Comporator. */ public Comparator<Future<Chunk>> createChunkTaskComporator() { return new ChunkTaskRelevanceComparator(); } /** * @param delta The time (in seconds) since the last engine update. */ @Override public void update(float delta) { updateRelevance(); } @Override public void initialise() { // ignore } @Override public void preBegin() { // ignore } @Override public void postBegin() { // ignore } @Override public void preSave() { // ignore } @Override public void postSave() { // ignore } @Override public void shutdown() { // ignore } private int regionsDistanceScore(Vector3i chunk) { int score = Integer.MAX_VALUE; regionLock.readLock().lock(); try { for (ChunkRelevanceRegion region : regions.values()) { int dist = distFromRegion(chunk, region.getCenter()); if (dist < score) { score = dist; } if (score == 0) { break; } } return score; } finally { regionLock.readLock().unlock(); } } private int distFromRegion(Vector3i pos, Vector3i regionCenter) { return pos.gridDistance(regionCenter); } /** * Compare ChunkTasks by distance from region's centers. */ private class ChunkTaskRelevanceComparator implements Comparator<Future<Chunk>> { @Override public int compare(Future<Chunk> o1, Future<Chunk> o2) { return score((PositionFuture<?>) o1) - score((PositionFuture<?>) o2); } private int score(PositionFuture<?> task) { return RelevanceSystem.this.regionsDistanceScore(JomlUtil.from(task.getPosition())); } } /** * Compare ChunkTasks by distance from region's centers. */ private class PositionRelevanceComparator implements Comparator<Vector3i> { @Override public int compare(Vector3i o1, Vector3i o2) { return score(o1) - score(o2); } private int score(Vector3i position) { return RelevanceSystem.this.regionsDistanceScore(position); } } }
package org.neo4j.kernel.impl.transaction.xaframework; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.transaction.xa.XAException; import javax.transaction.xa.Xid; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.kernel.Config; import org.neo4j.kernel.impl.util.ArrayMap; import org.neo4j.kernel.impl.util.DumpLogicalLog; import org.neo4j.kernel.impl.util.FileUtils; /** * <CODE>XaLogicalLog</CODE> is a transaction and logical log combined. In * this log information about the transaction (such as started, prepared and * committed) will be written. All commands participating in the transaction * will also be written to the log. * <p> * Normally you don't have to do anything with this log except open it after it * has been instanciated (see {@link XaContainer}). The only method that may be * of use when implementing a XA compatible resource is the * {@link #getCurrentTxIdentifier}. Leave everything else be unless you know * what you're doing. * <p> * When the log is opened it will be scaned for uncompleted transactions and * those transactions will be re-created. When scan of log is complete all * transactions that hasn't entered prepared state will be marked as done * (implies rolledback) and dropped. All transactions that have been prepared * will be held in memory until the transaction manager tells them to commit. * Transaction that already started commit but didn't get flagged as done will * be re-committed. */ public class XaLogicalLog { private Logger log; private static final char CLEAN = 'C'; private static final char LOG1 = '1'; private static final char LOG2 = '2'; private FileChannel fileChannel = null; private final ByteBuffer buffer; private LogBuffer writeBuffer = null; private long previousLogLastCommittedTx = -1; private long logVersion = 0; private ArrayMap<Integer,LogEntry.Start> xidIdentMap = new ArrayMap<Integer,LogEntry.Start>( 4, false, true ); private Map<Integer,XaTransaction> recoveredTxMap = new HashMap<Integer,XaTransaction>(); private int nextIdentifier = 1; private boolean scanIsComplete = false; private String fileName = null; private final XaResourceManager xaRm; private final XaCommandFactory cf; private final XaTransactionFactory xaTf; private char currentLog = CLEAN; private boolean keepLogs = false; private boolean autoRotate = true; private long rotateAtSize = 10*1024*1024; // 10MB private boolean backupSlave = false; private boolean slave = false; private boolean useMemoryMapped = true; XaLogicalLog( String fileName, XaResourceManager xaRm, XaCommandFactory cf, XaTransactionFactory xaTf, Map<Object,Object> config ) { this.fileName = fileName; this.xaRm = xaRm; this.cf = cf; this.xaTf = xaTf; this.useMemoryMapped = getMemoryMapped( config ); log = Logger.getLogger( this.getClass().getName() + "/" + fileName ); buffer = ByteBuffer.allocateDirect( 9 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE * 10 ); } private boolean getMemoryMapped( Map<Object,Object> config ) { String configValue = config != null ? (String) config.get( Config.USE_MEMORY_MAPPED_BUFFERS ) : null; return configValue != null ? Boolean.parseBoolean( configValue ) : true; } synchronized void open() throws IOException { String activeFileName = fileName + ".active"; if ( !new File( activeFileName ).exists() ) { if ( new File( fileName ).exists() ) { // old < b8 xaframework with no log rotation and we need to // do recovery on it open( fileName ); } else { open( fileName + ".1" ); setActiveLog( LOG1 ); } } else { FileChannel fc = new RandomAccessFile( activeFileName , "rw" ).getChannel(); byte bytes[] = new byte[256]; ByteBuffer buf = ByteBuffer.wrap( bytes ); int read = fc.read( buf ); fc.close(); if ( read != 4 ) { throw new IllegalStateException( "Read " + read + " bytes from " + activeFileName + " but expected 4" ); } buf.flip(); char c = buf.asCharBuffer().get(); File copy = new File( fileName + ".copy" ); if ( copy.exists() ) { if ( !copy.delete() ) { log.warning( "Unable to delete " + copy.getName() ); } } if ( c == CLEAN ) { // clean String newLog = fileName + ".1"; File file = new File( newLog ); if ( file.exists() ) { fixCleanKill( newLog ); } file = new File( fileName + ".2" ); if ( file.exists() ) { fixCleanKill( fileName + ".2" ); } open( newLog ); setActiveLog( LOG1 ); } else if ( c == LOG1 ) { String newLog = fileName + ".1"; if ( !new File( newLog ).exists() ) { throw new IllegalStateException( "Active marked as 1 but no " + newLog + " exist" ); } currentLog = LOG1; File otherLog = new File( fileName + ".2" ); if ( otherLog.exists() ) { if ( !otherLog.delete() ) { log.warning( "Unable to delete " + copy.getName() ); } } open( newLog ); } else if ( c == LOG2 ) { String newLog = fileName + ".2"; if ( !new File( newLog ).exists() ) { throw new IllegalStateException( "Active marked as 2 but no " + newLog + " exist" ); } File otherLog = new File( fileName + ".1" ); if ( otherLog.exists() ) { if ( !otherLog.delete() ) { log.warning( "Unable to delete " + copy.getName() ); } } currentLog = LOG2; open( newLog ); } else { throw new IllegalStateException( "Unknown active log: " + c ); } } if ( !useMemoryMapped ) { writeBuffer = new DirectMappedLogBuffer( fileChannel ); } else { writeBuffer = new MemoryMappedLogBuffer( fileChannel ); } } private void fixCleanKill( String fileName ) throws IOException { File file = new File( fileName ); if ( !keepLogs ) { if ( !file.delete() ) { throw new IllegalStateException( "Active marked as clean and unable to delete log " + fileName ); } } else { System.out.println( "close fix cleanKill () @ pos: " + writeBuffer.getFileChannelPosition() + " and endPos=" + file.length() ); renameCurrentLogFileAndIncrementVersion( fileName, file.length() ); } } private void open( String fileToOpen ) throws IOException { fileChannel = new RandomAccessFile( fileToOpen, "rw" ).getChannel(); if ( fileChannel.size() != 0 ) { doInternalRecovery( fileToOpen ); } else { logVersion = xaTf.getCurrentVersion(); buffer.clear(); buffer.putLong( logVersion ); long lastTxId = xaTf.getLastCommittedTx(); buffer.putLong( lastTxId ); previousLogLastCommittedTx = lastTxId; buffer.flip(); fileChannel.write( buffer ); scanIsComplete = true; } } public boolean scanIsComplete() { return scanIsComplete; } private int getNextIdentifier() { nextIdentifier++; if ( nextIdentifier < 0 ) { nextIdentifier = 1; } return nextIdentifier; } // returns identifier for transaction // [TX_START][xid[gid.length,bid.lengh,gid,bid]][identifier][format id] public synchronized int start( Xid xid ) throws XAException { if ( backupSlave ) { throw new XAException( "Resource is configured as backup slave, " + "no new transactions can be started for " + fileName + "." + currentLog ); } int xidIdent = getNextIdentifier(); try { byte globalId[] = xid.getGlobalTransactionId(); byte branchId[] = xid.getBranchQualifier(); int formatId = xid.getFormatId(); long position = writeBuffer.getFileChannelPosition(); writeBuffer.put( LogEntry.TX_START ).put( (byte) globalId.length ).put( (byte) branchId.length ).put( globalId ).put( branchId ) .putInt( xidIdent ).putInt( formatId ); xidIdentMap.put( xidIdent, new LogEntry.Start( xid, xidIdent, position ) ); } catch ( IOException e ) { throw new XAException( "Logical log couldn't start transaction: " + e ); } return xidIdent; } private boolean readTxStartEntry() throws IOException { // get the global id long position = fileChannel.position(); LogEntry.Start entry = LogIoUtils.readTxStartEntry( buffer, fileChannel, position ); if ( entry == null ) { return false; } int identifier = entry.getIdentifier(); if ( identifier >= nextIdentifier ) { nextIdentifier = (identifier + 1); } // re-create the transaction Xid xid = entry.getXid(); xidIdentMap.put( identifier, entry ); XaTransaction xaTx = xaTf.create( identifier ); xaTx.setRecovered(); recoveredTxMap.put( identifier, xaTx ); xaRm.injectStart( xid, xaTx ); return true; } // [TX_PREPARE][identifier] public synchronized void prepare( int identifier ) throws XAException { assert xidIdentMap.get( identifier ) != null; try { writeBuffer.put( LogEntry.TX_PREPARE ).putInt( identifier ); writeBuffer.force(); } catch ( IOException e ) { throw new XAException( "Logical log unable to mark prepare [" + identifier + "] " + e ); } } private boolean readTxPrepareEntry() throws IOException { // get the tx identifier LogEntry.Prepare prepareEntry = LogIoUtils.readTxPrepareEntry( buffer, fileChannel ); if ( prepareEntry == null ) { return false; } int identifier = prepareEntry.getIdentifier(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { return false; } Xid xid = entry.getXid(); if ( xaRm.injectPrepare( xid ) ) { // read only we can remove xidIdentMap.remove( identifier ); recoveredTxMap.remove( identifier ); } return true; } // [TX_1P_COMMIT][identifier] public synchronized void commitOnePhase( int identifier, long txId ) throws XAException { assert xidIdentMap.get( identifier ) != null; assert txId != -1; try { writeBuffer.put( LogEntry.TX_1P_COMMIT ).putInt( identifier ).putLong( txId ); writeBuffer.force(); } catch ( IOException e ) { throw new XAException( "Logical log unable to mark 1P-commit [" + identifier + "] " + e ); } } private boolean readTxOnePhaseCommit() throws IOException { // get the tx identifier LogEntry.OnePhaseCommit commit = LogIoUtils.readTxOnePhaseCommit( buffer, fileChannel ); if ( commit == null ) { return false; } int identifier = commit.getIdentifier(); long txId = commit.getTxId(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { return false; } Xid xid = entry.getXid(); try { XaTransaction xaTx = xaRm.getXaTransaction( xid ); xaTx.setCommitTxId( txId ); xaRm.injectOnePhaseCommit( xid ); } catch ( XAException e ) { e.printStackTrace(); throw new IOException( e.getMessage() ); } return true; } // [DONE][identifier] public synchronized void done( int identifier ) throws XAException { if ( backupSlave ) { return; } assert xidIdentMap.get( identifier ) != null; try { writeBuffer.put( LogEntry.DONE ).putInt( identifier ); xidIdentMap.remove( identifier ); } catch ( IOException e ) { throw new XAException( "Logical log unable to mark as done [" + identifier + "] " + e ); } } // [DONE][identifier] called from XaResourceManager during internal recovery synchronized void doneInternal( int identifier ) throws IOException { buffer.clear(); buffer.put( LogEntry.DONE ).putInt( identifier ); buffer.flip(); fileChannel.write( buffer ); xidIdentMap.remove( identifier ); } private boolean readDoneEntry() throws IOException { // get the tx identifier LogEntry.Done done = LogIoUtils.readTxDoneEntry( buffer, fileChannel ); if ( done == null ) { return false; } int identifier = done.getIdentifier(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { return false; } Xid xid = entry.getXid(); xaRm.pruneXid( xid ); xidIdentMap.remove( identifier ); recoveredTxMap.remove( identifier ); return true; } // [TX_2P_COMMIT][identifier] public synchronized void commitTwoPhase( int identifier, long txId ) throws XAException { assert xidIdentMap.get( identifier ) != null; assert txId != -1; try { writeBuffer.put( LogEntry.TX_2P_COMMIT ).putInt( identifier ).putLong( txId ); writeBuffer.force(); } catch ( IOException e ) { throw new XAException( "Logical log unable to mark 2PC [" + identifier + "] " + e ); } } private boolean readTxTwoPhaseCommit() throws IOException { // get the tx identifier LogEntry.TwoPhaseCommit commit = LogIoUtils.readTxTwoPhaseCommit( buffer, fileChannel ); if ( commit == null ) { return false; } int identifier = commit.getIdentifier(); long txId = commit.getTxId(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { return false; } Xid xid = entry.getXid(); if ( xid == null ) { return false; } try { XaTransaction xaTx = xaRm.getXaTransaction( xid ); xaTx.setCommitTxId( txId ); xaRm.injectTwoPhaseCommit( xid ); } catch ( XAException e ) { e.printStackTrace(); throw new IOException( e.getMessage() ); } return true; } // [COMMAND][identifier][COMMAND_DATA] public synchronized void writeCommand( XaCommand command, int identifier ) throws IOException { checkLogRotation(); assert xidIdentMap.get( identifier ) != null; writeBuffer.put( LogEntry.COMMAND ).putInt( identifier ); command.writeToFile( writeBuffer ); // fileChannel, buffer ); } private boolean readCommandEntry() throws IOException { LogEntry.Command entry = LogIoUtils.readTxCommand( buffer, fileChannel, cf ); if ( entry == null ) { return false; } int identifier = entry.getIdentifier(); XaCommand command = entry.getXaCommand(); if ( command == null ) { // readCommand returns null if full command couldn't be loaded return false; } command.setRecovered(); XaTransaction xaTx = recoveredTxMap.get( identifier ); xaTx.injectCommand( command ); return true; } private void checkLogRotation() throws IOException { if ( autoRotate && writeBuffer.getFileChannelPosition() >= rotateAtSize ) { long currentPos = writeBuffer.getFileChannelPosition(); long firstStartEntry = getFirstStartEntry( currentPos ); // only rotate if no huge tx is running if ( ( currentPos - firstStartEntry ) < rotateAtSize / 2 ) { rotate(); } } } private void renameCurrentLogFileAndIncrementVersion( String logFileName, long endPosition ) throws IOException { System.out.println( " DumpLogicalLog.main( new String[] { logFileName } ); System.out.println( " File file = new File( logFileName ); if ( !file.exists() ) { throw new IOException( "Logical log[" + logFileName + "] not found" ); } String newName = fileName + ".v" + xaTf.getAndSetNewVersion(); File newFile = new File( newName ); boolean renamed = FileUtils.renameFile( file, newFile ); if ( !renamed ) { throw new IOException( "Failed to rename log to: " + newName ); } else { try { FileChannel channel = new RandomAccessFile( newName, "rw" ).getChannel(); FileUtils.truncateFile( channel, endPosition ); } catch ( IOException e ) { log.log( Level.WARNING, "Failed to truncate log at correct size", e ); } } System.out.println( " DumpLogicalLog.main( new String[] { newName } ); System.out.println( " } private void deleteCurrentLogFile( String logFileName ) throws IOException { File file = new File( logFileName ); if ( !file.exists() ) { throw new IOException( "Logical log[" + logFileName + "] not found" ); } boolean deleted = FileUtils.deleteFile( file ); if ( !deleted ) { log.warning( "Unable to delete clean logical log[" + logFileName + "]" ); } } private void releaseCurrentLogFile() throws IOException { if ( writeBuffer != null ) { writeBuffer.force(); writeBuffer = null; } fileChannel.close(); fileChannel = null; } public synchronized void close() throws IOException { if ( fileChannel == null || !fileChannel.isOpen() ) { log.fine( "Logical log: " + fileName + " already closed" ); return; } long endPosition = writeBuffer.getFileChannelPosition(); if ( xidIdentMap.size() > 0 ) { log.info( "Close invoked with " + xidIdentMap.size() + " running transaction(s). " ); writeBuffer.force(); writeBuffer = null; fileChannel.close(); log.info( "Dirty log: " + fileName + "." + currentLog + " now closed. Recovery will be started automatically next " + "time it is opened." ); return; } releaseCurrentLogFile(); char logWas = currentLog; if ( currentLog != CLEAN ) // again special case, see above { setActiveLog( CLEAN ); } if ( !keepLogs || backupSlave ) { if ( logWas == CLEAN ) { // special case going from old xa version with no log rotation // and we started with a recovery deleteCurrentLogFile( fileName ); } else { deleteCurrentLogFile( fileName + "." + logWas ); } } else { System.out.println( "close() @ pos: " + writeBuffer.getFileChannelPosition() + " and endPos=" + endPosition ); renameCurrentLogFileAndIncrementVersion( fileName + "." + logWas, endPosition ); } } private void doInternalRecovery( String logFileName ) throws IOException { log.info( "Non clean shutdown detected on log [" + logFileName + "]. Recovery started ..." ); // get log creation time buffer.clear(); buffer.limit( 16 ); if ( fileChannel.read( buffer ) != 16 ) { log.info( "Unable to read timestamp information, " + "no records in logical log." ); fileChannel.close(); boolean success = FileUtils.renameFile( new File( logFileName ), new File( logFileName + "_unknown_timestamp_" + System.currentTimeMillis() + ".log" ) ); assert success; fileChannel = new RandomAccessFile( logFileName, "rw" ).getChannel(); return; } buffer.flip(); logVersion = buffer.getLong(); long lastCommittedTx = buffer.getLong(); previousLogLastCommittedTx = lastCommittedTx; log.fine( "Logical log version: " + logVersion + " with committed tx[" + lastCommittedTx + "]" ); long logEntriesFound = 0; long lastEntryPos = fileChannel.position(); while ( readEntry() ) { logEntriesFound++; lastEntryPos = fileChannel.position(); } // make sure we overwrite any broken records fileChannel.position( lastEntryPos ); // zero out the slow way since windows don't support truncate very well buffer.clear(); while ( buffer.hasRemaining() ) { buffer.put( (byte)0 ); } buffer.flip(); long endPosition = fileChannel.size(); do { long bytesLeft = fileChannel.size() - fileChannel.position(); if ( bytesLeft < buffer.capacity() ) { buffer.limit( (int) bytesLeft ); } fileChannel.write( buffer ); buffer.flip(); } while ( fileChannel.position() < endPosition ); fileChannel.position( lastEntryPos ); scanIsComplete = true; log.fine( "Internal recovery completed, scanned " + logEntriesFound + " log entries." ); xaRm.checkXids(); if ( xidIdentMap.size() == 0 ) { log.fine( "Recovery completed." ); } else { log.fine( "[" + logFileName + "] Found " + xidIdentMap.size() + " prepared 2PC transactions." ); for ( LogEntry.Start entry : xidIdentMap.values() ) { log.fine( "[" + logFileName + "] 2PC xid[" + entry.getXid() + "]" ); } } recoveredTxMap.clear(); } // for testing, do not use! void reset() { xidIdentMap.clear(); recoveredTxMap.clear(); } private boolean readEntry() throws IOException { buffer.clear(); buffer.limit( 1 ); if ( fileChannel.read( buffer ) != buffer.limit() ) { // ok no more entries we're done return false; } buffer.flip(); byte entry = buffer.get(); switch ( entry ) { case LogEntry.TX_START: return readTxStartEntry(); case LogEntry.TX_PREPARE: return readTxPrepareEntry(); case LogEntry.TX_1P_COMMIT: return readTxOnePhaseCommit(); case LogEntry.TX_2P_COMMIT: return readTxTwoPhaseCommit(); case LogEntry.COMMAND: return readCommandEntry(); case LogEntry.DONE: return readDoneEntry(); case LogEntry.EMPTY: fileChannel.position( fileChannel.position() - 1 ); return false; default: throw new IOException( "Internal recovery failed, " + "unknown log entry[" + entry + "]" ); } } private ArrayMap<Thread,Integer> txIdentMap = new ArrayMap<Thread,Integer>( 5, true, true ); void registerTxIdentifier( int identifier ) { txIdentMap.put( Thread.currentThread(), identifier ); } void unregisterTxIdentifier() { txIdentMap.remove( Thread.currentThread() ); } /** * If the current thread is committing a transaction the identifier of that * {@link XaTransaction} can be obtained invoking this method. * * @return the identifier of the transaction committing or <CODE>-1</CODE> * if current thread isn't committing any transaction */ public int getCurrentTxIdentifier() { Integer intValue = txIdentMap.get( Thread.currentThread() ); if ( intValue != null ) { return intValue; } return -1; } public ReadableByteChannel getLogicalLog( long version ) throws IOException { String name = fileName + ".v" + version; if ( !new File( name ).exists() ) { throw new IOException( "No such log version:" + version ); } return new RandomAccessFile( name, "r" ).getChannel(); } private List<LogEntry> extractPreparedTransactionFromLog( long identifier, ReadableByteChannel log ) throws IOException { buffer.clear(); buffer.limit( 16 ); log.read( buffer ); List<LogEntry> logEntryList = new ArrayList<LogEntry>(); buffer.clear(); buffer.limit( 1 ); boolean done = false; while ( !done && log.read( buffer ) == buffer.limit() ) { buffer.flip(); byte entry = buffer.get(); LogEntry logEntry; switch ( entry ) { case LogEntry.TX_START: logEntry = LogIoUtils.readTxStartEntry( buffer, log, -1 ); if ( logEntry.getIdentifier() == identifier ) { logEntryList.add( logEntry ); } break; case LogEntry.TX_PREPARE: logEntry = LogIoUtils.readTxPrepareEntry( buffer, log ); break; case LogEntry.COMMAND: logEntry = LogIoUtils.readTxCommand( buffer, log, cf ); if ( logEntry.getIdentifier() == identifier ) { logEntryList.add( logEntry ); } break; case LogEntry.TX_1P_COMMIT: logEntry = LogIoUtils.readTxOnePhaseCommit( buffer, log ); break; case LogEntry.TX_2P_COMMIT: logEntry = LogIoUtils.readTxTwoPhaseCommit( buffer, log ); break; case LogEntry.DONE: logEntry = LogIoUtils.readTxDoneEntry( buffer, log ); break; case LogEntry.EMPTY: done = true; break; default: throw new IOException( "Unknown log entry " + entry ); } buffer.clear(); buffer.limit( 1 ); } if ( logEntryList.isEmpty() ) { throw new IOException( "Transaction for internal identifier[" + identifier + "] not found in current log" ); } return logEntryList; } private List<LogEntry> extractTransactionFromLog( long txId, long expectedVersion, ReadableByteChannel log ) throws IOException { buffer.clear(); buffer.limit( 16 ); log.read( buffer ); buffer.flip(); long versionInLog = buffer.getLong(); assertExpectedVersion( expectedVersion, versionInLog ); long prevTxId = buffer.getLong(); assertLogCanContainTx( txId, prevTxId ); List<LogEntry> logEntryList = null; Map<Integer,List<LogEntry>> transactions = new HashMap<Integer,List<LogEntry>>(); buffer.clear(); buffer.limit( 1 ); while ( logEntryList == null && log.read( buffer ) == buffer.limit() ) { buffer.flip(); byte entry = buffer.get(); LogEntry logEntry; switch ( entry ) { case LogEntry.TX_START: logEntry = LogIoUtils.readTxStartEntry( buffer, log, -1 ); List<LogEntry> list = new LinkedList<LogEntry>(); list.add( logEntry ); transactions.put( logEntry.getIdentifier(), list ); break; case LogEntry.TX_PREPARE: logEntry = LogIoUtils.readTxPrepareEntry( buffer, log ); transactions.get( logEntry.getIdentifier() ).add( logEntry ); break; case LogEntry.TX_1P_COMMIT: logEntry = LogIoUtils.readTxOnePhaseCommit( buffer, log ); if ( ((LogEntry.OnePhaseCommit) logEntry).getTxId() == txId ) { logEntryList = transactions.get( logEntry.getIdentifier() ); logEntryList.add( logEntry ); } else { transactions.remove( logEntry.getIdentifier() ); } break; case LogEntry.TX_2P_COMMIT: logEntry = LogIoUtils.readTxTwoPhaseCommit( buffer, log ); if ( ((LogEntry.TwoPhaseCommit) logEntry).getTxId() == txId ) { logEntryList = transactions.get( logEntry.getIdentifier() ); logEntryList.add( logEntry ); } else { transactions.remove( logEntry.getIdentifier() ); } break; case LogEntry.COMMAND: logEntry = LogIoUtils.readTxCommand( buffer, log, cf ); transactions.get( logEntry.getIdentifier() ).add( logEntry ); break; case LogEntry.DONE: logEntry = LogIoUtils.readTxDoneEntry( buffer, log ); transactions.remove( logEntry.getIdentifier() ); break; default: throw new IOException( "Unable to locate transaction[" + txId + "]" ); } buffer.clear(); buffer.limit( 1 ); } if ( logEntryList == null ) { throw new IOException( "Transaction[" + txId + "] not found in log (" + expectedVersion + ", " + prevTxId + ")" ); } return logEntryList; } private void assertLogCanContainTx( long txId, long prevTxId ) throws IOException { if ( prevTxId >= txId ) { throw new IOException( "Log says " + txId + " can not exist in this log (prev tx id=" + prevTxId + ")" ); } } private void assertExpectedVersion( long expectedVersion, long versionInLog ) throws IOException { if ( versionInLog != expectedVersion ) { throw new IOException( "Expected version " + expectedVersion + " but got " + versionInLog ); } } private String generateUniqueName( String baseName ) { String tmpName = baseName + "-" + System.currentTimeMillis(); while ( new File( tmpName ).exists() ) { tmpName = baseName + "-" + System.currentTimeMillis() + "_"; } return tmpName; } public synchronized ReadableByteChannel getPreparedTransaction( long identifier ) throws IOException { String name = fileName + ".ptx_" + identifier; File txFile = new File( name ); if ( txFile.exists() ) { return new RandomAccessFile( name, "r" ).getChannel(); } ReadableByteChannel log = getLogicalLogOrMyself( logVersion ); List<LogEntry> logEntryList = extractPreparedTransactionFromLog( identifier, log ); log.close(); writeOutLogEntryList( logEntryList, name, "temporary-ptx-write-out-" + identifier ); return new RandomAccessFile( name, "r" ).getChannel(); } private void writeOutLogEntryList( List<LogEntry> logEntryList, String name, String tmpNameHint ) throws IOException { String tmpName = generateUniqueName( tmpNameHint ); FileChannel txLog = new RandomAccessFile( tmpName, "rw" ).getChannel(); LogBuffer buf = new DirectMappedLogBuffer( txLog ); for ( LogEntry entry : logEntryList ) { LogIoUtils.writeLogEntry( entry, buf ); } buf.force(); txLog.close(); if ( !new File( tmpName ).renameTo( new File( name ) ) ) { throw new IOException( "Failed to rename " + tmpName + " to " + name ); } } public synchronized ReadableByteChannel getCommittedTransaction( long txId ) throws IOException { // check if written out String name = fileName + ".tx_" + txId; File txFile = new File( name ); if ( txFile.exists() ) { return new RandomAccessFile( name, "r" ).getChannel(); } long version = findLogContainingTxId( txId ); if ( version == -1 ) { throw new RuntimeException( "txId:" + txId + " not found in any logical log " + "(starting at " + logVersion + " and searching backwards" ); } // extract transaction ReadableByteChannel log = getLogicalLogOrMyself( version ); List<LogEntry> logEntryList = extractTransactionFromLog( txId, version, log ); log.close(); writeOutLogEntryList( logEntryList, name, "temporary-tx-write-out-" + txId ); ReadableByteChannel result = new RandomAccessFile( name, "r" ).getChannel(); return result; } private ReadableByteChannel getLogicalLogOrMyself( long version ) throws IOException { if ( version < logVersion ) { return getLogicalLog( version ); } else if ( version == logVersion ) { String currentLogName = fileName + (currentLog == LOG1 ? ".1" : ".2" ); return new RandomAccessFile( currentLogName, "r" ).getChannel(); } else { throw new RuntimeException( "Version[" + version + "] is higher then current log version[" + logVersion + "]" ); } } private long findLogContainingTxId( long txId ) throws IOException { long version = logVersion; long committedTx = previousLogLastCommittedTx; while ( version >= 0 ) { ReadableByteChannel log = getLogicalLogOrMyself( version ); ByteBuffer buf = ByteBuffer.allocate( 16 ); if ( log.read( buf ) != 16 ) { throw new IOException( "Unable to read log version " + version ); } buf.flip(); long readVersion = buf.getLong(); if ( readVersion != version ) { throw new IOException( "Got " + readVersion + " from log when expecting " + version ); } committedTx = buf.getLong(); log.close(); if ( committedTx <= txId ) { break; } version } return version; } public long getLogicalLogLength( long version ) { String name = fileName + ".v" + version; File file = new File( name ); if ( !file.exists() ) { return -1; } return file.length(); } public boolean hasLogicalLog( long version ) { String name = fileName + ".v" + version; return new File( name ).exists(); } public boolean deleteLogicalLog( long version ) { String name = fileName + ".v" + version; File file = new File(name ); if ( file.exists() ) { return FileUtils.deleteFile( file ); } return false; } public void makeBackupSlave() { if ( xidIdentMap.size() > 0 ) { throw new IllegalStateException( "There are active transactions" ); } backupSlave = true; } private class LogApplier { private final ReadableByteChannel byteChannel; // private final ByteBuffer buffer; // private final XaTransactionFactory xaTf; // private final XaResourceManager xaRm; // private final XaCommandFactory xaCf; // private final ArrayMap<Integer,LogEntry.Start> xidIdentMap; // private final Map<Integer,XaTransaction> recoveredTxMap; private LogEntry.Start startEntry; LogApplier( ReadableByteChannel byteChannel ) /*, ByteBuffer buffer, XaTransactionFactory xaTf, XaResourceManager xaRm, XaCommandFactory xaCf, ArrayMap<Integer,LogEntry.Start> xidIdentMap, Map<Integer,XaTransaction> recoveredTxMap )*/ { this.byteChannel = byteChannel; // this.buffer = buffer; // this.xaTf = xaTf; // this.xaRm = xaRm; // this.xaCf = xaCf; // this.xidIdentMap = xidIdentMap; // this.recoveredTxMap = recoveredTxMap; } boolean readAndApplyEntry() throws IOException { buffer.clear(); buffer.limit( 1 ); if ( byteChannel.read( buffer ) != buffer.limit() ) { // ok no more entries we're done return false; } buffer.flip(); byte entry = buffer.get(); switch ( entry ) { case LogEntry.TX_START: readTxStartEntry(); return true; case LogEntry.TX_PREPARE: readTxPrepareEntry(); return true; case LogEntry.TX_1P_COMMIT: readAndApplyTxOnePhaseCommit(); return true; case LogEntry.TX_2P_COMMIT: readAndApplyTxTwoPhaseCommit(); return true; case LogEntry.COMMAND: readCommandEntry(); return true; case LogEntry.DONE: readDoneEntry(); return true; case LogEntry.EMPTY: return false; default: throw new IOException( "Internal recovery failed, " + "unknown log entry[" + entry + "]" ); } } boolean readAndApplyAndWriteEntry( int newXidIdentifier ) throws IOException { buffer.clear(); buffer.limit( 1 ); if ( byteChannel.read( buffer ) != buffer.limit() ) { // ok no more entries we're done return false; } buffer.flip(); byte entry = buffer.get(); LogEntry logEntry = null; switch ( entry ) { case LogEntry.TX_START: logEntry = readTxStartEntry(); startEntry = (LogEntry.Start) logEntry; break; case LogEntry.TX_PREPARE: logEntry = readTxPrepareEntry(); break; case LogEntry.TX_1P_COMMIT: logEntry = readAndApplyTxOnePhaseCommit(); break; case LogEntry.TX_2P_COMMIT: logEntry = readAndApplyTxTwoPhaseCommit(); break; case LogEntry.COMMAND: logEntry = readCommandEntry(); break; case LogEntry.DONE: logEntry = readDoneEntry(); break; case LogEntry.EMPTY: break; default: throw new IOException( "Internal recovery failed, " + "unknown log entry[" + entry + "]" ); } if ( logEntry != null ) { logEntry.setIdentifier( newXidIdentifier ); LogIoUtils.writeLogEntry( logEntry, writeBuffer ); return true; } return false; } private LogEntry readTxStartEntry() throws IOException { // get the global id LogEntry.Start entry = LogIoUtils.readTxStartEntry( buffer, byteChannel, -1 ); if ( entry == null ) { throw new IOException( "Unable to read tx start entry" ); } // re-create the transaction Xid xid = entry.getXid(); int identifier = entry.getIdentifier(); xidIdentMap.put( identifier, entry ); XaTransaction xaTx = xaTf.create( identifier ); xaTx.setRecovered(); recoveredTxMap.put( identifier, xaTx ); xaRm.injectStart( xid, xaTx ); return entry; } private LogEntry readTxPrepareEntry() throws IOException { // get the tx identifier LogEntry.Prepare prepareEntry = LogIoUtils.readTxPrepareEntry( buffer, byteChannel ); if ( prepareEntry == null ) { throw new IOException( "Unable to read tx prepare entry" ); } int identifier = prepareEntry.getIdentifier(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { throw new IOException( "Unable to read tx prepeare entry" ); } Xid xid = entry.getXid(); if ( xaRm.injectPrepare( xid ) ) { // read only, we can remove xidIdentMap.remove( identifier ); recoveredTxMap.remove( identifier ); } return prepareEntry; } private LogEntry readAndApplyTxOnePhaseCommit() throws IOException { // get the tx identifier LogEntry.OnePhaseCommit commit = LogIoUtils.readTxOnePhaseCommit( buffer, byteChannel ); if ( commit == null ) { throw new IOException( "Unable to read tx 1PC entry" ); } int identifier = commit.getIdentifier(); long txId = commit.getTxId(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { throw new IOException( "Unable to read tx prepeare entry" ); } Xid xid = entry.getXid(); try { XaTransaction xaTx = xaRm.getXaTransaction( xid ); xaTx.setCommitTxId( txId ); xaRm.commit( xid, true ); } catch ( XAException e ) { e.printStackTrace(); throw new IOException( e.getMessage() ); } return commit; } private LogEntry readAndApplyTxTwoPhaseCommit() throws IOException { LogEntry.TwoPhaseCommit commit = LogIoUtils.readTxTwoPhaseCommit( buffer, byteChannel ); if ( commit == null ) { throw new IOException( "Unable to read tx 2PC entry" ); } int identifier = commit.getIdentifier(); long txId = commit.getTxId(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { throw new IOException( "Unable to read tx prepeare entry" ); } Xid xid = entry.getXid(); try { XaTransaction xaTx = xaRm.getXaTransaction( xid ); xaTx.setCommitTxId( txId ); xaRm.commit( xid, true ); } catch ( XAException e ) { e.printStackTrace(); throw new IOException( e.getMessage() ); } return commit; } private LogEntry readCommandEntry() throws IOException { LogEntry.Command entry = LogIoUtils.readTxCommand( buffer, byteChannel, cf ); if ( entry == null ) { throw new IOException( "Unable to read tx command entry" ); } int identifier = entry.getIdentifier(); XaCommand command = entry.getXaCommand(); command.setRecovered(); XaTransaction xaTx = recoveredTxMap.get( identifier ); xaTx.injectCommand( command ); return entry; } private LogEntry readDoneEntry() throws IOException { LogEntry.Done done = LogIoUtils.readTxDoneEntry( buffer, byteChannel ); if ( done == null ) { // not throw exception? return null; } int identifier = done.getIdentifier(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { throw new IOException( "Unable to read tx done entry" ); } Xid xid = entry.getXid(); xaRm.pruneXidIfExist( xid ); xidIdentMap.remove( identifier ); recoveredTxMap.remove( identifier ); return done; } } public synchronized void applyLog( ReadableByteChannel byteChannel ) throws IOException { if ( !backupSlave ) { throw new IllegalStateException( "This is not a backup slave" ); } if ( xidIdentMap.size() > 0 ) { throw new IllegalStateException( "There are active transactions" ); } buffer.clear(); buffer.limit( 16 ); if ( byteChannel.read( buffer ) != 16 ) { throw new IOException( "Unable to read log version" ); } buffer.flip(); logVersion = buffer.getLong(); long previousCommittedTx = buffer.getLong(); if ( logVersion != xaTf.getCurrentVersion() ) { throw new IllegalStateException( "Tried to apply version " + logVersion + " but expected version " + xaTf.getCurrentVersion() ); } log.fine( "Logical log version: " + logVersion + "(previous committed tx=" + previousCommittedTx + ")" ); long logEntriesFound = 0; LogApplier logApplier = new LogApplier( byteChannel ); while ( logApplier.readAndApplyEntry() ) { logEntriesFound++; } byteChannel.close(); xaTf.flushAll(); xaTf.getAndSetNewVersion(); xaRm.reset(); log.info( "Log[" + fileName + "] version " + logVersion + " applied successfully." ); } public synchronized void applyTransactionWithoutTxId( ReadableByteChannel byteChannel, long nextTxId ) throws IOException { if ( nextTxId != (xaTf.getLastCommittedTx() + 1) ) { throw new IllegalStateException( "Tried to apply tx " + nextTxId + " but expected transaction " + (xaTf.getCurrentVersion() + 1) ); } log.fine( "Logical log version: " + logVersion + ", committing tx=" + nextTxId + ")" ); System.out.println( "applyTxWithoutTxId#start @ pos: " + writeBuffer.getFileChannelPosition() ); long logEntriesFound = 0; LogApplier logApplier = new LogApplier( byteChannel ); int xidIdent = getNextIdentifier(); while ( logApplier.readAndApplyAndWriteEntry( xidIdent ) ) { logEntriesFound++; } byteChannel.close(); LogEntry.Start entry = logApplier.startEntry; if ( entry == null ) { throw new IOException( "Unable to find start entry" ); } System.out.println( "applyTxWithoutTxId#before 1PC @ pos: " + writeBuffer.getFileChannelPosition() ); LogEntry.OnePhaseCommit commit = new LogEntry.OnePhaseCommit( entry.getIdentifier(), nextTxId ); LogIoUtils.writeLogEntry( commit, writeBuffer ); Xid xid = entry.getXid(); try { XaTransaction xaTx = xaRm.getXaTransaction( xid ); xaTx.setCommitTxId( nextTxId ); xaRm.commit( xid, true ); } catch ( XAException e ) { e.printStackTrace(); throw new IOException( e.getMessage() ); } // LogEntry.Done done = new LogEntry.Done( entry.getIdentifier() ); // LogIoUtils.writeLogEntry( done, writeBuffer ); // xaTf.setLastCommittedTx( nextTxId ); // done in doCommit log.info( "Tx[" + nextTxId + "] " + " applied successfully." ); System.out.println( "applyTxWithoutTxId#end @ pos: " + writeBuffer.getFileChannelPosition() ); } public synchronized void applyTransaction( ReadableByteChannel byteChannel ) throws IOException { System.out.println( "applyFullTx#start @ pos: " + writeBuffer.getFileChannelPosition() ); long logEntriesFound = 0; LogApplier logApplier = new LogApplier( byteChannel ); int xidIdent = getNextIdentifier(); while ( logApplier.readAndApplyAndWriteEntry( xidIdent ) ) { logEntriesFound++; } byteChannel.close(); System.out.println( "applyFullTx#end @ pos: " + writeBuffer.getFileChannelPosition() ); } public synchronized void rotate() throws IOException { new Exception().printStackTrace(); xaTf.flushAll(); String newLogFile = fileName + ".2"; String currentLogFile = fileName + ".1"; char newActiveLog = LOG2; long currentVersion = xaTf.getCurrentVersion(); String oldCopy = fileName + ".v" + currentVersion; if ( currentLog == CLEAN || currentLog == LOG2 ) { newActiveLog = LOG1; newLogFile = fileName + ".1"; currentLogFile = fileName + ".2"; } else { assert currentLog == LOG1; } if ( new File( newLogFile ).exists() ) { throw new IOException( "New log file: " + newLogFile + " already exist" ); } if ( new File( oldCopy ).exists() ) { throw new IOException( "Copy log file: " + oldCopy + " already exist" ); } System.out.println( " DumpLogicalLog.main( new String[] { currentLogFile } ); System.out.println( " long endPosition = writeBuffer.getFileChannelPosition(); writeBuffer.force(); FileChannel newLog = new RandomAccessFile( newLogFile, "rw" ).getChannel(); buffer.clear(); buffer.putLong( currentVersion + 1 ); long lastTx = xaTf.getLastCommittedTx(); buffer.putLong( lastTx ).flip(); previousLogLastCommittedTx = lastTx; if ( newLog.write( buffer ) != 16 ) { throw new IOException( "Unable to write log version to new" ); } fileChannel.position( 0 ); buffer.clear(); buffer.limit( 16 ); if( fileChannel.read( buffer ) != 16 ) { throw new IOException( "Verification of log version failed" ); } buffer.flip(); long verification = buffer.getLong(); if ( verification != currentVersion ) { throw new IOException( "Verification of log version failed, " + " expected " + currentVersion + " got " + verification ); } if ( xidIdentMap.size() > 0 ) { fileChannel.position( getFirstStartEntry( endPosition ) ); } buffer.clear(); // ignore other 8 bytes buffer.limit( 1 ); boolean emptyHit = false; while ( fileChannel.read( buffer ) == 1 && !emptyHit ) { buffer.flip(); byte entry = buffer.get(); switch ( entry ) { case LogEntry.TX_START: readAndWriteTxStartEntry( newLog ); break; case LogEntry.TX_PREPARE: readAndWriteTxPrepareEntry( newLog ); break; case LogEntry.TX_1P_COMMIT: readAndWriteTxOnePhaseCommit( newLog ); break; case LogEntry.TX_2P_COMMIT: readAndWriteTxTwoPhaseCommit( newLog ); break; case LogEntry.COMMAND: readAndWriteCommandEntry( newLog ); break; case LogEntry.DONE: readAndVerifyDoneEntry(); break; case LogEntry.EMPTY: emptyHit = true; break; default: throw new IOException( "Log rotation failed, " + "unknown log entry[" + entry + "]" ); } buffer.clear(); buffer.limit( 1 ); } newLog.force( false ); releaseCurrentLogFile(); setActiveLog( newActiveLog ); if ( keepLogs ) { renameCurrentLogFileAndIncrementVersion( currentLogFile, endPosition ); } else { deleteCurrentLogFile( currentLogFile ); xaTf.getAndSetNewVersion(); } if ( xaTf.getCurrentVersion() != ( currentVersion + 1 ) ) { throw new IOException( "version change failed" ); } fileChannel = newLog; if ( !useMemoryMapped ) { writeBuffer = new DirectMappedLogBuffer( fileChannel ); } else { writeBuffer = new MemoryMappedLogBuffer( fileChannel ); } } private long getFirstStartEntry( long endPosition ) { long firstEntryPosition = endPosition; for ( LogEntry.Start entry : xidIdentMap.values() ) { if ( entry.getStartPosition() < firstEntryPosition ) { assert entry.getStartPosition() > 0; firstEntryPosition = entry.getStartPosition(); } } return firstEntryPosition; } private void setActiveLog( char c ) throws IOException { if ( c != CLEAN && c != LOG1 && c != LOG2 ) { throw new IllegalArgumentException( "Log must be either clean, " + "1 or 2" ); } if ( c == currentLog ) { throw new IllegalStateException( "Log should not be equal to " + "current " + currentLog ); } ByteBuffer bb = ByteBuffer.wrap( new byte[4] ); bb.asCharBuffer().put( c ).flip(); FileChannel fc = new RandomAccessFile( fileName + ".active" , "rw" ).getChannel(); int wrote = fc.write( bb ); if ( wrote != 4 ) { throw new IllegalStateException( "Expected to write 4 -> " + wrote ); } fc.force( false ); fc.close(); currentLog = c; } // [COMMAND][identifier][COMMAND_DATA] private void readAndWriteCommandEntry( FileChannel newLog ) throws IOException { buffer.clear(); buffer.put( LogEntry.COMMAND ); buffer.limit( 1 + 4 ); if ( fileChannel.read( buffer ) != 4 ) { throw new IllegalStateException( "Unable to read command header" ); } buffer.flip(); buffer.position( 1 ); int identifier = buffer.getInt(); FileChannel writeToLog = null; if ( xidIdentMap.get( identifier ) != null ) { writeToLog = newLog; } if ( writeToLog != null ) { buffer.position( 0 ); if ( writeToLog.write( buffer ) != 5 ) { throw new TransactionFailureException( "Unable to write command header" ); } } XaCommand command = cf.readCommand( fileChannel, buffer ); if ( writeToLog != null ) { command.writeToFile( new DirectLogBuffer( writeToLog, buffer ) ); } } private void readAndVerifyDoneEntry() throws IOException { buffer.clear(); buffer.limit( 4 ); if ( fileChannel.read( buffer ) != 4 ) { throw new IllegalStateException( "Unable to read done entry" ); } buffer.flip(); int identifier = buffer.getInt(); if ( xidIdentMap.get( identifier ) != null ) { throw new IllegalStateException( identifier + " done entry found but still active" ); } } // [TX_1P_COMMIT][identifier] private void readAndWriteTxOnePhaseCommit( FileChannel newLog ) throws IOException { buffer.clear(); buffer.limit( 1 + 12 ); buffer.put( LogEntry.TX_1P_COMMIT ); if ( fileChannel.read( buffer ) != 12 ) { throw new IllegalStateException( "Unable to read 1P commit entry" ); } buffer.flip(); buffer.position( 1 ); int identifier = buffer.getInt(); // limit already set so no txId = buffer.getLong(); FileChannel writeToLog = null; if ( xidIdentMap.get( identifier ) != null ) { writeToLog = newLog; } buffer.position( 0 ); if ( writeToLog != null && writeToLog.write( buffer ) != 13 ) { throw new TransactionFailureException( "Unable to write 1P commit entry" ); } } private void readAndWriteTxTwoPhaseCommit( FileChannel newLog ) throws IOException { buffer.clear(); buffer.limit( 1 + 12 ); buffer.put( LogEntry.TX_2P_COMMIT ); if ( fileChannel.read( buffer ) != 12 ) { throw new IllegalStateException( "Unable to read 2P commit entry" ); } buffer.flip(); buffer.position( 1 ); int identifier = buffer.getInt(); // no txId = buffer.getLong();, limit already set FileChannel writeToLog = null; if ( xidIdentMap.get( identifier ) != null ) { // " 2PC found but still active" ); writeToLog = newLog; } buffer.position( 0 ); if ( writeToLog != null && writeToLog.write( buffer ) != 13 ) { throw new TransactionFailureException( "Unable to write 2P commit entry" ); } } private void readAndWriteTxPrepareEntry( FileChannel newLog ) throws IOException { // get the tx identifier buffer.clear(); buffer.limit( 1 + 4 ); buffer.put( LogEntry.TX_PREPARE ); if ( fileChannel.read( buffer ) != 4 ) { throw new IllegalStateException( "Unable to read prepare entry" ); } buffer.flip(); buffer.position( 1 ); int identifier = buffer.getInt(); FileChannel writeToLog = null; if ( xidIdentMap.get( identifier ) != null ) { writeToLog = newLog; } buffer.position( 0 ); if ( writeToLog != null && writeToLog.write( buffer ) != 5 ) { throw new TransactionFailureException( "Unable to write prepare entry" ); } } // [TX_START][xid[gid.length,bid.lengh,gid,bid]][identifier][format id] private void readAndWriteTxStartEntry( FileChannel newLog ) throws IOException { // get the global id buffer.clear(); buffer.put( LogEntry.TX_START ); buffer.limit( 3 ); if ( fileChannel.read( buffer ) != 2 ) { throw new IllegalStateException( "Unable to read tx start entry xid id lengths" ); } buffer.flip(); buffer.position( 1 ); byte globalIdLength = buffer.get(); byte branchIdLength = buffer.get(); int xidLength = globalIdLength + branchIdLength; buffer.limit( 3 + xidLength + 8 ); buffer.position( 3 ); if ( fileChannel.read( buffer ) != 8 + xidLength ) { throw new IllegalStateException( "Unable to read xid" ); } buffer.flip(); buffer.position( 3 + xidLength ); int identifier = buffer.getInt(); FileChannel writeToLog = null; LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry != null ) { writeToLog = newLog; entry.setStartPosition( newLog.position() ); } buffer.position( 0 ); if ( writeToLog != null && writeToLog.write( buffer ) != 3 + 8 + xidLength ) { throw new TransactionFailureException( "Unable to write tx start xid" ); } } public void setKeepLogs( boolean keep ) { this.keepLogs = keep; } public boolean isLogsKept() { return this.keepLogs; } public void setAutoRotateLogs( boolean autoRotate ) { this.autoRotate = autoRotate; } public boolean isLogsAutoRotated() { return this.autoRotate; } public void setLogicalLogTargetSize( long size ) { this.rotateAtSize = size; } public long getLogicalLogTargetSize() { return this.rotateAtSize; } public String getFileName( long version ) { return fileName + ".v" + version; } }
package restaurant_rancho.gui; import agent_rancho.Agent; import restaurant_rancho.CashierAgent; import restaurant_rancho.CookAgent; import restaurant_rancho.CustomerAgent; import restaurant_rancho.HostAgent; import restaurant_rancho.WaiterAgent; import bank.gui.Bank; import simcity.PersonAgent; import simcity.gui.SimCityGui; import simcity.RestMenu; import simcity.Restaurant; import restaurant_rancho.ProducerConsumerMonitor; import restaurant_rancho.WaiterAgentPC; import simcity.interfaces.Market_Douglass; import javax.swing.*; import simcity.interfaces.Person; import restaurant_rancho.WaiterAgentNorm; import market.Market; import java.awt.*; import java.util.List; import java.util.ArrayList; import java.util.Hashtable; import simcity.interfaces.Bank_Douglass; /** * Panel in frame that contains all the restaurant information, * including host, cook, waiters, and customers. */ public class RestaurantRancho extends JPanel implements Restaurant { private static final long serialVersionUID = 1L; //Host, cook, waiters and customers String name; String type; Bank_Douglass bank; Market_Douglass market; private Hashtable<Person, CustomerAgent> returningCusts = new Hashtable<Person, CustomerAgent>(); private HostAgent host; private CookAgent cook; private CashierAgent cashier; private List<WaiterAgent> waiters = new ArrayList<WaiterAgent>(); private List<CustomerAgent> customers = new ArrayList<CustomerAgent>(); private JPanel restLabel = new JPanel(); private ListPanel customerPanel = new ListPanel(this, "Customers"); private ListPanel waiterPanel = new ListPanel (this, "Waiters"); private JPanel group = new JPanel(); private RestMenu menu = new RestMenu(); boolean isOpen = true; public ProducerConsumerMonitor orderStand = new ProducerConsumerMonitor(); private MyWaitingCook waitingCook; private MyWaitingCashier waitingCashier; private MyWaitingHost waitingHost; private List<MyWaitingWaiter> waitingWaiters = new ArrayList<MyWaitingWaiter>(); private List<MyWaitingWaiter> waitingPCWaiters = new ArrayList<MyWaitingWaiter>(); private List<MyWaitingCustomer> waitingCustomers = new ArrayList<MyWaitingCustomer>(); public boolean hostShiftDone = false; public boolean cookShiftDone = false; public boolean waiterWorking = false; public boolean cashierShiftDone = false; public boolean shiftsSwitching = false; private SimCityGui gui; private CookGui cookgui; public RestaurantRancho(SimCityGui g, String n) { name = n; type = "Mexican"; this.gui = g; menu.addItem("Citrus Fire-Grilled Chicken", 13.49); menu.addItem("Red Chile Enchilada Platter", 9.99); menu.addItem("Soft Tacos Monterrey", 10.99); menu.addItem("Burrito Sonora", 10.99); menu.addItem("Chicken Tortilla Soup", 5.99); setLayout(new GridLayout(1, 2, 20, 20)); group.setLayout(new BoxLayout(group, BoxLayout.Y_AXIS)); group.add(customerPanel); group.add(waiterPanel); add(restLabel); add(group); } public SimCityGui getGui() { return gui; } public void setBank(Bank_Douglass b) { bank = b; if (cashier!=null) setBank(b); } public boolean isOpen() { return (!shiftsSwitching && isOpen); } public RestMenu getMenu() { return menu; } public String[] getFoodNames(){ return menu.menuList.toArray(new String[0]); } public String[] getWorkers(){ List<String> restWorkers = new ArrayList<String>(); if(cashier != null){ String cashierName = "Cashier: "+cashier.getName(); restWorkers.add(cashierName); } if(cook != null){ String cookName = "Cook: "+cook.getName(); restWorkers.add(cookName); } if(host != null){ String hostName = "Host: "+host.getName(); restWorkers.add(hostName); } for(WaiterAgent waiter : waiters){ String waiterName = "Waiter: "+waiter.getName(); restWorkers.add(waiterName); } String[] workers = new String[restWorkers.size()]; workers = restWorkers.toArray(workers); return workers; } public int getQuantity(String name){ if(cook != null){ return cook.getQuantity(name); } return 0; } public void setQuantityAndBalance(String name, int num, double balance){ if(cook != null){ cook.setQuantity(name, num); } } public boolean isChangingShifts() { if (host!=null && host.isWorking==false) { removeHost(); } if (cook!=null && cook.isWorking==false) { removeCook(); } if (cashier!=null && cashier.isWorking==false) { removeCashier(); } for (WaiterAgent w : waiters ) { if (w.isWorking==false) { removeWaiter(w); } } if (shiftsSwitching) { if (host!=null && host.isWorking == true) return true; else if (waiters.size()!=0) { for (WaiterAgent w : waiters) { if (w.isWorking == true) return true; } } else if (cook!=null && cook.isWorking == true) { return true; } else if (cashier!=null && cashier.isWorking == true) { return true; } else { shiftsSwitching = false; return false; } } return false; } public String getRestaurantName() { return name; } public String getType() { return type; } // public void personAs(String type, String name, PersonAgent p) { public void personAs(Person p, String type, String name, double money){ addPerson(p, type, name, money); } public void PauseandUnpauseAgents() { for (WaiterAgent w : waiters) { w.pauseOrRestart(); } for (CustomerAgent c : customers) { c.pauseOrRestart(); } cook.pauseOrRestart(); host.pauseOrRestart(); cashier.pauseOrRestart(); } public void waiterWantsBreak(WaiterAgent w) { host.msgWantBreak(w); } public void waiterWantsOffBreak(WaiterAgent w) { host.msgBackFromBreak(w); } /** * Sets up the restaurant label that includes the menu, * and host and cook information */ private void initRestLabel() { JLabel label = new JLabel(); restLabel.setLayout(new BorderLayout()); label.setText( "<html><h3><u>Tonight's Staff</u></h3><table><tr><td>host:</td><td>" + host.getName() + "</td></tr></table><h3><u> Menu</u></h3><table><tr><td>Steak</td><td>$14.50</td></tr><tr><td>Chicken</td><td>$12.50</td></tr><tr><td>Salad</td><td>$7.50</td></tr><tr><td>Pizza</td><td>$10.50</td></tr><tr><td>Latte</td><td>$3.25</td></tr></table><br></html>"); label.setFont(new Font("Helvetica", Font.PLAIN, 13)); restLabel.setBorder(BorderFactory.createRaisedBevelBorder()); restLabel.add(label, BorderLayout.CENTER); restLabel.add(new JLabel(" "), BorderLayout.EAST); restLabel.add(new JLabel(" "), BorderLayout.WEST); } /** * When a customer or waiter is clicked, this function calls * updatedInfoPanel() from the main gui so that person's information * will be shown * * @param type indicates whether the person is a customer or waiter * @param name name of person */ /* public void showInfo(String type, String name) { if (type.equals("Customer")) { for (int i = 0; i < customers.size(); i++) { CustomerAgent temp = customers.get(i); //if (temp.getName() == name) // gui.updateInfoPanel(temp); } } if (type.equals("Waiter")) { for (int i = 0; i < waiters.size(); i++) { WaiterAgent temp = waiters.get(i); if(temp.getName() == name) { gui.updateWInfoPanel(temp); } } } } */ /** * Adds a customer or waiter to the appropriate list * * @param type indicates whether the person is a customer or waiter (later) * @param name name of person */ public void setFoodAmount(String choice, int amount) { if (cook!=null) cook.setAmount(choice, amount); } public void addPerson(Person p, String type, String name, double money) { if (!isChangingShifts()) { if (type.equals("Customer")) { if ((p!=null) && returningCusts.containsKey(p)) { returningCusts.get(p).getGui().setHungry(); } else { CustomerAgent c = new CustomerAgent(name); CustomerGui g = new CustomerGui(c, gui, customers.size()); if (p!=null) c.setPerson(p); //returningCusts.put(p, c); g.setHungry(); gui.ranchoAniPanel.addGui(g); if (host!=null) c.setHost(host); c.setGui(g); if (cashier!=null) c.setCashier(cashier); c.setCash(money); customers.add(c); c.startThread(); g.updatePosition(); } } else if (type.equals("Waiter")) { waiterWorking = true; WaiterAgentNorm w = new WaiterAgentNorm(name, this); WaiterGui g = new WaiterGui(w, waiters.size()); w.isWorking = true; if (p!=null) w.setPerson(p); gui.ranchoAniPanel.addGui(g); if (host!=null) w.setHost(host); if (cook!= null) w.setCook(cook); if (cashier!=null)w.setCashier(cashier); if (host!=null) host.addWaiter(w); w.setGui(g); waiters.add(w); w.startThread(); g.updatePosition(); } else if (type.equals("WaiterPC")) { waiterWorking = true; WaiterAgentPC w = new WaiterAgentPC(name, this); WaiterGui g = new WaiterGui(w, waiters.size()); w.isWorking = true; if (p!=null) w.setPerson(p); gui.ranchoAniPanel.addGui(g); if (host!=null) w.setHost(host); if (cook!= null) w.setCook(cook); if (cashier!=null)w.setCashier(cashier); if (host!=null) host.addWaiter(w); w.setGui(g); waiters.add(w); w.startThread(); g.updatePosition(); } else if (type.equals("Host")) { //if (host == null) { hostShiftDone = true; host = new HostAgent(name); host.isWorking = true; if (p!=null) host.setPerson(p); host.startThread(); initRestLabel(); for (WaiterAgent w : waiters) { host.addWaiter(w); w.setHost(host); } } else if (type.equals("Cook")) { cookShiftDone = true; cook = new CookAgent(name, this, market); cookgui = new CookGui(cook); cook.isWorking = true; if (p!=null) cook.setPerson(p); cook.setGui(cookgui); //cookgui.updatePosition(); for (WaiterAgent w : waiters) { w.setCook(cook); } gui.ranchoAniPanel.addGui(cookgui); cook.startThread(); } else if (type.equals("Cashier")) { cashierShiftDone = true; cashier = new CashierAgent(name, this); if (p!=null) cashier.setPerson(p); if (bank!=null) cashier.setBank(bank); if (market!=null) cashier.setMarket(market); for (WaiterAgent w : waiters) { w.setCashier(cashier); } cashier.startThread(); } } else { if (type.equals("Customer")) { waitingCustomers.add(new MyWaitingCustomer(p, name, money)); } if (type.equals("Host")) { waitingHost = new MyWaitingHost(p, name); } if (type.equals("Waiter")) { waitingWaiters.add(new MyWaitingWaiter(p, name)); } if (type.equals("WaiterPC")) { waitingPCWaiters.add(new MyWaitingWaiter(p, name)); } if (type.equals("Cook")) { waitingCook = new MyWaitingCook(p, name); } if (type.equals("Cashier")) { waitingCashier = new MyWaitingCashier(p, name); } } } public void removeCashier() { cashier = null; } public void removeHost() { host = null; } public void removeCook() { cook = null; } public void removeWaiter(WaiterAgent w) { waiters.remove(w); } public void removeMe(WaiterAgent wa, String type) { if (type == "Waiter") { waiters.remove(wa); System.out.println("removing waiter " + wa.getName()); } } @Override public void setMarket(Market_Douglass m) { market = m; if (cashier!=null) { cashier.setMarket(m); } if (cook!=null) { cook.setMarket(m); } } @Override public void msgHereIsOrder(String food, int quantity, int ID) { cook.msgHereIsOrder(food, quantity, ID); } @Override public void msgStartOfShift() { isOpen = true; } @Override public void msgEndOfShift() { System.out.println("RESTAURANT RANCHO GOT END OF SHIFT"); if (host!=null) { host.msgShiftDone(); for (int i = 0; i < waiters.size(); i++) { if (cashier!=null) cashier.subtract(10); } } else { if (cashier!=null) { cashier.msgShiftDone(); cashier.subtract(10); } for (int i = 0; i < waiters.size(); i++) { WaiterAgent w = waiters.get(i); w.msgShiftDone(false); if (cashier!=null) cashier.subtract(10); } if (cook!=null) { cook.msgShiftDone(); if (cashier!=null) cashier.subtract(10); } } } @Override public void msgHereIsBill(Market_Douglass m, double amount) { cashier.msgHereIsMarketBill(m, amount); } class MyWaitingCustomer { Person per; String name; double money; MyWaitingCustomer(Person p, String n, double m) { per = p; name = n; money = m; } } class MyWaitingHost { Person per; String name; MyWaitingHost (Person p, String n) { per = p; name = n; } } class MyWaitingCook { Person per; String name; MyWaitingCook (Person p, String n) { per = p; name = n; } } class MyWaitingCashier { Person per; String name; MyWaitingCashier (Person p, String n) { per = p; name = n; } } class MyWaitingWaiter { Person per; String name; MyWaitingWaiter (Person p, String n) { per = p; name = n; } } }
package procesamientos.impresion; import procesamientos.Procesamiento; import programa.Programa.CteInt; import programa.Programa.CteBool; import programa.Programa.Suma; import programa.Programa.And; import programa.Programa.Dec; import programa.Programa.DecVar; import programa.Programa.Exp; import programa.Programa.IAsig; import programa.Programa.IBloque; import programa.Programa.Inst; import programa.Programa.Prog; import programa.Programa.Var; import programa.Programa.CteString; import programa.Programa.CteChar; import programa.Programa.CteReal; import programa.Programa.Resta; import programa.Programa.Multi; import programa.Programa.Div; import programa.Programa.Concat; import programa.Programa.RestoEntero; import programa.Programa.CambiaSigno; import programa.Programa.Elem; import programa.Programa.ConvInt; import programa.Programa.ConvReal; import programa.Programa.ConvChar; import programa.Programa.ConvBool; import programa.Programa.ConvString; import programa.Programa.Or; import programa.Programa.Not; import programa.Programa.Mayor; import programa.Programa.Menor; import programa.Programa.Igual; import programa.Programa.MayorIgual; import programa.Programa.MenorIgual; import programa.Programa.Distinto; import programa.Programa.ILee; import programa.Programa.IEscribe; public class Impresion extends Procesamiento { private boolean atributos; private int identacion; public Impresion(boolean atributos) { this.atributos = atributos; identacion = 0; } public Impresion() { this(false); } private void imprimeAtributos(Exp exp) { if(atributos) { System.out.print("@{t:"+exp.tipo()+"}"); } } private void imprimeAtributos(Prog prog) { if(atributos) { System.out.print("@{t:"+prog.tipo()+"}"); } } private void imprimeAtributos(Inst i) { if(atributos) { System.out.print("@{t:"+i.tipo()+"}"); } } private void identa() { for (int i=0; i < identacion; i++) System.out.print(" "); } public void procesa(CteInt exp) { System.out.print(exp.valEntero()); imprimeAtributos(exp); } public void procesa(CteBool exp) { System.out.print(exp.valBool()); imprimeAtributos(exp); } public void procesa(Var exp) { System.out.print(exp.var()); imprimeAtributos(exp); } public void procesa(Suma exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('+'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(And exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("&&"); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Prog p) { for(Dec d: p.decs()) d.procesaCon(this); p.inst().procesaCon(this); imprimeAtributos(p); System.out.println(); } public void procesa(DecVar t) { System.out.print(t.tipoDec()+" "+t.var()); System.out.println(); } public void procesa(IAsig i) { identa(); System.out.print(i.var()+"="); i.exp().procesaCon(this); imprimeAtributos(i); System.out.println(); } public void procesa(IBloque b) { identa(); System.out.println("{"); identacion += 3; for(Inst i: b.is()) i.procesaCon(this); identacion -=3; identa(); System.out.print("}"); imprimeAtributos(b); System.out.println(); } public void procesa(CteReal exp) { System.out.print(exp.valReal()); imprimeAtributos(exp); } public void procesa(CteChar exp) { System.out.print(exp.valChar()); imprimeAtributos(exp); } public void procesa(CteString exp) { System.out.print(exp.valString()); imprimeAtributos(exp); } public void procesa(Resta exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('-'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Multi exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('*'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Div exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('/'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Concat exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("++"); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(RestoEntero exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('%'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(CambiaSigno exp) { System.out.print('('); System.out.print('('); System.out.print("-1"); System.out.print(')'); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } public void procesa(Elem exp) { System.out.print('('); System.out.print("Elem"); exp.opnd1().procesaCon(this); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Or exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("||"); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Mayor exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('>'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Menor exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('<'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(MayorIgual exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print(">="); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(MenorIgual exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("MenorIgual"); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Igual exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("=="); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Distinto exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("!="); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Not exp) { System.out.print('('); System.out.print('¬'); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConvInt exp) { System.out.print('('); System.out.print("ConvInt"); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConvChar exp) { System.out.print('('); System.out.print("ConvChar"); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConvReal exp) { System.out.print('('); System.out.print("ConvReal"); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConvBool exp) { System.out.print('('); System.out.print("ConvBool"); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConvString exp) { System.out.print('('); System.out.print("ConvString"); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } }
package io.quarkus.arc.deployment; import javax.enterprise.context.spi.Contextual; import javax.enterprise.context.spi.CreationalContext; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget.Kind; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.DotName; import org.jboss.logging.Logger; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.ClientProxy; import io.quarkus.arc.InjectableBean; import io.quarkus.arc.InstanceHandle; import io.quarkus.arc.deployment.ObserverRegistrationPhaseBuildItem.ObserverConfiguratorBuildItem; import io.quarkus.arc.impl.CreationalContextImpl; import io.quarkus.arc.processor.AnnotationStore; import io.quarkus.arc.processor.BeanInfo; import io.quarkus.arc.processor.BuildExtension; import io.quarkus.arc.processor.BuiltinScope; import io.quarkus.arc.processor.ObserverConfigurator; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.gizmo.MethodDescriptor; import io.quarkus.gizmo.ResultHandle; import io.quarkus.runtime.Startup; import io.quarkus.runtime.StartupEvent; public class StartupBuildSteps { static final DotName STARTUP_NAME = DotName.createSimple(Startup.class.getName()); static final MethodDescriptor ARC_CONTAINER = MethodDescriptor.ofMethod(Arc.class, "container", ArcContainer.class); static final MethodDescriptor ARC_CONTAINER_BEAN = MethodDescriptor.ofMethod(ArcContainer.class, "bean", InjectableBean.class, String.class); static final MethodDescriptor ARC_CONTAINER_INSTANCE = MethodDescriptor.ofMethod(ArcContainer.class, "instance", InstanceHandle.class, InjectableBean.class); static final MethodDescriptor INSTANCE_HANDLE_GET = MethodDescriptor.ofMethod(InstanceHandle.class, "get", Object.class); static final MethodDescriptor CLIENT_PROXY_CONTEXTUAL_INSTANCE = MethodDescriptor.ofMethod(ClientProxy.class, "arc_contextualInstance", Object.class); static final MethodDescriptor CONTEXTUAL_CREATE = MethodDescriptor.ofMethod(Contextual.class, "create", Object.class, CreationalContext.class); static final MethodDescriptor CONTEXTUAL_DESTROY = MethodDescriptor.ofMethod(Contextual.class, "destroy", void.class, Object.class, CreationalContext.class); private static final Logger LOGGER = Logger.getLogger(StartupBuildSteps.class); @BuildStep AutoAddScopeBuildItem addScope(CustomScopeAnnotationsBuildItem customScopes) { // Class with no built-in scope annotation but with @Startup method return AutoAddScopeBuildItem.builder() .defaultScope(BuiltinScope.APPLICATION) .isAnnotatedWith(STARTUP_NAME) .reason("Found classes containing @Startup annotation.") .build(); } @BuildStep UnremovableBeanBuildItem unremovableBeans() { // Make all classes annotated with @Startup unremovable return UnremovableBeanBuildItem.targetWithAnnotation(STARTUP_NAME); } @BuildStep void registerStartupObservers(ObserverRegistrationPhaseBuildItem observerRegistrationPhase, BuildProducer<ObserverConfiguratorBuildItem> configurators) { AnnotationStore annotationStore = observerRegistrationPhase.getContext().get(BuildExtension.Key.ANNOTATION_STORE); for (BeanInfo bean : observerRegistrationPhase.getContext().beans().withTarget()) { AnnotationInstance startupAnnotation = annotationStore.getAnnotation(bean.getTarget().get(), STARTUP_NAME); if (startupAnnotation != null) { registerStartupObserver(observerRegistrationPhase, bean, startupAnnotation); } } } private void registerStartupObserver(ObserverRegistrationPhaseBuildItem observerRegistrationPhase, BeanInfo bean, AnnotationInstance startup) { ObserverConfigurator configurator = observerRegistrationPhase.getContext().configure() .beanClass(bean.getBeanClass()) .observedType(StartupEvent.class); if (startup.target().kind() == Kind.METHOD) { configurator.id(startup.target().asMethod().toString()); } else if (startup.target().kind() == Kind.FIELD) { configurator.id(startup.target().asField().name()); } AnnotationValue priority = startup.value(); if (priority != null) { configurator.priority(priority.asInt()); } configurator.notify(mc -> { // InjectableBean<Foo> bean = Arc.container().bean("bflmpsvz"); ResultHandle containerHandle = mc.invokeStaticMethod(ARC_CONTAINER); ResultHandle beanHandle = mc.invokeInterfaceMethod(ARC_CONTAINER_BEAN, containerHandle, mc.load(bean.getIdentifier())); if (BuiltinScope.DEPENDENT.is(bean.getScope())) { // It does not make a lot of sense to support @Startup dependent beans but it's still a valid use case ResultHandle contextHandle = mc.newInstance( MethodDescriptor.ofConstructor(CreationalContextImpl.class, Contextual.class), beanHandle); // Create a dependent instance ResultHandle instanceHandle = mc.invokeInterfaceMethod(CONTEXTUAL_CREATE, beanHandle, contextHandle); // But destroy the instance immediately mc.invokeInterfaceMethod(CONTEXTUAL_DESTROY, beanHandle, instanceHandle, contextHandle); } else { // Obtains the instance from the context // InstanceHandle<Foo> handle = Arc.container().instance(bean); ResultHandle instanceHandle = mc.invokeInterfaceMethod(ARC_CONTAINER_INSTANCE, containerHandle, beanHandle); if (bean.getScope().isNormal()) { // We need to unwrap the client proxy // ((ClientProxy) handle.get()).arc_contextualInstance(); ResultHandle proxyHandle = mc.checkCast( mc.invokeInterfaceMethod(INSTANCE_HANDLE_GET, instanceHandle), ClientProxy.class); mc.invokeInterfaceMethod(CLIENT_PROXY_CONTEXTUAL_INSTANCE, proxyHandle); } } mc.returnValue(null); }); configurator.done(); } }
package eu.amidst.reviewMeeting2016; import eu.amidst.core.distribution.Normal_MultinomialNormalParents; import eu.amidst.core.variables.Variable; import eu.amidst.dynamic.datastream.DynamicDataInstance; import eu.amidst.dynamic.models.DynamicBayesianNetwork; import eu.amidst.dynamic.models.DynamicDAG; import eu.amidst.dynamic.variables.DynamicVariables; import eu.amidst.flinklink.core.data.DataFlink; import eu.amidst.flinklink.core.io.DataFlinkLoader; import eu.amidst.flinklink.core.io.DataFlinkWriter; import eu.amidst.flinklink.core.utils.DBNSampler; import org.apache.flink.api.java.ExecutionEnvironment; import java.util.Random; public class GenerateData { public static int BATCHSIZE = 500; public static boolean connectDBN = true; public static String path = "./datasets/dataFlink/conceptdrift/data"; //String path = "hdfs:///tmp_conceptdrift_data"; public static DynamicBayesianNetwork createDBN1(int numVars) throws Exception { DynamicVariables dynamicVariables = new DynamicVariables(); Variable classVar = dynamicVariables.newMultinomialDynamicVariable("C", 2); for (int i = 0; i < numVars; i++) { dynamicVariables.newGaussianDynamicVariable("A" + i); } DynamicDAG dag = new DynamicDAG(dynamicVariables); for (int i = 0; i < numVars; i++) { dag.getParentSetTimeT(dynamicVariables.getVariableByName("A" + i)).addParent(classVar); if (connectDBN) dag.getParentSetTimeT(dynamicVariables.getVariableByName("A" + i)).addParent(dynamicVariables.getVariableByName("A" + i).getInterfaceVariable()); } //dag.getParentSetTimeT(classVar).addParent(classVar.getInterfaceVariable()); dag.setName("dbn1"); DynamicBayesianNetwork dbn = new DynamicBayesianNetwork(dag); dbn.randomInitialization(new Random(1)); return dbn; } public static void createDataSetsDBN(int numVars, int SAMPLESIZE, int NSETS) throws Exception { final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DynamicBayesianNetwork dbn = createDBN1(numVars); for (Variable variable : dbn.getDynamicVariables()) { if (!variable.getName().startsWith("A")) continue; Normal_MultinomialNormalParents dist = dbn.getConditionalDistributionTimeT(variable); dist.getNormal_NormalParentsDistribution(0).setCoeffParents(new double[]{1.0}); dist.getNormal_NormalParentsDistribution(0).setIntercept(10); dist.getNormal_NormalParentsDistribution(1).setCoeffParents(new double[]{1.0}); dist.getNormal_NormalParentsDistribution(1).setIntercept(10); } //System.out.println(dbn.toString()); DBNSampler sampler = new DBNSampler(dbn); sampler.setNSamples(SAMPLESIZE); sampler.setBatchSize(BATCHSIZE); sampler.setSeed(0); DataFlink<DynamicDataInstance> data0 = sampler.cascadingSample(null); System.out.println(" DataFlinkWriter.writeDataToARFFFolder(data0, path+"0.arff"); data0 = DataFlinkLoader.loadDynamicDataFromFolder(env, path+"0.arff", false); DataFlink<DynamicDataInstance> dataPrev = data0; for (int i = 1; i < NSETS; i++) { System.out.println(" if (i==4){ for (Variable variable : dbn.getDynamicVariables()) { if (!variable.getName().startsWith("A")) continue; Normal_MultinomialNormalParents dist = dbn.getConditionalDistributionTimeT(variable); dist.getNormal_NormalParentsDistribution(0).setCoeffParents(new double[]{1.0}); dist.getNormal_NormalParentsDistribution(0).setIntercept(0); dist.getNormal_NormalParentsDistribution(1).setCoeffParents(new double[]{1.0}); dist.getNormal_NormalParentsDistribution(1).setIntercept(0); } //System.out.println(dbn); sampler.setDBN(dbn); } if (i==7){ for (Variable variable : dbn.getDynamicVariables()) { if (!variable.getName().startsWith("A")) continue; Normal_MultinomialNormalParents dist = dbn.getConditionalDistributionTimeT(variable); dist.getNormal_NormalParentsDistribution(0).setCoeffParents(new double[]{1.0}); dist.getNormal_NormalParentsDistribution(0).setIntercept(-10); dist.getNormal_NormalParentsDistribution(1).setCoeffParents(new double[]{1.0}); dist.getNormal_NormalParentsDistribution(1).setIntercept(-10); } //System.out.println(dbn); sampler.setDBN(dbn); } DataFlink<DynamicDataInstance> dataNew = sampler.cascadingSample(dataPrev);//i%4==1); DataFlinkWriter.writeDataToARFFFolder(dataNew, path + i + ".arff"); dataNew = DataFlinkLoader.loadDynamicDataFromFolder(env, path + i + ".arff", false); dataPrev = dataNew; } } public static void main(String[] args) throws Exception { int numVars = Integer.parseInt(args[0]); int SAMPLESIZE = Integer.parseInt(args[1]); int NSETS = Integer.parseInt(args[2]); createDataSetsDBN(numVars, SAMPLESIZE, NSETS); } }
package maximsblog.blogspot.com.wheelview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RadialGradient; import android.graphics.Paint.Cap; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Shader.TileMode; import android.graphics.RectF; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class WheelView extends View implements OnTouchListener, Runnable { private int mFirstValue = 0; private int mExtNumberOfSector = 23; private int mTotalEnableDegree = 322; private int mExtAnglePerSector = mTotalEnableDegree / mExtNumberOfSector; private float mCurrentDegrees = 0; private float mExtTotalDegrees = 0; private float mExtTop = 0; private double mStartSessionAngle; private double mStartAngle; private Touchs mTouch; private Bitmap mExtRing; private Bitmap mStartButton; private Bitmap mExtRingTouch; private Bitmap mVisor; private int mRadiusExtRing; private int mRadiusStartButton; private Paint mBitmapPaint; private Paint mBitmapPaintRing; public final static long DEFAULT_LOOP_INTERVAL = 5; // 100 ms private Thread thread = new Thread(this); private float mEndTop; private boolean mClock; private boolean mClickVolume; private boolean mThreadStop = false; private enum AnimationViewState { extRing, enabling } private AnimationViewState animationViewState; private IRing mOnTouchRingListener; private boolean mEnable = true; private int mExtCurrentSector = 0; private int mEventPointerId = -1; private float mSigma; private Paint mBitmapPaintRingRadianLine; private Paint mBitmapPaintStart; private Paint mBitmapPaintStartText; private Paint mBitmapPaintTempText; private int mSelectedSector = 0; private Bitmap mStartButtonGreenTouch; private Bitmap mStartButtonGreen; private Bitmap mExtRingGrey; private Paint mBitmapPaintUnable; private Bitmap mStartButtonUnable; private int mNumberSimpleBars; public interface IRing { void onCurrentValueChanged(int currentValue); void onStartClick(int selectedValue); void onRotateChangeState(); } public enum Touchs { nothing, startButton, extRing } public void setOnTouchRingListener(IRing onTouchRingListener) { this.mOnTouchRingListener = onTouchRingListener; } public WheelView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Wheel, defStyleAttr, 0); mEnable = a.getBoolean(R.styleable.Wheel_enable, true); mFirstValue = a.getInt(R.styleable.Wheel_start_value, 0); mExtNumberOfSector = a.getInt(R.styleable.Wheel_total_number_sectors, 23); mTotalEnableDegree = a.getInt(R.styleable.Wheel_total_enable_degree, 322); mNumberSimpleBars = a.getInt( R.styleable.Wheel_number_simple_bars_interval, 7); a.recycle(); init(); } public WheelView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Wheel); mEnable = a.getBoolean(R.styleable.Wheel_enable, true); mFirstValue = a.getInt(R.styleable.Wheel_start_value, 0); mExtNumberOfSector = a.getInt(R.styleable.Wheel_total_number_sectors, 23); mTotalEnableDegree = a.getInt(R.styleable.Wheel_total_enable_degree, 322); mNumberSimpleBars = a.getInt( R.styleable.Wheel_number_simple_bars_interval, 7); a.recycle(); init(); } public WheelView(Context context) { super(context); mEnable = true; mFirstValue = 0; mExtNumberOfSector = 23; mTotalEnableDegree = 322; mNumberSimpleBars = 7; init(); } private void init() { mExtAnglePerSector = mTotalEnableDegree / mExtNumberOfSector; this.setOnTouchListener(this); mTouch = Touchs.nothing; mBitmapPaint = new Paint(); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setFilterBitmap(true); mBitmapPaint.setDither(true); mBitmapPaint.setAlpha(255); mBitmapPaintUnable = new Paint(); mBitmapPaintUnable.setAntiAlias(true); mBitmapPaintUnable.setFilterBitmap(true); mBitmapPaintUnable.setDither(true); mBitmapPaintRing = new Paint(); mBitmapPaintRing.setAntiAlias(true); mBitmapPaintRing.setFilterBitmap(true); mBitmapPaintRing.setDither(true); mBitmapPaintRing.setAlpha(255); mBitmapPaintRing.setStyle(Style.FILL_AND_STROKE); mBitmapPaintRing.setColor(0xFFFF0000); mBitmapPaintRingRadianLine = new Paint(); mBitmapPaintRingRadianLine.setStyle(Style.STROKE); mBitmapPaintRingRadianLine.setStrokeWidth(5); mBitmapPaintRingRadianLine.setAntiAlias(true); mBitmapPaintRingRadianLine.setStrokeCap(Cap.ROUND); mBitmapPaintRingRadianLine.setColor(0xFF0000FF); mBitmapPaintStart = new Paint(); mBitmapPaintStart.setAntiAlias(true); mBitmapPaintStart.setFilterBitmap(true); mBitmapPaintStart.setDither(true); mBitmapPaintStart.setAlpha(255); mBitmapPaintStart.setTextSize(20); mBitmapPaintStart.setStyle(Style.FILL_AND_STROKE); mBitmapPaintStart.setColor(0xFFFFFFFF); mBitmapPaintStartText = new Paint(); mBitmapPaintStartText.setAntiAlias(true); mBitmapPaintStartText.setAlpha(255); mBitmapPaintStartText.setTextSize(44); mBitmapPaintStartText.setStyle(Style.FILL_AND_STROKE); mBitmapPaintStartText.setColor(0xFFFFFFFF); mBitmapPaintTempText = new Paint(); mBitmapPaintTempText.setAntiAlias(true); mBitmapPaintTempText.setFilterBitmap(true); mBitmapPaintTempText.setDither(true); mBitmapPaintTempText.setAlpha(255); mBitmapPaintTempText.setTextSize(30); mBitmapPaintTempText.setStyle(Style.FILL_AND_STROKE); mBitmapPaintTempText.setColor(Color.WHITE); mSigma = 1; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = 0; int width = getMeasuredWidth(); int height = getMeasuredHeight(); if (width > height) { size = height; } else { size = width; } setMeasuredDimension(size, size); } private void drawRings(int w, int h) { mExtRing = Bitmap.createBitmap(w, h, Config.ARGB_4444); mExtRingGrey = Bitmap.createBitmap(w, h, Config.ARGB_4444); mRadiusExtRing = mExtRing.getWidth() / 2; Canvas c = new Canvas(mExtRing); Canvas c1 = new Canvas(mExtRingGrey); mBitmapPaintRing.setShader(new RadialGradient(w / 2, h / 2, w / 2 - h / 16, 0xFFEA0707, 0xFFA30707, TileMode.CLAMP)); mBitmapPaintUnable.setShader(new RadialGradient(w / 2, h / 2, w / 2 - h / 16, 0xFF666666, 0xFFaaaaaa, TileMode.CLAMP)); c.drawCircle(w / 2, h / 2, w / 2 - 16, mBitmapPaintRing); int a = mBitmapPaintUnable.getAlpha(); mBitmapPaintUnable.setAlpha(255); c1.drawCircle(w / 2, h / 2, w / 2 - 16, mBitmapPaintUnable); mBitmapPaintUnable.setAlpha(a); mBitmapPaintRingRadianLine.setColor(0xAA000000); c.drawCircle(w / 2, h / 2, w / 2 - 16 , mBitmapPaintRingRadianLine); c1.drawCircle(w / 2, h / 2, w / 2 - 16 , mBitmapPaintRingRadianLine); c.save(); c1.save(); for (int i1 = 0; i1 <= mExtNumberOfSector; i1++) { c.drawLine(w / 2, 16, w / 2, h / 12, mBitmapPaintRingRadianLine); c1.drawLine(w / 2, 16, w / 2, h / 12, mBitmapPaintRingRadianLine); if (i1 == mSelectedSector) { mBitmapPaintTempText.setColor(Color.BLACK); } else { mBitmapPaintTempText.setColor(Color.WHITE); } c.drawText( String.valueOf(mFirstValue + i1), w / 2 - mBitmapPaintTempText.measureText(String .valueOf(mFirstValue + i1)) / 2, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent, mBitmapPaintTempText); c1.drawText( String.valueOf(mFirstValue + i1), w / 2 - mBitmapPaintTempText.measureText(String .valueOf(mFirstValue + i1)) / 2, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent, mBitmapPaintTempText); c.drawLine(w / 2, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent + mBitmapPaintTempText.getFontMetricsInt().descent , w / 2, h / 2, mBitmapPaintRingRadianLine); c1.drawLine(w / 2, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent + mBitmapPaintTempText.getFontMetricsInt().descent , w / 2, h / 2, mBitmapPaintRingRadianLine); c.rotate(-mExtAnglePerSector, w / 2, h / 2); c1.rotate(-mExtAnglePerSector, w / 2, h / 2); } mBitmapPaintTempText.setColor(Color.WHITE); c.restore(); c1.restore(); c.save(); c1.save(); if (mNumberSimpleBars > 0) { mBitmapPaintRingRadianLine.setStrokeWidth(2); for (int i1 = 0; i1 <= mExtNumberOfSector * mNumberSimpleBars; i1++) { c.drawLine( w / 2, 16, w / 2, h / 12 - 2 * mBitmapPaintTempText.getFontMetricsInt().descent, mBitmapPaintRingRadianLine); c1.drawLine( w / 2, 16, w / 2, h / 12 - 2 * mBitmapPaintTempText.getFontMetricsInt().descent, mBitmapPaintRingRadianLine); c.drawLine( w / 2, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent + mBitmapPaintTempText.getFontMetricsInt().descent + + 2 * mBitmapPaintTempText.getFontMetricsInt().descent, w / 2, h / 2, mBitmapPaintRingRadianLine); c1.drawLine( w / 2, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent + mBitmapPaintTempText.getFontMetricsInt().descent + + 2 * mBitmapPaintTempText.getFontMetricsInt().descent, w / 2, h / 2, mBitmapPaintRingRadianLine); c.rotate(-mExtAnglePerSector / mNumberSimpleBars, w / 2, h / 2); c1.rotate(-mExtAnglePerSector / mNumberSimpleBars, w / 2, h / 2); } } c.restore(); c1.restore(); c.rotate(-mTotalEnableDegree, w / 2, h / 2); c1.rotate(-mTotalEnableDegree, w / 2, h / 2); mBitmapPaintRingRadianLine.setStrokeWidth(5); int offset = h / 2 - (int) (0 + (mRadiusExtRing - h / 12 - (-mBitmapPaintTempText .getFontMetricsInt().ascent + mBitmapPaintTempText .getFontMetricsInt().descent) / 2)); final RectF r = new RectF(0 + offset, 0 + offset, w - offset, h - offset); mBitmapPaintRingRadianLine.setColor(Color.WHITE); mBitmapPaintRingRadianLine.setStrokeWidth(2); double A = mBitmapPaintTempText.measureText(String.valueOf(mExtNumberOfSector + mFirstValue)); double alpha = Math.toDegrees(Math.atan(A/(r.height()))); c.drawArc(r, (int)Math.floor(0 - 90 + mTotalEnableDegree + alpha), (int)Math.ceil(360 - mTotalEnableDegree - 2 * alpha), false, mBitmapPaintRingRadianLine); c1.drawArc(r, (int)Math.floor(0 - 90 + mTotalEnableDegree + alpha), (int)Math.ceil(360 - mTotalEnableDegree - 2 * alpha), false, mBitmapPaintRingRadianLine); c.rotate((int)-alpha, w / 2, h / 2); c1.rotate((int)-alpha, w / 2, h / 2); c.save(); c1.save(); c.rotate(13, w/2, offset); c1.rotate(13, w/2, offset); c.translate(w/2, offset); c1.translate(w/2, offset); c.drawLine(0, 0, (int)-A, 0, mBitmapPaintRingRadianLine); c1.drawLine(0, 0, (int)-A, 0, mBitmapPaintRingRadianLine); c.restore(); c1.restore(); c.rotate(-13, w/2, offset); c1.rotate(-13, w/2, offset); c.translate(w/2, offset); c1.translate(w/2, offset); c.drawLine(0, 0, (int)-A, 0, mBitmapPaintRingRadianLine); c1.drawLine(0, 0, (int)-A, 0, mBitmapPaintRingRadianLine); c.save(); c1.save(); mExtRingTouch = mExtRing; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mBitmapPaintTempText.setTextSize((h / 4 - h / 16 - h / 12) / 2); drawRings(w, h); mBitmapPaintUnable.setAlpha(mEnable ? 0 : 255); mBitmapPaintRingRadianLine.setColor(Color.BLACK); mStartButton = Bitmap.createBitmap(w / 2, h / 2, Config.ARGB_4444); Canvas c = new Canvas(mStartButton); mRadiusStartButton = mStartButton.getWidth() / 2; mBitmapPaintStart.setShader(new RadialGradient(w / 4, h / 4, mRadiusStartButton, 0xFFEA0707, 0xFFA30707, TileMode.CLAMP)); c.drawCircle(w / 4, h / 4, w / 4, mBitmapPaintStart); mBitmapPaintRingRadianLine.setColor(0xAA000000); c.drawCircle(w / 4, h / 4, w / 4, mBitmapPaintRingRadianLine); c.save(); mStartButtonGreenTouch = Bitmap.createBitmap(w / 2, h / 2, Config.ARGB_4444); c = new Canvas(mStartButtonGreenTouch); mBitmapPaintStart.setShader(new RadialGradient(w / 4, h / 4, mRadiusStartButton, 0xFF449D44, 0xFF5CB85C, TileMode.CLAMP)); c.drawCircle(w / 4, h / 4, w / 4, mBitmapPaintStart); c.drawCircle(w / 4, h / 4, w / 4, mBitmapPaintRingRadianLine); c.save(); mStartButtonGreen = Bitmap.createBitmap(w / 2, h / 2, Config.ARGB_4444); c = new Canvas(mStartButtonGreen); mBitmapPaintStart.setShader(new RadialGradient(w / 4, h / 4, mRadiusStartButton, 0xFF5CB85C, 0xFF449D44, TileMode.CLAMP)); c.drawCircle(w / 4, h / 4, w / 4, mBitmapPaintStart); c.drawCircle(w / 4, h / 4, w / 4, mBitmapPaintRingRadianLine); c.save(); mStartButtonUnable = Bitmap .createBitmap(w / 2, h / 2, Config.ARGB_4444); c = new Canvas(mStartButtonUnable); mBitmapPaintStart.setShader(new RadialGradient(w / 4, h / 4, mRadiusStartButton, 0xFF666666, 0xFFaaaaaa, TileMode.CLAMP)); c.drawCircle(w / 4, h / 4, w / 4, mBitmapPaintStart); c.drawCircle(w / 4, h / 4, w / 4, mBitmapPaintRingRadianLine); c.save(); mVisor = Bitmap.createBitmap(w, h, Config.ARGB_4444); c = new Canvas(mVisor); mBitmapPaintRingRadianLine.setColor(Color.BLACK); Path path = new Path(); path.moveTo(w / 2 - 20, 0); path.lineTo(w / 2 + 20, 0); path.lineTo(w / 2 + 20, h / 12 - 2 * mBitmapPaintTempText.getFontMetricsInt().descent); path.lineTo(w / 2, h / 12); path.lineTo(w / 2 - 20, h / 12 - 2 * mBitmapPaintTempText.getFontMetricsInt().descent); path.lineTo(w / 2 - 20, 0); mBitmapPaintRingRadianLine.setShader(new LinearGradient(w / 2 - 20, 0, w / 2, 0, Color.BLACK, Color.GRAY, TileMode.MIRROR)); mBitmapPaintRingRadianLine.setStyle(Style.FILL_AND_STROKE); c.drawPath(path, mBitmapPaintRingRadianLine); path.reset(); path.moveTo(w / 2, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent + mBitmapPaintTempText.getFontMetricsInt().descent); path.lineTo(w / 2 + 20, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent + mBitmapPaintTempText.getFontMetricsInt().descent + + 2 * mBitmapPaintTempText.getFontMetricsInt().descent); path.lineTo(w / 2 + 20, h / 2); path.lineTo(w / 2 - 20, h / 2); path.lineTo(w / 2 - 20, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent + mBitmapPaintTempText.getFontMetricsInt().descent + + 2 * mBitmapPaintTempText.getFontMetricsInt().descent); path.lineTo(w / 2, h / 12 + - mBitmapPaintTempText.getFontMetricsInt().ascent + mBitmapPaintTempText.getFontMetricsInt().descent); mBitmapPaintRingRadianLine.setShader(new LinearGradient(w / 2 - 20, 0, w / 2, 0, Color.BLACK, Color.GRAY, TileMode.MIRROR)); c.drawPath(path, mBitmapPaintRingRadianLine); mBitmapPaintRingRadianLine.setStyle(Style.STROKE); mBitmapPaintRingRadianLine.setShader(null); c.save(); }; private int getQuadrant(double x, double y) { if (x >= 0) { return y >= 0 ? 1 : 4; } else { return y >= 0 ? 2 : 3; } } public void setEnableRingWithAnim(boolean enable) { mEnable = enable; if (thread != null && thread.isAlive()) { thread.interrupt(); if (animationViewState == AnimationViewState.extRing) { mExtTop = mEndTop % mTotalEnableDegree; mExtTotalDegrees = mExtTop; } invalidate(); } animationViewState = AnimationViewState.enabling; thread = new Thread(this); thread.start(); } public void setEnableRingWithoutAnim(boolean enable) { mEnable = enable; if (enable) mBitmapPaintUnable.setAlpha(0); else mBitmapPaintUnable.setAlpha(255); invalidate(); } public void setExtCurrentState(int sector) { mEndTop = sector * mExtAnglePerSector; mExtTotalDegrees = mEndTop; mExtTop = mEndTop; mSelectedSector = sector; mExtCurrentSector = sector; int nn = Math.min(getWidth(), getHeight()); int w = nn; int h = nn; if (w != 0) drawRings(w, h); invalidate(); } public double getAngle(double xTouch, double yTouch) { double x = xTouch - (getWidth() / 2d); double y = getHeight() - yTouch - (getHeight() / 2d); switch (getQuadrant(x, y)) { case 1: return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI; case 2: return 180 - Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI; case 3: return 180 + (-1 * Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI); case 4: return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI; default: return 0; } } public double getRadius(double xTouch, double yTouch) { return Math.sqrt((xTouch - getWidth() / 2) * (xTouch - getWidth() / 2) + (yTouch - getHeight() / 2) * (yTouch - getHeight() / 2)); } public Touchs getTouch(double radius) { if (radius < mRadiusStartButton) { return Touchs.startButton; } else if (radius < mRadiusExtRing) { return Touchs.extRing; } else return Touchs.nothing; } public boolean onTouch(View v, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if (mEventPointerId == -1) { mEventPointerId = event.getPointerId(0); if (thread != null && thread.isAlive()) { thread.interrupt(); } double radius = getRadius(event.getX(), event.getY()); mTouch = getTouch(radius); if (!mEnable && (mTouch == Touchs.extRing)) { mTouch = Touchs.nothing; mCurrentDegrees = 0; invalidate(); return true; } mCurrentDegrees = 0; mClickVolume = false; if (mTouch == Touchs.extRing) mStartAngle = mStartSessionAngle = getAngle(event.getX(), event.getY()) + mExtTop; } invalidate(); break; case MotionEvent.ACTION_MOVE: if (!mEnable && (mTouch == Touchs.extRing)) { mTouch = Touchs.nothing; mCurrentDegrees = 0; invalidate(); return true; } for (int i1 = 0; i1 < event.getPointerCount(); i1++) { if (event.getPointerId(i1) == mEventPointerId) { double currentAngle; currentAngle = getAngle(event.getX(), event.getY()) + mExtTop; double p = mExtTotalDegrees + (mStartSessionAngle - currentAngle); p = p % 360; boolean stop = false; if (p < 0.0) { p = 0.0f; stop = true; } if (p > mTotalEnableDegree) { p = mTotalEnableDegree; stop = true; } if (stop) { mCurrentDegrees = 0; mStartSessionAngle = currentAngle; invalidate(); return true; } mCurrentDegrees = (float) (mStartSessionAngle - currentAngle); if (!mClickVolume) mClickVolume = Math.abs(Math.abs(mStartAngle) - Math.abs(currentAngle)) > 10; invalidate(); mStartSessionAngle = currentAngle; break; } } break; case MotionEvent.ACTION_POINTER_UP: if (event.getPointerId(event.getActionIndex()) == mEventPointerId) { actionUp(event); mEventPointerId = -1; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: if (event.getPointerId(event.getActionIndex()) == mEventPointerId) { actionUp(event); mEventPointerId = -1; } break; } return true; } private void actionUp(MotionEvent event) { if (!mEnable) { mTouch = Touchs.nothing; mCurrentDegrees = 0; invalidate(); } if (mTouch == Touchs.extRing) { animationViewState = animationViewState.extRing; mExtTotalDegrees %= 360; if (mExtTotalDegrees < 0) { mExtTotalDegrees = 360 + mExtTotalDegrees; } float endDegrees = mExtTotalDegrees; int currentSector = Math.round(endDegrees / getExtAnglePerSector()); mEndTop = currentSector * getExtAnglePerSector(); mExtTop = mExtTotalDegrees; if (Math.round(mExtTotalDegrees) % getExtAnglePerSector() == getExtAnglePerSector() / 2) { int i1 = 0; i1++; } if (mEndTop - mExtTotalDegrees > 0) mClock = true; else mClock = false; if (thread != null && thread.isAlive()) { thread.interrupt(); } if (mEndTop != mExtTop) { thread = new Thread(this); thread.start(); } } else if (mTouch == Touchs.startButton) { double r = getRadius(event.getX(), event.getY()); if (r <= mRadiusStartButton) { drawRings(getWidth(), getHeight()); if (mOnTouchRingListener != null && mEnable) { if (mSelectedSector != mExtCurrentSector) { mSelectedSector = mExtCurrentSector; mOnTouchRingListener.onStartClick(mFirstValue + mExtCurrentSector); } } else mSelectedSector = mExtCurrentSector; } } mTouch = Touchs.nothing; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Bitmap startButton; Bitmap extRing; if (mTouch == Touchs.startButton) { extRing = mExtRing; } else if (mTouch == Touchs.extRing) { extRing = mExtRingTouch; } else { extRing = mExtRing; } if (mTouch == Touchs.extRing) { mExtTotalDegrees += mCurrentDegrees; if ((int) (mExtTotalDegrees % getExtAnglePerSector() - mExtNumberOfSector / 2) == 0) { if (mClickVolume && mOnTouchRingListener != null) { mClickVolume = false; mOnTouchRingListener.onRotateChangeState(); } } float endDegrees = mExtTotalDegrees % 360; if (endDegrees < 0) { endDegrees = 360 + endDegrees; } if (endDegrees > mExtAnglePerSector * mExtNumberOfSector) endDegrees = mExtAnglePerSector * mExtNumberOfSector; int currentSector = Math.round(endDegrees / getExtAnglePerSector()); if (currentSector > mExtNumberOfSector) currentSector = 0; if (mExtCurrentSector != currentSector && mOnTouchRingListener != null) { mExtCurrentSector = currentSector; mOnTouchRingListener.onCurrentValueChanged(mFirstValue + currentSector); } else { mExtCurrentSector = currentSector; } drawRotateBitmap(canvas, mExtTotalDegrees, extRing, mBitmapPaintRing); drawRotateBitmap(canvas, mExtTotalDegrees, mExtRingGrey, mBitmapPaintUnable); } else { drawRotateBitmap(canvas, mExtTop, extRing, mBitmapPaintRing); drawRotateBitmap(canvas, mExtTop, mExtRingGrey, mBitmapPaintUnable); } canvas.drawBitmap(mVisor, (getWidth() - mVisor.getWidth()) / 2, (getHeight() - mVisor.getHeight()) / 2, mBitmapPaintRing); if (mEnable) { if ((mSelectedSector == mExtCurrentSector)) startButton = mStartButton; else if (mTouch == Touchs.startButton) { startButton = mStartButtonGreenTouch; } else { startButton = mStartButtonGreen; } } else { startButton = mStartButtonUnable; } canvas.drawBitmap(startButton, (getWidth() - startButton.getWidth()) / 2, (getHeight() - startButton.getHeight()) / 2, mBitmapPaint); mBitmapPaintStartText.setTextSize((int) (mRadiusStartButton * Math .cos(Math.toRadians(45)))); mBitmapPaintStartText.setColor(mEnable ? 0xFFFFFFFF : 0xFF000000); drawCenter(canvas, mBitmapPaintStartText, String.valueOf(mFirstValue + mExtCurrentSector)); } private void drawCenter(Canvas canvas, Paint paint, String text) { int cHeight = canvas.getClipBounds().height(); int cWidth = canvas.getClipBounds().width(); Rect r = new Rect(); paint.setTextAlign(Paint.Align.LEFT); paint.getTextBounds(text, 0, text.length(), r); float x = cWidth / 2f - r.width() / 2f - r.left; float y = cHeight / 2f + r.height() / 2f - r.bottom; canvas.drawText(text, x, y, paint); } private void drawRotateBitmap(Canvas canvas, float degree, Bitmap bitmap, Paint paint) { canvas.save(); canvas.rotate(degree, getWidth() / 2, getHeight() / 2); canvas.drawBitmap(bitmap, (getWidth() - bitmap.getWidth()) / 2, (getHeight() - bitmap.getHeight()) / 2, paint); canvas.restore(); } @Override public void run() { this.setOnTouchListener(null); mThreadStop = false; while (!Thread.interrupted()) { post(new Runnable() { public void run() { if (mThreadStop) return; float delta; float sigma; boolean end = false; if (mClock) sigma = mSigma; else sigma = -mSigma; switch (animationViewState) { case extRing: delta = Math.abs(mExtTop - mEndTop); if (delta > Math.abs(sigma)) { } else { boolean stop = false; for (int i = 1; i <= 16; i *= 2) { if (delta < Math.abs(sigma)) { sigma = mSigma / i; } else { stop = true; break; } } if (!stop) end = true; } if (end) { mThreadStop = true; thread.interrupt(); // mExtTop = mEndTop % mTotalEnableDegree; mExtTotalDegrees = mExtTop; WheelView.this.setOnTouchListener(WheelView.this); return; } mExtTop += sigma; break; case enabling: if (!mEnable) { int currentAlpha = mBitmapPaintUnable.getAlpha(); if (currentAlpha < 255) { currentAlpha += 1; mBitmapPaintUnable.setAlpha(currentAlpha); } else { mThreadStop = true; thread.interrupt(); } } else { int currentAlpha = mBitmapPaintUnable.getAlpha(); if (currentAlpha > 0) { currentAlpha -= 1; mBitmapPaintUnable.setAlpha(currentAlpha); } else { mThreadStop = true; thread.interrupt(); } } break; default: break; } WheelView.this.postInvalidate(); } }); try { Thread.sleep(DEFAULT_LOOP_INTERVAL); } catch (InterruptedException e) { mThreadStop = true; mTouch = Touchs.nothing; WheelView.this.postInvalidate(); this.setOnTouchListener(WheelView.this); break; } } } public int getExtAnglePerSector() { return mExtAnglePerSector; } public Touchs getTouchState() { return mTouch; } }
package com.nokia.springboot.training.d04.s02.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.Date; @Service public class SimpleScheduledTasks { private static final Logger LOGGER = LoggerFactory.getLogger(SimpleScheduledTasks.class); @Scheduled(cron = "2 * * * * MON-FRI") // every two minutes, from Monday to Friday public void cronTask() { LOGGER.info("[cronTask] Running at {}...", new Date()); } @Scheduled(fixedDelay = 10000) // 10 seconds public void fixedDelayTask() { LOGGER.info("[fixedDelayTask] Running at {}...", new Date()); } @Scheduled(fixedRate = 10000) // every 10 seconds public void fixedRateTask() { LOGGER.info("[fixedRateTask] Running at {}...", new Date()); } @Scheduled(fixedDelayString = "10000") // 10 seconds public void initialDelayTask() { LOGGER.info("[initialDelayTask] Running at {}...", new Date()); } }
package org.frontcache.cache.impl.lucene; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import org.frontcache.FCConfig; import org.frontcache.cache.CacheProcessor; import org.frontcache.cache.CacheProcessorBase; import org.frontcache.core.WebResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Cache processor based on Apache Lucene. * */ public class LuceneCacheProcessor extends CacheProcessorBase implements CacheProcessor { private static final Logger logger = LoggerFactory.getLogger(LuceneCacheProcessor.class); private LuceneIndexManager indexManager; private static String CACHE_BASE_DIR_DEFAULT = "/tmp/cache/"; private static final String CACHE_BASE_DIR_KEY = "front-cache.cache-processor.impl.cache-dir"; // to override path in configs private static String CACHE_RELATIVE_DIR = "cache/lucene-index/"; private static String INDEX_BASE_DIR = CACHE_BASE_DIR_DEFAULT + CACHE_RELATIVE_DIR; @Override public void init(Properties properties) { Objects.requireNonNull(properties, "Properties should not be null"); if (null != properties.getProperty(CACHE_BASE_DIR_KEY)) { CACHE_BASE_DIR_DEFAULT = properties.getProperty(CACHE_BASE_DIR_KEY); INDEX_BASE_DIR = CACHE_BASE_DIR_DEFAULT + CACHE_RELATIVE_DIR; } else { // get from FRONTCACHE_HOME String frontcacheHome = System.getProperty(FCConfig.FRONT_CACHE_HOME_SYSTEM_KEY); File fsBaseDir = new File(new File(frontcacheHome), CACHE_RELATIVE_DIR); INDEX_BASE_DIR = fsBaseDir.getAbsolutePath(); if (!INDEX_BASE_DIR.endsWith("/")) INDEX_BASE_DIR += "/"; } indexManager = new LuceneIndexManager(INDEX_BASE_DIR); } @Override public void destroy() { indexManager.close(); } public LuceneIndexManager getIndexManager(){ return indexManager; } /** * Saves web response to cache-file */ @Override public void putToCache(String url, WebResponse component) { try { indexManager.indexDoc(component); } catch (IOException e) { logger.error("Error during putting response to cache", e); } } /** * Load web-response from file */ @Override public WebResponse getFromCacheImpl(String url) { logger.debug("Getting from cache {}", url); WebResponse webResponse = indexManager.getResponse(url); if (webResponse.isExpired()) { removeFromCache(url); return null; } return webResponse; } @Override public void removeFromCache(String filter) { logger.debug("Removing from cache {}", filter); indexManager.delete(filter); } @Override public void removeFromCacheAll() { logger.debug("truncate cache"); indexManager.truncate(); } @Override public Map<String, String> getCacheStatus() { Map<String, String> status = super.getCacheStatus(); status.put("impl", this.getClass().getName()); status.put(CacheProcessor.CACHED_ENTRIES, "" + indexManager.getIndexSize()); return status; } @Override public List<String> getCachedKeys() { return indexManager.getKeys(); } }
package org.opendaylight.controller.flowprogrammer.northbound; import java.util.ArrayList; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import org.codehaus.enunciate.jaxrs.ResponseCode; import org.codehaus.enunciate.jaxrs.StatusCodes; import org.codehaus.enunciate.jaxrs.TypeHint; import org.opendaylight.controller.containermanager.IContainerManager; import org.opendaylight.controller.forwardingrulesmanager.FlowConfig; import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; import org.opendaylight.controller.northbound.commons.RestMessages; import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException; import org.opendaylight.controller.northbound.commons.exception.MethodNotAllowedException; import org.opendaylight.controller.northbound.commons.exception.NotAcceptableException; import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; import org.opendaylight.controller.sal.authorization.Privilege; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.utils.GlobalConstants; import org.opendaylight.controller.sal.utils.ServiceHelper; import org.opendaylight.controller.sal.utils.Status; import org.opendaylight.controller.switchmanager.ISwitchManager; /** * Flow Configuration Northbound API provides capabilities to program flows. * * <br> * <br> * Authentication scheme : <b>HTTP Basic</b><br> * Authentication realm : <b>opendaylight</b><br> * Transport : <b>HTTP and HTTPS</b><br> * <br> * HTTPS Authentication is disabled by default. * */ @Path("/") public class FlowProgrammerNorthbound { private String username; @Context public void setSecurityContext(SecurityContext context) { if (context != null && context.getUserPrincipal() != null) { username = context.getUserPrincipal().getName(); } } protected String getUserName() { return username; } private IForwardingRulesManager getForwardingRulesManagerService(String containerName) { IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( IContainerManager.class, this); if (containerManager == null) { throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString()); } boolean found = false; List<String> containerNames = containerManager.getContainerNames(); for (String cName : containerNames) { if (cName.trim().equalsIgnoreCase(containerName.trim())) { found = true; } } if (found == false) { throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString()); } IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( IForwardingRulesManager.class, containerName, this); if (frm == null) { throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); } return frm; } private List<FlowConfig> getStaticFlowsInternal(String containerName, Node node) { IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); if (frm == null) { throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); } List<FlowConfig> flows = new ArrayList<FlowConfig>(); if (node == null) { for (FlowConfig flow : frm.getStaticFlows()) { flows.add(flow); } } else { ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this); if (sm == null) { throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); } if (!sm.getNodes().contains(node)) { throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString()); } for (FlowConfig flow : frm.getStaticFlows(node)) { flows.add(flow); } } return flows; } @Path("/{containerName}") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @TypeHint(FlowConfigs.class) @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 404, condition = "The containerName is not found"), @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName) { if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container " + containerName); } List<FlowConfig> flowConfigs = getStaticFlowsInternal(containerName, null); return new FlowConfigs(flowConfigs); } @Path("/{containerName}/node/{nodeType}/{nodeId}") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @TypeHint(FlowConfigs.class) @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 404, condition = "The containerName or nodeId is not found"), @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName, @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId) { if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container " + containerName); } Node node = Node.fromString(nodeType, nodeId); if (node == null) { throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString()); } List<FlowConfig> flows = getStaticFlowsInternal(containerName, node); return new FlowConfigs(flows); } @Path("/{containerName}/node/{nodeType}/{nodeId}/staticFlow/{name}") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @TypeHint(FlowConfig.class) @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 404, condition = "The containerName or NodeId or Configuration name is not found"), @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) public FlowConfig getStaticFlow(@PathParam("containerName") String containerName, @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, @PathParam("name") String name) { if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container " + containerName); } IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); if (frm == null) { throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); } Node node = handleNodeAvailability(containerName, nodeType, nodeId); FlowConfig staticFlow = frm.getStaticFlow(name, node); if (staticFlow == null) { throw new ResourceNotFoundException(RestMessages.NOFLOW.toString()); } return new FlowConfig(staticFlow); } @Path("/{containerName}/node/{nodeType}/{nodeId}/staticFlow/{name}") @PUT @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @StatusCodes({ @ResponseCode(code = 200, condition = "Static Flow modified successfully"), @ResponseCode(code = 201, condition = "Flow Config processed successfully"), @ResponseCode(code = 400, condition = "Failed to create Static Flow entry due to invalid flow configuration"), @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 404, condition = "The Container Name or nodeId is not found"), @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"), @ResponseCode(code = 409, condition = "Failed to create Static Flow entry due to Conflicting Name or configuration"), @ResponseCode(code = 500, condition = "Failed to create Static Flow entry. Failure Reason included in HTTP Error response"), @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) public Response addOrModifyFlow(@PathParam(value = "containerName") String containerName, @PathParam(value = "name") String name, @PathParam("nodeType") String nodeType, @PathParam(value = "nodeId") String nodeId, @TypeHint(FlowConfig.class) FlowConfig flowConfig) { if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container " + containerName); } if (flowConfig.getNode() == null) { return Response.status(Response.Status.BAD_REQUEST).entity("Invalid Configuration. Node is null or empty") .build(); } handleResourceCongruence(name, flowConfig.getName()); handleResourceCongruence(nodeId, flowConfig.getNode().getNodeIDString()); handleDefaultDisabled(containerName); IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); if (frm == null) { throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); } Node node = handleNodeAvailability(containerName, nodeType, nodeId); Status status; FlowConfig staticFlow = frm.getStaticFlow(name, node); if (staticFlow == null) { status = frm.addStaticFlow(flowConfig); if(status.isSuccess()){ NorthboundUtils.auditlog("Flow Entry", username, "added", name + " on Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName); return Response.status(Response.Status.CREATED).entity("Success").build(); } } else { status = frm.modifyStaticFlow(flowConfig); if(status.isSuccess()){ NorthboundUtils.auditlog("Flow Entry", username, "updated", name + " on Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName); return NorthboundUtils.getResponse(status); } } return NorthboundUtils.getResponse(status); } @Path("/{containerName}/node/{nodeType}/{nodeId}/staticFlow/{name}") @DELETE @StatusCodes({ @ResponseCode(code = 204, condition = "Flow Config deleted successfully"), @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 404, condition = "The Container Name or Node-id or Flow Name passed is not found"), @ResponseCode(code = 406, condition = "Failed to delete Flow config due to invalid operation. Failure details included in HTTP Error response"), @ResponseCode(code = 500, condition = "Failed to delete Flow config. Failure Reason included in HTTP Error response"), @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") }) public Response deleteFlow(@PathParam(value = "containerName") String containerName, @PathParam(value = "name") String name, @PathParam("nodeType") String nodeType, @PathParam(value = "nodeId") String nodeId) { if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container " + containerName); } handleDefaultDisabled(containerName); IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); if (frm == null) { throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); } Node node = handleNodeAvailability(containerName, nodeType, nodeId); FlowConfig staticFlow = frm.getStaticFlow(name, node); if (staticFlow == null) { throw new ResourceNotFoundException(name + " : " + RestMessages.NOFLOW.toString()); } Status status = frm.removeStaticFlow(name, node); if (status.isSuccess()) { NorthboundUtils.auditlog("Flow Entry", username, "removed", name + " from Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName); return Response.noContent().build(); } return NorthboundUtils.getResponse(status); } @Path("/{containerName}/node/{nodeType}/{nodeId}/staticFlow/{name}") @POST @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @StatusCodes({ @ResponseCode(code = 200, condition = "Flow Config processed successfully"), @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 404, condition = "The Container Name or Node-id or Flow Name passed is not found"), @ResponseCode(code = 406, condition = "Failed to delete Flow config due to invalid operation. Failure details included in HTTP Error response"), @ResponseCode(code = 500, condition = "Failed to delete Flow config. Failure Reason included in HTTP Error response"), @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") }) public Response toggleFlow(@PathParam(value = "containerName") String containerName, @PathParam("nodeType") String nodeType, @PathParam(value = "nodeId") String nodeId, @PathParam(value = "name") String name) { if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container " + containerName); } handleDefaultDisabled(containerName); IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); if (frm == null) { throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); } Node node = handleNodeAvailability(containerName, nodeType, nodeId); FlowConfig staticFlow = frm.getStaticFlow(name, node); if (staticFlow == null) { throw new ResourceNotFoundException(name + " : " + RestMessages.NOFLOW.toString()); } Status status = frm.toggleStaticFlowStatus(staticFlow); if (status.isSuccess()) { NorthboundUtils.auditlog("Flow Entry", username, "toggled", name + " on Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName); } return NorthboundUtils.getResponse(status); } private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) { Node node = Node.fromString(nodeType, nodeId); if (node == null) { throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString()); } ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this); if (sm == null) { throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); } if (!sm.getNodes().contains(node)) { throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString()); } return node; } private void handleDefaultDisabled(String containerName) { IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( IContainerManager.class, this); if (containerManager == null) { throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString()); } if (containerName.equals(GlobalConstants.DEFAULT.toString()) && containerManager.hasNonDefaultContainer()) { throw new NotAcceptableException(RestMessages.DEFAULTDISABLED.toString()); } } private void handleResourceCongruence(String resource, String configured) { if (!resource.equals(configured)) { throw new MethodNotAllowedException("Path's resource name conflicts with payload's resource name"); } } }
package fr.openwide.core.wicket.markup.html.form; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IModel; import com.google.common.collect.Lists; public class ListMultipleChoice<T> extends org.apache.wicket.markup.html.form.ListMultipleChoice<T> { private static final long serialVersionUID = 8054894237478953799L; public ListMultipleChoice(String id) { super(id); } public ListMultipleChoice(String id, List<? extends T> choices) { super(id, choices); } public ListMultipleChoice(String id, IModel<? extends List<? extends T>> choices) { super(id, choices); } public ListMultipleChoice(String id, List<? extends T> choices, int maxRows) { super(id, choices, maxRows); } public ListMultipleChoice(String id, List<? extends T> choices, IChoiceRenderer<? super T> renderer) { super(id, choices, renderer); } public ListMultipleChoice(String id, IModel<? extends Collection<T>> object, List<? extends T> choices) { super(id, object, choices); } public ListMultipleChoice(String id, IModel<? extends Collection<T>> model, IModel<? extends List<? extends T>> choices) { super(id, model, choices); } public ListMultipleChoice(String id, IModel<? extends List<? extends T>> choices, IChoiceRenderer<? super T> renderer) { super(id, choices, renderer); } public ListMultipleChoice(String id, IModel<? extends Collection<T>> object, List<? extends T> choices, IChoiceRenderer<? super T> renderer) { super(id, object, choices, renderer); } public ListMultipleChoice(String id, IModel<? extends Collection<T>> model, IModel<? extends List<? extends T>> choices, IChoiceRenderer<? super T> renderer) { super(id, model, choices, renderer); } @Override public void updateModel() { Collection<T> convertedInput = getConvertedInput(); if (convertedInput == null) { convertedInput = Collections.emptyList(); } if (getModelObject() != null) { modelChanging(); setModelObject(Lists.newArrayList(convertedInput)); modelChanged(); } else { setModelObject(Lists.newArrayList(convertedInput)); } } }
package io.flutter.plugins.firebase.functions; import android.net.Uri; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.Tasks; import com.google.firebase.FirebaseApp; import com.google.firebase.functions.FirebaseFunctions; import com.google.firebase.functions.FirebaseFunctionsException; import com.google.firebase.functions.HttpsCallableReference; import com.google.firebase.functions.HttpsCallableResult; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugins.firebase.core.FlutterFirebasePlugin; import java.io.IOException; import java.io.InterruptedIOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; public class FlutterFirebaseFunctionsPlugin implements FlutterPlugin, FlutterFirebasePlugin, MethodCallHandler { private static final String METHOD_CHANNEL_NAME = "plugins.flutter.io/firebase_functions"; private MethodChannel channel; /** * Default Constructor. * * <p>Use this when adding the plugin to your FlutterEngine */ public FlutterFirebaseFunctionsPlugin() {} @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { channel = new MethodChannel(binding.getBinaryMessenger(), METHOD_CHANNEL_NAME); channel.setMethodCallHandler(this); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { channel.setMethodCallHandler(null); channel = null; } private FirebaseFunctions getFunctions(Map<String, Object> arguments) { String appName = (String) Objects.requireNonNull(arguments.get("appName")); String region = (String) Objects.requireNonNull(arguments.get("region")); FirebaseApp app = FirebaseApp.getInstance(appName); return FirebaseFunctions.getInstance(app, region); } private Task<Object> httpsFunctionCall(Map<String, Object> arguments) { return Tasks.call( cachedThreadPool, () -> { FirebaseFunctions firebaseFunctions = getFunctions(arguments); String functionName = (String) Objects.requireNonNull(arguments.get("functionName")); String origin = (String) arguments.get("origin"); Integer timeout = (Integer) arguments.get("timeout"); Object parameters = arguments.get("parameters"); if (origin != null) { Uri originUri = Uri.parse(origin); firebaseFunctions.useEmulator(originUri.getHost(), originUri.getPort()); } HttpsCallableReference httpsCallableReference = firebaseFunctions.getHttpsCallable(functionName); if (timeout != null) { httpsCallableReference.setTimeout(timeout.longValue(), TimeUnit.MILLISECONDS); } HttpsCallableResult result = Tasks.await(httpsCallableReference.call(parameters)); return result.getData(); }); } @Override public void onMethodCall(MethodCall call, @NonNull final Result result) { if (!call.method.equals("FirebaseFunctions#call")) { result.notImplemented(); return; } httpsFunctionCall(call.arguments()) .addOnCompleteListener( task -> { if (task.isSuccessful()) { result.success(task.getResult()); } else { Exception exception = task.getException(); result.error( "firebase_functions", exception != null ? exception.getMessage() : null, getExceptionDetails(exception)); } }); } private Map<String, Object> getExceptionDetails(@Nullable Exception exception) { Map<String, Object> details = new HashMap<>(); if (exception == null) { return details; } String code = "UNKNOWN"; String message = exception.getMessage(); Object additionalData = null; if (exception.getCause() instanceof FirebaseFunctionsException) { FirebaseFunctionsException functionsException = (FirebaseFunctionsException) exception.getCause(); code = functionsException.getCode().name(); message = functionsException.getMessage(); additionalData = functionsException.getDetails(); if (functionsException.getCause() instanceof IOException && "Canceled".equals(functionsException.getCause().getMessage())) { // return DEADLINE_EXCEEDED for IOException cancel errors, to match iOS & Web code = FirebaseFunctionsException.Code.DEADLINE_EXCEEDED.name(); message = FirebaseFunctionsException.Code.DEADLINE_EXCEEDED.name(); } else if (functionsException.getCause() instanceof InterruptedIOException // return DEADLINE_EXCEEDED for InterruptedIOException errors, to match iOS & Web && "timeout".equals(functionsException.getCause().getMessage())) { code = FirebaseFunctionsException.Code.DEADLINE_EXCEEDED.name(); message = FirebaseFunctionsException.Code.DEADLINE_EXCEEDED.name(); } else if (functionsException.getCause() instanceof IOException) { // return UNAVAILABLE for network io errors, to match iOS & Web code = FirebaseFunctionsException.Code.UNAVAILABLE.name(); message = FirebaseFunctionsException.Code.UNAVAILABLE.name(); } } details.put("code", code.replace("_", "-").toLowerCase()); details.put("message", message); if (additionalData != null) { details.put("additionalData", additionalData); } return details; } @Override public Task<Map<String, Object>> getPluginConstantsForFirebaseApp(FirebaseApp firebaseApp) { return Tasks.call(() -> null); } @Override public Task<Void> didReinitializeFirebaseCore() { return Tasks.call(() -> null); } }
package soot.dexpler.instructions; import org.jf.dexlib2.iface.instruction.Instruction; import org.jf.dexlib2.iface.instruction.HatLiteralInstruction; import org.jf.dexlib2.iface.instruction.NarrowLiteralInstruction; import org.jf.dexlib2.iface.instruction.TwoRegisterInstruction; import org.jf.dexlib2.iface.instruction.WideLiteralInstruction; import org.jf.dexlib2.iface.instruction.formats.Instruction22b; import org.jf.dexlib2.iface.instruction.formats.Instruction22s; import org.jf.dexlib2.Opcode; import soot.Local; import soot.Value; import soot.dexpler.DexBody; import soot.dexpler.IDalvikTyper; import soot.dexpler.tags.IntOpTag; import soot.jimple.AssignStmt; import soot.jimple.BinopExpr; import soot.jimple.IntConstant; import soot.jimple.Jimple; import soot.jimple.internal.JAssignStmt; public class BinopLitInstruction extends TaggedInstruction { Value expr = null; AssignStmt assign = null; public BinopLitInstruction (Instruction instruction, int codeAdress) { super(instruction, codeAdress); } public void jimplify (DexBody body) { if(!(instruction instanceof Instruction22s) && !(instruction instanceof Instruction22b)) throw new IllegalArgumentException("Expected Instruction22s or Instruction22b but got: "+instruction.getClass()); NarrowLiteralInstruction binOpLitInstr = (NarrowLiteralInstruction) this.instruction; int dest = ((TwoRegisterInstruction) instruction).getRegisterA(); int source = ((TwoRegisterInstruction) instruction).getRegisterB(); Local source1 = body.getRegisterLocal(source); IntConstant constant = IntConstant.v((int)binOpLitInstr.getNarrowLiteral()); expr = getExpression(source1, constant); assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), expr); assign.addTag(getTag()); setUnit(assign); tagWithLineNumber(assign); body.add(assign); } public void getConstraint(IDalvikTyper dalvikTyper) { if (IDalvikTyper.ENABLE_DVKTYPER) { int op = (int)instruction.getOpcode().value; if (!(op >= 0xd0 && op <= 0xe2)) { throw new RuntimeException ("wrong value of op: 0x"+ Integer.toHexString(op) +". should be between 0xd0 and 0xe2."); } if (op >= 0xd8) { op -= 0xd8; } else { op -= 0xd0; } BinopExpr bexpr = (BinopExpr)expr; //body.dvkTyper.setType((op == 1) ? bexpr.getOp2Box() : bexpr.getOp1Box(), op1BinType[op]); dalvikTyper.setType(((JAssignStmt)assign).leftBox, op1BinType[op]); } } private Value getExpression(Local source1, Value source2) { Opcode opcode = instruction.getOpcode(); switch(opcode) { case ADD_INT_LIT16: setTag (new IntOpTag()); case ADD_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newAddExpr(source1, source2); case RSUB_INT: setTag (new IntOpTag()); case RSUB_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newSubExpr(source2, source1); case MUL_INT_LIT16: setTag (new IntOpTag()); case MUL_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newMulExpr(source1, source2); case DIV_INT_LIT16: setTag (new IntOpTag()); case DIV_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newDivExpr(source1, source2); case REM_INT_LIT16: setTag (new IntOpTag()); case REM_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newRemExpr(source1, source2); case AND_INT_LIT8: setTag (new IntOpTag()); case AND_INT_LIT16: setTag (new IntOpTag()); return Jimple.v().newAndExpr(source1, source2); case OR_INT_LIT16: setTag (new IntOpTag()); case OR_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newOrExpr(source1, source2); case XOR_INT_LIT16: setTag (new IntOpTag()); case XOR_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newXorExpr(source1, source2); case SHL_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newShlExpr(source1, source2); case SHR_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newShrExpr(source1, source2); case USHR_INT_LIT8: setTag (new IntOpTag()); return Jimple.v().newUshrExpr(source1, source2); default : throw new RuntimeException("Invalid Opcode: " + opcode); } } @Override boolean overridesRegister(int register) { TwoRegisterInstruction i = (TwoRegisterInstruction) instruction; int dest = i.getRegisterA(); return register == dest; } }
package com.googlecode.gentyref; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; public class Issue13Test extends TestCase { /** * Test that Object is seen as superclass of any class, interface and array */ public void testObjectSuperclassOfInterface() throws NoSuchMethodException { assertEquals(Object.class, GenericTypeReflector.getExactSuperType(ArrayList.class, Object.class)); assertEquals(Object.class, GenericTypeReflector.getExactSuperType(List.class, Object.class)); assertEquals(Object.class, GenericTypeReflector.getExactSuperType(String[].class, Object.class)); } /** * Test that toString method can be resolved in any class, interface or array */ public void testObjectMethodOnInterface() throws NoSuchMethodException { Method toString = Object.class.getMethod("toString", new Class<?>[]{}); assertEquals(String.class, GenericTypeReflector.getExactReturnType(toString, ArrayList.class)); assertEquals(String.class, GenericTypeReflector.getExactReturnType(toString, List.class)); assertEquals(String.class, GenericTypeReflector.getExactReturnType(toString, String[].class)); } }
package com.matao; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class Q31_StackPushPopOrderTest { private Q31_StackPushPopOrder stackPushPopOrder; @BeforeEach void setUp() { stackPushPopOrder = new Q31_StackPushPopOrder(); } @Test void testTrue() { int[] push = {1, 2, 3, 4, 5}; int[] pop = {4, 5, 3, 2, 1}; Assertions.assertTrue(stackPushPopOrder.isPopOrder(push, pop)); } @Test void testFalse() { int[] push = {1, 2, 3, 4, 5}; int[] pop = {4, 3, 5, 1, 2}; Assertions.assertFalse(stackPushPopOrder.isPopOrder(push, pop)); } }
package com.frontend; /* * Defines elements of a GameMap */ public class GameMapEntry { private char symbol; private GameMapEntryColor color; private GameMapEntryAttribute attribute; public GameMapEntry(char symbol, GameMapEntryColor color, GameMapEntryAttribute attribute){ this.symbol=symbol; this.color=color; this.attribute=attribute; } /* * copy constructor */ public GameMapEntry(GameMapEntry other){ this.symbol=other.symbol; this.color=other.color; this.attribute=other.attribute; } //accessor methods public char getSymbol(){ return symbol; } public GameMapEntryColor getColor(){ return color; } public GameMapEntryAttribute getAttribute(){ return attribute; } }
package com.mpatric.mp3agic; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import static org.junit.Assert.*; public class FileWrapperTest { private static final String fs = File.separator; private static final String VALID_FILENAME = "src" + fs + "test" + fs + "resources" + fs + "notags.mp3"; private static final long VALID_FILE_LENGTH = 2869; private static final String NON_EXISTANT_FILENAME = "just-not.there"; private static final String MALFORMED_FILENAME = "malformed.?"; @Test public void shouldReadValidFile() throws IOException { FileWrapper fileWrapper = new FileWrapper(VALID_FILENAME); System.out.println(fileWrapper.getFilename()); System.out.println(VALID_FILENAME); assertEquals(fileWrapper.getFilename(), VALID_FILENAME); assertTrue(fileWrapper.getLastModified() > 0); assertEquals(fileWrapper.getLength(), VALID_FILE_LENGTH); } @Test(expected = FileNotFoundException.class) public void testShouldFailForNonExistentFile() throws IOException { new FileWrapper(NON_EXISTANT_FILENAME); } @Test(expected = FileNotFoundException.class) public void testShouldFailForMalformedFilename() throws IOException { new FileWrapper(MALFORMED_FILENAME); } @Test(expected = NullPointerException.class) public void testShouldFailForNullFilename() throws IOException { new FileWrapper((String) null); } @Test(expected = NullPointerException.class) public void testShouldFailForNullFilenameFile() throws IOException { new FileWrapper((java.io.File) null); } }
package com.rabidgremlin.mutters.ml; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.number.IsCloseTo.*; import static org.junit.Assert.*; import java.net.URL; import org.junit.Test; import opennlp.tools.namefind.NameFinderME; import opennlp.tools.namefind.TokenNameFinderModel; import opennlp.tools.tokenize.SimpleTokenizer; import opennlp.tools.util.Span; public class TestNER { @Test public void testModelLoad() throws Exception { URL modelUrl = Thread.currentThread().getContextClassLoader().getResource("models/en-ner-persons.bin"); assertThat(modelUrl,is(notNullValue())); TokenNameFinderModel model = new TokenNameFinderModel(modelUrl); assertThat(model,is(notNullValue())); } @Test public void testPersonNER() throws Exception { URL modelUrl = Thread.currentThread().getContextClassLoader().getResource("models/en-ner-persons.bin"); assertThat(modelUrl,is(notNullValue())); TokenNameFinderModel model = new TokenNameFinderModel(modelUrl); assertThat(model,is(notNullValue())); NameFinderME nameFinder = new NameFinderME(model); String[] tokens = SimpleTokenizer.INSTANCE.tokenize("Mr. John Smith of New York, married Anne Green of London today."); assertThat(tokens.length,is(15)); Span[] spans = nameFinder.find(tokens); assertThat(spans.length,is(2)); String[] names = Span.spansToStrings(spans, tokens); assertThat(names.length,is(2)); assertThat(names[0],is("John Smith")); assertThat(names[1],is("Anne Green")); } @Test public void testLocationNER() throws Exception { URL modelUrl = Thread.currentThread().getContextClassLoader().getResource("models/en-ner-locations.bin"); assertThat(modelUrl,is(notNullValue())); TokenNameFinderModel model = new TokenNameFinderModel(modelUrl); assertThat(model,is(notNullValue())); NameFinderME nameFinder = new NameFinderME(model); String[] tokens = SimpleTokenizer.INSTANCE.tokenize("Mr. John Smith of New York, married Anne Green of London today."); assertThat(tokens.length,is(15)); Span[] spans = nameFinder.find(tokens); assertThat(spans.length,is(2)); String[] locations = Span.spansToStrings(spans, tokens); assertThat(locations.length,is(2)); assertThat(locations[0],is("New York")); assertThat(locations[1],is("London")); } @Test public void testDateNER() throws Exception { URL modelUrl = Thread.currentThread().getContextClassLoader().getResource("models/en-ner-dates.bin"); assertThat(modelUrl,is(notNullValue())); TokenNameFinderModel model = new TokenNameFinderModel(modelUrl); assertThat(model,is(notNullValue())); NameFinderME nameFinder = new NameFinderME(model); String[] tokens = SimpleTokenizer.INSTANCE.tokenize("Mr. John Smith of New York, married Anne Green of London today."); assertThat(tokens.length,is(15)); Span[] spans = nameFinder.find(tokens); assertThat(spans.length,is(1)); String[] locations = Span.spansToStrings(spans, tokens); assertThat(locations.length,is(1)); assertThat(locations[0],is("today")); } @Test public void testAddressNER() throws Exception { URL modelUrl = Thread.currentThread().getContextClassLoader().getResource("models/en-ner-locations.bin"); assertThat(modelUrl,is(notNullValue())); TokenNameFinderModel model = new TokenNameFinderModel(modelUrl); assertThat(model,is(notNullValue())); NameFinderME nameFinder = new NameFinderME(model); String[] tokens = SimpleTokenizer.INSTANCE.tokenize("Send a taxi to 12 Pleasent Street"); Span[] spans = nameFinder.find(tokens); assertThat(spans.length,is(1)); String[] locations = Span.spansToStrings(spans, tokens); assertThat(locations.length,is(1)); assertThat(locations[0],is("12 Pleasent Street")); } }
package com.slickqa.client.impl; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.slickqa.client.SlickClient; import com.slickqa.client.errors.SlickCommunicationError; import mockit.*; import org.junit.Before; import org.junit.Test; import javax.swing.text.html.parser.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.URI; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; /** * Tests for com.slickqa.client.impl.ApiPart */ public class ApiPartTest { @Injectable ParentApiPart parent; @Injectable WebTarget webTarget; @Injectable SlickClient client; @Injectable ObjectMapper mapper; @Injectable Invocation.Builder builder; @Injectable Response response; String jsonResponseString = "{}"; ApiPart<Object> apiPart; JavaType objectType; @Before public void setUp() { final ObjectMapper realMapper = JsonUtil.getObjectMapper(); objectType = realMapper.constructType(Object.class); new NonStrictExpectations() {{ mapper.constructType(Object.class); result = realMapper.constructType(Object.class); mapper.getTypeFactory(); result = realMapper.getTypeFactory(); }}; apiPart = new ApiPart<>(Object.class, parent, mapper); } @Test public void getParentTest() { ParentApiPart retval = apiPart.getParent(); assertNotNull("The parent of the apiPart should be the one injected, not null.", retval); assertSame("The parent of the apiPart should be the one injected.", retval, parent); } @Test public void getWebTargetPassThroughTest() throws Exception { new NonStrictExpectations() {{ parent.getWebTarget(); result = webTarget; }}; WebTarget retval = apiPart.getWebTarget(); assertNotNull("A non null webtarget should be returned from getWebTarget().", retval); assertSame("The web target returned from getWebTarget should be the one from the parent, this apipart has nothing to add.", retval, webTarget); } @Test public void getSlickClientPassThroughTest() { new NonStrictExpectations() {{ parent.getSlickClient(); result = client; }}; SlickClient retval = apiPart.getSlickClient(); assertNotNull("A non null slick client should be returned from getSlickClient().", retval); assertSame("The slick client returned from getSlickClient should be the one from the parent, this apipart should just return it.", retval, client); } @Test public void deleteNormalWorkflow() throws Exception { new Expectations() {{ parent.getWebTarget(); result = webTarget; webTarget.request(); result = builder; builder.method("DELETE"); result = response; response.getStatus(); result = 200; }}; apiPart.delete(); } @Test(expected = SlickCommunicationError.class) public void deleteErrorReturned() throws Exception { new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; builder.method("DELETE"); result = response; response.getStatus(); result = 500; }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.delete(); } @Test public void getObjectNormalWorkflow() throws Exception { final Object expectedResult = new Object(); new Expectations() {{ parent.getWebTarget(); result = webTarget; webTarget.request(); result = builder; builder.method("GET"); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); result = expectedResult; }}; Object retval = apiPart.get(); assertSame("Instance should be the same instance that is returned from the mapper.", retval, expectedResult); } @Test(expected = SlickCommunicationError.class) public void getObjectBadResponseCode() throws Exception { new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; builder.method("GET"); result = response; response.getStatus(); result = 500; }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.get(); } @Test(expected = SlickCommunicationError.class) public void getObjectMapperError() throws Exception { new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; builder.method("GET"); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); //mapper.readValue(jsonResponseString, withAny(TypeReference.class)); result = new JsonMappingException(""); }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.get(); } @Test public void updateObjectNormalWorkflow() throws Exception { final Object expectedResult = new Object(); final Object toUpdate = new Object(); final String updateJson = "foo"; new Expectations() {{ parent.getWebTarget(); result = webTarget; webTarget.request(); result = builder; mapper.writeValueAsString(withSameInstance(toUpdate)); result = updateJson; builder.method("PUT", withAny(javax.ws.rs.client.Entity.entity(updateJson, MediaType.APPLICATION_JSON))); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); result = expectedResult; }}; Object retval = apiPart.update(toUpdate); assertSame("Instance should be the same instance that is returned from the mapper.", retval, expectedResult); } @Test(expected = SlickCommunicationError.class) public void updateObjectBadResponseCode() throws Exception { final Object toUpdate = new Object(); final String updateJson = "foo"; new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; mapper.writeValueAsString(withSameInstance(toUpdate)); result = updateJson; builder.method("PUT", withAny(javax.ws.rs.client.Entity.entity(updateJson, MediaType.APPLICATION_JSON))); result = response; response.getStatus(); result = 500; }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.update(toUpdate); } @Test(expected = SlickCommunicationError.class) public void updateObjectMapperError() throws Exception { final Object toUpdate = new Object(); final String updateJson = "foo"; new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; mapper.writeValueAsString(withSameInstance(toUpdate)); result = updateJson; builder.method("PUT", withAny(javax.ws.rs.client.Entity.entity(updateJson, MediaType.APPLICATION_JSON))); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); result = new JsonMappingException(""); }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.update(toUpdate); } @Test public void getListNormalWorkflow() throws Exception { final List<Object> expectedResult = new ArrayList<>(); new Expectations() {{ parent.getWebTarget(); result = webTarget; webTarget.request(); result = builder; builder.method("GET"); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); result = expectedResult; }}; List<Object> retval = apiPart.getList(); assertSame("Instance should be the same instance that is returned from the mapper.", retval, expectedResult); } @Test(expected = SlickCommunicationError.class) public void getListBadResponseCode() throws Exception { new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; builder.method("GET"); result = response; response.getStatus(); result = 500; }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.getList(); } @Test(expected = SlickCommunicationError.class) public void getListMapperError() throws Exception { new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; builder.method("GET"); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); //mapper.readValue(jsonResponseString, withAny(TypeReference.class)); result = new JsonMappingException(""); }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.getList(); } @Test public void createObjectNormalWorkflow() throws Exception { final Object expectedResult = new Object(); final Object toUpdate = new Object(); final String updateJson = "foo"; new Expectations() {{ parent.getWebTarget(); result = webTarget; webTarget.request(); result = builder; mapper.writeValueAsString(withSameInstance(toUpdate)); result = updateJson; builder.method("POST", withAny(javax.ws.rs.client.Entity.entity(updateJson, MediaType.APPLICATION_JSON))); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); result = expectedResult; }}; Object retval = apiPart.create(toUpdate); assertSame("Instance should be the same instance that is returned from the mapper.", retval, expectedResult); } @Test(expected = SlickCommunicationError.class) public void createObjectBadResponseCode() throws Exception { final Object toUpdate = new Object(); final String updateJson = "foo"; new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; mapper.writeValueAsString(withSameInstance(toUpdate)); result = updateJson; builder.method("POST", withAny(javax.ws.rs.client.Entity.entity(updateJson, MediaType.APPLICATION_JSON))); result = response; response.getStatus(); result = 500; }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.create(toUpdate); } @Test(expected = SlickCommunicationError.class) public void createObjectMapperError() throws Exception { final Object toUpdate = new Object(); final String updateJson = "foo"; new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; mapper.writeValueAsString(withSameInstance(toUpdate)); result = updateJson; builder.method("POST", withAny(javax.ws.rs.client.Entity.entity(updateJson, MediaType.APPLICATION_JSON))); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); result = new JsonMappingException(""); }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; apiPart.create(toUpdate); } @Test public void findOrCreateFoundItem() throws Exception { final Object expectedResult = new Object(); new Expectations() {{ parent.getWebTarget(); result = webTarget; webTarget.request(); result = builder; builder.method("GET"); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); result = expectedResult; }}; Object retval = apiPart.findOrCreate(new Object()); assertSame("Instance should be the same instance that is returned from the mapper.", retval, expectedResult); } @Test public void findOrCreateMustCreate() throws Exception { final Object passedIn = new Object(); final Object expected = new Object(); new Expectations() {{ parent.getWebTarget(); result = webTarget; }}; // retry up to 3 times when we get an error new Expectations(3) {{ webTarget.request(); result = builder; builder.method("GET"); result = response; response.getStatus(); result = 404; }}; new Expectations() {{ webTarget.getUri(); result = new URI("http://foo/bar"); }}; final String updateJson = "foo"; new Expectations() {{ parent.getWebTarget(); result = webTarget; webTarget.request(); result = builder; mapper.writeValueAsString(withSameInstance(passedIn)); result = updateJson; builder.method("POST", withAny(javax.ws.rs.client.Entity.entity(updateJson, MediaType.APPLICATION_JSON))); result = response; response.getStatus(); result = 200; response.readEntity(String.class); result = jsonResponseString; mapper.readValue(jsonResponseString, withAny(objectType)); result = expected; }}; Object retval = apiPart.findOrCreate(passedIn); assertSame("Instance should be the same instance that is returned from the mapper.", retval, expected); } }
package com.suse.salt.netapi.examples; import com.suse.salt.netapi.AuthModule; import com.suse.salt.netapi.calls.WheelResult; import com.suse.salt.netapi.calls.modules.Grains; import com.suse.salt.netapi.calls.modules.Test; import com.suse.salt.netapi.calls.wheel.Key; import com.suse.salt.netapi.client.SaltClient; import com.suse.salt.netapi.datatypes.target.Glob; import com.suse.salt.netapi.datatypes.target.MinionList; import com.suse.salt.netapi.datatypes.target.Target; import com.suse.salt.netapi.exception.SaltException; import com.suse.salt.netapi.results.Result; import java.net.URI; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Example code calling salt modules using the generic interface. */ public class Calls { private static final String SALT_API_URL = "http://localhost:8000"; private static final String USER = "saltdev"; private static final String PASSWORD = "saltdev"; public static void main(String[] args) throws SaltException { // Init the client SaltClient client = new SaltClient(URI.create(SALT_API_URL)); // Ping all minions using a glob matcher Target<String> globTarget = new Glob("*"); Map<String, Result<Boolean>> results = Test.ping().callSync( client, globTarget, USER, PASSWORD, AuthModule.AUTO); System.out.println("--> Ping results:\n"); results.forEach((minion, result) -> System.out.println(minion + " -> " + result)); // Get the grains from a list of minions Target<List<String>> minionList = new MinionList("minion1", "minion2"); Map<String, Result<Map<String, Object>>> grainResults = Grains.items(false) .callSync(client, minionList, USER, PASSWORD, AuthModule.AUTO); grainResults.forEach((minion, grains) -> { System.out.println("\n--> Listing grains for '" + minion + "':\n"); String grainsOutput = grains.fold( error -> "Error: " + error.toString(), grainsMap -> grainsMap.entrySet().stream() .map(e -> e.getKey() + ": " + e.getValue()) .collect(Collectors.joining("\n")) ); System.out.println(grainsOutput); }); // Call a wheel function: list accepted and pending minion keys WheelResult<Key.Names> keyResults = Key.listAll().callSync( client, USER, PASSWORD, AuthModule.AUTO); Key.Names keys = keyResults.getData().getResult(); System.out.println("\n--> Accepted minion keys:\n"); keys.getMinions().forEach(System.out::println); System.out.println("\n--> Pending minion keys:\n"); keys.getUnacceptedMinions().forEach(System.out::println); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package perudo; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; public class Perudo { public List<Player> players; public Bet currentbet; public Bet previousbet; private int currentplayer; public GameState g; public Perudo(){ players = new ArrayList<Player>(); currentbet= new Bet(5,0); currentplayer = 0; } public void newGame(){ Random ran = new Random(); for(Player p:players){ p.getFiveDices(); //p.reInitStats(); } currentbet= new Bet(5,0); currentplayer = ran.nextInt(players.size()); Collections.shuffle(players); } public void addPlayer(Player p){ players.add(p); } public boolean currentPlayerWin(){ return countDice(previousbet.getDice()) <= previousbet.getNbDice(); } public int countDice(int d){ int count = 0; for(Player p:players){ count += p.countDice(d); } return count; } public void goNextPlayer(){ do{ currentplayer++; currentplayer%=players.size(); }while(players.get(currentplayer).dicesLeft()==0); } public Player currentPlayer(){ return players.get(currentplayer); } public Player previousPlayer(){ int c= currentplayer; do{ c if(c < 0)c = players.size()-1; }while(players.get(c).dicesLeft()==0); return players.get(c); } public void shuffleAll(){ for(Player p:players){ p.shuffleDices(); } } public boolean isGameFinished(){ int playerStillAlive=0; for(Player p:this.players){ if(p.dicesLeft()>0){ playerStillAlive++; } } return playerStillAlive<2; } public int playerLeft(){ int playerStillAlive=0; for(Player p:this.players){ if(p.dicesLeft()>0){ playerStillAlive++; } } return playerStillAlive; } public void runOnce(){ previousbet= currentbet; currentbet=players.get(currentplayer).decide(); if(currentbet.isDudo()){ if(currentPlayerWin()){ //System.out.println("Player "+currentplayer+" win"); previousPlayer().removeDice(); previousPlayer().updateTurn(0); for(Player p : players){ if(p!=previousPlayer()&&p!=currentPlayer())p.updateTurn(1); if(p==currentPlayer()){ p.updateTurn(1); } } currentplayer = currentplayer-1; if(currentplayer<0)currentplayer = players.size()-1; currentbet = new Bet(5,0); }else{ currentPlayer().removeDice(); currentPlayer().updateTurn(0); for(Player p : players){ if(p!=currentPlayer())p.updateTurn(1); } //System.out.println("Player "+currentplayer+" lose"); currentbet = new Bet(5,0); } shuffleAll(); //System.out.println(players.get(0).state.totalDices()); }else if(currentbet.isPerudo()){ if(this.countDice(previousbet.getDice())==previousbet.getNbDice()){ currentPlayer().addDice(); currentbet = new Bet(5,0); }else{ currentPlayer().removeDice(); currentbet = new Bet(5,0); } }else{ goNextPlayer(); } } public void run(){ for(int i=0;i<7500000;i++){ while(!isGameFinished())runOnce(); for(Player p : players){ if(p.dicesLeft()>0){ p.updateGame(2); p.addGameResult(true); }else{ p.updateGame(0); p.addGameResult(false); } p.endOfGame(); } if(i%10000==0){ LearningPlayer l=null; SmartPlayer s = null; for(Player p : players){ if(p.name=="Learning"){ l = (LearningPlayer)p; //System.out.print(i/10000+" "+(int)(l.wins)+" "+l.states.size()); } else if(p.name=="Smart"){ s = (SmartPlayer)p; //System.out.print(" "+(int)(p.wins)); }else{ p.reInitStats(); } } System.out.println(i/10000+" "+(int)(l.wins)+" "+(int)(s.wins)+" "+l.states.size()); s.reInitStats(); l.reInitStats(); } /*if(i==1000000){ Player remove=null; for(Player p:players){ if(p.name=="Random"){ remove=p; } } //players.remove(remove); players.add(new SmartPlayer("Random2", g)); }*/ newGame(); } } public static void main(String[]argv){ Perudo p = new Perudo(); GameState g = new GameState(p); //p.addPlayer(new RandomPlayer("Random1", g)); p.addPlayer(new LearningPlayer("Learning", g,10)); //p.addPlayer(new LearningPlayer("RL1", g,2)); p.addPlayer(new SmartPlayer("Smart", g)); p.addPlayer(new RandomPlayer("Random", g)); /*p.addPlayer(new SmartPlayer("Smart3", g)); p.addPlayer(new SmartPlayer("Smart4", g)); p.addPlayer(new SmartPlayer("Smart5", g));*/ /* p.addPlayer(new RandomPlayer("R1", g)); p.addPlayer(new RandomPlayer("R2", g)); p.addPlayer(new RandomPlayer("R3", g)); p.addPlayer(new RandomPlayer("R4", g)); p.addPlayer(new RandomPlayer("R5", g));*/ p.run(); } }
package com.vdurmont.emoji; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.Collection; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @RunWith(JUnit4.class) public class EmojiManagerTest { @Test public void getForTag_with_unknown_tag_returns_null() { // GIVEN // WHEN Set<Emoji> emojis = EmojiManager.getForTag("jkahsgdfjksghfjkshf"); // THEN assertNull(emojis); } @Test public void getForTag_returns_the_emojis_for_the_tag() { // GIVEN // WHEN Set<Emoji> emojis = EmojiManager.getForTag("happy"); // THEN assertEquals(4, emojis.size()); assertTrue(TestTools.containsEmojis( emojis, "smile", "smiley", "grinning", "satisfied" )); } @Test public void getForTag_returns_the_eu_emoji_for_same_tag() { // GIVEN // WHEN Set<Emoji> emojis = EmojiManager.getForTag("european union"); // THEN assertEquals(1, emojis.size()); assertTrue(TestTools.containsEmojis(emojis, "eu")); } @Test public void getForAlias_with_unknown_alias_returns_null() { // GIVEN // WHEN Emoji emoji = EmojiManager.getForAlias("jkahsgdfjksghfjkshf"); // THEN assertNull(emoji); } @Test public void getForAlias_returns_the_emoji_for_the_alias() { // GIVEN // WHEN Emoji emoji = EmojiManager.getForAlias("smile"); // THEN assertEquals( "smiling face with open mouth and smiling eyes", emoji.getDescription() ); } @Test public void getForAlias_with_colons_returns_the_emoji_for_the_alias() { // GIVEN // WHEN Emoji emoji = EmojiManager.getForAlias(":smile:"); // THEN assertEquals( "smiling face with open mouth and smiling eyes", emoji.getDescription() ); } @Test public void isEmoji_for_an_emoji_returns_true() { // GIVEN String emoji = ""; // WHEN boolean isEmoji = EmojiManager.isEmoji(emoji); // THEN assertTrue(isEmoji); } @Test public void isEmoji_with_fitzpatric_modifier_returns_true() { // GIVEN String emoji = "\uD83E\uDD30\uD83C\uDFFB"; // WHEN boolean isEmoji = EmojiManager.isEmoji(emoji); // THEN assertTrue(isEmoji); } @Test public void isEmoji_for_a_non_emoji_returns_false() { // GIVEN String str = "test"; // WHEN boolean isEmoji = EmojiManager.isEmoji(str); // THEN assertFalse(isEmoji); } @Test public void isEmoji_for_an_emoji_and_other_chars_returns_false() { // GIVEN String str = " test"; // WHEN boolean isEmoji = EmojiManager.isEmoji(str); // THEN assertFalse(isEmoji); } @Test public void isOnlyEmojis_for_an_emoji_returns_true() { // GIVEN String str = ""; // WHEN boolean isEmoji = EmojiManager.isOnlyEmojis(str); // THEN assertTrue(isEmoji); } @Test public void isOnlyEmojis_for_emojis_returns_true() { // GIVEN String str = ""; // WHEN boolean isEmoji = EmojiManager.isOnlyEmojis(str); // THEN assertTrue(isEmoji); } @Test public void isOnlyEmojis_for_random_string_returns_false() { // GIVEN String str = "a"; // WHEN boolean isEmoji = EmojiManager.isOnlyEmojis(str); // THEN assertFalse(isEmoji); } @Test public void getAllTags_returns_the_tags() { // GIVEN // WHEN Collection<String> tags = EmojiManager.getAllTags(); // THEN // We know the number of distinct tags int the...! assertEquals(656, tags.size()); } @Test public void getAll_doesnt_return_duplicates() { // GIVEN // WHEN Collection<Emoji> emojis = EmojiManager.getAll(); // THEN Set<String> unicodes = new HashSet<String>(); for (Emoji emoji : emojis) { assertFalse( "Duplicate: " + emoji.getDescription(), unicodes.contains(emoji.getUnicode()) ); unicodes.add(emoji.getUnicode()); } assertEquals(unicodes.size(), emojis.size()); } @Test public void no_duplicate_alias() { // GIVEN // WHEN Collection<Emoji> emojis = EmojiManager.getAll(); // THEN Set<String> aliases = new HashSet<String>(); Set<String> duplicates = new HashSet<String>(); for (Emoji emoji : emojis) { for (String alias : emoji.getAliases()) { if (aliases.contains(alias)) { duplicates.add(alias); } aliases.add(alias); } } assertEquals("Duplicates: " + duplicates, duplicates.size(), 0); } }
package com.tinkerpop.gremlin.process.util; import com.tinkerpop.gremlin.process.Traversal; import com.tinkerpop.gremlin.process.Traverser; import com.tinkerpop.gremlin.process.TraverserGenerator; import com.tinkerpop.gremlin.util.function.CloneableLambda; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; public class TraversalObjectLambda<S, E> implements Function<S, E>, Predicate<S>, Consumer<S>, Cloneable, CloneableLambda { private Traversal.Admin<S, E> traversal; private TraverserGenerator generator; public TraversalObjectLambda(final Traversal<S, E> traversal) { this.traversal = traversal.asAdmin(); this.generator = this.traversal.getTraverserGenerator(); } // function @Override public E apply(final S start) { this.traversal.reset(); this.traversal.addStart(this.generator.generate(start, this.traversal.getStartStep(), 1l)); return this.traversal.next(); } // predicate @Override public boolean test(final S start) { this.traversal.reset(); this.traversal.addStart(this.generator.generate(start, this.traversal.getStartStep(), 1l)); return this.traversal.hasNext(); } // consumer @Override public void accept(final S start) { this.traversal.reset(); this.traversal.addStart(this.generator.generate(start, this.traversal.getStartStep(), 1l)); this.traversal.iterate(); } public Traversal<S, E> getTraversal() { return this.traversal; } @Override public String toString() { return this.traversal.toString(); } @Override public TraversalObjectLambda<S, E> clone() throws CloneNotSupportedException { final TraversalObjectLambda<S, E> clone = (TraversalObjectLambda<S, E>) super.clone(); clone.traversal = this.traversal.clone().asAdmin(); clone.generator = clone.traversal.getTraverserGenerator(); return clone; } @Override public TraversalObjectLambda<S, E> cloneLambda() throws CloneNotSupportedException { return this.clone(); } }
package edu.rosehulman.minijavac; import com.google.common.io.Files; import edu.rosehulman.minijavac.generated.Lexer; import edu.rosehulman.minijavac.generated.Parser; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Collection; import java.util.List; @RunWith(value = Parameterized.class) public class ParserTest { private static final String INPUT_FOLDER = "src/test/resources/parser/java"; private static final String OUTPUT_FOLDER = "src/test/resources/parser/out"; private static final String OUTPUT_EXTENSION = ".out"; @Parameterized.Parameters(name = "{0}") public static Collection<File[]> testCases() { List<File[]> fileCollection = new ArrayList<>(); for (File testFile : Files.fileTreeTraverser().children(new File(INPUT_FOLDER))) { File outputFile = new File(OUTPUT_FOLDER, Files.getNameWithoutExtension(testFile.getName()) + OUTPUT_EXTENSION); File[] filePair = {testFile, outputFile}; fileCollection.add(filePair); } return fileCollection; } private final File testFile; private final File outputFile; public ParserTest(File testFile, File outputFile) { this.testFile = testFile; this.outputFile = outputFile; } @Test public void test() throws Exception { Lexer lexer = new Lexer(new FileReader(testFile)); Parser parser = new Parser(lexer); parser.parse(); } }
package me.andrz.builder.map; import org.junit.Test; import java.util.AbstractMap; import java.util.HashMap; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import org.hamcrest.Matchers; public class MapBuilderTest { private static class Animal {} private static class Dog extends Animal {} @Test public void testMapBuilder() { Map<String,Integer> m = new MapBuilder<String,Integer>() .put("a", 1) .p("b", 2) .putAll(new HashMap<String, Integer>()) .put(new AbstractMap.SimpleEntry<String,Integer>("c", 3)) .build(); assertThat(m, Matchers.hasKey("a")); assertThat(m, Matchers.hasKey("b")); assertThat(m, Matchers.hasKey("c")); assertThat(m, Matchers.hasValue(1)); System.out.println(m); } @Test public void testMapBuilderExtends() { Animal d = new Dog(); Map<String,Animal> m = new MapBuilder<String,Animal>(new HashMap<String, Animal>()) .put("a", new Animal()) .p("b", d) .putAll(new HashMap<String, Dog>()) .put(new AbstractMap.SimpleEntry<String,Animal>("c", new Animal())) .p(new AbstractMap.SimpleEntry<String,Animal>("d", new Dog())) .build(); assertThat(m, Matchers.hasKey("a")); assertThat(m, Matchers.hasKey("b")); assertThat(m, Matchers.hasKey("c")); assertThat(m, Matchers.hasKey("d")); assertThat(m, Matchers.hasValue(d)); System.out.println(m); } @Test public void testMapBuilderClass() throws InstantiationException, IllegalAccessException { Animal d = new Dog(); Map<String,Animal> m = new MapBuilder<String, Animal>(HashMap.class) .put("a", new Animal()) .p("b", d) .putAll(new HashMap<String, Dog>()) .put(new AbstractMap.SimpleEntry<String,Animal>("c", new Animal())) .p(new AbstractMap.SimpleEntry<String,Animal>("d", new Dog())) .build(); assertThat(m, Matchers.hasKey("a")); assertThat(m, Matchers.hasKey("b")); assertThat(m, Matchers.hasKey("c")); assertThat(m, Matchers.hasKey("d")); assertThat(m, Matchers.hasValue(d)); System.out.println(m); } @Test public void testMapBuilderRemove() throws InstantiationException, IllegalAccessException { Map<String,Integer> em = new HashMap<String,Integer>(); em.put("a", 1); Map<String,Integer> m = new MapBuilder<String,Integer>(em) .remove("a") .build(); assertThat(m.keySet(), Matchers.empty()); assertThat(m.values(), Matchers.empty()); System.out.println(m); } }
package net.sf.gaboto.test; import java.util.Collection; import java.util.HashSet; import junit.framework.TestCase; import org.junit.BeforeClass; import org.junit.Test; import org.oucs.gaboto.GabotoConfiguration; import org.oucs.gaboto.GabotoLibrary; import org.oucs.gaboto.beans.Location; import org.oucs.gaboto.entities.Building; import org.oucs.gaboto.entities.Carpark; import org.oucs.gaboto.entities.Unit; import org.oucs.gaboto.entities.pool.GabotoEntityPool; import org.oucs.gaboto.exceptions.EntityAlreadyExistsException; import org.oucs.gaboto.model.Gaboto; import org.oucs.gaboto.model.GabotoFactory; import org.oucs.gaboto.model.GabotoSnapshot; import org.oucs.gaboto.model.QuerySolutionProcessor; import org.oucs.gaboto.timedim.TimeInstant; import org.oucs.gaboto.timedim.TimeSpan; import org.oucs.gaboto.util.GabotoPredefinedQueries; import org.oucs.gaboto.vocabulary.OxPointsVocab; import com.hp.hpl.jena.query.QuerySolution; public class TestGabotoEntity extends TestCase { static Gaboto oxp = null; @BeforeClass public void setUp() throws Exception { GabotoLibrary.init(GabotoConfiguration.fromConfigFile()); //oxp = GabotoFactory.getPersistentGaboto(); oxp = GabotoFactory.getInMemoryGaboto(); } @Test public void testGetPropertyValue(){ Building b = new Building(); b.setTimeSpan(new TimeSpan(1900,null,null)); b.setName("Test Building"); Location loc = new Location(); loc.setPos("50.12312414234 0.12312432"); b.setLocation(loc); Building b2 = new Building(); b2.setTimeSpan(new TimeSpan(1900,null,null)); b2.setName("Test Building 2"); Location loc2 = new Location(); loc2.setPos("57.1239812 21.123987"); b2.setLocation(loc2); Unit u = new Unit(); u.setUri(oxp.generateID()); u.setTimeSpan(new TimeSpan(1900,null,null)); u.setName("Test Unit"); u.setPrimaryPlace(b); Unit u2 = new Unit(); u2.setUri(oxp.generateID()); u2.setTimeSpan(new TimeSpan(1900,null,null)); u2.setName("Test Unit"); u2.setPrimaryPlace(b2); Unit u3 = new Unit(); u3.setUri(oxp.generateID()); u3.setTimeSpan(new TimeSpan(1900,null,null)); u3.setName("Test Unit"); u3.setSubsetOf(u2); assertEquals(loc, u.getPropertyValue(OxPointsVocab.hasLocation_URI)); assertEquals(loc2, u3.getPropertyValue(OxPointsVocab.hasLocation_URI)); } @Test public void testGetPropertyValue2() throws EntityAlreadyExistsException{ oxp = GabotoFactory.getPersistentGaboto(); Gaboto oxp_mem = GabotoFactory.getInMemoryGaboto(); Building b = new Building(); b.setUri(oxp.generateID()); b.setTimeSpan(new TimeSpan(1900,null,null)); b.setName("Test Building"); Location loc = new Location(); loc.setPos("50.12312414234 0.12312432"); b.setLocation(loc); Unit u = new Unit(); u.setUri(oxp.generateID()); u.setTimeSpan(new TimeSpan(1900,null,null)); u.setName("Test Unit"); u.addOccupiedBuilding(b); // add to data store oxp.add(b); oxp.add(u); // create pool for passive properties GabotoEntityPool pool = new GabotoEntityPool(oxp_mem, oxp_mem.getSnapshot(TimeInstant.now())); pool.addEntity(b); pool.addEntity(u); assertEquals(loc, u.getPropertyValue(OxPointsVocab.hasLocation_URI)); } @Test public void testTypedLiteral1() throws EntityAlreadyExistsException{ String uri1 = oxp.generateID(); Carpark cp1 = new Carpark(); cp1.setUri(uri1); cp1.setName("small carpark"); cp1.setCapacity(30); final String uri2 = oxp.generateID(); Carpark cp2 = new Carpark(); cp2.setUri(uri2); cp2.setName("big carpark"); cp2.setCapacity(80); // add carparks oxp.add(cp1); oxp.add(cp2); // snapshot GabotoSnapshot snap = oxp.getSnapshot(TimeInstant.now()); // ask for small String query = GabotoPredefinedQueries.getStandardPrefixes(); query += "SELECT ?cp WHERE { \n"; query += "?cp a oxp:Carpark .\n"; query += "?cp oxp:capacity ?capacity .\n"; query += "FILTER (?capacity > 50) .\n"; query += "}"; final Collection<String> foundURIs = new HashSet<String>(); snap.execSPARQLSelect(query, new QuerySolutionProcessor(){ public void processSolution(QuerySolution solution) { foundURIs.add(solution.getResource("cp").getURI()); } public boolean stopProcessing() { return false; } }); assertTrue(foundURIs.contains(uri2)); } }
package org.cojen.tupl.repl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.ClosedByInterruptException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import org.junit.*; import static org.junit.Assert.*; import org.cojen.tupl.util.Latch; import org.cojen.tupl.util.LatchCondition; import org.cojen.tupl.util.Worker; import org.cojen.tupl.TestUtils; import org.cojen.tupl.io.Utils; /** * * * @author Brian S O'Neill */ public class FileTermLogTest { public static void main(String[] args) throws Exception { org.junit.runner.JUnitCore.main(FileTermLogTest.class.getName()); } @Before public void setup() throws Exception { mBase = TestUtils.newTempBaseFile(getClass()); mWorker = Worker.make(1, 15, TimeUnit.SECONDS, null); mLog = FileTermLog.openTerm(mWorker, mBase, 0, 1, 0, 0, 0, null); } @After public void teardown() throws Exception { if (mLog != null) { mLog.close(); } TestUtils.deleteTempFiles(getClass()); if (mWorker != null) { mWorker.join(true); } } private File mBase; private Worker mWorker; private TermLog mLog; @Test public void basic() throws Exception { basic(283742, false); } @Test public void basicReopen() throws Exception { basic(3209441, true); } private void basic(final long seed, boolean reopen) throws Exception { assertEquals(Long.MAX_VALUE, mLog.endIndex()); // Write a bunch of data and read it back. final byte[] buf = new byte[10000]; Random rnd = new Random(seed); Random rnd2 = new Random(seed + 1); LogWriter writer = mLog.openWriter(0); assertEquals(0, writer.prevTerm()); assertEquals(1, writer.term()); long index = 0; for (int i=0; i<100000; i++) { assertEquals(index, writer.index()); int len = rnd.nextInt(buf.length); for (int j=0; j<len; j++) { buf[j] = (byte) rnd2.nextInt(); } assertEquals(len, writer.write(buf, 0, len, index + len)); index += len; LogInfo info = new LogInfo(); mLog.captureHighest(info); assertEquals(index, info.mHighestIndex); } writer.release(); if (reopen) { LogInfo info = new LogInfo(); mLog.captureHighest(info); mLog.sync(); mLog.close(); mLog = FileTermLog.openTerm(mWorker, mBase, 0, 1, 0, 0, info.mHighestIndex, null); } rnd = new Random(seed); rnd2 = new Random(seed + 1); LogReader reader = mLog.openReader(0); assertEquals(0, reader.prevTerm()); assertEquals(1, reader.term()); long total = index; index = 0; while (true) { assertEquals(index, reader.index()); int amt = reader.readAny(buf, 0, buf.length); if (amt <= 0) { assertTrue(amt == 0); break; } for (int j=0; j<amt; j++) { assertEquals((byte) rnd2.nextInt(), buf[j]); } index += amt; } reader.release(); assertEquals(total, index); mLog.finishTerm(index); assertEquals(index, mLog.endIndex()); mLog.finishTerm(index); assertEquals(index, mLog.endIndex()); try { mLog.finishTerm(index + 1); fail(); } catch (IllegalStateException e) { // Expected. } // Cannot write past end. if (reopen) { try { writer.write(buf, 0, 1, 9_999_999_999L); fail(); } catch (IOException e) { // Closed. } writer = mLog.openWriter(writer.index()); } assertEquals(0, writer.write(buf, 0, 1, 9_999_999_999L)); writer.release(); assertEquals(index, mLog.endIndex()); LogInfo info = new LogInfo(); mLog.captureHighest(info); assertEquals(index, info.mHighestIndex); // Permit partial write up to the end. writer = mLog.openWriter(index - 1); assertEquals(1, writer.write(buf, 0, 2, 9_999_999_999L)); writer.release(); assertEquals(index, mLog.endIndex()); info = new LogInfo(); mLog.captureHighest(info); assertEquals(index, info.mHighestIndex); } @Test public void reopenCleanup() throws Exception { reopenCleanup(false); } @Test public void reopenCleanupDiscover() throws Exception { reopenCleanup(true); } private void reopenCleanup(boolean discoverStart) throws Exception { mLog.close(); final long term = 1; final long startIndex = 1000; mLog = FileTermLog.openTerm (mWorker, mBase, 0, term, startIndex, startIndex, startIndex, null); final byte[] buf = new byte[1000]; Random rnd = new Random(62723); Random rnd2 = new Random(8675309); LogWriter writer = mLog.openWriter(startIndex); long index = startIndex; for (int i=0; i<10_000; i++) { int len = rnd.nextInt(buf.length); for (int j=0; j<len; j++) { buf[j] = (byte) rnd2.nextInt(); } assertEquals(len, writer.write(buf, 0, len, index + len)); index += len; } writer.release(); final String basePath = mBase.getPath() + '.' + term; // Create some files that should be ignored. new File(basePath).createNewFile(); TestUtils.newTempBaseFile(getClass()).createNewFile(); new File(basePath + "foo").createNewFile(); new File(basePath + ".foo").createNewFile(); new File(basePath + ".123foo").createNewFile(); new File(basePath + ".123.foo").createNewFile(); // Create some out-of-bounds segments that should be deleted. File low = new File(basePath + ".123"); low.createNewFile(); assertTrue(low.exists()); File high = new File(basePath + ".999999999999"); high.createNewFile(); assertTrue(high.exists()); // Expand a segment that should be truncated. File first = new File(basePath + ".1000"); assertTrue(first.exists()); long firstLen = first.length(); assertTrue(firstLen > 1_000_000); try (FileOutputStream out = new FileOutputStream(first, true)) { out.write("hello".getBytes()); } assertEquals(firstLen + 5, first.length()); // Close and reopen. LogInfo info = new LogInfo(); mLog.captureHighest(info); mLog.close(); final long startWith; if (!discoverStart) { startWith = startIndex; } else { try { FileTermLog.openTerm (mWorker, mBase, 0, term, -1, startIndex, info.mHighestIndex, null); fail(); } catch (Exception e) { assertTrue(e.getMessage().indexOf(low.toString()) >= 0); } low.delete(); low = null; startWith = -1; } mLog = FileTermLog.openTerm (mWorker, mBase, 0, term, startWith, startIndex, info.mHighestIndex, null); if (low != null) { assertTrue(!low.exists()); } assertTrue(!high.exists()); assertEquals(firstLen, first.length()); // Verify the data. rnd2 = new Random(8675309); LogReader reader = mLog.openReader(startIndex); assertEquals(0, reader.prevTerm()); assertEquals(1, reader.term()); long total = index; index = startIndex; while (true) { assertEquals(index, reader.index()); int amt = reader.readAny(buf, 0, buf.length); if (amt <= 0) { assertTrue(amt == 0); break; } for (int j=0; j<amt; j++) { assertEquals((byte) rnd2.nextInt(), buf[j]); } index += amt; } reader.release(); assertEquals(total, index); // Reopen with missing segments. mLog.close(); if (!discoverStart) { first.delete(); } else { teardown(); } try { FileTermLog.openTerm (mWorker, mBase, 0, term, startWith, startIndex, info.mHighestIndex, null); fail(); } catch (Exception e) { String msg = e.getMessage(); String expect; if (!discoverStart) { expect = "Missing start"; } else { expect = "No segment files"; } assertTrue(expect, msg.indexOf(expect) >= 0); } } @Test public void tail() throws Throwable { // Write and commit a bunch of data, while concurrently reading it. final int seed = 762390; class Reader extends Thread { volatile Throwable mEx; volatile long mTotal; @Override public void run() { try { byte[] buf = new byte[1024]; Random rnd2 = new Random(seed + 1); LogReader reader = mLog.openReader(0); while (true) { int amt = reader.read(buf, 0, buf.length); if (amt <= 0) { assertTrue(amt < 0); break; } for (int j=0; j<amt; j++) { assertEquals((byte) rnd2.nextInt(), buf[j]); } } mTotal = reader.index(); } catch (Throwable e) { mEx = e; } } } Reader r = new Reader(); TestUtils.startAndWaitUntilBlocked(r); final byte[] buf = new byte[10000]; Random rnd = new Random(seed); Random rnd2 = new Random(seed + 1); LogWriter writer = mLog.openWriter(0); assertEquals(0, writer.prevTerm()); assertEquals(1, writer.term()); long index = 0; for (int i=0; i<100000; i++) { assertEquals(index, writer.index()); int len = rnd.nextInt(buf.length); for (int j=0; j<len; j++) { buf[j] = (byte) rnd2.nextInt(); } assertEquals(len, writer.write(buf, 0, len, index + len)); index += len; LogInfo info = new LogInfo(); mLog.captureHighest(info); assertEquals(index, info.mHighestIndex); long commitIndex = index + (rnd.nextInt(1000) - 500); if (commitIndex >= 0) { mLog.commit(commitIndex); } } writer.release(); mLog.commit(index); LogInfo info = new LogInfo(); mLog.captureHighest(info); assertEquals(index, info.mHighestIndex); assertEquals(index, info.mCommitIndex); mLog.finishTerm(index); assertEquals(index, mLog.endIndex()); r.join(); assertEquals(index, r.mTotal); Throwable ex = r.mEx; if (ex != null) { throw ex; } } @Test public void waitForCommit() throws Exception { commitWait(false); } @Test public void uponCommit() throws Exception { commitWait(true); } private void commitWait(boolean upon) throws Exception { // Test waiting for a commit. class Waiter extends Thread { final long mWaitFor; final boolean mUpon; final Latch mLatch; final LatchCondition mLatchCondition; Exception mEx; long mCommit; Waiter(long waitFor, boolean upon) { mLatch = new Latch(); mUpon = upon; mLatchCondition = new LatchCondition(); mWaitFor = waitFor; } void begin() { if (mUpon) { mLog.uponCommit(new Delayed(mWaitFor) { @Override protected void doRun(long commit) { mLatch.acquireExclusive(); mCommit = commit; mLatchCondition.signal(); mLatch.releaseExclusive(); } }); } else { TestUtils.startAndWaitUntilBlocked(this); } } @Override public void run() { try { long commit = mLog.waitForCommit(mWaitFor, -1); mLatch.acquireExclusive(); mCommit = commit; mLatchCondition.signal(); mLatch.releaseExclusive(); } catch (Exception e) { mLatch.acquireExclusive(); mEx = e; mLatchCondition.signal(); mLatch.releaseExclusive(); } } long waitForResult(long timeoutMillis) throws Exception { mLatch.acquireExclusive(); try { int r = Integer.MAX_VALUE; while (true) { if (mCommit != 0) { return mCommit; } if (mEx != null) { throw mEx; } if (r != Integer.MAX_VALUE) { return -1; } r = mLatchCondition.await(mLatch, timeoutMillis, TimeUnit.MILLISECONDS); } } finally { mLatch.releaseExclusive(); } } } long index = 0; byte[] msg1 = "hello".getBytes(); // Wait for the full message. Waiter waiter = new Waiter(index + msg1.length, upon); waiter.begin(); LogWriter writer = mLog.openWriter(0); write(writer, msg1); // Timed out waiting, because noting has been committed yet. assertEquals(-1, waiter.waitForResult(500)); // Commit too little. mLog.commit(index += 2); assertEquals(-1, waiter.waitForResult(500)); // Commit the rest. mLog.commit(index += 3); assertEquals(index, waiter.waitForResult(-1)); byte[] msg2 = "world!!!".getBytes(); // Wait for a partial message. waiter = new Waiter(index + 5, upon); waiter.begin(); write(writer, msg2); // Timed out waiting. assertEquals(-1, waiter.waitForResult(500)); // Commit too little. mLog.commit(index += 2); assertEquals(-1, waiter.waitForResult(500)); // Commit the rest, observing more than what was requested. mLog.commit(index += 6); assertEquals(index, waiter.waitForResult(-1)); byte[] msg3 = "stuff".getBytes(); // Wait for the full message. waiter = new Waiter(index + msg3.length, upon); waiter.begin(); // Commit ahead. mLog.commit(index + 100); // Timed out waiting, because nothing has been written yet. assertEquals(-1, waiter.waitForResult(500)); write(writer, msg3); index += msg3.length; assertEquals(index, waiter.waitForResult(-1)); writer.release(); // No wait. waiter = new Waiter(index, upon); waiter.begin(); assertEquals(index, waiter.waitForResult(-1)); // Unblock after term is finished. long findex = index; TestUtils.startAndWaitUntilBlocked(new Thread(() -> { TestUtils.sleep(1000); try { mLog.finishTerm(findex); } catch (IOException e) { Utils.uncaught(e); } })); waiter = new Waiter(index + 1, upon); waiter.begin(); assertEquals(-1, waiter.waitForResult(-1)); // Verify that everything is read back properly, with no blocking. byte[] complete = concat(msg1, msg2, msg3); byte[] buf = new byte[100]; LogReader reader = mLog.openReader(0); int amt = reader.read(buf, 0, buf.length); reader.release(); TestUtils.fastAssertArrayEquals(complete, Arrays.copyOf(buf, amt)); } @Test public void rangesNoSync() throws Exception { ranges(false); } @Test public void rangesWithSync() throws Exception { ranges(true); } private void ranges(boolean sync) throws Exception { // Define a bunch of random ranges, with random data, and write to them in random order // via several threads. The reader shouldn't read beyond the contiguous range, and the // data it observes should match what was written. final long seed = 289023475245L; Random rnd = new Random(seed); final int threadCount = 10; final int sliceLength = 100_000; Range[] ranges = new Range[sliceLength * threadCount]; long index = 0; for (int i=0; i<ranges.length; i++) { Range range = new Range(); range.mStart = index; int len = rnd.nextInt(1000); index += len; range.mEnd = index; ranges[i] = range; } // Commit and finish in advance. mLog.commit(index); mLog.finishTerm(index); Collections.shuffle(Arrays.asList(ranges), rnd); Range[][] slices = new Range[threadCount][]; for (int i=0; i<slices.length; i++) { int from = i * sliceLength; slices[i] = Arrays.copyOfRange(ranges, from, from + sliceLength); } class Writer extends Thread { private final Range[] mRanges; private final Random mRnd; volatile long mSum; Writer(Range[] ranges, Random rnd) { mRanges = ranges; mRnd = rnd; } @Override public void run() { try { long sum = 0; for (Range range : mRanges) { byte[] data = new byte[(int) (range.mEnd - range.mStart)]; mRnd.nextBytes(data); LogWriter writer = mLog.openWriter(range.mStart); write(writer, data); writer.release(); for (int i=0; i<data.length; i++) { sum += 1 + (data[i] & 0xff); } } mSum = sum; } catch (IOException e) { Utils.uncaught(e); } } } Thread syncThread = null; if (sync) { // First one should do nothing. mLog.sync(); syncThread = new Thread(() -> { try { while (true) { Thread.sleep(500); mLog.sync(); } } catch (InterruptedException | ClosedByInterruptException e) { // Done. } catch (IOException e) { Utils.uncaught(e); } }); syncThread.start(); } Writer[] writers = new Writer[threadCount]; for (int i=0; i<writers.length; i++) { writers[i] = new Writer(slices[i], new Random(seed + i)); } for (Writer w : writers) { w.start(); } LogReader reader = mLog.openReader(0); byte[] buf = new byte[1024]; long sum = 0; while (true) { int amt = reader.read(buf, 0, buf.length); if (amt < 0) { break; } for (int i=0; i<amt; i++) { sum += 1 + (buf[i] & 0xff); } } assertEquals(index, reader.index()); reader.release(); long expectedSum = 0; for (Writer w : writers) { w.join(); expectedSum += w.mSum; } assertEquals(expectedSum, sum); if (syncThread != null) { syncThread.interrupt(); syncThread.join(); } } @Test public void missingRanges() throws Exception { // Verify that missing ranges can be queried. RangeResult result = new RangeResult(); assertEquals(0, mLog.checkForMissingData(Long.MAX_VALUE, result)); assertEquals(0, result.mRanges.size()); LogWriter writer = mLog.openWriter(50); write(writer, new byte[100]); writer.release(); result = new RangeResult(); assertEquals(0, mLog.checkForMissingData(0, result)); assertEquals(1, result.mRanges.size()); assertEquals(new Range(0, 50), result.mRanges.get(0)); // Fill in the missing range. Overlap is fine. writer = mLog.openWriter(0); write(writer, new byte[55]); writer.release(); result = new RangeResult(); assertEquals(150, mLog.checkForMissingData(0, result)); assertEquals(0, result.mRanges.size()); assertEquals(150, mLog.checkForMissingData(10, result)); assertEquals(0, result.mRanges.size()); assertEquals(150, mLog.checkForMissingData(1000, result)); assertEquals(0, result.mRanges.size()); // Create a few missing ranges. writer = mLog.openWriter(200); write(writer, new byte[50]); writer.release(); writer = mLog.openWriter(350); write(writer, new byte[50]); writer.release(); writer = mLog.openWriter(300); write(writer, new byte[50]); writer.release(); result = new RangeResult(); assertEquals(150, mLog.checkForMissingData(100, result)); assertEquals(0, result.mRanges.size()); assertEquals(150, mLog.checkForMissingData(150, result)); assertEquals(2, result.mRanges.size()); assertEquals(new Range(150, 200), result.mRanges.get(0)); assertEquals(new Range(250, 300), result.mRanges.get(1)); // Finish the term, creating a new missing range. mLog.finishTerm(1000); result = new RangeResult(); assertEquals(150, mLog.checkForMissingData(150, result)); assertEquals(3, result.mRanges.size()); assertEquals(new Range(150, 200), result.mRanges.get(0)); assertEquals(new Range(250, 300), result.mRanges.get(1)); assertEquals(new Range(400, 1000), result.mRanges.get(2)); // Fill in the missing ranges... writer = mLog.openWriter(150); write(writer, new byte[50]); writer.release(); result = new RangeResult(); assertEquals(250, mLog.checkForMissingData(150, result)); assertEquals(0, result.mRanges.size()); assertEquals(250, mLog.checkForMissingData(250, result)); assertEquals(2, result.mRanges.size()); assertEquals(new Range(250, 300), result.mRanges.get(0)); assertEquals(new Range(400, 1000), result.mRanges.get(1)); writer = mLog.openWriter(400); write(writer, new byte[600]); writer.release(); result = new RangeResult(); assertEquals(250, mLog.checkForMissingData(250, result)); assertEquals(1, result.mRanges.size()); assertEquals(new Range(250, 300), result.mRanges.get(0)); LogInfo info = new LogInfo(); mLog.captureHighest(info); assertEquals(250, info.mHighestIndex); writer = mLog.openWriter(250); write(writer, new byte[50]); writer.release(); result = new RangeResult(); assertEquals(1000, mLog.checkForMissingData(250, result)); assertEquals(0, result.mRanges.size()); assertEquals(1000, mLog.checkForMissingData(1000, result)); assertEquals(0, result.mRanges.size()); info = new LogInfo(); mLog.captureHighest(info); assertEquals(1000, info.mHighestIndex); } @Test public void discardNonContigRanges() throws Exception { // Any non-contiguous ranges past the end of a finished term must be discarded. LogWriter writer = mLog.openWriter(100); write(writer, new byte[50]); writer.release(); writer = mLog.openWriter(250); write(writer, new byte[50]); writer.release(); writer = mLog.openWriter(400); write(writer, new byte[100]); writer.release(); RangeResult result = new RangeResult(); assertEquals(0, mLog.checkForMissingData(Long.MAX_VALUE, result)); assertEquals(0, result.mRanges.size()); result = new RangeResult(); assertEquals(0, mLog.checkForMissingData(-1, result)); assertEquals(3, result.mRanges.size()); assertEquals(new Range(0, 100), result.mRanges.get(0)); assertEquals(new Range(150, 250), result.mRanges.get(1)); assertEquals(new Range(300, 400), result.mRanges.get(2)); mLog.finishTerm(200); result = new RangeResult(); assertEquals(0, mLog.checkForMissingData(0, result)); assertEquals(2, result.mRanges.size()); assertEquals(new Range(0, 100), result.mRanges.get(0)); assertEquals(new Range(150, 200), result.mRanges.get(1)); LogInfo info = new LogInfo(); mLog.captureHighest(info); assertEquals(0, info.mHighestIndex); writer = mLog.openWriter(0); write(writer, new byte[100]); writer.release(); info = new LogInfo(); mLog.captureHighest(info); assertEquals(150, info.mHighestIndex); result = new RangeResult(); assertEquals(150, mLog.checkForMissingData(0, result)); assertEquals(0, result.mRanges.size()); assertEquals(150, mLog.checkForMissingData(150, result)); assertEquals(1, result.mRanges.size()); assertEquals(new Range(150, 200), result.mRanges.get(0)); } @Test public void discardAllRanges() throws Exception { // All ranges past the end of a finished term must be discarded. LogWriter writer = mLog.openWriter(0); write(writer, new byte[200]); writer.release(); writer = mLog.openWriter(300); write(writer, new byte[100]); writer.release(); RangeResult result = new RangeResult(); assertEquals(200, mLog.checkForMissingData(Long.MAX_VALUE, result)); assertEquals(0, result.mRanges.size()); assertEquals(200, mLog.checkForMissingData(200, result)); assertEquals(1, result.mRanges.size()); assertEquals(new Range(200, 300), result.mRanges.get(0)); LogInfo info = new LogInfo(); mLog.captureHighest(info); assertEquals(200, info.mHighestIndex); mLog.finishTerm(170); info = new LogInfo(); mLog.captureHighest(info); assertEquals(170, info.mHighestIndex); assertEquals(0, info.mCommitIndex); result = new RangeResult(); assertEquals(170, mLog.checkForMissingData(200, result)); assertEquals(0, result.mRanges.size()); mLog.commit(170); info = new LogInfo(); mLog.captureHighest(info); assertEquals(170, info.mHighestIndex); assertEquals(170, info.mCommitIndex); try { mLog.finishTerm(100); fail(); } catch (IllegalArgumentException e) { // Expected. } } private static void write(LogWriter writer, byte[] data) throws IOException { int amt = writer.write(data, 0, data.length, writer.index() + data.length); assertEquals(data.length, amt); } private static byte[] concat(byte[]... chunks) { int length = 0; for (byte[] chunk : chunks) { length += chunk.length; } byte[] complete = new byte[length]; int pos = 0; for (byte[] chunk : chunks) { System.arraycopy(chunk, 0, complete, pos, chunk.length); pos += chunk.length; } return complete; } static class Range { long mStart, mEnd; Range() { } Range(long start, long end) { mStart = start; mEnd = end; } @Override public boolean equals(Object obj) { if (obj instanceof Range) { return ((Range) obj).mStart == mStart && ((Range) obj).mEnd == mEnd; } return false; } @Override public String toString() { return "[" + mStart + "," + mEnd + "]"; } } static class RangeResult implements IndexRange { List<Range> mRanges = new ArrayList<>(); @Override public void range(long start, long end) { mRanges.add(new Range(start, end)); } @Override public String toString() { return mRanges.toString(); } } }
package org.g_node.srv; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import org.apache.commons.io.FileUtils; import static org.assertj.core.api.Assertions.assertThat; import org.g_node.micro.commons.RDFService; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit tests for the {@link CtrlCheckService} class. * * @author Michael Sonntag (sonntag@bio.lmu.de) */ public class CtrlCheckServiceTest { private final String tmpRoot = System.getProperty("java.io.tmpdir"); private final String testFolderName = "ctrlCheckServiceTest"; private final String testFileName = "test.txt"; private final Path testFileFolder = Paths.get(tmpRoot, testFolderName); /** * Create a test folder and the main test file in the java temp directory. * @throws Exception */ @Before public void setUp() throws Exception { final File currTestFile = this.testFileFolder.resolve(this.testFileName).toFile(); FileUtils.write(currTestFile, "This is a normal test file"); } /** * Remove all created folders and files after the tests are done. * @throws Exception */ @After public void tearDown() throws Exception { if (Files.exists(this.testFileFolder)) { FileUtils.deleteDirectory(this.testFileFolder.toFile()); } } /** * Test if the method returns false when presented with a * String referencing a non existing file and returns true if it is * presented with String referencing an existing file. * @throws Exception */ @Test public void testExistingFile() throws Exception { final String testNonExistingFilePath = this.testFileFolder .resolve("IdoNotExist") .toAbsolutePath().normalize().toString(); assertThat(CtrlCheckService.isExistingFile(testNonExistingFilePath)).isFalse(); final String testExistingFilePath = this.testFileFolder .resolve(this.testFileName) .toAbsolutePath().normalize().toString(); assertThat(CtrlCheckService.isExistingFile(testExistingFilePath)).isTrue(); } /** * Check, that a file without a file type extension or a file type extension that * is not supported returns false and test that a file with a supported * file type extension returns true. * @throws Exception */ @Test public void testSupportedInFileType() throws Exception { final String testFileType = "test"; final String testFileTypeExt = "test.tex"; final File currTestFileType = this.testFileFolder.resolve(testFileType).toFile(); final File currTestFileTypeExt = this.testFileFolder.resolve(testFileTypeExt).toFile(); FileUtils.write(currTestFileType, "This is a normal test file"); FileUtils.write(currTestFileTypeExt, "This is a normal test file"); final List<String> testFileTypes = Collections.singletonList("TXT"); assertThat( CtrlCheckService.isSupportedInFileType( this.testFileFolder .resolve(testFileType) .toAbsolutePath().normalize().toString(), testFileTypes) ).isFalse(); assertThat( CtrlCheckService.isSupportedInFileType( this.testFileFolder .resolve(testFileTypeExt) .toAbsolutePath().normalize().toString(), testFileTypes) ).isFalse(); assertThat( CtrlCheckService.isSupportedInFileType( this.testFileFolder .resolve(this.testFileName) .toAbsolutePath().normalize().toString(), testFileTypes) ).isTrue(); } /** * Test that the method returns true if it is provided with a string * contained as key in {@link RDFService#RDF_FORMAT_MAP} and false if * it is not. It will also test all currently implemented keys from * {@link RDFService#RDF_FORMAT_MAP}. * @throws Exception */ @Test public void testSupportedOutputFormat() throws Exception { assertThat(CtrlCheckService.isSupportedOutputFormat("txt", RDFService.RDF_FORMAT_MAP.keySet())).isFalse(); assertThat(CtrlCheckService.isSupportedOutputFormat("TTL", RDFService.RDF_FORMAT_MAP.keySet())).isTrue(); assertThat(CtrlCheckService.isSupportedOutputFormat("NTRIPLES", RDFService.RDF_FORMAT_MAP.keySet())).isTrue(); assertThat(CtrlCheckService.isSupportedOutputFormat("RDF/XML", RDFService.RDF_FORMAT_MAP.keySet())).isTrue(); assertThat(CtrlCheckService.isSupportedOutputFormat("JSON-LD", RDFService.RDF_FORMAT_MAP.keySet())).isTrue(); } }
package seedu.doit.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.time.LocalDateTime; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.doit.logic.parser.DateTimeParser; /** * Tests if DateTimeParser is parsing the date correctly **/ public class DateTimeParserTest { @Rule public ExpectedException thrown = ExpectedException.none(); private void assertSameDate(LocalDateTime time1, LocalDateTime time2) { LocalDateTime diff = time1.minusHours(time2.getHour()).minusMinutes(time2.getMinute()) .minusSeconds(time2.getSecond()); assertEquals(time1, diff); } @Test public void check_ifDateParsedCorrectly() throws Exception { Optional<LocalDateTime> t = DateTimeParser.parseDateTime("03/20/17"); assertSameDate(t.get(), LocalDateTime.of(2017, 3, 20, 0, 0)); } @Test public void parseEmptyString() { Optional<LocalDateTime> dateParsed = DateTimeParser.parseDateTime(""); assertFalse(dateParsed.isPresent()); } @Test public void parseNullString() throws Exception { thrown.expect(NullPointerException.class); DateTimeParser.parseDateTime(null); } @Test public void parseRubbishString() { Optional<LocalDateTime> dateParsed = DateTimeParser.parseDateTime("jsadf"); assertFalse(dateParsed.isPresent()); } }
package com.baoyongan.java.eg.base.numberAndString_ch; import java.math.BigDecimal; import java.math.BigInteger; public class NumberTest { public static void main(String[] args) { Short i = new Short((short) -1); System.out.println(Short.toUnsignedInt(i)); // int 1 int max = Integer.MAX_VALUE; int sm = max + 1; System.out.println("" + sm); int lowest = -2147483648; int low = Integer.MIN_VALUE; int abs = Math.abs(lowest); System.out.printf("int %d, %d,math.abs %d, \n", lowest, low, abs); // (a/b)*b+a%b=a System.out.printf("-14/3= %d \n", -14 / 3); System.out.printf("14/-3= %d \n", 14 / -3); System.out.printf("-14%%3= %d \n", -14 % 3); System.out.printf("14%%-3= %d \n", 14 % -3); BigInteger bigInteger = new BigInteger("1212132132132212"); // String s = Integer.toHexString(1); // System.out.println(s); // System.out.println(Integer.parseInt()); // int a=0x0f; int a = 0x7FFFFFFF; System.out.println(a); System.out.println(Integer.parseInt("F", 16)); System.out.println(Integer.toHexString(15)); String s = Integer.toBinaryString(a); System.out.println(s.length()); // System.out.println(Integer.toBinaryString(a)); System.out.println("4_1.1.1 "); int A = (0 + 15) / 2; double B = 2.0e-6 * 100000000.1; // 2.0e-6 2.0*10^-6; double B_1 = 2.0 * (Math.pow(10, -6)) * 100000000.1; boolean C = true && false || true && true; System.out.println(A); System.out.println(B); System.out.println(B_1); System.out.println(C); System.out.println(new BigDecimal("2.0e-6").toPlainString()); double v = (1 + 2.236) / 2; System.out.println(v); double v1 = 1 + 2 + 3 + 4.0; System.out.println(v1); boolean b = 4.1 >= 4; System.out.println(b); String s1 = 1 + 2 + "3"; System.out.println(s1); System.out.println("0%2="+0%2); System.out.println("1%2="+1%2); System.out.println("2%2="+2%2); } }
package org.broadinstitute.sting.oneoffprojects.walkers; import net.sf.samtools.SAMRecord; import org.broad.tribble.util.variantcontext.Genotype; import org.broad.tribble.util.variantcontext.VariantContext; import org.broadinstitute.sting.commandline.Argument; import org.broadinstitute.sting.commandline.Output; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.walkers.*; import org.broadinstitute.sting.gatk.walkers.indels.HaplotypeIndelErrorModel; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.GenomeLocParser; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.collections.CircularArray; import org.broadinstitute.sting.utils.genotype.Haplotype; import org.broadinstitute.sting.utils.pileup.ExtendedEventPileupElement; import org.broadinstitute.sting.utils.pileup.ReadBackedExtendedEventPileup; import org.broadinstitute.sting.utils.pileup.ReadBackedPileup; import java.io.PrintStream; import java.util.*; import org.broadinstitute.sting.gatk.walkers.Reference; import org.broadinstitute.sting.gatk.walkers.Window; @Reference(window=@Window(start=-10,stop=80)) @Allows({DataSource.READS, DataSource.REFERENCE}) public class SimpleIndelGenotyperWalker extends RefWalker<Integer,Integer> { @Output PrintStream out; @Argument(fullName="maxReadDeletionLength",shortName="maxReadDeletionLength",doc="Max deletion length allowed when aligning reads to candidate haplotypes.",required=false) int maxReadDeletionLength = 3; @Argument(fullName="insertionStartProbability",shortName="insertionStartProbability",doc="Assess only sites with coverage at or below the specified value.",required=false) double insertionStartProbability = 0.01; @Argument(fullName="insertionEndProbability",shortName="insertionEndProbability",doc="Assess only sites with coverage at or below the specified value.",required=false) double insertionEndProbability = 0.5; @Argument(fullName="alphaDeletionProbability",shortName="alphaDeletionProbability",doc="Assess only sites with coverage at or below the specified value.",required=false) double alphaDeletionProbability = 0.01; @Argument(fullName="haplotypeSize",shortName="hsize",doc="Size of haplotypes to evaluate calls.",required=true) int HAPLOTYPE_SIZE = 40; @Override public boolean generateExtendedEvents() { return true; } @Override public boolean includeReadsWithDeletionAtLoci() { return true; } private HaplotypeIndelErrorModel model; private static final int MAX_READ_LENGTH = 200; // TODO- make this dynamic @Override public void initialize() { model = new HaplotypeIndelErrorModel(maxReadDeletionLength, insertionStartProbability, insertionEndProbability, alphaDeletionProbability, HAPLOTYPE_SIZE, MAX_READ_LENGTH); } /* private void countIndels(ReadBackedExtendedEventPileup p) { for ( ExtendedEventPileupElement pe : p.toExtendedIterable() ) { if ( ! pe.isIndel() ) continue; if ( pe.getEventLength() > MAX_LENGTH ) continue; if ( pe.isInsertion() ) insCounts[pe.getEventLength()-1]++; else delCounts[pe.getEventLength()-1]++; } } */ public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { if ( tracker == null ) return 0; if (!context.hasBasePileup()) return 0; VariantContext vc = tracker.getVariantContext(ref, "indels", null, context.getLocation(), true); // ignore places where we don't have a variant if ( vc == null ) return 0; if (!vc.isIndel()) return 0; List<Haplotype> haplotypesInVC = Haplotype.makeHaplotypeListFromVariantContextAlleles( vc, ref, HAPLOTYPE_SIZE); // combine likelihoods for all possible haplotype pair (n*(n-1)/2 combinations) double[][] haplotypeLikehoodMatrix = new double[haplotypesInVC.size()][haplotypesInVC.size()]; double bestLikelihood = 1e13; // for given allele haplotype, compute likelihood of read pileup given haplotype ReadBackedPileup pileup = context.getBasePileup().getPileupWithoutMappingQualityZeroReads(); int bestIndexI =0, bestIndexJ=0; for (int i=0; i < haplotypesInVC.size(); i++) { for (int j=i; j < haplotypesInVC.size(); j++){ // combine likelihoods of haplotypeLikelihoods[i], haplotypeLikelihoods[j] for (SAMRecord read : pileup.getReads()) { // compute Pr(r | hi, hj) = 1/2*(Pr(r|hi) + Pr(r|hj) double readLikelihood[] = new double[2]; readLikelihood[0]= -model.computeReadLikelihoodGivenHaplotype(haplotypesInVC.get(i), read)/10.0; if (i != j) readLikelihood[1] = -model.computeReadLikelihoodGivenHaplotype(haplotypesInVC.get(j), read)/10.0; else readLikelihood[1] = readLikelihood[0]; // likelihood is by convention -10*log10(pr(r|h)) // sumlog10 computes 10^x[0]+10^x[1]+... double probRGivenHPair = MathUtils.sumLog10(readLikelihood)/2; haplotypeLikehoodMatrix[i][j] += HaplotypeIndelErrorModel.probToQual(probRGivenHPair); } if (haplotypeLikehoodMatrix[i][j] < bestLikelihood) { bestIndexI = i; bestIndexJ = j; bestLikelihood = haplotypeLikehoodMatrix[i][j]; } } } //we say that most likely genotype at site is index (i,j) maximizing likelihood matrix String type; if (vc.isDeletion()) type = "DEL"; else if (vc.isInsertion()) type = "INS"; else type = "OTH"; type += vc.getIndelLengths().toString(); out.format("%s %d %s ",vc.getChr(), vc.getStart(), type); Genotype originalGenotype = vc.getGenotype("NA12878"); String oldG, newG; if (originalGenotype.isHomRef()) oldG = "HOMREF"; else if (originalGenotype.isHet()) oldG = "HET"; else if (originalGenotype.isHomVar()) oldG = "HOMVAR"; else oldG = "OTHER"; int x = bestIndexI+bestIndexJ; if (x == 0) newG = "HOMREF"; else if (x == 1) newG = "HET"; else if (x == 2) newG = "HOMVAR"; else newG = "OTHER"; out.format("NewG %s OldG %s\n", newG, oldG); /* if ( context.hasExtendedEventPileup() ) { // if we got indels at current position: ReadBackedExtendedEventPileup pileup = context.getExtendedEventPileup().getPileupWithoutMappingQualityZeroReads(); if ( pileup.size() < MIN_COVERAGE ) return 0; if ( pileup.getNumberOfDeletions() + pileup.getNumberOfInsertions() > MAX_INDELS ) { // we got too many indel events. Maybe it's even a true event, and what we are looking for are // errors rather than true calls. Hence, we do not need these indels. We have to 1) discard // all remaining indels from the buffer: if they are still in the buffer, they are too close // to the current position; and 2) make sure that the next position at which we attempt to count again is // sufficiently far *after* the current position. // System.out.println("Non countable indel event at "+pileup.getLocation()); countableIndelBuffer.clear(); coverageBuffer.clear(); // we do not want to count observations (read bases) around non-countable indel as well skipToLoc = GenomeLocParser.createGenomeLoc(pileup.getLocation().getContigIndex(),pileup.getLocation().getStop()+pileup.getMaxDeletionLength()+MIN_DISTANCE+1); // System.out.println("Skip to "+skipToLoc); } else { // pileup does not contain too many indels, we need to store them in the buffer and count them later, // if a non-countable indel event(s) do not show up too soon: countableIndelBuffer.add(pileup); } return 0; } */ return 1; //To change body of implemented methods use File | Settings | File Templates. } /** * Provide an initial value for reduce computations. * * @return Initial value of reduce. */ public Integer reduceInit() { return 0; //To change body of implemented methods use File | Settings | File Templates. } /** * Reduces a single map with the accumulator provided as the ReduceType. * * @param value result of the map. * @param sum accumulator for the reduce. * @return accumulator with result of the map taken into account. */ public Integer reduce(Integer value, Integer sum) { return value+sum; //To change body of implemented methods use File | Settings | File Templates. } @Override public void onTraversalDone(Integer result) { } }
package org.uma.jmetal.auto.algorithm.nsgaii; import org.uma.jmetal.auto.algorithm.EvolutionaryAlgorithm; import org.uma.jmetal.auto.component.evaluation.Evaluation; import org.uma.jmetal.auto.component.evaluation.impl.SequentialEvaluation; import org.uma.jmetal.auto.component.initialsolutionscreation.InitialSolutionsCreation; import org.uma.jmetal.auto.component.replacement.Replacement; import org.uma.jmetal.auto.component.replacement.impl.RankingAndDensityEstimatorReplacement; import org.uma.jmetal.auto.component.selection.MatingPoolSelection; import org.uma.jmetal.auto.component.termination.Termination; import org.uma.jmetal.auto.component.termination.impl.TerminationByEvaluations; import org.uma.jmetal.auto.component.variation.Variation; import org.uma.jmetal.auto.parameter.IntegerParameter; import org.uma.jmetal.auto.parameter.Parameter; import org.uma.jmetal.auto.parameter.RealParameter; import org.uma.jmetal.auto.parameter.catalogue.*; import org.uma.jmetal.auto.parameter.irace.NSGAIIiraceParameterFile; import org.uma.jmetal.auto.util.densityestimator.DensityEstimator; import org.uma.jmetal.auto.util.densityestimator.impl.CrowdingDistanceDensityEstimator; import org.uma.jmetal.auto.util.observer.impl.ExternalArchiveObserver; import org.uma.jmetal.auto.util.ranking.Ranking; import org.uma.jmetal.auto.util.ranking.impl.DominanceRanking; import org.uma.jmetal.problem.doubleproblem.DoubleProblem; import org.uma.jmetal.solution.doublesolution.DoubleSolution; import org.uma.jmetal.util.archive.impl.CrowdingDistanceArchive; import org.uma.jmetal.util.comparator.DominanceComparator; import org.uma.jmetal.util.comparator.MultiComparator; import org.uma.jmetal.util.fileoutput.SolutionListOutput; import org.uma.jmetal.util.fileoutput.impl.DefaultFileOutputContext; import java.util.*; public class NSGAIIWithParameters { public List<Parameter<?>> autoConfigurableParameterList = new ArrayList<>(); public List<Parameter<?>> fixedParameterList = new ArrayList<>(); private ProblemNameParameter<DoubleSolution> problemNameParameter; private ReferenceFrontFilenameParameter referenceFrontFilename; private IntegerParameter maximumNumberOfEvaluationsParameter; private AlgorithmResultParameter algorithmResultParameter; private PopulationSizeParameter populationSizeParameter; private PopulationSizeWithArchive populationSizeWithArchiveParameter; private OffspringPopulationSizeParameter offspringPopulationSizeParameter; private CreateInitialSolutionsParameter createInitialSolutionsParameter; private SelectionParameter selectionParameter; private VariationParameter variationParameter; public void parseParameters(String[] args) { problemNameParameter = new ProblemNameParameter<>(args); referenceFrontFilename = new ReferenceFrontFilenameParameter(args); maximumNumberOfEvaluationsParameter = new IntegerParameter("maximumNumberOfEvaluations", args, 1, 10000000); fixedParameterList.add(problemNameParameter); fixedParameterList.add(referenceFrontFilename); fixedParameterList.add(maximumNumberOfEvaluationsParameter); for (Parameter<?> parameter : fixedParameterList) { parameter.parse().check(); } algorithmResultParameter = new AlgorithmResultParameter(args, Arrays.asList("externalArchive", "population")); populationSizeParameter = new PopulationSizeParameter(args); populationSizeWithArchiveParameter = new PopulationSizeWithArchive(args, Arrays.asList(10, 20, 50, 100, 200)); algorithmResultParameter.addGlobalParameter(populationSizeParameter); // algorithmResultParameter.addSpecificParameter("population", populationSizeParameter); algorithmResultParameter.addSpecificParameter( "externalArchive", populationSizeWithArchiveParameter); offspringPopulationSizeParameter = new OffspringPopulationSizeParameter(args, Arrays.asList(1, 10, 50, 100)); createInitialSolutionsParameter = new CreateInitialSolutionsParameter( args, Arrays.asList("random", "latinHypercubeSampling", "scatterSearch")); selectionParameter = new SelectionParameter(args, Arrays.asList("tournament", "random")); IntegerParameter selectionTournamentSize = new IntegerParameter("selectionTournamentSize", args, 2, 10); selectionParameter.addSpecificParameter("tournament", selectionTournamentSize); CrossoverParameter crossover = new CrossoverParameter(args, Arrays.asList("SBX", "BLX_ALPHA")); ProbabilityParameter crossoverProbability = new ProbabilityParameter("crossoverProbability", args); crossover.addGlobalParameter(crossoverProbability); RepairDoubleSolutionStrategyParameter crossoverRepairStrategy = new RepairDoubleSolutionStrategyParameter( "crossoverRepairStrategy", args, Arrays.asList("random", "round", "bounds")); crossover.addGlobalParameter(crossoverRepairStrategy); RealParameter distributionIndex = new RealParameter("sbxDistributionIndex", args, 5.0, 400.0); crossover.addSpecificParameter("SBX", distributionIndex); RealParameter alpha = new RealParameter("blxAlphaCrossoverAlphaValue", args, 0.0, 1.0); crossover.addSpecificParameter("BLX_ALPHA", alpha); MutationParameter mutation = new MutationParameter(args, Arrays.asList("uniform", "polynomial")); ProbabilityParameter mutationProbability = new ProbabilityParameter("mutationProbability", args); mutation.addGlobalParameter(mutationProbability); RepairDoubleSolutionStrategyParameter mutationRepairStrategy = new RepairDoubleSolutionStrategyParameter( "mutationRepairStrategy", args, Arrays.asList("random", "round", "bounds")); mutation.addGlobalParameter(mutationRepairStrategy); RealParameter distributionIndexForMutation = new RealParameter("polynomialMutationDistributionIndex", args, 5.0, 400.0); mutation.addSpecificParameter("polynomial", distributionIndexForMutation); RealParameter uniformMutationPerturbation = new RealParameter("uniformMutationPerturbation", args, 0.0, 1.0); mutation.addSpecificParameter("uniform", uniformMutationPerturbation); variationParameter = new VariationParameter(args, Arrays.asList("crossoverAndMutationVariation")); variationParameter.addGlobalParameter(crossover); variationParameter.addGlobalParameter(mutation); autoConfigurableParameterList.add(algorithmResultParameter); autoConfigurableParameterList.add(offspringPopulationSizeParameter); autoConfigurableParameterList.add(createInitialSolutionsParameter); autoConfigurableParameterList.add(variationParameter); autoConfigurableParameterList.add(selectionParameter); for (Parameter<?> parameter : autoConfigurableParameterList) { parameter.parse().check(); } } /** * Creates an instance of NSGA-II from the parsed parameters * * @return */ EvolutionaryAlgorithm<DoubleSolution> create() { DoubleProblem problem = (DoubleProblem) problemNameParameter.getProblem(); ExternalArchiveObserver<DoubleSolution> boundedArchiveObserver = null; if (algorithmResultParameter.getValue().equals("externalArchive")) { boundedArchiveObserver = new ExternalArchiveObserver<>( new CrowdingDistanceArchive<>(populationSizeParameter.getValue())); populationSizeParameter.setValue(populationSizeWithArchiveParameter.getValue()); } Ranking<DoubleSolution> ranking = new DominanceRanking<>(new DominanceComparator<>()); DensityEstimator<DoubleSolution> densityEstimator = new CrowdingDistanceDensityEstimator<>(); MultiComparator<DoubleSolution> rankingAndCrowdingComparator = new MultiComparator<DoubleSolution>( Arrays.asList( ranking.getSolutionComparator(), densityEstimator.getSolutionComparator())); InitialSolutionsCreation<DoubleSolution> initialSolutionsCreation = createInitialSolutionsParameter.getParameter(problem, populationSizeParameter.getValue()); Variation<DoubleSolution> variation = (Variation<DoubleSolution>) variationParameter.getParameter(offspringPopulationSizeParameter.getValue()); MatingPoolSelection<DoubleSolution> selection = (MatingPoolSelection<DoubleSolution>) selectionParameter.getParameter( variation.getMatingPoolSize(), rankingAndCrowdingComparator); Evaluation<DoubleSolution> evaluation = new SequentialEvaluation<>(problem); Replacement<DoubleSolution> replacement = new RankingAndDensityEstimatorReplacement<>(ranking, densityEstimator); Termination termination = new TerminationByEvaluations(maximumNumberOfEvaluationsParameter.getValue()); class NSGAII extends EvolutionaryAlgorithm<DoubleSolution> { private ExternalArchiveObserver<DoubleSolution> archiveObserver; public NSGAII( String name, Evaluation<DoubleSolution> evaluation, InitialSolutionsCreation<DoubleSolution> createInitialSolutionList, Termination termination, MatingPoolSelection<DoubleSolution> selection, Variation<DoubleSolution> variation, Replacement<DoubleSolution> replacement, ExternalArchiveObserver<DoubleSolution> archiveObserver) { super( name, evaluation, createInitialSolutionList, termination, selection, variation, replacement); this.archiveObserver = archiveObserver; evaluation.getObservable().register(archiveObserver); } @Override public List<DoubleSolution> getResult() { if (archiveObserver != null) { return archiveObserver.getArchive().getSolutionList(); } else { return population; } } } NSGAII nsgaii = new NSGAII( "NSGAII", evaluation, initialSolutionsCreation, termination, selection, variation, replacement, boundedArchiveObserver); return nsgaii; } public static void print(List<Parameter<?>> parameterList) { parameterList.forEach(item -> System.out.println(item)); } public static void main(String[] args) { String[] parameters = ("--populationSizeParameter 100 " + "--problemName org.uma.jmetal.problem.multiobjective.zdt.ZDT1 " + "--referenceFrontFileName ZDT1.pf " + "--maximumNumberOfEvaluations 25000 " + "--algorithmResult externalArchive " + "--populationSize 100 " + "--populationSizeWithArchive 100 " + "--offspringPopulationSize 100 " + "--createInitialSolutions random " + "--variation crossoverAndMutationVariation " + "--selection tournament " + "--selectionTournamentSize 2 " + "--crossover SBX " + "--crossoverProbability 0.9 " + "--crossoverRepairStrategy bounds " + "--sbxDistributionIndex 20.0 " + "--mutation polynomial " + "--mutationProbability 0.01 " + "--mutationRepairStrategy bounds " + "--polynomialMutationDistributionIndex 20.0 ") .split("\\s+"); NSGAIIWithParameters nsgaiiWithParameters = new NSGAIIWithParameters(); nsgaiiWithParameters.parseParameters(parameters); nsgaiiWithParameters.print(nsgaiiWithParameters.fixedParameterList); nsgaiiWithParameters.print(nsgaiiWithParameters.autoConfigurableParameterList); EvolutionaryAlgorithm<DoubleSolution> nsgaII = nsgaiiWithParameters.create(); nsgaII.run(); new SolutionListOutput(nsgaII.getResult()) .setSeparator("\t") .setVarFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) .setFunFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) .print(); NSGAIIiraceParameterFile nsgaiiiraceParameterFile = new NSGAIIiraceParameterFile(); nsgaiiiraceParameterFile.generateConfigurationFile( nsgaiiWithParameters.autoConfigurableParameterList); } }
package com.igormaznitsa.sciareto.ui.misc; import java.awt.Color; import java.awt.Component; import java.util.Locale; import javax.annotation.Nonnull; import javax.swing.DefaultListCellRenderer; import javax.swing.JList; import javax.swing.UIManager; import org.apache.commons.io.FilenameUtils; import com.igormaznitsa.sciareto.ui.Icons; import com.igormaznitsa.sciareto.ui.editors.PictureViewer; import com.igormaznitsa.sciareto.ui.tree.NodeFileOrFolder; import com.igormaznitsa.sciareto.ui.tree.NodeProject; import com.igormaznitsa.sciareto.ui.tree.TreeCellRenderer; import javax.swing.JLabel; public final class NodeListRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 3875614392486198647L; private final Color COLOR_ROW_EVEN; private final Color COLOR_ROW_ODD; public NodeListRenderer() { super(); final Color defaultBackground = UIManager.getLookAndFeelDefaults().getColor("List.background"); //NOI18N if (defaultBackground == null) { COLOR_ROW_EVEN = null; COLOR_ROW_ODD = null; } else { final float FACTOR = 0.97f; COLOR_ROW_EVEN = defaultBackground; COLOR_ROW_ODD = new Color(Math.max((int) (COLOR_ROW_EVEN.getRed() * FACTOR), 0), Math.max((int) (COLOR_ROW_EVEN.getGreen() * FACTOR), 0), Math.max((int) (COLOR_ROW_EVEN.getBlue() * FACTOR), 0), COLOR_ROW_EVEN.getAlpha()); } } @Nonnull private static String makeTextForNode(@Nonnull final NodeFileOrFolder node) { final NodeProject project = node.findProject(); if (project == null) { return node.toString(); } else { final String projectName = project.toString(); return node.toString() + " (found in " + projectName + ')'; } } @Override @Nonnull public Component getListCellRendererComponent(@Nonnull final JList<?> list, @Nonnull final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { final JLabel result = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); final NodeFileOrFolder node = (NodeFileOrFolder) value; final String ext = FilenameUtils.getExtension(node.toString()).toLowerCase(Locale.ENGLISH); if (!isSelected && COLOR_ROW_EVEN != null && COLOR_ROW_ODD != null) { if (index % 2 == 0) { result.setBackground(COLOR_ROW_EVEN); } else { result.setBackground(COLOR_ROW_ODD); } } if (node instanceof NodeProject || !node.isLeaf()) { result.setIcon(TreeCellRenderer.DEFAULT_FOLDER_CLOSED); } else if (ext.equals("mmd")) { //NOI18N result.setIcon(Icons.DOCUMENT.getIcon()); } else if (PictureViewer.SUPPORTED_FORMATS.contains(ext)) { result.setIcon(TreeCellRenderer.ICON_IMAGE); } else { result.setIcon(TreeCellRenderer.DEFAULT_FILE); } result.setText(makeTextForNode(node)); return result; } }
package org.opencps.api.controller.util; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.opencps.api.dossier.model.DossierDataModel; import org.opencps.api.dossier.model.DossierDetailModel; import org.opencps.auth.utils.APIDateTimeUtils; import org.opencps.datamgt.model.DictCollection; import org.opencps.datamgt.model.DictItem; import org.opencps.datamgt.service.DictCollectionLocalServiceUtil; import org.opencps.datamgt.service.DictItemLocalServiceUtil; import org.opencps.dossiermgt.action.util.DossierOverDueUtils; import org.opencps.dossiermgt.constants.DossierTerm; import org.opencps.dossiermgt.model.Dossier; import org.opencps.dossiermgt.model.DossierAction; import org.opencps.dossiermgt.model.DossierActionUser; import org.opencps.dossiermgt.model.ProcessStep; import org.opencps.dossiermgt.service.DossierActionLocalServiceUtil; import org.opencps.dossiermgt.service.DossierActionUserLocalServiceUtil; import org.opencps.dossiermgt.service.DossierLocalServiceUtil; import org.opencps.dossiermgt.service.ProcessStepLocalServiceUtil; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.search.Document; import com.liferay.portal.kernel.search.Field; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.Validator; public class DossierUtils { public static List<DossierDataModel> mappingForGetList(List<Document> docs) { List<DossierDataModel> ouputs = new ArrayList<DossierDataModel>(); for (Document doc : docs) { DossierDataModel model = new DossierDataModel(); model.setDossierIdCTN(doc.get(DossierTerm.DOSSIER_ID+"CTN")); model.setDossierId(GetterUtil.getInteger(doc.get(Field.ENTRY_CLASS_PK))); model.setGroupId(GetterUtil.getInteger(doc.get(Field.GROUP_ID))); model.setCreateDate(doc.get(Field.CREATE_DATE)); model.setModifiedDate(doc.get(Field.MODIFIED_DATE)); model.setReferenceUid(doc.get(DossierTerm.REFERENCE_UID)); model.setCounter(GetterUtil.getInteger(doc.get(DossierTerm.COUNTER))); model.setServiceCode(doc.get(DossierTerm.SERVICE_CODE)); model.setServiceName(doc.get(DossierTerm.SERVICE_NAME)); model.setGovAgencyCode(doc.get(DossierTerm.GOV_AGENCY_CODE)); model.setGovAgencyName(doc.get(DossierTerm.GOV_AGENCY_NAME)); model.setApplicantName(doc.get(DossierTerm.APPLICANT_NAME)); model.setApplicantNote(doc.get(DossierTerm.APPLICANT_NOTE)); model.setApplicantIdType(doc.get(DossierTerm.APPLICANT_ID_TYPE)); model.setApplicantIdNo(doc.get(DossierTerm.APPLICANT_ID_NO)); model.setApplicantIdDate(doc.get(DossierTerm.APPLICANT_ID_DATE)); model.setAddress(doc.get(DossierTerm.ADDRESS)); model.setCityCode(doc.get(DossierTerm.CITY_CODE)); model.setCityName(doc.get(DossierTerm.CITY_NAME)); model.setDistrictCode(doc.get(DossierTerm.DISTRICT_CODE)); model.setDistrictName(doc.get(DossierTerm.DISTRICT_NAME)); model.setWardCode(doc.get(DossierTerm.WARD_CODE)); model.setWardName(doc.get(DossierTerm.WARD_NAME)); model.setContactName(doc.get(DossierTerm.CONTACT_NAME)); model.setContactTelNo(doc.get(DossierTerm.CONTACT_TEL_NO)); model.setContactEmail(doc.get(DossierTerm.CONTACT_EMAIL)); model.setDossierNote(doc.get(DossierTerm.DOSSIER_NOTE)); model.setSubmissionNote(doc.get(DossierTerm.SUBMISSION_NOTE)); model.setBriefNote(doc.get(DossierTerm.BRIEF_NOTE)); model.setDossierNo(doc.get(DossierTerm.DOSSIER_NO)); model.setBriefNote(doc.get(DossierTerm.BRIEF_NOTE)); // model.setSubmitDate(doc.get(DossierTerm.SUBMIT_DATE)); if (Validator.isNotNull(doc.get(DossierTerm.SUBMIT_DATE))) { Date submitDate = APIDateTimeUtils.convertStringToDate(doc.get(DossierTerm.SUBMIT_DATE), APIDateTimeUtils._LUCENE_PATTERN); model.setSubmitDate(APIDateTimeUtils.convertDateToString(submitDate, APIDateTimeUtils._NORMAL_PARTTERN)); } else { model.setSubmitDate(doc.get(DossierTerm.SUBMIT_DATE)); } if (Validator.isNotNull(doc.get(DossierTerm.RECEIVE_DATE))) { Date receiveDate = APIDateTimeUtils.convertStringToDate(doc.get(DossierTerm.RECEIVE_DATE), APIDateTimeUtils._LUCENE_PATTERN); model.setReceiveDate(APIDateTimeUtils.convertDateToString(receiveDate, APIDateTimeUtils._NORMAL_PARTTERN)); } else { model.setSubmitDate(doc.get(DossierTerm.RECEIVE_DATE)); } model.setDueDate(doc.get(DossierTerm.DUE_DATE)); model.setFinishDate(doc.get(DossierTerm.FINISH_DATE)); model.setCancellingDate(doc.get(DossierTerm.CANCELLING_DATE)); model.setCorrectingDate(doc.get(DossierTerm.CORRECTING_DATE)); model.setDossierStatus(doc.get(DossierTerm.DOSSIER_STATUS)); model.setDossierStatusText(doc.get(DossierTerm.DOSSIER_STATUS_TEXT)); model.setDossierSubStatus(doc.get(DossierTerm.DOSSIER_SUB_STATUS)); model.setDossierSubStatusText(doc.get(DossierTerm.DOSSIER_SUB_STATUS_TEXT)); model.setDossierOverdue(doc.get(DossierTerm.DOSSIER_OVER_DUE)); model.setSubmitting(doc.get(DossierTerm.SUBMITTING)); model.setPermission(getPermission(GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)))); model.setLastActionDate(doc.get(DossierTerm.LAST_ACTION_DATE)); model.setLastActionCode(doc.get(DossierTerm.LAST_ACTION_CODE)); model.setLastActionName(doc.get(DossierTerm.LAST_ACTION_NAME)); model.setLastActionUser(doc.get(DossierTerm.LAST_ACTION_USER)); model.setLastActionNote(doc.get(DossierTerm.LAST_ACTION_NOTE)); model.setStepCode(doc.get(DossierTerm.STEP_CODE)); model.setStepName(doc.get(DossierTerm.STEP_NAME)); model.setStepDuedate(doc.get(DossierTerm.STEP_DUE_DATE)); model.setStepOverdue(doc.get(DossierTerm.STEP_OVER_DUE)); model.setVisited(getVisisted(GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)))); model.setPending(getPendding(GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)))); model.setOnline(doc.get(DossierTerm.ONLINE)); model.setHasPassword(doc.get(DossierTerm.PASSWORD)); model.setDossierTemplateNo(doc.get(DossierTerm.DOSSIER_TEMPLATE_NO)); model.setServerNo(doc.get(DossierTerm.SERVER_NO)); model.setViaPostal(doc.get(DossierTerm.VIA_POSTAL)); model.setPostalAddress(doc.get(DossierTerm.POSTAL_ADDRESS)); model.setPostalCityCode(doc.get(DossierTerm.POSTAL_CITY_CODE)); model.setPostalCityName(doc.get(DossierTerm.POSTAL_CITY_NAME)); model.setPostalTelNo(doc.get(DossierTerm.POSTAL_TEL_NO)); model.setCertNo(doc.get("so_chung_chi")); model.setCertDate(doc.get("ngay_ky_cc")); //TODO: Get info cert Number // List<DossierFile> dossierFileList = DossierFileLocalServiceUtil // .getDossierFilesByDossierId(GetterUtil.getInteger(doc.get(Field.ENTRY_CLASS_PK))); // StringBuilder sb = new StringBuilder(); // String deliverableCode = StringPool.BLANK; // if (dossierFileList != null && dossierFileList.size() > 0) { // int length = dossierFileList.size(); // _log.info("Size dossier File: "+ length); // int ii = 0; // for (int i = 0; i < length; i++) { // DossierFile dossierFile = dossierFileList.get(i); // deliverableCode = dossierFile.getDeliverableCode(); //// _log.info("deliverableCode: "+ deliverableCode); // if (Validator.isNotNull(deliverableCode)) { //// _log.info("deliverableCode Check: "+ deliverableCode); // ii += 1; // if (ii == 1) { // sb.append(StringPool.APOSTROPHE); // sb.append(deliverableCode); // sb.append(StringPool.APOSTROPHE); // } else { // sb.append(StringPool.COMMA); // sb.append(StringPool.APOSTROPHE); // sb.append(deliverableCode); // sb.append(StringPool.APOSTROPHE); //// _log.info("Str Dossier Id: "+ sb.toString()); // DeliverableActions action = new DeliverableActionsImpl(); // if (Validator.isNotNull(sb.toString())) { // List<Deliverable> deliverableList = action.getDeliverableByState(sb.toString(), "2"); // if (deliverableList != null && deliverableList.size() > 0) { // // int lengthDeliver = deliverableList.size(); // // _log.info("Size list deliverable: "+ lengthDeliver); // String formData = StringPool.BLANK; // List<CertNumberModel> certNumberList = new ArrayList<CertNumberModel>(); // for (Deliverable deliverable : deliverableList) { // CertNumberModel certNumberDetail = new CertNumberModel(); // formData = deliverable.getFormData(); // // _log.info("formData: "+ formData); // try { // JSONObject jsonData = JSONFactoryUtil.createJSONObject(formData); // String certNo = String.valueOf(jsonData.get("so_chung_chi")); // String certDate = String.valueOf(jsonData.get("ngay_ky_cc")); // certNumberDetail.setCertNo(certNo); // certNumberDetail.setCertDate(certDate); // certNumberList.add(certNumberDetail); // } catch (Exception e) { // // TODO: // model.getCertNumber().addAll(certNumberList); ouputs.add(model); } return ouputs; } //TODO: Process get list Paging public static List<DossierDataModel> mappingForGetListPaging(List<Document> docs, int start, int end) { List<DossierDataModel> ouputs = new ArrayList<DossierDataModel>(); int lengthDossier = docs.size(); int endPage = 0; if (lengthDossier < end) { endPage = lengthDossier; } else { endPage = end; } for (int i = start; i < endPage; i++) { Document doc = docs.get(i); // _log.info("i: "+i); DossierDataModel model = new DossierDataModel(); model.setDossierIdCTN(doc.get(DossierTerm.DOSSIER_ID+"CTN")); model.setDossierId(GetterUtil.getInteger(doc.get(Field.ENTRY_CLASS_PK))); model.setGroupId(GetterUtil.getInteger(doc.get(Field.GROUP_ID))); model.setCreateDate(doc.get(Field.CREATE_DATE)); model.setModifiedDate(doc.get(Field.MODIFIED_DATE)); model.setReferenceUid(doc.get(DossierTerm.REFERENCE_UID)); model.setCounter(GetterUtil.getInteger(doc.get(DossierTerm.COUNTER))); model.setServiceCode(doc.get(DossierTerm.SERVICE_CODE)); model.setServiceName(doc.get(DossierTerm.SERVICE_NAME)); model.setGovAgencyCode(doc.get(DossierTerm.GOV_AGENCY_CODE)); model.setGovAgencyName(doc.get(DossierTerm.GOV_AGENCY_NAME)); model.setApplicantName(doc.get(DossierTerm.APPLICANT_NAME)); model.setApplicantNote(doc.get(DossierTerm.APPLICANT_NOTE)); model.setApplicantIdType(doc.get(DossierTerm.APPLICANT_ID_TYPE)); model.setApplicantIdNo(doc.get(DossierTerm.APPLICANT_ID_NO)); model.setApplicantIdDate(doc.get(DossierTerm.APPLICANT_ID_DATE)); model.setAddress(doc.get(DossierTerm.ADDRESS)); model.setCityCode(doc.get(DossierTerm.CITY_CODE)); model.setCityName(doc.get(DossierTerm.CITY_NAME)); model.setDistrictCode(doc.get(DossierTerm.DISTRICT_CODE)); model.setDistrictName(doc.get(DossierTerm.DISTRICT_NAME)); model.setWardCode(doc.get(DossierTerm.WARD_CODE)); model.setWardName(doc.get(DossierTerm.WARD_NAME)); model.setContactName(doc.get(DossierTerm.CONTACT_NAME)); model.setContactTelNo(doc.get(DossierTerm.CONTACT_TEL_NO)); model.setContactEmail(doc.get(DossierTerm.CONTACT_EMAIL)); model.setDossierNote(doc.get(DossierTerm.DOSSIER_NOTE)); model.setSubmissionNote(doc.get(DossierTerm.SUBMISSION_NOTE)); model.setBriefNote(doc.get(DossierTerm.BRIEF_NOTE)); model.setDossierNo(doc.get(DossierTerm.DOSSIER_NO)); model.setBriefNote(doc.get(DossierTerm.BRIEF_NOTE)); model.setSubmitDate(doc.get(DossierTerm.SUBMIT_DATE)); model.setReceiveDate(doc.get(DossierTerm.RECEIVE_DATE)); model.setDueDate(doc.get(DossierTerm.DUE_DATE)); model.setFinishDate(doc.get(DossierTerm.FINISH_DATE)); model.setCancellingDate(doc.get(DossierTerm.CANCELLING_DATE)); model.setCorrectingDate(doc.get(DossierTerm.CORRECTING_DATE)); model.setDossierStatus(doc.get(DossierTerm.DOSSIER_STATUS)); model.setDossierStatusText(doc.get(DossierTerm.DOSSIER_STATUS_TEXT)); model.setDossierSubStatus(doc.get(DossierTerm.DOSSIER_SUB_STATUS)); model.setDossierSubStatusText(doc.get(DossierTerm.DOSSIER_SUB_STATUS_TEXT)); model.setDossierOverdue(doc.get(DossierTerm.DOSSIER_OVER_DUE)); model.setSubmitting(doc.get(DossierTerm.SUBMITTING)); model.setPermission(getPermission(GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)))); model.setLastActionDate(doc.get(DossierTerm.LAST_ACTION_DATE)); model.setLastActionCode(doc.get(DossierTerm.LAST_ACTION_CODE)); model.setLastActionName(doc.get(DossierTerm.LAST_ACTION_NAME)); model.setLastActionUser(doc.get(DossierTerm.LAST_ACTION_USER)); model.setLastActionNote(doc.get(DossierTerm.LAST_ACTION_NOTE)); model.setStepCode(doc.get(DossierTerm.STEP_CODE)); model.setStepName(doc.get(DossierTerm.STEP_NAME)); model.setStepDuedate(doc.get(DossierTerm.STEP_DUE_DATE)); model.setStepOverdue(doc.get(DossierTerm.STEP_OVER_DUE)); model.setVisited(getVisisted(GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)))); model.setPending(getPendding(GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)))); model.setOnline(doc.get(DossierTerm.ONLINE)); model.setHasPassword(doc.get(DossierTerm.PASSWORD)); model.setDossierTemplateNo(doc.get(DossierTerm.DOSSIER_TEMPLATE_NO)); model.setServerNo(doc.get(DossierTerm.SERVER_NO)); model.setViaPostal(doc.get(DossierTerm.VIA_POSTAL)); model.setPostalAddress(doc.get(DossierTerm.POSTAL_ADDRESS)); model.setPostalCityCode(doc.get(DossierTerm.POSTAL_CITY_CODE)); model.setPostalCityName(doc.get(DossierTerm.POSTAL_CITY_NAME)); model.setPostalTelNo(doc.get(DossierTerm.POSTAL_TEL_NO)); String certNo = doc.get("so_chung_chi"); String certDate = doc.get("ngay_ky_cc"); if (Validator.isNotNull(certNo) && Validator.isNotNull(certDate)) { Date tempDate = APIDateTimeUtils.convertStringToDate(certDate, APIDateTimeUtils._LUCENE_PATTERN); model.setCertDate(APIDateTimeUtils.convertDateToString(tempDate, APIDateTimeUtils._NORMAL_PARTTERN)); model.setCertNo(doc.get("so_chung_chi")); } ouputs.add(model); } // _log.info("ouputs: "+ouputs.size()); return ouputs; } static Log _log = LogFactoryUtil.getLog(DossierUtils.class); public static DossierDetailModel mappingForGetDetail(Dossier input, long userId) { DossierDetailModel model = new DossierDetailModel(); try { Document dossierDoc = DossierLocalServiceUtil.getDossierById(input.getDossierId(), input.getCompanyId()); model.setDossierIdCTN(dossierDoc.get(DossierTerm.DOSSIER_ID+"CTN")); } catch (Exception e) { model.setDossierIdCTN(""); } model.setDossierId(GetterUtil.getInteger(input.getDossierId())); model.setUserId(GetterUtil.getInteger(input.getUserId())); model.setCreateDate( APIDateTimeUtils.convertDateToString(input.getCreateDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setModifiedDate( APIDateTimeUtils.convertDateToString(input.getModifiedDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setReferenceUid(input.getReferenceUid()); model.setCounter(input.getCounter()); model.setServiceCode(input.getServiceCode()); model.setServiceName(input.getServiceName()); model.setGovAgencyCode(input.getGovAgencyCode()); model.setGovAgencyName(input.getGovAgencyName()); model.setDossierTemplateNo(input.getDossierTemplateNo()); model.setApplicantName(input.getApplicantName()); model.setApplicantIdType(input.getApplicantIdType()); model.setApplicantIdNo(input.getApplicantIdNo()); model.setApplicantIdDate( APIDateTimeUtils.convertDateToString(input.getApplicantIdDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setAddress(input.getAddress()); model.setCityCode(input.getCityCode()); model.setCityName(input.getCityName()); model.setDistrictCode(input.getDistrictCode()); model.setDistrictName(input.getDistrictName()); model.setWardCode(input.getWardCode()); model.setWardName(input.getWardName()); model.setContactName(input.getContactName()); model.setContactTelNo(input.getContactTelNo()); model.setContactEmail(input.getContactEmail()); model.setDossierNote(input.getDossierNote()); model.setSubmissionNote(input.getSubmissionNote()); model.setBriefNote(input.getBriefNote()); model.setDossierNo(input.getDossierNo()); model.setSubmitting(Boolean.toString(input.getSubmitting())); model.setSubmitDate( APIDateTimeUtils.convertDateToString(input.getSubmitDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setReceiveDate( APIDateTimeUtils.convertDateToString(input.getReceiveDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setDueDate(APIDateTimeUtils.convertDateToString(input.getDueDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setReleaseDate( APIDateTimeUtils.convertDateToString(input.getReleaseDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setFinishDate( APIDateTimeUtils.convertDateToString(input.getFinishDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setCancellingDate( APIDateTimeUtils.convertDateToString(input.getCancellingDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setCorrectingDate( APIDateTimeUtils.convertDateToString(input.getCorrecttingDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setDossierStatus(input.getDossierStatus()); model.setDossierStatusText(input.getDossierStatusText()); model.setDossierSubStatus(input.getDossierSubStatus()); model.setDossierSubStatusText(input.getDossierSubStatusText()); model.setViaPostal(Integer.toString(input.getViaPostal())); model.setPostalAddress(input.getPostalAddress()); model.setPostalCityCode(input.getPostalCityCode()); model.setPostalCityName(input.getPostalCityName()); model.setPostalTelNo(input.getPostalTelNo()); model.setPermission(getPermission(input.getPrimaryKey())); if (input.getDossierActionId() != 0) { DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(input.getDossierActionId()); model.setLastActionDate(APIDateTimeUtils.convertDateToString(dossierAction.getCreateDate(), APIDateTimeUtils._NORMAL_PARTTERN)); model.setLastActionName(dossierAction.getActionName()); model.setLastActionUser(dossierAction.getActionUser()); model.setLastActionNote(dossierAction.getActionNote()); model.setLastActionCode(dossierAction.getActionCode()); model.setStepCode(dossierAction.getStepCode()); model.setStepName(dossierAction.getStepName()); Date stepDuedate = DossierOverDueUtils.getStepOverDue(dossierAction.getActionOverdue(), new Date()); if (dossierAction.getActionOverdue() != 0) { model.setStepOverdue(StringPool.TRUE); } else { model.setStepOverdue(StringPool.TRUE); } model.setStepDuedate(APIDateTimeUtils.convertDateToString(stepDuedate, APIDateTimeUtils._NORMAL_PARTTERN)); ProcessStep step = ProcessStepLocalServiceUtil.fetchBySC_GID(dossierAction.getStepCode(), dossierAction.getGroupId(), dossierAction.getServiceProcessId()); model.setStepInstruction(step.getStepInstruction()); DictCollection dictCollection = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode("DOSSIER_STATUS", input.getGroupId()); String statusCode = input.getDossierStatus(); String subStatusCode = input.getDossierSubStatus(); if (Validator.isNotNull(statusCode) || Validator.isNotNull(subStatusCode)) { DictItem dictItem = null; if (Validator.isNotNull(subStatusCode)) { dictItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(subStatusCode, dictCollection.getDictCollectionId(), input.getGroupId()); } else { dictItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(statusCode, dictCollection.getDictCollectionId(), input.getGroupId()); } if (dictItem != null) { _log.info("53"); String metaData = dictItem.getMetaData(); String specialStatus = StringPool.BLANK; if (Validator.isNotNull(metaData)) { _log.info("metaData: " +metaData); try { JSONObject metaJson = JSONFactoryUtil.createJSONObject(metaData); specialStatus = metaJson.getString("specialStatus"); _log.info("specialStatus: " +specialStatus); } catch (Exception e) { // TODO: handle exception } } if (Validator.isNotNull(specialStatus) && Boolean.parseBoolean(specialStatus)) { DossierActionUser dau = DossierActionUserLocalServiceUtil.getByDossierAndUser(input.getDossierActionId(), userId); if (dau != null) { model.setSpecialNo(dau.getModerator()); } else { model.setSpecialNo(0); } } else { model.setSpecialNo(1); } } } } model.setVisited(getVisisted(input.getPrimaryKey())); model.setPending(getPendding(input.getPrimaryKey())); model.setApplicantNote(input.getApplicantNote()); model.setNotification(Boolean.toString(input.getNotification())); model.setOnline(Boolean.toString(input.getOnline())); return model; } private static String getPermission(long dossierId) { // TODO add logic here return StringPool.BLANK; } private static String getVisisted(long dossierId) { // TODO add logic here // return true or false in String type return StringPool.FALSE; } private static String getPendding(long dossierId) { // TODO add logic here // return true or false in String type return StringPool.FALSE; } private static String getApplicationNote(long dossierId) { // TODO add logic here // return true or false in String type return StringPool.BLANK; } }
package net.mcft.copy.core.inventory.slot; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import net.mcft.copy.core.misc.Enumerator; import net.mcft.copy.core.misc.IEnumerable; import net.minecraft.inventory.IInventory; public class SlotGroup implements IEnumerable<SlotBase> { public List<SlotBase> slots = new ArrayList<SlotBase>(); public SlotGroup() { } public SlotGroup(Class<? extends SlotBase> slotClass, IInventory inventory, int startIndex, int x, int y, int columns, int rows) { try { Constructor<? extends SlotBase> constructor = slotClass.getConstructor(IInventory.class, int.class, int.class, int.class); for (int j = 0; j < rows; j++) for (int i = 0; i < columns; i++) { int index = startIndex + i + j * columns; int xx = x + i * 18; int yy = y + j * 18; add(constructor.newInstance(inventory, index, xx, yy)); } } catch (Exception e) { e.printStackTrace(); } } /** Adds a slot to this slot group. */ public void add(SlotBase slot) { slots.add(slot); } // IEnumerable implementation @Override public Enumerator<SlotBase> iterator() { return Enumerator.of(slots); } }
package at.sw2017xp3.regionalo; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Arrays; import at.sw2017xp3.regionalo.model.Product; import at.sw2017xp3.regionalo.util.HttpUtils; import at.sw2017xp3.regionalo.util.JsonObjectMapper; public class ProductDetailActivity extends AppCompatActivity implements View.OnClickListener{ private ArrayList<View> list_of_elements = new ArrayList<>(); private int like_button_counter_; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_detailes); list_of_elements.addAll(Arrays.asList( findViewById(R.id.buttonLike), findViewById(R.id.ButtonContact))); for (int i = 0; i < list_of_elements.size(); i++) { list_of_elements.get(i).setOnClickListener(this); } Uri uri = Uri.parse("http://sw-ma-xp3.bplaced.net/MySQLadmin/product.php") .buildUpon() .appendQueryParameter("id", "1").build(); new GetProductTask().execute(uri.toString()); } private class GetProductTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { try { return downloadContent(params[0]); } catch (IOException e) { return "Unable to retrieve data. URL may be invalid."; } } } private String downloadContent(String myurl) throws IOException { InputStream is = null; int length = 10000; try { HttpURLConnection conn = HttpUtils.httpGet(myurl); String contentAsString = HttpUtils.convertInputStreamToString(conn.getInputStream(), length); JSONArray arr = new JSONArray(contentAsString); //featured products JSONObject mJsonObject = arr.getJSONObject(0);//one product String allProductNames; Product p = JsonObjectMapper.CreateProduct(mJsonObject); return p.getName(); } catch (Exception ex) { return ""; } finally { if (is != null) { is.close(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.loginbutton, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.buttonLogin) { Intent myIntent = new Intent(this, LoginActivity.class); startActivity(myIntent); } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { Button clickedButton = (Button)v; switch (clickedButton.getId()){ case R.id.buttonLike: like_button_counter_ = Integer.valueOf((String)(((TextView)findViewById(R.id.textViewLikeCount)).getText())); like_button_counter_++; ((TextView)findViewById(R.id.textViewLikeCount)).setText(Integer.toString(like_button_counter_)); break; case R.id.ButtonContact: //onClick moveTo Website or show contact data break; } } }
package org.apache.jackrabbit.oak.plugins.mongomk; import com.google.common.io.ByteStreams; import com.mongodb.*; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.io.PrintStream; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertNotNull; public class BlobThroughPutTest { private static final int NO_OF_NODES = 100; private static final int BLOB_SIZE = 1024 * 1024 * 2; private static final String TEST_DB1 = "tptest1"; private static final String TEST_DB2 = "tptest2"; private static final int MAX_EXEC_TIME = 5; //In seconds private static final int[] READERS = {5, 10, 15, 20}; private static final int[] WRITERS = {0, 1, 2, 4}; private final List<Result> results = new ArrayList<Result>(); @Ignore @Test public void performBenchMark() throws UnknownHostException, InterruptedException { Mongo local = new Mongo(new DBAddress("localhost:27017/test")); Mongo remote = new Mongo(new DBAddress("remote:27017/test")); run(local, false, false); run(local, true, false); run(remote, false, true); run(remote, true, true); dumpResult(); } private void dumpResult() { PrintStream ps = System.out; ps.println(Result.OUTPUT_FORMAT); for (Result r : results) { ps.println(r.toString()); } } private void run(Mongo mongo, boolean useSameDB, boolean remote) throws InterruptedException { final DB nodeDB = mongo.getDB(TEST_DB1); final DB blobDB = useSameDB ? mongo.getDB(TEST_DB1) : mongo.getDB(TEST_DB2); final DBCollection nodes = nodeDB.getCollection("nodes"); final DBCollection blobs = blobDB.getCollection("blobs"); final Benchmark b = new Benchmark(nodes, blobs); for (int readers : READERS) { for (int writers : WRITERS) { MongoUtils.dropCollections(nodeDB); MongoUtils.dropCollections(blobDB); createTestNodes(nodes); Result r = b.run(readers, writers, remote); results.add(r); } } } private void createTestNodes(DBCollection nodes) { for (int i = 0; i < NO_OF_NODES; i++) { DBObject obj = new BasicDBObject("_id", i) .append("foo", "bar1" + i); nodes.insert(obj, WriteConcern.SAFE); } } private static class Result { final static String OUTPUT_FORMAT = "remote, samedb, readers, writers, reads, writes, " + "time, readThroughPut, writeThroughPut"; int totalReads; int totalWrites = 0; int noOfReaders; int noOfWriters; int execTime; int dataSize = BLOB_SIZE; boolean sameDB; boolean remote; double readThroughPut() { return totalReads / execTime; } double writeThroughPut() { return totalWrites * dataSize / execTime; } @Override public String toString() { return String.format("%s,%s,%d,%d,%d,%d,%d,%1.0f,%s", remote, sameDB, noOfReaders, noOfWriters, totalReads, totalWrites, execTime, readThroughPut(), humanReadableByteCount((long) writeThroughPut(), true)); } } private static String humanReadableByteCount(long bytes, boolean si) { if (bytes < 0) { return "0"; } int unit = si ? 1000 : 1024; if (bytes < unit) { return bytes + " B"; } int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } private static class Benchmark { private final DBCollection nodes; private final DBCollection blobs; private final Random random = new Random(); private final AtomicBoolean stopTest = new AtomicBoolean(false); private final static byte[] DATA; private final CountDownLatch startLatch = new CountDownLatch(1); static { try { DATA = ByteStreams.toByteArray(new RandomStream(BLOB_SIZE, 100)); } catch (IOException e) { throw new IllegalStateException(e); } } private Benchmark(DBCollection nodes, DBCollection blobs) { this.nodes = nodes; this.blobs = blobs; } public Result run(int noOfReaders, int noOfWriters, boolean remote) throws InterruptedException { boolean sameDB = nodes.getDB().getName().equals(blobs.getDB().getName()); List<Reader> readers = new ArrayList<Reader>(noOfReaders); List<Writer> writers = new ArrayList<Writer>(noOfWriters); List<Runnable> runnables = new ArrayList<Runnable>(noOfReaders + noOfWriters); final CountDownLatch stopLatch = new CountDownLatch(noOfReaders + noOfWriters); for (int i = 0; i < noOfReaders; i++) { readers.add(new Reader(stopLatch)); } for (int i = 0; i < noOfWriters; i++) { writers.add(new Writer(i, stopLatch)); } runnables.addAll(readers); runnables.addAll(writers); stopTest.set(false); List<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < runnables.size(); i++) { Thread worker = new Thread(runnables.get(i)); worker.start(); threads.add(worker); } System.err.printf("Running with [%d] readers and [%d] writers. " + "Same DB [%s], Remote server [%s], Max Time [%d] seconds %n", noOfReaders, noOfWriters, sameDB, remote, MAX_EXEC_TIME); startLatch.countDown(); TimeUnit.SECONDS.sleep(MAX_EXEC_TIME); stopTest.set(true); stopLatch.await(); int totalReads = 0; for (Reader r : readers) { totalReads += r.readCount; } int totalWrites = 0; for (Writer w : writers) { totalWrites += w.writeCount; } Result r = new Result(); r.execTime = MAX_EXEC_TIME; r.noOfReaders = noOfReaders; r.noOfWriters = noOfWriters; r.totalReads = totalReads; r.totalWrites = totalWrites; r.remote = remote; r.sameDB = sameDB; System.err.printf("Run complete. Reads [%d] and writes [%d] %n", totalReads, totalWrites); System.err.println(r.toString()); return r; } private void waitForStart() { try { startLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } } private class Reader implements Runnable { int readCount = 0; final CountDownLatch stopLatch; public Reader(CountDownLatch stopLatch) { this.stopLatch = stopLatch; } public void run() { waitForStart(); while (!stopTest.get()) { int id = random.nextInt(NO_OF_NODES); DBObject o = nodes.findOne(QueryBuilder.start("_id").is(id).get()); assertNotNull("did not found object with id " + id, o); readCount++; } stopLatch.countDown(); } } private class Writer implements Runnable { int writeCount = 0; final int id; final CountDownLatch stopLatch; private Writer(int id, CountDownLatch stopLatch) { this.id = id; this.stopLatch = stopLatch; } public void run() { waitForStart(); while (!stopTest.get()) { String _id = id + "-" + writeCount; DBObject obj = new BasicDBObject() .append("foo", _id); obj.put("blob", DATA); blobs.insert(obj, WriteConcern.SAFE); writeCount++; } stopLatch.countDown(); } } } }
package org.apache.xerces.dom; import org.w3c.dom.*; /** * The DOMImplementation class is description of a particular * implementation of the Document Object Model. As such its data is * static, shared by all instances of this implementation. * <P> * The DOM API requires that it be a real object rather than static * methods. However, there's nothing that says it can't be a singleton, * so that's how I've implemented it. * * @version * @since PR-DOM-Level-1-19980818. */ public class DOMImplementationImpl implements DOMImplementation { // Data // static /** Dom implementation singleton. */ static DOMImplementationImpl singleton = new DOMImplementationImpl(); // DOMImplementation methods /** * Test if the DOM implementation supports a specific "feature" -- * currently meaning language and level thereof. * * @param feature The package name of the feature to test. * In Level 1, supported values are "HTML" and "XML" (case-insensitive). * At this writing, org.apache.xerces.dom supports only XML. * * @param version The version number of the feature being tested. * This is interpreted as "Version of the DOM API supported for the * specified Feature", and in Level 1 should be "1.0" * * @returns true iff this implementation is compatable with the * specified feature and version. */ public boolean hasFeature(String feature, String version) { // Currently, we support only XML Level 1 version 1.0 boolean anyVersion = version == null || version.length() == 0; return (feature.equalsIgnoreCase("Core") && (anyVersion || version.equals("1.0") || version.equals("2.0"))) || (feature.equalsIgnoreCase("XML") && (anyVersion || version.equals("1.0") || version.equals("2.0"))) || (feature.equalsIgnoreCase("Events") && (anyVersion || version.equals("2.0"))) || (feature.equalsIgnoreCase("MutationEvents") && (anyVersion || version.equals("2.0"))) || (feature.equalsIgnoreCase("Traversal") && (anyVersion || version.equals("2.0"))) ; } // hasFeature(String,String):boolean // Public methods /** NON-DOM: Obtain and return the single shared object */ public static DOMImplementation getDOMImplementation() { return singleton; } /** * Introduced in DOM Level 2. <p> * * Creates an empty DocumentType node. * * @param qualifiedName The qualified name of the document type to be created. * @param publicID The document type public identifier. * @param systemID The document type system identifier. * @since WD-DOM-Level-2-19990923 */ public DocumentType createDocumentType(String qualifiedName, String publicID, String systemID) { if (!DocumentImpl.isXMLName(qualifiedName)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, "DOM002 Illegal character"); } int index = qualifiedName.indexOf(':'); if (index == 0 || index == qualifiedName.length() - 1) { throw new DOMException(DOMException.NAMESPACE_ERR, "DOM003 Namespace error"); } return new DocumentTypeImpl(null, qualifiedName, publicID, systemID); } /** * Introduced in DOM Level 2. <p> * * Creates an XML Document object of the specified type with its document * element. * * @param namespaceURI The namespace URI of the document * element to create, or null. * @param qualifiedName The qualified name of the document * element to create. * @param doctype The type of document to be created or null.<p> * * When doctype is not null, its * Node.ownerDocument attribute is set to * the document being created. * @return Document A new Document object. * @throws DOMException WRONG_DOCUMENT_ERR: Raised if doctype has * already been used with a different document. * @since WD-DOM-Level-2-19990923 */ public Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) throws DOMException { if (doctype != null && doctype.getOwnerDocument() != null) { throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "DOM005 Wrong document"); } DocumentImpl doc = new DocumentImpl(doctype); Element e = doc.createElementNS( namespaceURI, qualifiedName); doc.appendChild(e); return doc; } } // class DOMImplementationImpl
package org.innovateuk.ifs.application.terms.controller; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.application.common.populator.ApplicationTermsModelPopulator; import org.innovateuk.ifs.application.common.populator.ApplicationTermsPartnerModelPopulator; import org.innovateuk.ifs.application.common.viewmodel.ApplicationTermsPartnerViewModel; import org.innovateuk.ifs.application.common.viewmodel.ApplicationTermsViewModel; import org.innovateuk.ifs.application.resource.ApplicationResource; import org.innovateuk.ifs.application.service.ApplicationRestService; import org.innovateuk.ifs.application.service.QuestionStatusRestService; import org.innovateuk.ifs.application.terms.form.ApplicationTermsForm; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.form.resource.SectionResource; import org.innovateuk.ifs.user.resource.ProcessRoleResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.UserRestService; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import java.time.ZonedDateTime; import static java.time.ZonedDateTime.now; import static org.assertj.core.util.Lists.emptyList; import static org.innovateuk.ifs.application.builder.ApplicationResourceBuilder.newApplicationResource; import static org.innovateuk.ifs.application.resource.ApplicationState.OPEN; import static org.innovateuk.ifs.application.resource.ApplicationState.SUBMITTED; import static org.innovateuk.ifs.commons.error.Error.fieldError; import static org.innovateuk.ifs.commons.rest.RestResult.restFailure; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource; import static org.innovateuk.ifs.form.builder.SectionResourceBuilder.newSectionResource; import static org.innovateuk.ifs.user.builder.ProcessRoleResourceBuilder.newProcessRoleResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; public class ApplicationTermsControllerTest extends BaseControllerMockMVCTest<ApplicationTermsController> { @Mock private UserRestService userRestServiceMock; @Mock private QuestionStatusRestService questionStatusRestServiceMock; @Mock private ApplicationRestService applicationRestServiceMock; @Mock private ApplicationTermsModelPopulator applicationTermsModelPopulatorMock; @Mock private ApplicationTermsPartnerModelPopulator applicationTermsPartnerModelPopulatorMock; @Override protected ApplicationTermsController supplyControllerUnderTest() { return new ApplicationTermsController(userRestServiceMock, questionStatusRestServiceMock, applicationRestServiceMock, applicationTermsPartnerModelPopulatorMock, applicationTermsModelPopulatorMock); } @Test public void getTerms() throws Exception { long applicationId = 3L; long compeitionId = 5L; long questionId = 7L; String competitionTermsTemplate = "terms-template"; boolean collaborativeApplication = false; boolean termsAccepted = false; UserResource loggedInUser = newUserResource() .withFirstName("Tom") .withLastName("Baldwin") .build(); ZonedDateTime termsAcceptedOn = now(); ApplicationTermsViewModel viewModel = new ApplicationTermsViewModel(applicationId, compeitionId, questionId, competitionTermsTemplate, collaborativeApplication, termsAccepted, loggedInUser.getName(), termsAcceptedOn, true); when(applicationTermsModelPopulatorMock.populate(loggedInUser, applicationId, questionId, false)).thenReturn(viewModel); setLoggedInUser(loggedInUser); mockMvc.perform(get("/application/{applicationId}/form/question/{questionId}/terms-and-conditions", applicationId, questionId)) .andExpect(status().isOk()) .andExpect(model().attribute("model", viewModel)) .andExpect(view().name("application/terms-and-conditions")); verify(applicationTermsModelPopulatorMock, only()).populate(loggedInUser, applicationId, questionId, false); } @Test public void getTerms_readOnly() throws Exception { long applicationId = 3L; long compeitionId = 5L; long questionId = 7L; String competitionTermsTemplate = "terms-template"; boolean collaborativeApplication = false; boolean termsAccepted = false; UserResource loggedInUser = newUserResource() .withFirstName("Tom") .withLastName("Baldwin") .build(); ZonedDateTime termsAcceptedOn = now(); ApplicationTermsViewModel viewModel = new ApplicationTermsViewModel(applicationId, compeitionId, questionId, competitionTermsTemplate, collaborativeApplication, termsAccepted, loggedInUser.getName(), termsAcceptedOn, true); when(applicationTermsModelPopulatorMock.populate(loggedInUser, applicationId, questionId, true)).thenReturn(viewModel); setLoggedInUser(loggedInUser); mockMvc.perform(get("/application/{applicationId}/form/question/{questionId}/terms-and-conditions?readonly=true", applicationId, questionId)) .andExpect(status().isOk()) .andExpect(model().attribute("model", viewModel)) .andExpect(view().name("application/terms-and-conditions")); verify(applicationTermsModelPopulatorMock, only()).populate(loggedInUser, applicationId, questionId, true); } @Test public void acceptTerms() throws Exception { long questionId = 7L; CompetitionResource competition = newCompetitionResource() .build(); ApplicationResource application = newApplicationResource() .withId(3L) .withCompetition(competition.getId()) .build(); SectionResource termsAndConditionsSection = newSectionResource().build(); ProcessRoleResource processRole = newProcessRoleResource() .withUser(getLoggedInUser()) .withApplication(application.getId()) .build(); when(userRestServiceMock.findProcessRole(processRole.getUser(), processRole.getApplicationId())).thenReturn(restSuccess(processRole)); when(questionStatusRestServiceMock.markAsComplete(questionId, application.getId(), processRole.getId())).thenReturn(restSuccess(emptyList())); ApplicationTermsForm form = new ApplicationTermsForm(); mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/terms-and-conditions", application.getId(), questionId) .param("agreed", "true")) .andExpect(status().is3xxRedirection()) .andExpect(model().attribute("form", form)) .andExpect(model().hasNoErrors()) .andExpect(redirectedUrlTemplate("/application/{applicationId}/form/question/{questionId}/terms-and-conditions#terms-accepted", application.getId(), questionId)); InOrder inOrder = inOrder(userRestServiceMock, questionStatusRestServiceMock); inOrder.verify(userRestServiceMock).findProcessRole(processRole.getUser(), processRole.getApplicationId()); inOrder.verify(questionStatusRestServiceMock).markAsComplete(questionId, application.getId(), processRole.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void acceptTerms_notAgreed() throws Exception { String competitionTermsTemplate = "terms-template"; boolean collaborativeApplication = false; boolean termsAccepted = false; long questionId = 7L; CompetitionResource competition = newCompetitionResource() .withId(5L) .build(); ApplicationResource application = newApplicationResource() .withId(3L) .withCompetition(competition.getId()) .build(); SectionResource termsAndConditionsSection = newSectionResource().build(); ProcessRoleResource processRole = newProcessRoleResource() .withUser(getLoggedInUser()) .withApplication(application.getId()) .build(); when(userRestServiceMock.findProcessRole(processRole.getUser(), processRole.getApplicationId())).thenReturn(restSuccess(processRole)); when(questionStatusRestServiceMock.markAsComplete(questionId, application.getId(), processRole.getId())) .thenReturn(restFailure(fieldError("agreed", "false", ""))); ApplicationTermsViewModel viewModel = new ApplicationTermsViewModel(application.getId(), competition.getId(), questionId, competitionTermsTemplate, collaborativeApplication, termsAccepted, loggedInUser.getName(), null, true); when(applicationTermsModelPopulatorMock.populate(loggedInUser, application.getId(), questionId, false)).thenReturn(viewModel); ApplicationTermsForm form = new ApplicationTermsForm(); mockMvc.perform(post("/application/{applicationId}/form/question/{questionId}/terms-and-conditions", application.getId(), questionId) .param("agreed", "false")) .andExpect(status().isOk()) .andExpect(model().attribute("form", form)) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors("form", "agreed")) .andExpect(view().name("application/terms-and-conditions")); InOrder inOrder = inOrder(userRestServiceMock, questionStatusRestServiceMock, applicationTermsModelPopulatorMock); inOrder.verify(userRestServiceMock).findProcessRole(processRole.getUser(), processRole.getApplicationId()); inOrder.verify(questionStatusRestServiceMock).markAsComplete(questionId, application.getId(), processRole.getId()); inOrder.verify(applicationTermsModelPopulatorMock).populate(loggedInUser, application.getId(), questionId, false); inOrder.verifyNoMoreInteractions(); } @Test public void getPartnerStatus() throws Exception { long questionId = 7L; CompetitionResource competition = newCompetitionResource() .build(); ApplicationResource application = newApplicationResource() .withId(3L) .withCompetition(competition.getId()) .withCollaborativeProject(true) .withApplicationState(OPEN) .build(); ApplicationTermsPartnerViewModel viewModel = new ApplicationTermsPartnerViewModel(application.getId(), questionId, emptyList()); when(applicationRestServiceMock.getApplicationById(application.getId())).thenReturn(restSuccess(application)); when(applicationTermsPartnerModelPopulatorMock.populate(application, questionId)).thenReturn(viewModel); mockMvc.perform(get("/application/{applicationId}/form/question/{questionId}/terms-and-conditions/partner-status", application.getId(), questionId)) .andExpect(status().isOk()) .andExpect(model().attribute("model", viewModel)) .andExpect(view().name("application/terms-and-conditions-partner-status")); InOrder inOrder = inOrder(applicationRestServiceMock, applicationTermsPartnerModelPopulatorMock); inOrder.verify(applicationRestServiceMock).getApplicationById(application.getId()); inOrder.verify(applicationTermsPartnerModelPopulatorMock).populate(application, questionId); inOrder.verifyNoMoreInteractions(); } @Test public void getPartnerStatus_nonCollaborative() throws Exception { long questionId = 7L; CompetitionResource competition = newCompetitionResource() .build(); ApplicationResource application = newApplicationResource() .withId(3L) .withCompetition(competition.getId()) .withCollaborativeProject(false) .withApplicationState(OPEN) .build(); ApplicationTermsPartnerViewModel viewModel = new ApplicationTermsPartnerViewModel(application.getId(), questionId, emptyList()); when(applicationRestServiceMock.getApplicationById(application.getId())).thenReturn(restSuccess(application)); mockMvc.perform(get("/application/{applicationId}/form/question/{questionId}/terms-and-conditions/partner-status", application.getId(), questionId)) .andExpect(status().isForbidden()); InOrder inOrder = inOrder(applicationRestServiceMock, applicationTermsPartnerModelPopulatorMock); inOrder.verify(applicationRestServiceMock).getApplicationById(application.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void getPartnerStatus_nonOpen() throws Exception { long questionId = 7L; CompetitionResource competition = newCompetitionResource() .build(); ApplicationResource application = newApplicationResource() .withId(3L) .withCompetition(competition.getId()) .withCollaborativeProject(true) .withApplicationState(SUBMITTED) .build(); ApplicationTermsPartnerViewModel viewModel = new ApplicationTermsPartnerViewModel(application.getId(), questionId, emptyList()); when(applicationRestServiceMock.getApplicationById(application.getId())).thenReturn(restSuccess(application)); mockMvc.perform(get("/application/{applicationId}/form/question/{questionId}/terms-and-conditions/partner-status", application.getId(), questionId)) .andExpect(status().isForbidden()); InOrder inOrder = inOrder(applicationRestServiceMock, applicationTermsPartnerModelPopulatorMock); inOrder.verify(applicationRestServiceMock).getApplicationById(application.getId()); inOrder.verifyNoMoreInteractions(); } }
package org.apache.xerces.parsers; import org.apache.xerces.dom.AttrImpl; import org.apache.xerces.dom.DeferredDocumentImpl; import org.apache.xerces.dom.CoreDocumentImpl; import org.apache.xerces.dom.DocumentImpl; import org.apache.xerces.dom.DocumentTypeImpl; import org.apache.xerces.dom.ElementDefinitionImpl; import org.apache.xerces.dom.ElementImpl; import org.apache.xerces.dom.EntityImpl; import org.apache.xerces.dom.EntityReferenceImpl; import org.apache.xerces.dom.NodeImpl; import org.apache.xerces.dom.NotationImpl; import org.apache.xerces.dom.TextImpl; import org.apache.xerces.impl.Constants; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLParserConfiguration; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.psvi.AttributePSVI; import org.apache.xerces.xni.psvi.ElementPSVI; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; /** * This is the base class of all DOM parsers. It implements the XNI * callback methods to create the DOM tree. After a successful parse of * an XML document, the DOM Document object can be queried using the * <code>getDocument</code> method. The actual pipeline is defined in * parser configuration. * * @author Arnaud Le Hors, IBM * @author Andy Clark, IBM * @author Elena Litani, IBM * * @version $Id$ */ public abstract class AbstractDOMParser extends AbstractXMLDocumentParser { // Constants // feature ids /** Feature id: namespace. */ protected static final String NAMESPACES = Constants.SAX_FEATURE_PREFIX+Constants.NAMESPACES_FEATURE; /** Feature id: create entity ref nodes. */ protected static final String CREATE_ENTITY_REF_NODES = Constants.XERCES_FEATURE_PREFIX + Constants.CREATE_ENTITY_REF_NODES_FEATURE; /** Feature id: include comments. */ protected static final String INCLUDE_COMMENTS_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.INCLUDE_COMMENTS_FEATURE; /** Feature id: create cdata nodes. */ protected static final String CREATE_CDATA_NODES_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.CREATE_CDATA_NODES_FEATURE; /** Feature id: include ignorable whitespace. */ protected static final String INCLUDE_IGNORABLE_WHITESPACE = Constants.XERCES_FEATURE_PREFIX + Constants.INCLUDE_IGNORABLE_WHITESPACE; /** Feature id: defer node expansion. */ protected static final String DEFER_NODE_EXPANSION = Constants.XERCES_FEATURE_PREFIX + Constants.DEFER_NODE_EXPANSION_FEATURE; /** Expose XML Schema normalize value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; // property ids /** Property id: document class name. */ protected static final String DOCUMENT_CLASS_NAME = Constants.XERCES_PROPERTY_PREFIX + Constants.DOCUMENT_CLASS_NAME_PROPERTY; protected static final String CURRENT_ELEMENT_NODE= Constants.XERCES_PROPERTY_PREFIX + Constants.CURRENT_ELEMENT_NODE_PROPERTY; // other /** Default document class name. */ protected static final String DEFAULT_DOCUMENT_CLASS_NAME = "org.apache.xerces.dom.DocumentImpl"; protected static final String CORE_DOCUMENT_CLASS_NAME = "org.apache.xerces.dom.CoreDocumentImpl"; // debugging /** Set to true and recompile to debug entity references. */ private static final boolean DEBUG_ENTITY_REF = false; private static final boolean DEBUG_EVENTS = false; // Data // features /** Create entity reference nodes. */ protected boolean fCreateEntityRefNodes; /** Include ignorable whitespace. */ protected boolean fIncludeIgnorableWhitespace; /** Include Comments. */ protected boolean fIncludeComments; /** Create cdata nodes. */ protected boolean fCreateCDATANodes; /** Expose XML Schema schema_normalize_values via DOM*/ protected boolean fNormalizeData = true; // dom information /** The document. */ protected Document fDocument; /** The default Xerces document implementation, if used. */ protected CoreDocumentImpl fDocumentImpl; /** The document class name to use. */ protected String fDocumentClassName; /** The document type node. */ protected DocumentType fDocumentType; /** Current node. */ protected Node fCurrentNode; protected CDATASection fCurrentCDATASection; /** Character buffer */ protected final StringBuffer fStringBuffer = new StringBuffer(50); // internal subset /** Internal subset buffer. */ protected StringBuffer fInternalSubset; // deferred expansion data protected boolean fDeferNodeExpansion; protected boolean fNamespaceAware; protected DeferredDocumentImpl fDeferredDocumentImpl; protected int fDocumentIndex; protected int fDocumentTypeIndex; protected int fCurrentNodeIndex; protected int fCurrentCDATASectionIndex; // state /** True if inside DTD external subset. */ protected boolean fInDTDExternalSubset; /** True if inside document. */ protected boolean fInDocument; /** True if inside CDATA section. */ protected boolean fInCDATASection; /** True if saw the first chunk of characters*/ protected boolean fFirstChunk = false; // data /** Attribute QName. */ private QName fAttrQName = new QName(); // Constructors /** Default constructor. */ protected AbstractDOMParser(XMLParserConfiguration config) { super(config); // add recognized features final String[] recognizedFeatures = { CREATE_ENTITY_REF_NODES, INCLUDE_IGNORABLE_WHITESPACE, DEFER_NODE_EXPANSION, INCLUDE_COMMENTS_FEATURE, CREATE_CDATA_NODES_FEATURE }; fConfiguration.addRecognizedFeatures(recognizedFeatures); // set default values fConfiguration.setFeature(CREATE_ENTITY_REF_NODES, true); fConfiguration.setFeature(INCLUDE_IGNORABLE_WHITESPACE, true); fConfiguration.setFeature(DEFER_NODE_EXPANSION, true); fConfiguration.setFeature(INCLUDE_COMMENTS_FEATURE, true); fConfiguration.setFeature(CREATE_CDATA_NODES_FEATURE, true); // add recognized properties final String[] recognizedProperties = { DOCUMENT_CLASS_NAME }; fConfiguration.addRecognizedProperties(recognizedProperties); // set default values fConfiguration.setProperty(DOCUMENT_CLASS_NAME, DEFAULT_DOCUMENT_CLASS_NAME); } // <init>(XMLParserConfiguration) /** * This method retreives the name of current document class. */ protected String getDocumentClassName() { return fDocumentClassName; } /** * This method allows the programmer to decide which document * factory to use when constructing the DOM tree. However, doing * so will lose the functionality of the default factory. Also, * a document class other than the default will lose the ability * to defer node expansion on the DOM tree produced. * * @param documentClassName The fully qualified class name of the * document factory to use when constructing * the DOM tree. * * @see #getDocumentClassName * @see #DEFAULT_DOCUMENT_CLASS_NAME */ protected void setDocumentClassName(String documentClassName) { // normalize class name if (documentClassName == null) { documentClassName = DEFAULT_DOCUMENT_CLASS_NAME; } // verify that this class exists and is of the right type try { Class _class = Class.forName(documentClassName); //if (!_class.isAssignableFrom(Document.class)) { if (!Document.class.isAssignableFrom(_class)) { // REVISIT: message throw new IllegalArgumentException("PAR002 Class, \"" + documentClassName + "\", is not of type org.w3c.dom.Document.\n" + documentClassName); } } catch (ClassNotFoundException e) { // REVISIT: message throw new IllegalArgumentException("PAR003 Class, \"" + documentClassName + "\", not found.\n" + documentClassName); } // set document class name fDocumentClassName = documentClassName; if (!documentClassName.equals(DEFAULT_DOCUMENT_CLASS_NAME)) { fDeferNodeExpansion = false; } } // setDocumentClassName(String) // Public methods /** Returns the DOM document object. */ public Document getDocument() { return fDocument; } // getDocument():Document // XMLDocumentParser methods /** * Resets the parser state. * * @throws SAXException Thrown on initialization error. */ public void reset() throws XNIException { super.reset(); // get feature state fCreateEntityRefNodes = fConfiguration.getFeature(CREATE_ENTITY_REF_NODES); fIncludeIgnorableWhitespace = fConfiguration.getFeature(INCLUDE_IGNORABLE_WHITESPACE); fDeferNodeExpansion = fConfiguration.getFeature(DEFER_NODE_EXPANSION); fNamespaceAware = fConfiguration.getFeature(NAMESPACES); fIncludeComments = fConfiguration.getFeature(INCLUDE_COMMENTS_FEATURE); fCreateCDATANodes = fConfiguration.getFeature(CREATE_CDATA_NODES_FEATURE); try { fNormalizeData = fConfiguration.getFeature(NORMALIZE_DATA); } catch (XMLConfigurationException x) { fNormalizeData = false; } // get property setDocumentClassName((String) fConfiguration.getProperty(DOCUMENT_CLASS_NAME)); // reset dom information fDocument = null; fDocumentImpl = null; fDocumentType = null; fDocumentTypeIndex = -1; fDeferredDocumentImpl = null; fCurrentNode = null; // reset string buffer fStringBuffer.setLength(0); // reset state information fInDocument = false; fInDTD = false; fInDTDExternalSubset = false; fInCDATASection = false; fFirstChunk = false; fCurrentCDATASection = null; fCurrentCDATASectionIndex = -1; } // reset() // XMLDocumentHandler methods /** * This method notifies the start of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the general entity. * @param identifier The resource identifier. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @exception XNIException Thrown by handler to signal an error. */ public void startGeneralEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println("==>startGeneralEntity ("+name+")"); } // Always create entity reference nodes to be able to recreate // entity as a part of doctype if (!fDeferNodeExpansion) { setCharacterData(true); EntityReference er = fDocument.createEntityReference(name); // we don't need synchronization now, because entity ref will be // expanded anyway. Synch only needed when user creates entityRef node ((EntityReferenceImpl)er).needsSyncChildren(false); fCurrentNode.appendChild(er); fCurrentNode = er; } else { int er = fDeferredDocumentImpl.createDeferredEntityReference(name); fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, er); fCurrentNodeIndex = er; } } // startGeneralEntity(String,XMLResourceIdentifier, Augmentations) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { if (!fDeferNodeExpansion) { // REVISIT: when DOM Level 3 is REC rely on Document.support // instead of specific class if (fDocumentType != null) { NamedNodeMap entities = fDocumentType.getEntities(); String name = fCurrentNode.getNodeName(); EntityImpl entity = (EntityImpl) entities.getNamedItem(name); if (entity != null) { entity.setVersion(version); entity.setEncoding(encoding); } } } else { String name = fDeferredDocumentImpl.getNodeName(fCurrentNodeIndex, false); if (fDocumentTypeIndex != -1 && name != null) { // find corresponding Entity decl boolean found = false; int node = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false); while (node != -1) { short nodeType = fDeferredDocumentImpl.getNodeType(node, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName(node, false); if (nodeName.equals(name)) { found = true; break; } } node = fDeferredDocumentImpl.getRealPrevSibling(node, false); } if (found) { fDeferredDocumentImpl.setEntityInfo(node, version, encoding); } } } } // textDecl(String,String) /** * A comment. * * @param text The text in the comment. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by application to signal an error. */ public void comment(XMLString text, Augmentations augs) throws XNIException { if (fInDTD) { if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append("<! fInternalSubset.append(text.toString()); fInternalSubset.append(" } return; } if (!fIncludeComments) { return; } if (!fDeferNodeExpansion) { setCharacterData(false); Comment comment = fDocument.createComment(text.toString()); fCurrentNode.appendChild(comment); } else { int comment = fDeferredDocumentImpl.createDeferredComment(text.toString()); fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, comment); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { if (fInDTD) { if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append("<?"); fInternalSubset.append(target.toString()); fInternalSubset.append(' '); fInternalSubset.append(data.toString()); fInternalSubset.append("?>"); } } if (!fDeferNodeExpansion) { setCharacterData(false); ProcessingInstruction pi = fDocument.createProcessingInstruction(target, data.toString()); fCurrentNode.appendChild(pi); } else { int pi = fDeferredDocumentImpl. createDeferredProcessingInstruction(target, data.toString()); fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, pi); } } // processingInstruction(String,XMLString) /** * The start of the document. * * @param locator The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument(XMLLocator locator, String encoding, Augmentations augs) throws XNIException { fInDocument = true; if (!fDeferNodeExpansion) { if (fDocumentClassName.equals(DEFAULT_DOCUMENT_CLASS_NAME)) { fDocument = new DocumentImpl(); fDocumentImpl = (CoreDocumentImpl)fDocument; // REVISIT: when DOM Level 3 is REC rely on Document.support // instead of specific class // set DOM error checking off fDocumentImpl.setStrictErrorChecking(false); // set actual encoding fDocumentImpl.setActualEncoding(encoding); // set documentURI fDocumentImpl.setDocumentURI(locator.getExpandedSystemId()); } else { // use specified document class try { Class documentClass = Class.forName(fDocumentClassName); fDocument = (Document)documentClass.newInstance(); // if subclass of our own class that's cool too Class defaultDocClass = Class.forName(CORE_DOCUMENT_CLASS_NAME); if (defaultDocClass.isAssignableFrom(documentClass)) { fDocumentImpl = (CoreDocumentImpl)fDocument; // REVISIT: when DOM Level 3 is REC rely on // Document.support instead of specific class // set DOM error checking off fDocumentImpl.setStrictErrorChecking(false); // set actual encoding fDocumentImpl.setActualEncoding(encoding); // set documentURI fDocumentImpl.setDocumentURI(locator.getExpandedSystemId()); } } catch (ClassNotFoundException e) { // won't happen we already checked that earlier } catch (Exception e) { // REVISIT: Localize this message. throw new RuntimeException( "Failed to create document object of class: " + fDocumentClassName); } } fCurrentNode = fDocument; } else { fDeferredDocumentImpl = new DeferredDocumentImpl(fNamespaceAware); fDocument = fDeferredDocumentImpl; fDocumentIndex = fDeferredDocumentImpl.createDeferredDocument(); // REVISIT: when DOM Level 3 is REC rely on // Document.support instead of specific class fDeferredDocumentImpl.setStrictErrorChecking(false); // set actual encoding fDeferredDocumentImpl.setActualEncoding(encoding); // set documentURI fDeferredDocumentImpl.setDocumentURI(locator.getExpandedSystemId()); fCurrentNodeIndex = fDocumentIndex; } } // startDocument(String,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException { if (!fDeferNodeExpansion) { // REVISIT: when DOM Level 3 is REC rely on Document.support // instead of specific class if (fDocumentImpl != null) { fDocumentImpl.setVersion(version); fDocumentImpl.setEncoding(encoding); fDocumentImpl.setStandalone("true".equals(standalone)); } } else { fDeferredDocumentImpl.setVersion(version); fDeferredDocumentImpl.setEncoding(encoding); fDeferredDocumentImpl.setStandalone("true".equals(standalone)); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl(String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { if (!fDeferNodeExpansion) { if (fDocumentImpl != null) { fDocumentType = fDocumentImpl.createDocumentType( rootElement, publicId, systemId); fCurrentNode.appendChild(fDocumentType); } } else { fDocumentTypeIndex = fDeferredDocumentImpl. createDeferredDocumentType(rootElement, publicId, systemId); fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, fDocumentTypeIndex); } } // doctypeDecl(String,String,String) /** * The start of an element. If the document specifies the start element * by using an empty tag, then the startElement method will immediately * be followed by the endElement method, with no intervening methods. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println("==>startElement ("+element.rawname+")"); } if (!fDeferNodeExpansion) { Element el = createElementNode(element); int attrCount = attributes.getLength(); for (int i = 0; i < attrCount; i++) { attributes.getName(i, fAttrQName); // DOM Level 2 wants all namespace declaration attributes String attributeName = fAttrQName.rawname; if (attributeName !=null && (attributeName.startsWith("xmlns:") || attributeName.equals("xmlns"))) { fAttrQName.uri = NamespaceContext.XMLNS_URI; } Attr attr = createAttrNode(fAttrQName); String attrValue = attributes.getValue(i); // REVISIT: Should this happen here ? Why not in schema validator? if (fNormalizeData) { AttributePSVI attrPSVI = (AttributePSVI)attributes.getAugmentations(i).getItem(Constants.ATTRIBUTE_PSVI); // If validation is not attempted, the SchemaNormalizedValue will be null. // We shouldn't take the normalized value in this case. if (attrPSVI != null && attrPSVI.getValidationAttempted() == AttributePSVI.FULL_VALIDATION) { attrValue = attrPSVI.getSchemaNormalizedValue(); } } attr.setValue(attrValue); el.setAttributeNode(attr); // NOTE: The specified value MUST be set after you set // the node value because that turns the "specified" // flag to "true" which may overwrite a "false" // value from the attribute list. -Ac if (fDocumentImpl != null) { AttrImpl attrImpl = (AttrImpl)attr; boolean specified = attributes.isSpecified(i); attrImpl.setSpecified(specified); // identifier registration if (attributes.getType(i).equals("ID")) { ((ElementImpl) el).setIdAttributeNode(attr); } } // REVISIT: Handle entities in attribute value. } setCharacterData(false); fCurrentNode.appendChild(el); fCurrentNode = el; } else { int el = fDeferredDocumentImpl.createDeferredElement(fNamespaceAware ? element.uri : null, element.rawname); int attrCount = attributes.getLength(); for (int i = 0; i < attrCount; i++) { String attrValue = attributes.getValue(i); // REVISIT: Should this happen here ? Why not in schema validator? if (fNormalizeData) { AttributePSVI attrPSVI = (AttributePSVI)attributes.getAugmentations(i).getItem(Constants.ATTRIBUTE_PSVI); // If validation is not attempted, the SchemaNormalizedValue will be null. // We shouldn't take the normalized value in this case. if (attrPSVI != null && attrPSVI.getValidationAttempted() == AttributePSVI.FULL_VALIDATION) { attrValue = attrPSVI.getSchemaNormalizedValue(); } } int attr = fDeferredDocumentImpl.setDeferredAttribute(el, attributes.getQName(i), attributes.getURI(i), attrValue, attributes.isSpecified(i)); // identifier registration if (attributes.getType(i).equals("ID")) { fDeferredDocumentImpl.setIdAttributeNode(el, attr); } } fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, el); fCurrentNodeIndex = el; } } // startElement(QName,XMLAttributes) /** * Character content. * * @param text The content. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void characters(XMLString text, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println("==>characters(): "+text.toString()); } if (!fDeferNodeExpansion) { if (fInCDATASection && fCreateCDATANodes) { if (fCurrentCDATASection == null) { fCurrentCDATASection = fDocument.createCDATASection(text.toString()); fCurrentNode.appendChild(fCurrentCDATASection); fCurrentNode = fCurrentCDATASection; } else { fCurrentCDATASection.appendData(text.toString()); } } else if (!fInDTD) { // if type is union (XML Schema) it is possible that we receive // character call with empty data if (text.length == 0) { return; } String value = null; // normalized value for element is stored in schema_normalize_value property // of PSVI element. if (fNormalizeData && augs != null) { ElementPSVI elemPSVI = (ElementPSVI)augs.getItem(Constants.ELEMENT_PSVI); if (elemPSVI != null) { value = elemPSVI.getSchemaNormalizedValue(); } } if (value == null) { value = text.toString(); } Node child = fCurrentNode.getLastChild(); if (child != null && child.getNodeType() == Node.TEXT_NODE) { // collect all the data into the string buffer. if (fFirstChunk) { fStringBuffer.append(((TextImpl)child).removeData()); fFirstChunk = false; } fStringBuffer.append(value); } else { fFirstChunk = true; Text textNode = fDocument.createTextNode(value); fCurrentNode.appendChild(textNode); } } } else { // The Text and CDATASection normalization is taken care of within // the DOM in the deferred case. if (fInCDATASection && fCreateCDATANodes) { if (fCurrentCDATASectionIndex == -1) { int cs = fDeferredDocumentImpl. createDeferredCDATASection(text.toString()); fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, cs); fCurrentCDATASectionIndex = cs; fCurrentNodeIndex = cs; } else { int txt = fDeferredDocumentImpl. createDeferredTextNode(text.toString(), false); fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, txt); } } else if (!fInDTD) { // if type is union (XML Schema) it is possible that we receive // character call with empty data if (text.length == 0) { return; } String value = null; // normalized value for element is stored in schema_normalize_value property // of PSVI element. if (fNormalizeData && augs != null) { ElementPSVI elemPSVI = (ElementPSVI)augs.getItem(Constants.ELEMENT_PSVI); if (elemPSVI != null) { value = elemPSVI.getSchemaNormalizedValue(); } } if (value == null) { value = text.toString(); } int txt = fDeferredDocumentImpl. createDeferredTextNode(value, false); fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, txt); } } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { if (!fIncludeIgnorableWhitespace) { return; } if (!fDeferNodeExpansion) { Node child = fCurrentNode.getLastChild(); if (child != null && child.getNodeType() == Node.TEXT_NODE) { Text textNode = (Text)child; textNode.appendData(text.toString()); } else { Text textNode = fDocument.createTextNode(text.toString()); if (fDocumentImpl != null) { TextImpl textNodeImpl = (TextImpl)textNode; textNodeImpl.setIgnorableWhitespace(true); } fCurrentNode.appendChild(textNode); } } else { // The Text normalization is taken care of within the DOM in the // deferred case. int txt = fDeferredDocumentImpl. createDeferredTextNode(text.toString(), true); fDeferredDocumentImpl.appendChild(fCurrentNodeIndex, txt); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endElement(QName element, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println("==>endElement ("+element.rawname+")"); } if (!fDeferNodeExpansion) { setCharacterData(false); fCurrentNode = fCurrentNode.getParentNode(); } else { fCurrentNodeIndex = fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex, false); } } // endElement(QName) /** * The end of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endPrefixMapping(String prefix, Augmentations augs) throws XNIException { } // endPrefixMapping(String) /** * The start of a CDATA section. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA(Augmentations augs) throws XNIException { setCharacterData(false); fInCDATASection = true; } // startCDATA() /** * The end of a CDATA section. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA(Augmentations augs) throws XNIException { fInCDATASection = false; if (!fDeferNodeExpansion) { if (fCurrentCDATASection !=null) { fCurrentNode = fCurrentNode.getParentNode(); fCurrentCDATASection = null; } } else { if (fCurrentCDATASectionIndex !=-1) { fCurrentNodeIndex = fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex, false); fCurrentCDATASectionIndex = -1; } } } // endCDATA() /** * The end of the document. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument(Augmentations augs) throws XNIException { fInDocument = false; if (!fDeferNodeExpansion) { // REVISIT: when DOM Level 3 is REC rely on Document.support // instead of specific class // set DOM error checking back on if (fDocumentImpl != null) { fDocumentImpl.setStrictErrorChecking(true); } fCurrentNode = null; } else { fCurrentNodeIndex = -1; } } // endDocument() /** * This method notifies the end of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param augs Additional information that may include infoset augmentations * * @exception XNIException * Thrown by handler to signal an error. */ public void endGeneralEntity(String name, Augmentations augs) throws XNIException { if (DEBUG_EVENTS) { System.out.println("==>endGeneralEntity: ("+name+")"); } if (!fDeferNodeExpansion) { setCharacterData(true); if (fDocumentType != null) { NamedNodeMap entities = fDocumentType.getEntities(); NodeImpl entity = (NodeImpl)entities.getNamedItem(name); if (entity != null && entity.getFirstChild() == null) { entity.setReadOnly(false, true); Node child = fCurrentNode.getFirstChild(); while (child != null) { Node copy = child.cloneNode(true); entity.appendChild(copy); child = child.getNextSibling(); } entity.setReadOnly(true, true); entities.setNamedItem(entity); } } if (fCreateEntityRefNodes) { // Make entity ref node read only ((NodeImpl)fCurrentNode).setReadOnly(true, true); fCurrentNode = fCurrentNode.getParentNode(); } else { //!fCreateEntityRefNodes // move entity reference children to the list of // siblings of its parent and remove entity reference NodeList children = fCurrentNode.getChildNodes(); Node parent = fCurrentNode.getParentNode(); int length = children.getLength(); Node previous = fCurrentNode.getPreviousSibling(); // normalize text nodes if (previous != null && previous.getNodeType() == Node.TEXT_NODE && children.item(0).getNodeType() == Node.TEXT_NODE) { ((Text)previous).appendData(children.item(0).getNodeValue()); } else { parent.insertBefore(children.item(0), fCurrentNode); } for (int i=1;i <length;i++) { parent.insertBefore(children.item(0), fCurrentNode); } parent.removeChild(fCurrentNode); fCurrentNode = parent; } } else { int entityIndex = -1; int dtChildIndex = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false); while (dtChildIndex != -1) { short nodeType = fDeferredDocumentImpl.getNodeType(dtChildIndex, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName(dtChildIndex, false); if (nodeName.equals(name)) { if (fDeferredDocumentImpl.getLastChild(dtChildIndex, false) == -1) { entityIndex = dtChildIndex; } break; } } dtChildIndex = fDeferredDocumentImpl.getRealPrevSibling(dtChildIndex, false); } if (entityIndex != -1) { int prevIndex = -1; int childIndex = fDeferredDocumentImpl.getLastChild(fCurrentNodeIndex, false); while (childIndex != -1) { int cloneIndex = fDeferredDocumentImpl.cloneNode(childIndex, true); fDeferredDocumentImpl.insertBefore(entityIndex, cloneIndex, prevIndex); prevIndex = cloneIndex; childIndex = fDeferredDocumentImpl.getRealPrevSibling(childIndex, false); } } if (fCreateEntityRefNodes) { fCurrentNodeIndex = fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex, false); } else { //!fCreateEntityRefNodes // move children of entity ref before the entity ref. // remove entity ref. // holds a child of entity ref int childIndex = fDeferredDocumentImpl.getLastChild(fCurrentNodeIndex, false); int parentIndex = fDeferredDocumentImpl.getParentNode(fCurrentNodeIndex, false); int prevIndex = fCurrentNodeIndex; int lastChild = childIndex; int sibling = -1; while (childIndex != -1) { sibling = fDeferredDocumentImpl.getRealPrevSibling(childIndex, false); fDeferredDocumentImpl.insertBefore(parentIndex, childIndex, prevIndex); prevIndex = childIndex; childIndex = sibling; } fDeferredDocumentImpl.setAsLastChild(parentIndex, lastChild); fCurrentNodeIndex = parentIndex; } } } // endGeneralEntity(String, Augmentations) // XMLDTDHandler methods /** * The start of the DTD. * * @param locator The document locator, or null if the document * location cannot be reported during the parsing of * the document DTD. However, it is <em>strongly</em> * recommended that a locator be supplied that can * at least report the base system identifier of the * DTD. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void startDTD(XMLLocator locator, Augmentations augs) throws XNIException { super.startDTD(locator, augs); if (fDeferNodeExpansion || fDocumentImpl != null) { fInternalSubset = new StringBuffer(1024); } } // startDTD(XMLLocator) /** * The end of the DTD. * * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void endDTD(Augmentations augs) throws XNIException { super.endDTD(augs); String internalSubset = fInternalSubset != null && fInternalSubset.length() > 0 ? fInternalSubset.toString() : null; if (fDeferNodeExpansion) { if (internalSubset != null) { fDeferredDocumentImpl.setInternalSubset(fDocumentTypeIndex, internalSubset); } } else if (fDocumentImpl != null) { if (internalSubset != null) { ((DocumentTypeImpl)fDocumentType).setInternalSubset(internalSubset); } } } // endDTD() /** * The start of the DTD external subset. * * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void startExternalSubset(Augmentations augs) throws XNIException { fInDTDExternalSubset = true; } // startExternalSubset(Augmentations) /** * The end of the DTD external subset. * * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void endExternalSubset(Augmentations augs) throws XNIException { fInDTDExternalSubset = false; } // endExternalSubset(Augmentations) /** * An internal entity declaration. * * @param name The name of the entity. Parameter entity names start with * '%', whereas the name of a general entity is just the * entity name. * @param text The value of the entity. * @param nonNormalizedText The non-normalized value of the entity. This * value contains the same sequence of characters that was in * the internal entity declaration, without any entity * references expanded. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void internalEntityDecl(String name, XMLString text, XMLString nonNormalizedText, Augmentations augs) throws XNIException { // internal subset string if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append("<!ENTITY "); if (name.startsWith("%")) { fInternalSubset.append("% "); fInternalSubset.append(name.substring(1)); } else { fInternalSubset.append(name); } fInternalSubset.append(' '); String value = nonNormalizedText.toString(); boolean singleQuote = value.indexOf('\'') == -1; fInternalSubset.append(singleQuote ? '\'' : '"'); fInternalSubset.append(value); fInternalSubset.append(singleQuote ? '\'' : '"'); fInternalSubset.append(">\n"); } // NOTE: We only know how to create these nodes for the Xerces // DOM implementation because DOM Level 2 does not specify // that functionality. -Ac // create full node // don't add parameter entities! if(name.startsWith("%")) return; if (fDocumentType != null) { NamedNodeMap entities = fDocumentType.getEntities(); EntityImpl entity = (EntityImpl)entities.getNamedItem(name); if (entity == null) { entity = (EntityImpl)fDocumentImpl.createEntity(name); entities.setNamedItem(entity); } } // create deferred node if (fDocumentTypeIndex != -1) { boolean found = false; int node = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false); while (node != -1) { short nodeType = fDeferredDocumentImpl.getNodeType(node, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName(node, false); if (nodeName.equals(name)) { found = true; break; } } node = fDeferredDocumentImpl.getRealPrevSibling(node, false); } if (!found) { int entityIndex = fDeferredDocumentImpl.createDeferredEntity(name, null, null, null); fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, entityIndex); } } } // internalEntityDecl(String,XMLString,XMLString) /** * An external entity declaration. * * @param name The name of the entity. Parameter entity names start * with '%', whereas the name of a general entity is just * the entity name. * @param identifier An object containing all location information * pertinent to this notation. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void externalEntityDecl(String name, XMLResourceIdentifier identifier, Augmentations augs) throws XNIException { // internal subset string String publicId = identifier.getPublicId(); String literalSystemId = identifier.getLiteralSystemId(); if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append("<!ENTITY "); if (name.startsWith("%")) { fInternalSubset.append("% "); fInternalSubset.append(name.substring(1)); } else { fInternalSubset.append(name); } fInternalSubset.append(' '); if (publicId != null) { fInternalSubset.append("PUBLIC '"); fInternalSubset.append(publicId); fInternalSubset.append("' '"); } else { fInternalSubset.append("SYSTEM '"); } fInternalSubset.append(literalSystemId); fInternalSubset.append("'>\n"); } // NOTE: We only know how to create these nodes for the Xerces // DOM implementation because DOM Level 2 does not specify // that functionality. -Ac // create full node // don't add parameter entities! if(name.startsWith("%")) return; if (fDocumentType != null) { NamedNodeMap entities = fDocumentType.getEntities(); EntityImpl entity = (EntityImpl)entities.getNamedItem(name); if (entity == null) { entity = (EntityImpl)fDocumentImpl.createEntity(name); entity.setPublicId(publicId); entity.setSystemId(literalSystemId); entities.setNamedItem(entity); } } // create deferred node if (fDocumentTypeIndex != -1) { boolean found = false; int nodeIndex = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false); while (nodeIndex != -1) { short nodeType = fDeferredDocumentImpl.getNodeType(nodeIndex, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName(nodeIndex, false); if (nodeName.equals(name)) { found = true; break; } } nodeIndex = fDeferredDocumentImpl.getRealPrevSibling(nodeIndex, false); } if (!found) { int entityIndex = fDeferredDocumentImpl.createDeferredEntity( name, publicId, literalSystemId, null); fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, entityIndex); } } } // externalEntityDecl(String,XMLResourceIdentifier, Augmentations) /** * An unparsed entity declaration. * * @param name The name of the entity. * @param identifier An object containing all location information * pertinent to this entity. * @param notation The name of the notation. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void unparsedEntityDecl(String name, XMLResourceIdentifier identifier, String notation, Augmentations augs) throws XNIException { // internal subset string String publicId = identifier.getPublicId(); String literalSystemId = identifier.getLiteralSystemId(); if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append("<!ENTITY "); fInternalSubset.append(name); fInternalSubset.append(' '); if (publicId != null) { fInternalSubset.append("PUBLIC '"); fInternalSubset.append(publicId); if (literalSystemId != null) { fInternalSubset.append("' '"); fInternalSubset.append(literalSystemId); } } else { fInternalSubset.append("SYSTEM '"); fInternalSubset.append(literalSystemId); } fInternalSubset.append("' NDATA "); fInternalSubset.append(notation); fInternalSubset.append(">\n"); } // NOTE: We only know how to create these nodes for the Xerces // DOM implementation because DOM Level 2 does not specify // that functionality. -Ac // create full node if (fDocumentType != null) { NamedNodeMap entities = fDocumentType.getEntities(); EntityImpl entity = (EntityImpl)entities.getNamedItem(name); if (entity == null) { entity = (EntityImpl)fDocumentImpl.createEntity(name); entity.setPublicId(publicId); entity.setSystemId(literalSystemId); entity.setNotationName(notation); entities.setNamedItem(entity); } } // create deferred node if (fDocumentTypeIndex != -1) { boolean found = false; int nodeIndex = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false); while (nodeIndex != -1) { short nodeType = fDeferredDocumentImpl.getNodeType(nodeIndex, false); if (nodeType == Node.ENTITY_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName(nodeIndex, false); if (nodeName.equals(name)) { found = true; break; } } nodeIndex = fDeferredDocumentImpl.getRealPrevSibling(nodeIndex, false); } if (!found) { int entityIndex = fDeferredDocumentImpl.createDeferredEntity( name, publicId, literalSystemId, notation); fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, entityIndex); } } } // unparsedEntityDecl(String,XMLResourceIdentifier, String, Augmentations) /** * A notation declaration * * @param name The name of the notation. * @param identifier An object containing all location information * pertinent to this notation. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void notationDecl(String name, XMLResourceIdentifier identifier, Augmentations augs) throws XNIException { // internal subset string String publicId = identifier.getPublicId(); String literalSystemId = identifier.getLiteralSystemId(); if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append("<!NOTATION "); fInternalSubset.append(name); if (publicId != null) { fInternalSubset.append(" PUBLIC '"); fInternalSubset.append(publicId); if (literalSystemId != null) { fInternalSubset.append("' '"); fInternalSubset.append(literalSystemId); } } else { fInternalSubset.append(" SYSTEM '"); fInternalSubset.append(literalSystemId); } fInternalSubset.append("'>\n"); } // NOTE: We only know how to create these nodes for the Xerces // DOM implementation because DOM Level 2 does not specify // that functionality. -Ac // create full node if (fDocumentType != null) { NamedNodeMap notations = fDocumentType.getNotations(); if (notations.getNamedItem(name) == null) { NotationImpl notation = (NotationImpl)fDocumentImpl.createNotation(name); notation.setPublicId(publicId); notation.setSystemId(literalSystemId); notations.setNamedItem(notation); } } // create deferred node if (fDocumentTypeIndex != -1) { boolean found = false; int nodeIndex = fDeferredDocumentImpl.getLastChild(fDocumentTypeIndex, false); while (nodeIndex != -1) { short nodeType = fDeferredDocumentImpl.getNodeType(nodeIndex, false); if (nodeType == Node.NOTATION_NODE) { String nodeName = fDeferredDocumentImpl.getNodeName(nodeIndex, false); if (nodeName.equals(name)) { found = true; break; } } nodeIndex = fDeferredDocumentImpl.getPrevSibling(nodeIndex, false); } if (!found) { int notationIndex = fDeferredDocumentImpl.createDeferredNotation( name, publicId, literalSystemId); fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, notationIndex); } } } // notationDecl(String,XMLResourceIdentifier, Augmentations) /** * An element declaration. * * @param name The name of the element. * @param contentModel The element content model. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void elementDecl(String name, String contentModel, Augmentations augs) throws XNIException { // internal subset string if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append("<!ELEMENT "); fInternalSubset.append(name); fInternalSubset.append(' '); fInternalSubset.append(contentModel); fInternalSubset.append(">\n"); } } // elementDecl(String,String) /** * An attribute declaration. * * @param elementName The name of the element that this attribute * is associated with. * @param attributeName The name of the attribute. * @param type The attribute type. This value will be one of * the following: "CDATA", "ENTITY", "ENTITIES", * "ENUMERATION", "ID", "IDREF", "IDREFS", * "NMTOKEN", "NMTOKENS", or "NOTATION". * @param enumeration If the type has the value "ENUMERATION" or * "NOTATION", this array holds the allowed attribute * values; otherwise, this array is null. * @param defaultType The attribute default type. This value will be * one of the following: "#FIXED", "#IMPLIED", * "#REQUIRED", or null. * @param defaultValue The attribute default value, or null if no * default value is specified. * @param nonNormalizedDefaultValue The attribute default value with no normalization * performed, or null if no default value is specified. * @param augs Additional information that may include infoset * augmentations. * * @throws XNIException Thrown by handler to signal an error. */ public void attributeDecl(String elementName, String attributeName, String type, String[] enumeration, String defaultType, XMLString defaultValue, XMLString nonNormalizedDefaultValue, Augmentations augs) throws XNIException { // internal subset string if (fInternalSubset != null && !fInDTDExternalSubset) { fInternalSubset.append("<!ATTLIST "); fInternalSubset.append(elementName); fInternalSubset.append(' '); fInternalSubset.append(attributeName); fInternalSubset.append(' '); if (type.equals("ENUMERATION")) { fInternalSubset.append('('); for (int i = 0; i < enumeration.length; i++) { if (i > 0) { fInternalSubset.append('|'); } fInternalSubset.append(enumeration[i]); } fInternalSubset.append(')'); } else { fInternalSubset.append(type); } if (defaultType != null) { fInternalSubset.append(' '); fInternalSubset.append(defaultType); } if (defaultValue != null) { fInternalSubset.append(" '"); for (int i = 0; i < defaultValue.length; i++) { char c = defaultValue.ch[defaultValue.offset + i]; if (c == '\'') { fInternalSubset.append("&apos;"); } else { fInternalSubset.append(c); } } fInternalSubset.append('\''); } fInternalSubset.append(">\n"); } // deferred expansion if (fDeferredDocumentImpl != null) { // get the default value if (defaultValue != null) { // get element definition int elementDefIndex = fDeferredDocumentImpl.lookupElementDefinition(elementName); // create element definition if not already there if (elementDefIndex == -1) { elementDefIndex = fDeferredDocumentImpl.createDeferredElementDefinition(elementName); fDeferredDocumentImpl.appendChild(fDocumentTypeIndex, elementDefIndex); } // add default attribute int attrIndex = fDeferredDocumentImpl.createDeferredAttribute( attributeName, defaultValue.toString(), false); // REVISIT: set ID type correctly fDeferredDocumentImpl.appendChild(elementDefIndex, attrIndex); } } // if deferred // full expansion else if (fDocumentImpl != null) { // get the default value if (defaultValue != null) { // get element definition node NamedNodeMap elements = ((DocumentTypeImpl)fDocumentType).getElements(); ElementDefinitionImpl elementDef = (ElementDefinitionImpl)elements.getNamedItem(elementName); if (elementDef == null) { elementDef = fDocumentImpl.createElementDefinition(elementName); ((DocumentTypeImpl)fDocumentType).getElements().setNamedItem(elementDef); } // REVISIT: Check for uniqueness of element name? -Ac // create attribute and set properties boolean nsEnabled = fNamespaceAware; AttrImpl attr; if (nsEnabled) { String namespaceURI = null; // DOM Level 2 wants all namespace declaration attributes // So as long as the XML parser doesn't do it, it needs to // done here. if (attributeName.startsWith("xmlns:") || attributeName.equals("xmlns")) { namespaceURI = NamespaceContext.XMLNS_URI; } attr = (AttrImpl)fDocumentImpl.createAttributeNS(namespaceURI, attributeName); } else { attr = (AttrImpl)fDocumentImpl.createAttribute(attributeName); } attr.setValue(defaultValue.toString()); attr.setSpecified(false); // add default attribute to element definition if (nsEnabled){ elementDef.getAttributes().setNamedItemNS(attr); } else { elementDef.getAttributes().setNamedItem(attr); } } } // if NOT defer-node-expansion } // attributeDecl(String,String,String,String[],String,XMLString, XMLString, Augmentations) // method to create an element node. // subclasses can override this method to create element nodes in other ways. protected Element createElementNode(QName element) { Element el = null; if (fNamespaceAware) { // if we are using xerces DOM implementation, call our // own constructor to reuse the strings we have here. if (fDocumentImpl != null) { el = fDocumentImpl.createElementNS(element.uri, element.rawname, element.localpart); } else { el = fDocument.createElementNS(element.uri, element.rawname); } } else { el = fDocument.createElement(element.rawname); } return el; } // method to create an attribute node. // subclasses can override this method to create attribute nodes in other ways. protected Attr createAttrNode(QName attrQName) { Attr attr = null; if (fNamespaceAware) { if (fDocumentImpl != null) { // if we are using xerces DOM implementation, call our // own constructor to reuse the strings we have here. attr = fDocumentImpl.createAttributeNS(attrQName.uri, attrQName.rawname, attrQName.localpart); } else { attr = fDocument.createAttributeNS(attrQName.uri, attrQName.rawname); } } else { attr = fDocument.createAttribute(attrQName.rawname); } return attr; } // If data rececived in more than one chunk, the data // is stored in StringBuffer. // This function is called then the state is changed and the // data needs to be appended to the current node protected void setCharacterData(boolean sawChars){ // handle character data fFirstChunk = sawChars; if (fStringBuffer.length() > 0) { // if we have data in the buffer we must have created // a text node already. Node child = fCurrentNode.getLastChild(); // REVISIT: should this check be performed? if (child != null && child.getNodeType() == Node.TEXT_NODE) { ((TextImpl)child).replaceData(fStringBuffer.toString()); } // reset string buffer fStringBuffer.setLength(0); } } } // class AbstractDOMParser
package com.grarak.kerneladiutor.utils.tools; import android.accessibilityservice.AccessibilityServiceInfo; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import com.grarak.kerneladiutor.utils.database.PerAppDB; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; public class Per_App { public static Map getInstalledApps (Context context) { // Get a list of installed apps. Currently this is only the package name final PackageManager pm = context.getPackageManager(); //ArrayList<String> installedApps = new ArrayList<String>(); final Map applist = new TreeMap(); final List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA); // Add a "Default" Selection to set the default profile" applist.put("Default","Default"); Thread t = new Thread() { @Override public void run() { for (ApplicationInfo packageInfo : packages) { applist.put(packageInfo.loadLabel(pm), packageInfo.packageName); } } }; t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } return applist; } public static String[] getPackageNames (Map apps) { ArrayList<String> packages = new ArrayList<String>(); for (int i = 0; i < apps.size(); i++) { packages.add(i, apps.values().toArray()[i].toString()); } // Convert the list to strings for displaying String[] packagelist = new String[packages.size()]; packagelist = packages.toArray(packagelist); return packagelist; } public static String[] getAppNames (Map apps) { ArrayList<String> applist = new ArrayList<String>(); for (int i = 0; i < apps.size(); i++) { applist.add(i, apps.keySet().toArray()[i].toString()); } // Convert the list to strings for displaying String[] app_names = new String[applist.size()]; app_names = applist.toArray(app_names); return app_names; } public static void save_app (String app, String id, Context context) { PerAppDB perappDB = new PerAppDB(context); List<PerAppDB.PerAppItem> PerAppItem = perappDB.getAllApps() ; for (int i = 0; i < PerAppItem.size(); i++) { String p = PerAppItem.get(i).getApp(); if (p != null && p.equals(app)) { perappDB.delApp(i); } } perappDB.putApp(app, id); perappDB.commit(); } public static void remove_app (String app, String id, Context context) { PerAppDB perappDB = new PerAppDB(context); List<PerAppDB.PerAppItem> PerAppItem = perappDB.getAllApps() ; for (int i = 0; i < PerAppItem.size(); i++) { String p = PerAppItem.get(i).getApp(); if (p != null && p.equals(app)) { perappDB.delApp(i); } } perappDB.commit(); } public static boolean app_profile_exists (String app, Context context) { PerAppDB perappDB = new PerAppDB(context); boolean exists = perappDB.containsApp(app); return exists; } public static ArrayList<String> app_profile_info (String app, Context context) { PerAppDB perappDB = new PerAppDB(context); if (perappDB.containsApp(app)) { return perappDB.get_info(app); } return null; } public static boolean[] getExistingSelections (String[] apps, String profile, Context context) { PerAppDB perappDB = new PerAppDB(context); boolean exists[] = new boolean[apps.length]; List<PerAppDB.PerAppItem> PerAppItem = perappDB.getAllApps() ; for (int i = 0; i < PerAppItem.size(); i++) { String p = PerAppItem.get(i).getApp(); String id = PerAppItem.get(i).getID(); if (p != null && Arrays.asList(apps).contains(p)) { if (id != null && id.equals(profile)) { exists[Arrays.asList(apps).indexOf(p)] = true; } } } return exists; } public static boolean isAccessibilityEnabled(Context context, String id) { AccessibilityManager am = (AccessibilityManager) context .getSystemService(Context.ACCESSIBILITY_SERVICE); List<AccessibilityServiceInfo> runningServices = am .getEnabledAccessibilityServiceList(AccessibilityEvent.TYPES_ALL_MASK); for (AccessibilityServiceInfo service : runningServices) { if (id != null && id.equals(service.getId())) { return true; } } return false; } }
package org.bouncycastle.cms; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.BERConstructedOctetString; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.cms.SignedData; import org.bouncycastle.asn1.cms.SignerIdentifier; import org.bouncycastle.asn1.cms.SignerInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.Provider; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; /** * general class for generating a pkcs7-signature message. * <p> * A simple example of usage. * * <pre> * CertStore certs... * CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); * * gen.addSigner(privKey, cert, CMSSignedGenerator.DIGEST_SHA1); * gen.addCertificatesAndCRLs(certs); * * CMSSignedData data = gen.generate(content, "BC"); * </pre> */ public class CMSSignedDataGenerator extends CMSSignedGenerator { List signerInfs = new ArrayList(); private class SignerInf { private final PrivateKey key; private final SignerIdentifier signerIdentifier; private final String digestOID; private final String encOID; private final CMSAttributeTableGenerator sAttr; private final CMSAttributeTableGenerator unsAttr; private final AttributeTable baseSignedTable; SignerInf( PrivateKey key, SignerIdentifier signerIdentifier, String digestOID, String encOID, CMSAttributeTableGenerator sAttr, CMSAttributeTableGenerator unsAttr, AttributeTable baseSignedTable) { this.key = key; this.signerIdentifier = signerIdentifier; this.digestOID = digestOID; this.encOID = encOID; this.sAttr = sAttr; this.unsAttr = unsAttr; this.baseSignedTable = baseSignedTable; } AlgorithmIdentifier getDigestAlgorithmID() { return new AlgorithmIdentifier(new DERObjectIdentifier(digestOID), new DERNull()); } SignerInfo toSignerInfo( DERObjectIdentifier contentType, CMSProcessable content, SecureRandom random, Provider sigProvider, boolean addDefaultAttributes, boolean isCounterSignature) throws IOException, SignatureException, InvalidKeyException, NoSuchAlgorithmException, CertificateEncodingException, CMSException { AlgorithmIdentifier digAlgId = getDigestAlgorithmID(); String digestName = CMSSignedHelper.INSTANCE.getDigestAlgName(digestOID); String signatureName = digestName + "with" + CMSSignedHelper.INSTANCE.getEncryptionAlgName(encOID); Signature sig = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, sigProvider); MessageDigest dig = CMSSignedHelper.INSTANCE.getDigestInstance(digestName, sigProvider); AlgorithmIdentifier encAlgId = getEncAlgorithmIdentifier(encOID, sig); byte[] hash = null; if (content != null) { content.write(new DigOutputStream(dig)); hash = dig.digest(); _digests.put(digestOID, hash.clone()); } AttributeTable signed; if (addDefaultAttributes) { Map parameters = getBaseParameters(contentType, digAlgId, hash); signed = (sAttr != null) ? sAttr.getAttributes(Collections.unmodifiableMap(parameters)) : null; } else { signed = baseSignedTable; } if (isCounterSignature) { Hashtable ats = signed.toHashtable(); ats.remove(CMSAttributes.contentType); signed = new AttributeTable(ats); } ASN1Set signedAttr = getAttributeSet(signed); // sig must be composed from the DER encoding. byte[] tmp; if (signedAttr != null) { tmp = signedAttr.getEncoded(ASN1Encodable.DER); } else { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); content.write(bOut); tmp = bOut.toByteArray(); } sig.initSign(key, random); sig.update(tmp); byte[] sigBytes = sig.sign(); ASN1Set unsignedAttr = null; if (unsAttr != null) { Map parameters = getBaseParameters(contentType, digAlgId, hash); parameters.put(CMSAttributeTableGenerator.SIGNATURE, sigBytes.clone()); AttributeTable unsigned = unsAttr.getAttributes(Collections.unmodifiableMap(parameters)); unsignedAttr = getAttributeSet(unsigned); } return new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DEROctetString(sigBytes), unsignedAttr); } } /** * base constructor */ public CMSSignedDataGenerator() { } /** * constructor allowing specific source of randomness * @param rand instance of SecureRandom to use */ public CMSSignedDataGenerator( SecureRandom rand) { super(rand); } /** * add a signer - no attributes other than the default ones will be * provided here. * * @param key signing key to use * @param cert certificate containing corresponding public key * @param digestOID digest algorithm OID */ public void addSigner( PrivateKey key, X509Certificate cert, String digestOID) throws IllegalArgumentException { addSigner(key, cert, getEncOID(key, digestOID), digestOID); } /** * add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be * provided here. * * @param key signing key to use * @param cert certificate containing corresponding public key * @param encryptionOID digest encryption algorithm OID * @param digestOID digest algorithm OID */ public void addSigner( PrivateKey key, X509Certificate cert, String encryptionOID, String digestOID) throws IllegalArgumentException { signerInfs.add(new SignerInf(key, getSignerIdentifier(cert), digestOID, encryptionOID, new DefaultSignedAttributeTableGenerator(), null, null)); } /** * add a signer - no attributes other than the default ones will be * provided here. */ public void addSigner( PrivateKey key, byte[] subjectKeyID, String digestOID) throws IllegalArgumentException { addSigner(key, subjectKeyID, getEncOID(key, digestOID), digestOID); } /** * add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be * provided here. */ public void addSigner( PrivateKey key, byte[] subjectKeyID, String encryptionOID, String digestOID) throws IllegalArgumentException { signerInfs.add(new SignerInf(key, getSignerIdentifier(subjectKeyID), digestOID, encryptionOID, new DefaultSignedAttributeTableGenerator(), null, null)); } /** * add a signer with extra signed/unsigned attributes. * * @param key signing key to use * @param cert certificate containing corresponding public key * @param digestOID digest algorithm OID * @param signedAttr table of attributes to be included in signature * @param unsignedAttr table of attributes to be included as unsigned */ public void addSigner( PrivateKey key, X509Certificate cert, String digestOID, AttributeTable signedAttr, AttributeTable unsignedAttr) throws IllegalArgumentException { addSigner(key, cert, getEncOID(key, digestOID), digestOID, signedAttr, unsignedAttr); } /** * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes. * * @param key signing key to use * @param cert certificate containing corresponding public key * @param encryptionOID digest encryption algorithm OID * @param digestOID digest algorithm OID * @param signedAttr table of attributes to be included in signature * @param unsignedAttr table of attributes to be included as unsigned */ public void addSigner( PrivateKey key, X509Certificate cert, String encryptionOID, String digestOID, AttributeTable signedAttr, AttributeTable unsignedAttr) throws IllegalArgumentException { signerInfs.add(new SignerInf(key, getSignerIdentifier(cert), digestOID, encryptionOID, new DefaultSignedAttributeTableGenerator(signedAttr), new SimpleAttributeTableGenerator(unsignedAttr), signedAttr)); } /** * add a signer with extra signed/unsigned attributes. * * @param key signing key to use * @param subjectKeyID subjectKeyID of corresponding public key * @param digestOID digest algorithm OID * @param signedAttr table of attributes to be included in signature * @param unsignedAttr table of attributes to be included as unsigned */ public void addSigner( PrivateKey key, byte[] subjectKeyID, String digestOID, AttributeTable signedAttr, AttributeTable unsignedAttr) throws IllegalArgumentException { addSigner(key, subjectKeyID, digestOID, getEncOID(key, digestOID), new DefaultSignedAttributeTableGenerator(signedAttr), new SimpleAttributeTableGenerator(unsignedAttr)); } /** * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes. * * @param key signing key to use * @param subjectKeyID subjectKeyID of corresponding public key * @param encryptionOID digest encryption algorithm OID * @param digestOID digest algorithm OID * @param signedAttr table of attributes to be included in signature * @param unsignedAttr table of attributes to be included as unsigned */ public void addSigner( PrivateKey key, byte[] subjectKeyID, String encryptionOID, String digestOID, AttributeTable signedAttr, AttributeTable unsignedAttr) throws IllegalArgumentException { signerInfs.add(new SignerInf(key, getSignerIdentifier(subjectKeyID), digestOID, encryptionOID, new DefaultSignedAttributeTableGenerator(signedAttr), new SimpleAttributeTableGenerator(unsignedAttr), signedAttr)); } /** * add a signer with extra signed/unsigned attributes based on generators. */ public void addSigner( PrivateKey key, X509Certificate cert, String digestOID, CMSAttributeTableGenerator signedAttrGen, CMSAttributeTableGenerator unsignedAttrGen) throws IllegalArgumentException { addSigner(key, cert, getEncOID(key, digestOID), digestOID, signedAttrGen, unsignedAttrGen); } /** * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes based on generators. */ public void addSigner( PrivateKey key, X509Certificate cert, String encryptionOID, String digestOID, CMSAttributeTableGenerator signedAttrGen, CMSAttributeTableGenerator unsignedAttrGen) throws IllegalArgumentException { signerInfs.add(new SignerInf(key, getSignerIdentifier(cert), digestOID, encryptionOID, signedAttrGen, unsignedAttrGen, null)); } /** * add a signer with extra signed/unsigned attributes based on generators. */ public void addSigner( PrivateKey key, byte[] subjectKeyID, String digestOID, CMSAttributeTableGenerator signedAttrGen, CMSAttributeTableGenerator unsignedAttrGen) throws IllegalArgumentException { addSigner(key, subjectKeyID, digestOID, getEncOID(key, digestOID), signedAttrGen, unsignedAttrGen); } /** * add a signer, including digest encryption algorithm, with extra signed/unsigned attributes based on generators. */ public void addSigner( PrivateKey key, byte[] subjectKeyID, String encryptionOID, String digestOID, CMSAttributeTableGenerator signedAttrGen, CMSAttributeTableGenerator unsignedAttrGen) throws IllegalArgumentException { signerInfs.add(new SignerInf(key, getSignerIdentifier(subjectKeyID), digestOID, encryptionOID, signedAttrGen, unsignedAttrGen, null)); } /** * generate a signed object that for a CMS Signed Data * object using the given provider. */ public CMSSignedData generate( CMSProcessable content, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return generate(content, CMSUtils.getProvider(sigProvider)); } /** * generate a signed object that for a CMS Signed Data * object using the given provider. */ public CMSSignedData generate( CMSProcessable content, Provider sigProvider) throws NoSuchAlgorithmException, CMSException { return generate(content, false, sigProvider); } /** * generate a signed object that for a CMS Signed Data * object using the given provider - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. */ public CMSSignedData generate( String eContentType, CMSProcessable content, boolean encapsulate, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return generate(eContentType, content, encapsulate, CMSUtils.getProvider(sigProvider), true); } /** * generate a signed object that for a CMS Signed Data * object using the given provider - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. */ public CMSSignedData generate( String eContentType, CMSProcessable content, boolean encapsulate, Provider sigProvider) throws NoSuchAlgorithmException, CMSException { return generate(eContentType, content, encapsulate, sigProvider, true); } /** * Similar method to the other generate methods. The additional argument * addDefaultAttributes indicates whether or not a default set of signed attributes * need to be added automatically. If the argument is set to false, no * attributes will get added at all. */ public CMSSignedData generate( String eContentType, CMSProcessable content, boolean encapsulate, String sigProvider, boolean addDefaultAttributes) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return generate(eContentType, content, encapsulate, CMSUtils.getProvider(sigProvider), addDefaultAttributes); } /** * Similar method to the other generate methods. The additional argument * addDefaultAttributes indicates whether or not a default set of signed attributes * need to be added automatically. If the argument is set to false, no * attributes will get added at all. */ public CMSSignedData generate( String eContentType, CMSProcessable content, boolean encapsulate, Provider sigProvider, boolean addDefaultAttributes) throws NoSuchAlgorithmException, CMSException { // TODO // if (signerInfs.isEmpty()) // /* RFC 3852 5.2 // * "In the degenerate case where there are no signers, the // * EncapsulatedContentInfo value being "signed" is irrelevant. In this // * case, the content type within the EncapsulatedContentInfo value being // * "signed" MUST be id-data (as defined in section 4), and the content // * field of the EncapsulatedContentInfo value MUST be omitted." // */ // if (encapsulate) // if (!DATA.equals(eContentType)) // if (!DATA.equals(eContentType)) // /* RFC 3852 5.3 // * [The 'signedAttrs']... // * field is optional, but it MUST be present if the content type of // * the EncapsulatedContentInfo value being signed is not id-data. // */ // // TODO signedAttrs must be present for all signers ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); ASN1EncodableVector signerInfos = new ASN1EncodableVector(); _digests.clear(); // clear the current preserved digest state // add the precalculated SignerInfo objects. Iterator it = _signers.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); digestAlgs.add(CMSSignedHelper.INSTANCE.fixAlgID(signer.getDigestAlgorithmID())); signerInfos.add(signer.toSignerInfo()); } // add the SignerInfo objects boolean isCounterSignature = (eContentType == null); DERObjectIdentifier contentTypeOID = isCounterSignature ? CMSObjectIdentifiers.data : new DERObjectIdentifier(eContentType); it = signerInfs.iterator(); while (it.hasNext()) { SignerInf signer = (SignerInf)it.next(); try { digestAlgs.add(signer.getDigestAlgorithmID()); signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, sigProvider, addDefaultAttributes, isCounterSignature)); } catch (IOException e) { throw new CMSException("encoding error.", e); } catch (InvalidKeyException e) { throw new CMSException("key inappropriate for signature.", e); } catch (SignatureException e) { throw new CMSException("error creating signature.", e); } catch (CertificateEncodingException e) { throw new CMSException("error creating sid.", e); } } ASN1Set certificates = null; if (_certs.size() != 0) { certificates = CMSUtils.createBerSetFromList(_certs); } ASN1Set certrevlist = null; if (_crls.size() != 0) { certrevlist = CMSUtils.createBerSetFromList(_crls); } ASN1OctetString octs = null; if (encapsulate) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { content.write(bOut); } catch (IOException e) { throw new CMSException("encapsulation error.", e); } octs = new BERConstructedOctetString(bOut.toByteArray()); } ContentInfo encInfo = new ContentInfo(contentTypeOID, octs); SignedData sd = new SignedData( new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos)); ContentInfo contentInfo = new ContentInfo( CMSObjectIdentifiers.signedData, sd); return new CMSSignedData(content, contentInfo); } /** * generate a signed object that for a CMS Signed Data * object using the given provider - if encapsulate is true a copy * of the message will be included in the signature with the * default content type "data". */ public CMSSignedData generate( CMSProcessable content, boolean encapsulate, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return this.generate(DATA, content, encapsulate, sigProvider); } /** * generate a signed object that for a CMS Signed Data * object using the given provider - if encapsulate is true a copy * of the message will be included in the signature with the * default content type "data". */ public CMSSignedData generate( CMSProcessable content, boolean encapsulate, Provider sigProvider) throws NoSuchAlgorithmException, CMSException { return this.generate(DATA, content, encapsulate, sigProvider); } /** * generate a set of one or more SignerInformation objects representing counter signatures on * the passed in SignerInformation object. * * @param signer the signer to be countersigned * @param sigProvider the provider to be used for counter signing. * @return a store containing the signers. */ public SignerInformationStore generateCounterSigners(SignerInformation signer, Provider sigProvider) throws NoSuchAlgorithmException, CMSException { return this.generate(null, new CMSProcessableByteArray(signer.getSignature()), false, sigProvider).getSignerInfos(); } /** * generate a set of one or more SignerInformation objects representing counter signatures on * the passed in SignerInformation object. * * @param signer the signer to be countersigned * @param sigProvider the provider to be used for counter signing. * @return a store containing the signers. */ public SignerInformationStore generateCounterSigners(SignerInformation signer, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return this.generate(null, new CMSProcessableByteArray(signer.getSignature()), false, CMSUtils.getProvider(sigProvider)).getSignerInfos(); } }
package org.opennms.netmgt.dao.hibernate; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.hibernate.criterion.Restrictions; import org.opennms.core.criteria.CriteriaBuilder; import org.opennms.core.spring.BeanUtils; import org.opennms.netmgt.dao.api.AcknowledgmentDao; import org.opennms.netmgt.dao.api.AlarmDao; import org.opennms.netmgt.dao.api.AlarmRepository; import org.opennms.netmgt.dao.api.MemoDao; import org.opennms.netmgt.model.AckAction; import org.opennms.netmgt.model.AckType; import org.opennms.netmgt.model.OnmsAcknowledgment; import org.opennms.netmgt.model.OnmsAlarm; import org.opennms.netmgt.model.OnmsCriteria; import org.opennms.netmgt.model.OnmsMemo; import org.opennms.netmgt.model.OnmsReductionKeyMemo; import org.opennms.netmgt.model.OnmsSeverity; import org.opennms.netmgt.model.alarm.AlarmSummary; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; /** * <p>DaoWebAlarmRepository class.</p> * * @author ranger * @version $Id: $ * @since 1.8.1 */ public class AlarmRepositoryHibernate implements AlarmRepository, InitializingBean { @Autowired AlarmDao m_alarmDao; @Autowired MemoDao m_memoDao; @Autowired AcknowledgmentDao m_ackDao; @Override public void afterPropertiesSet() throws Exception { BeanUtils.assertAutowiring(this); } /** * {@inheritDoc} */ @Transactional @Override public void acknowledgeAll(String user, Date timestamp) { acknowledgeMatchingAlarms(user, timestamp, new OnmsCriteria(OnmsAlarm.class)); } @Transactional public void acknowledgeAlarms(String user, Date timestamp, int[] alarmIds) { OnmsCriteria criteria = new OnmsCriteria(OnmsAlarm.class); criteria.add(Restrictions.in("id", Arrays.asList(ArrayUtils.toObject(alarmIds)))); acknowledgeMatchingAlarms(user, timestamp, criteria); } /** * {@inheritDoc} */ @Transactional @Override public void acknowledgeMatchingAlarms(String user, Date timestamp, OnmsCriteria criteria) { List<OnmsAlarm> alarms = m_alarmDao.findMatching(criteria); Iterator<OnmsAlarm> alarmsIt = alarms.iterator(); while (alarmsIt.hasNext()) { OnmsAlarm alarm = alarmsIt.next(); OnmsAcknowledgment ack = new OnmsAcknowledgment(alarm, user); ack.setAckTime(timestamp); ack.setAckAction(AckAction.ACKNOWLEDGE); m_ackDao.processAck(ack); } } /** * {@inheritDoc} */ @Transactional @Override public void clearAlarms(int[] alarmIds, String user, Date timestamp) { OnmsCriteria criteria = new OnmsCriteria(OnmsAlarm.class); criteria.add(Restrictions.in("id", Arrays.asList(ArrayUtils.toObject(alarmIds)))); List<OnmsAlarm> alarms = m_alarmDao.findMatching(criteria); Iterator<OnmsAlarm> alarmsIt = alarms.iterator(); while (alarmsIt.hasNext()) { OnmsAlarm alarm = alarmsIt.next(); OnmsAcknowledgment ack = new OnmsAcknowledgment(alarm, user); ack.setAckTime(timestamp); ack.setAckAction(AckAction.CLEAR); m_ackDao.processAck(ack); } } /** * {@inheritDoc} */ @Transactional @Override public int countMatchingAlarms(OnmsCriteria criteria) { return m_alarmDao.countMatching(criteria); } /** * {@inheritDoc} */ @Transactional @Override public int[] countMatchingAlarmsBySeverity(final OnmsCriteria criteria) { final int[] alarmCounts = new int[8]; for (final OnmsSeverity value : OnmsSeverity.values()) { alarmCounts[value.getId()] = m_alarmDao.countMatching(criteria.doClone().add(Restrictions.eq("severity", value))); } return alarmCounts; } /** * {@inheritDoc} */ @Transactional @Override public void escalateAlarms(int[] alarmIds, String user, Date timestamp) { OnmsCriteria criteria = new OnmsCriteria(OnmsAlarm.class); criteria.add(Restrictions.in("id", Arrays.asList(ArrayUtils.toObject(alarmIds)))); List<OnmsAlarm> alarms = m_alarmDao.findMatching(criteria); Iterator<OnmsAlarm> alarmsIt = alarms.iterator(); while (alarmsIt.hasNext()) { OnmsAlarm alarm = alarmsIt.next(); OnmsAcknowledgment ack = new OnmsAcknowledgment(alarm, user); ack.setAckTime(timestamp); ack.setAckAction(AckAction.ESCALATE); m_ackDao.processAck(ack); } } /** * {@inheritDoc} */ @Transactional @Override public OnmsAlarm getAlarm(int alarmId) { return m_alarmDao.get(alarmId); } /** * {@inheritDoc} */ @Transactional @Override public OnmsAlarm[] getMatchingAlarms(OnmsCriteria criteria) { List<OnmsAlarm> alarms = m_alarmDao.findMatching(criteria); return alarms == null ? new OnmsAlarm[0] : alarms.toArray(new OnmsAlarm[0]); } /** * {@inheritDoc} */ @Transactional @Override public void unacknowledgeAll(String user) { unacknowledgeMatchingAlarms(new OnmsCriteria(OnmsAlarm.class), user); } /** * {@inheritDoc} */ @Transactional @Override public void unacknowledgeMatchingAlarms(OnmsCriteria criteria, String user) { List<OnmsAlarm> alarms = m_alarmDao.findMatching(criteria); for (OnmsAlarm alarm : alarms) { OnmsAcknowledgment ack = new OnmsAcknowledgment(alarm, user); ack.setAckAction(AckAction.UNACKNOWLEDGE); m_ackDao.processAck(ack); } } /** * {@inheritDoc} */ @Transactional @Override public void acknowledgeAlarms(int[] alarmIds, String user, Date timestamp) { OnmsCriteria criteria = new OnmsCriteria(OnmsAlarm.class); criteria.add(Restrictions.in("id", Arrays.asList(ArrayUtils.toObject(alarmIds)))); acknowledgeMatchingAlarms(user, timestamp, criteria); } /** * {@inheritDoc} */ @Transactional @Override public void unacknowledgeAlarms(int[] alarmIds, String user) { OnmsCriteria criteria = new OnmsCriteria(OnmsAlarm.class); criteria.add(Restrictions.in("id", Arrays.asList(ArrayUtils.toObject(alarmIds)))); unacknowledgeMatchingAlarms(criteria, user); } /** * {@inheritDoc} */ @Override @Transactional public void updateStickyMemo(Integer alarmId, String body, String user) { OnmsAlarm onmsAlarm = m_alarmDao.get(alarmId); if (onmsAlarm != null) { if (onmsAlarm.getStickyMemo() == null) { onmsAlarm.setStickyMemo(new OnmsMemo()); onmsAlarm.getStickyMemo().setCreated(new Date()); } onmsAlarm.getStickyMemo().setBody(body); onmsAlarm.getStickyMemo().setAuthor(user); onmsAlarm.getStickyMemo().setUpdated(new Date()); m_alarmDao.saveOrUpdate(onmsAlarm); } } /** * {@inheritDoc} */ @Override @Transactional public void updateReductionKeyMemo(Integer alarmId, String body, String user) { OnmsAlarm onmsAlarm = m_alarmDao.get(alarmId); if (onmsAlarm != null) { OnmsReductionKeyMemo memo = onmsAlarm.getReductionKeyMemo(); if (memo == null) { memo = new OnmsReductionKeyMemo(); memo.setCreated(new Date()); } memo.setBody(body); memo.setAuthor(user); memo.setReductionKey(onmsAlarm.getReductionKey()); memo.setUpdated(new Date()); m_memoDao.saveOrUpdate(memo); onmsAlarm.setReductionKeyMemo(memo); } } /** * {@inheritDoc} */ @Override @Transactional public void removeStickyMemo(Integer alarmId) { OnmsAlarm onmsAlarm = m_alarmDao.get(alarmId); if (onmsAlarm != null && onmsAlarm.getStickyMemo() != null) { m_memoDao.delete(onmsAlarm.getStickyMemo()); onmsAlarm.setStickyMemo(null); } } /** * {@inheritDoc} */ @Override @Transactional public void removeReductionKeyMemo(int alarmId) { OnmsAlarm onmsAlarm = m_alarmDao.get(alarmId); if (onmsAlarm != null && onmsAlarm.getReductionKeyMemo() != null) { m_memoDao.delete(onmsAlarm.getReductionKeyMemo()); onmsAlarm.setReductionKeyMemo(null); } } @Override @Transactional public List<OnmsAcknowledgment> getAcknowledgments(int alarmId) { CriteriaBuilder cb = new CriteriaBuilder(OnmsAcknowledgment.class); cb.eq("refId", alarmId); cb.eq("ackType", AckType.ALARM); return m_ackDao.findMatching(cb.toCriteria()); } @Override @Transactional public List<AlarmSummary> getCurrentNodeAlarmSummaries() { return m_alarmDao.getNodeAlarmSummaries(); } }
package org.nuxeo.ecm.platform.comment.web; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.faces.event.ActionEvent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.annotations.Create; import org.jboss.seam.annotations.Destroy; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Observer; import org.jboss.seam.annotations.intercept.BypassInterceptors; import org.jboss.seam.annotations.web.RequestParameter; import org.jboss.seam.contexts.Contexts; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.ClientRuntimeException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.platform.actions.Action; import org.nuxeo.ecm.platform.comment.api.CommentableDocument; import org.nuxeo.ecm.platform.comment.workflow.utils.CommentsConstants; import org.nuxeo.ecm.platform.comment.workflow.utils.FollowTransitionUnrestricted; import org.nuxeo.ecm.platform.ui.web.api.NavigationContext; import org.nuxeo.ecm.platform.ui.web.api.WebActions; import org.nuxeo.ecm.webapp.helpers.EventNames; import org.nuxeo.ecm.webapp.security.UserSession; /** * @author <a href="mailto:glefter@nuxeo.com">George Lefter</a> * */ public abstract class AbstractCommentManagerActionsBean implements CommentManagerActions { protected static final String COMMENTS_ACTIONS = "COMMENT_ACTIONS"; private static final Log log = LogFactory.getLog(AbstractCommentManagerActionsBean.class); protected NuxeoPrincipal principal; protected boolean principalIsAdmin; protected boolean showCreateForm; @In(create = true, required = false) protected transient CoreSession documentManager; @In(create = true) protected transient WebActions webActions; protected String newContent; protected CommentableDocument commentableDoc; protected List<UIComment> uiComments; protected List<ThreadEntry> commentThread; // the id of the comment to delete @RequestParameter protected String deleteCommentId; // the id of the comment to reply to @RequestParameter protected String replyCommentId; protected String savedReplyCommentId; protected Map<String, UIComment> commentMap; protected boolean commentStarted; protected List<UIComment> flatComments; @In(create = true) protected UserSession userSession; @In(create = true) protected NavigationContext navigationContext; @Override @Create public void initialize() throws Exception { log.debug("Initializing..."); commentMap = new HashMap<String, UIComment>(); showCreateForm = false; principal = userSession.getCurrentNuxeoPrincipal(); principalIsAdmin = principal.isAdministrator(); } @Override @Destroy public void destroy() { commentMap = null; log.debug("Removing Seam action listener..."); } @Override public String getPrincipalName() { return principal.getName(); } @Override public boolean getPrincipalIsAdmin() { return principalIsAdmin; } protected DocumentModel initializeComment(DocumentModel comment) { if (comment != null) { try { if (comment.getProperty("dublincore", "contributors") == null) { String[] contributors = new String[1]; contributors[0] = getPrincipalName(); comment.setProperty("dublincore", "contributors", contributors); } } catch (ClientException e) { throw new ClientRuntimeException(e); } try { if (comment.getProperty("dublincore", "created") == null) { comment.setProperty("dublincore", "created", Calendar.getInstance()); } } catch (ClientException e) { throw new ClientRuntimeException(e); } } return comment; } public DocumentModel addComment(DocumentModel comment, DocumentModel docToComment) throws ClientException { try { comment = initializeComment(comment); UIComment parentComment = null; if (savedReplyCommentId != null) { parentComment = commentMap.get(savedReplyCommentId); } if (docToComment != null) { commentableDoc = getCommentableDoc(docToComment); } if (commentableDoc == null) { commentableDoc = getCommentableDoc(); } // what if commentableDoc is still null? shouldn't, but... if (commentableDoc == null) { throw new ClientException("Can't comment on null document"); } DocumentModel newComment; if (parentComment != null) { newComment = commentableDoc.addComment( parentComment.getComment(), comment); } else { newComment = commentableDoc.addComment(comment); } // automatically validate the comments if (CommentsConstants.COMMENT_LIFECYCLE.equals(newComment.getLifeCyclePolicy())) { new FollowTransitionUnrestricted(documentManager, newComment.getRef(), CommentsConstants.TRANSITION_TO_PUBLISHED_STATE).runUnrestricted(); } // Events.instance().raiseEvent(CommentEvents.COMMENT_ADDED, null, // newComment); cleanContextVariable(); return newComment; } catch (Throwable t) { log.error("failed to add comment", t); throw ClientException.wrap(t); } } @Override public DocumentModel addComment(DocumentModel comment) throws ClientException { return addComment(comment, null); } @Override public String addComment() throws ClientException { DocumentModel myComment = documentManager.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); myComment.setPropertyValue(CommentsConstants.COMMENT_AUTHOR, principal.getName()); myComment.setPropertyValue(CommentsConstants.COMMENT_TEXT, newContent); myComment.setPropertyValue(CommentsConstants.COMMENT_CREATION_DATE, Calendar.getInstance()); myComment = addComment(myComment); // do not navigate to newly-created comment, they are hidden documents return null; } @Override public String createComment(DocumentModel docToComment) throws ClientException { DocumentModel myComment = documentManager.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); myComment.setProperty("comment", "author", principal.getName()); myComment.setProperty("comment", "text", newContent); myComment.setProperty("comment", "creationDate", Calendar.getInstance()); myComment = addComment(myComment, docToComment); // do not navigate to newly-created comment, they are hidden documents return null; } @Override @Observer(value = { EventNames.DOCUMENT_SELECTION_CHANGED, EventNames.CONTENT_ROOT_SELECTION_CHANGED, EventNames.DOCUMENT_CHANGED }, create = false) @BypassInterceptors public void documentChanged() { cleanContextVariable(); } protected CommentableDocument getCommentableDoc() { if (commentableDoc == null) { DocumentModel currentDocument = navigationContext.getCurrentDocument(); commentableDoc = currentDocument.getAdapter(CommentableDocument.class); } return commentableDoc; } protected CommentableDocument getCommentableDoc(DocumentModel doc) { if (doc == null) { doc = navigationContext.getCurrentDocument(); } commentableDoc = doc.getAdapter(CommentableDocument.class); return commentableDoc; } /** * Initializes uiComments with Comments of current document. */ @Override public void initComments() throws ClientException { DocumentModel currentDoc = navigationContext.getCurrentDocument(); if (currentDoc == null) { throw new ClientException("Unable to find current Document"); } initComments(currentDoc); } /** * Initializes uiComments with Comments of current document. */ @Override public void initComments(DocumentModel commentedDoc) throws ClientException { commentableDoc = getCommentableDoc(commentedDoc); if (uiComments == null) { uiComments = new ArrayList<UIComment>(); if (commentableDoc != null) { List<DocumentModel> comments = commentableDoc.getComments(); for (DocumentModel comment : comments) { UIComment uiComment = createUIComment(null, comment); uiComments.add(uiComment); } } } } public List<UIComment> getComments(DocumentModel doc) throws ClientException { List<UIComment> allComments = new ArrayList<UIComment>(); commentableDoc = doc.getAdapter(CommentableDocument.class); if (commentableDoc != null) { List<DocumentModel> comments = commentableDoc.getComments(); for (DocumentModel comment : comments) { UIComment uiComment = createUIComment(null, comment); allComments.add(uiComment); } } return allComments; } /** * Recursively retrieves all comments of a doc. */ @Override public List<ThreadEntry> getCommentsAsThreadOnDoc(DocumentModel doc) throws ClientException { List<ThreadEntry> allComments = new ArrayList<ThreadEntry>(); List<UIComment> allUIComments = getComments(doc); for (UIComment uiComment : allUIComments) { allComments.add(new ThreadEntry(uiComment.getComment(), 0)); if (uiComment.getChildren() != null) { flattenTree(allComments, uiComment, 0); } } return allComments; } @Override public List<ThreadEntry> getCommentsAsThread(DocumentModel commentedDoc) throws ClientException { if (commentThread != null) { return commentThread; } commentThread = new ArrayList<ThreadEntry>(); if (uiComments == null) { initComments(commentedDoc); // Fetches all the comments associated // with the // document into uiComments (a list of comment // roots). } for (UIComment uiComment : uiComments) { commentThread.add(new ThreadEntry(uiComment.getComment(), 0)); if (uiComment.getChildren() != null) { flattenTree(commentThread, uiComment, 0); } } return commentThread; } /** * Visits a list of comment trees and puts them into a list of * "ThreadEntry"s. */ public void flattenTree(List<ThreadEntry> commentThread, UIComment uiComment, int depth) { List<UIComment> uiChildren = uiComment.getChildren(); for (UIComment uiChild : uiChildren) { commentThread.add(new ThreadEntry(uiChild.getComment(), depth + 1)); if (uiChild.getChildren() != null) { flattenTree(commentThread, uiChild, depth + 1); } } } /** * Creates a UIComment wrapping "comment", having "parent" as parent. */ protected UIComment createUIComment(UIComment parent, DocumentModel comment) throws ClientException { UIComment wrapper = new UIComment(parent, comment); commentMap.put(wrapper.getId(), wrapper); List<DocumentModel> children = commentableDoc.getComments(comment); for (DocumentModel child : children) { UIComment uiChild = createUIComment(wrapper, child); wrapper.addChild(uiChild); } return wrapper; } @Override public String deleteComment(String commentId) throws ClientException { if ("".equals(commentId)) { log.error("No comment id to delete"); return null; } if (commentableDoc == null) { log.error("Can't delete comments of null document"); return null; } try { UIComment selectedComment = commentMap.get(commentId); commentableDoc.removeComment(selectedComment.getComment()); cleanContextVariable(); // Events.instance().raiseEvent(CommentEvents.COMMENT_REMOVED, null, // selectedComment.getComment()); return null; } catch (Throwable t) { log.error("failed to delete comment", t); throw ClientException.wrap(t); } } @Override public String deleteComment() throws ClientException { return deleteComment(deleteCommentId); } @Override public String getNewContent() { return newContent; } @Override public void setNewContent(String newContent) { this.newContent = newContent; } @Override public String beginComment() { commentStarted = true; savedReplyCommentId = replyCommentId; showCreateForm = false; return null; } @Override public String cancelComment() { cleanContextVariable(); return null; } @Override public boolean getCommentStarted() { return commentStarted; } /** * Retrieves children for a given comment. */ public void getChildren(UIComment comment) { assert comment != null; List<UIComment> children = comment.getChildren(); if (!children.isEmpty()) { for (UIComment childComment : children) { getChildren(childComment); } } flatComments.add(comment); } @Override @SuppressWarnings("unchecked") public List<UIComment> getLastCommentsByDate(String commentNumber, DocumentModel commentedDoc) throws ClientException { int number = Integer.parseInt(commentNumber); List<UIComment> comments = new ArrayList<UIComment>(); flatComments = new ArrayList<UIComment>(); // Initialize uiComments initComments(commentedDoc); if (number < 0 || uiComments.isEmpty()) { return null; } for (UIComment comment : uiComments) { getChildren(comment); } if (!flatComments.isEmpty()) { Collections.sort(flatComments); } if (number > flatComments.size()) { number = flatComments.size(); } for (int i = 0; i < number; i++) { comments.add(flatComments.get(flatComments.size() - 1 - i)); } return comments; } @Override public List<UIComment> getLastCommentsByDate(String commentNumber) throws ClientException { return getLastCommentsByDate(commentNumber, null); } @Override public String getSavedReplyCommentId() { return savedReplyCommentId; } @Override public void setSavedReplyCommentId(String savedReplyCommentId) { this.savedReplyCommentId = savedReplyCommentId; } @Override public List<Action> getActionsForComment() { return webActions.getActionsList(COMMENTS_ACTIONS); } @Override public List<Action> getActionsForComment(String category) { return webActions.getActionsList(category); } @Override public boolean getShowCreateForm() { return showCreateForm; } @Override public void setShowCreateForm(boolean flag) { showCreateForm = flag; } @Override public void toggleCreateForm(ActionEvent event) { showCreateForm = !showCreateForm; } public void cleanContextVariable() { commentableDoc = null; uiComments = null; commentThread = null; showCreateForm = false; commentStarted = false; savedReplyCommentId = null; newContent = null; // NXP-11462: reset factory to force comment fetching after the new // comment is added Contexts.getEventContext().remove("documentThreadedComments"); } }
package org.mwc.debrief.dis.listeners.impl; import java.awt.Color; import org.mwc.debrief.dis.listeners.IDISCollisionListener; import Debrief.ReaderWriter.Replay.ImportReplay; import Debrief.Wrappers.LabelWrapper; import Debrief.Wrappers.NarrativeWrapper; import MWC.GUI.BaseLayer; import MWC.GUI.Layer; import MWC.GUI.Plottable; import MWC.GenericData.HiResDate; import MWC.GenericData.WorldLocation; import MWC.TacticalData.NarrativeEntry; public class DebriefCollisionListener extends DebriefCoreListener implements IDISCollisionListener { final private String COLLISIONS_LAYER = "Collisions"; public DebriefCollisionListener(IDISContext context) { super(context); } @Override public void add(final long time, final short eid, int movingId, final String rawMovingName, int recipientId, final String rawRecipientName, final double dLat, final double dLong, final double depthM) { final String recipientName; // special handling - and ID of -1 means the environment if(recipientId == -1) { recipientName = "Environment"; } else { recipientName = rawRecipientName; } final String movingName; if(movingId == -1) { movingName = "Environment"; } else { movingName = rawMovingName; } final String message = "Collision between platform:" + movingName + " and " + recipientName; // and the narrative entry addNewItem(eid, ImportReplay.NARRATIVE_LAYER, new ListenerHelper() { @Override public Layer createLayer() { return new NarrativeWrapper(ImportReplay.NARRATIVE_LAYER); } @Override public Plottable createItem() { NarrativeEntry newE = new NarrativeEntry(movingName, "COLLISION", new HiResDate(time), message); Color theColor = colorFor(eid, movingName); newE.setColor(theColor); return newE; } }); // create the text marker addNewItem(eid, COLLISIONS_LAYER, new ListenerHelper() { @Override public Layer createLayer() { Layer newB = new BaseLayer(); newB.setName(COLLISIONS_LAYER); return newB; } @Override public Plottable createItem() { WorldLocation newLoc = new WorldLocation(dLat, dLong, depthM); Color theColor = colorFor(eid, movingName); return new LabelWrapper(message, newLoc, theColor); } }); } }
package smp.components.staff; import smp.ImageLoader; import smp.SoundfontLoader; import smp.components.Constants; import smp.components.InstrumentIndex; import smp.components.topPanel.ButtonLine; import smp.stateMachine.StateMachine; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.image.ImageView; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; /** * A Staff event handler. The StaffImages implementation was getting bulky * and there are still many many features to be implemented here... * @author RehdBlob * @since 2013.07.27 */ public class StaffEventHandler implements EventHandler<MouseEvent> { /** The position of this note. */ private int position; /** Whether we've placed a note down on the staff or not. */ private boolean clicked = false; /** * This is the list of image notes that we have. These should * all be ImageView-type objects. */ private ObservableList<Node> theImages; /** The topmost image of the instrument. */ private ImageView theImage = new ImageView(); // Somewhere down the line, we will extend ImageView to // include more things. // private StaffNote theImage = new StaffNote(); /** The StackPane that this handler is attached to. */ private StackPane s; /** * Constructor for this StaffEventHandler. This creates a handler * that takes a StackPane and a position on the staff. * @param stPane The StackPane that we are interested in. * @param position The position that this handler is located on the * staff. */ public StaffEventHandler(StackPane stPane, int pos) { position = pos; s = stPane; theImages = s.getChildren(); } @Override public void handle(MouseEvent event) { InstrumentIndex theInd = ButtonLine.getSelectedInstrument(); ObservableList<Node> children = s.getChildren(); if (event.getEventType() == MouseEvent.MOUSE_PRESSED) { if (event.getButton() == MouseButton.PRIMARY) leftMousePressed(children, theInd); else if (event.getButton() == MouseButton.SECONDARY) rightMousePressed(children, theInd); } else if (event.getEventType() == MouseEvent.MOUSE_ENTERED) { mouseEntered(children, theInd); } else if (event.getEventType() == MouseEvent.MOUSE_EXITED) { mouseExited(children, theInd); } } /** * The method that is called when the left mouse button is pressed. * This is generally the signal to add an instrument to that line. * @param children List of Nodes that we have here, hopefully full of * ImageView-type objects. * @param theInd The InstrumentIndex corresponding to what * instrument is currently selected. */ private void leftMousePressed(ObservableList<Node> children, InstrumentIndex theInd) { theImage.setImage( ImageLoader.getSpriteFX( theInd.imageIndex())); playSound(theInd, position); theImage = new ImageView(); clicked = true; } /** * The method that is called when the right mouse button is pressed. * This is generally the signal to remove the instrument from that line. * @param children List of Nodes that we have here, hopefully full of * ImageView-type objects. * @param theInd The InstrumentIndex corresponding to what * instrument is currently selected. */ private void rightMousePressed(ObservableList<Node> children, InstrumentIndex theInd) { if (!children.isEmpty()) { children.remove(children.size() - 1); } if (!children.isEmpty()) { children.remove(children.size() - 1); } } /** * The method that is called when the mouse enters the object. * @param children List of Nodes that we have here, hopefully full of * ImageView-type objects. * @param theInd The InstrumentIndex corresponding to what * instrument is currently selected. */ private void mouseEntered(ObservableList<Node> children, InstrumentIndex theInd) { theImage.setVisible(true); theImage.setImage( ImageLoader.getSpriteFX( theInd.imageIndex().silhouette())); children.add(theImage); } /** * The method that is called when the mouse exits the object. * @param children List of Nodes that we have here, hopefully full of * ImageView-type objects. * @param theInd The InstrumentIndex corresponding to what * instrument is currently selected. */ private void mouseExited(ObservableList<Node> children, InstrumentIndex theInd) { if (!clicked) { theImage.setVisible(false); if (!children.isEmpty()) children.remove(children.size() - 1); } clicked = false; } /** * Plays a sound given an index and a position. * @param theInd The index at which this instrument is located at. * @param pos The position at which this note is located at. */ private static void playSound(InstrumentIndex theInd, int pos) { int acc; if (StateMachine.isAltPressed() || StateMachine.isCtrlPressed()) acc = -1; else if (StateMachine.isShiftPressed()) acc = 1; else acc = 0; SoundfontLoader.playSound(Constants.staffNotes[pos].getKeyNum(), theInd, acc); } }
package org.jitsi.videobridge.sim; import java.beans.*; import java.io.*; import java.lang.ref.*; import java.util.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; import org.jitsi.util.event.*; import org.jitsi.videobridge.*; import org.jitsi.videobridge.sim.messages.*; /** * @author George Politis */ class SimulcastReceiver implements PropertyChangeListener { /** * Ctor. * * @param mySM * @param peerSM */ public SimulcastReceiver(SimulcastManager mySM, SimulcastManager peerSM) { this.weakPeerSM = new WeakReference<SimulcastManager>(peerSM); this.mySM = mySM; // Listen for property changes. peerSM.addPropertyChangeListener(weakPropertyChangeListener); onPeerLayersChanged(peerSM); mySM.getVideoChannel() .addPropertyChangeListener(weakPropertyChangeListener); Endpoint self = getSelf(); onEndpointChanged(self, null); } /** * The <tt>Logger</tt> used by the <tt>ReceivingLayers</tt> class and its * instances to print debug information. */ private static final Logger logger = Logger.getLogger(SimulcastReceiver.class); /** * The <tt>PropertyChangeListener</tt> implementation employed by this * instance to listen to changes in the values of properties of interest to * this instance. For example, listens to <tt>Conference</tt> in order to * notify about changes in the list of <tt>Endpoint</tt>s participating in * the multipoint conference. The implementation keeps a * <tt>WeakReference</tt> to this instance and automatically removes itself * from <tt>PropertyChangeNotifier</tt>s. */ private final PropertyChangeListener weakPropertyChangeListener = new WeakReferencePropertyChangeListener(this); /** * The <tt>SimulcastManager</tt> of the parent endpoint. */ private final SimulcastManager mySM; /** * The <tt>SimulcastManager</tt> of the peer endpoint. */ private final WeakReference<SimulcastManager> weakPeerSM; /** * A <tt>WeakReference</tt> to the <tt>SimulcastLayer</tt> that is * currently being received. */ private WeakReference<SimulcastLayer> weakCurrent; /** * A <tt>WeakReference</tt> to the <tt>SimulcastLayer</tt> that will be * (possibly) received next. */ private WeakReference<SimulcastLayer> weakNext; /** * The sync root object for synchronizing access to the receive layers. */ private final Object receiveLayersSyncRoot = new Object(); /** * Holds the number of packets of the next layer have been seen so far. */ private int seenNext; /** * Defines how many packets of the next layer must be seen before switching * to that layer. This value is appropriate for the base layer and needs to * be adjusted for use with upper layers, if one wants to achieve * (approximately) the same timeout for layers of different order. */ private static final int MAX_NEXT_SEEN = 125; /** * Helper object that <tt>SimulcastReceiver</tt> instances use to build * JSON messages. */ private final static SimulcastMessagesMapper mapper = new SimulcastMessagesMapper(); /** * Gets the <tt>SimulcastLayer</tt> that is currently being received. * * @return */ private SimulcastLayer getCurrent() { WeakReference<SimulcastLayer> wr = this.weakCurrent; return (wr != null) ? wr.get() : null; } /** * Gets the <tt>SimulcastLayer</tt> that was previously being received. * * @return */ private SimulcastLayer getNext() { WeakReference<SimulcastLayer> wr = this.weakNext; return (wr != null) ? wr.get() : null; } /** * * @param ssrc * @return */ public boolean accept(long ssrc) { boolean accept = false; SimulcastLayer current = getCurrent(); if (current != null) { accept = current.accept(ssrc); } SimulcastLayer next; if (!accept && (next = getNext()) != null) { accept = next.accept(ssrc); if (accept) { maybeSwitchToNext(); } } return accept; } private void maybeForgetNext() { synchronized (receiveLayersSyncRoot) { SimulcastLayer next = getNext(); if (next != null && !next.isStreaming()) { this.weakNext = null; this.seenNext = 0; } } } private void maybeSwitchToNext() { synchronized (receiveLayersSyncRoot) { SimulcastLayer next = getNext(); // If there is a previous layer to timeout, and we have received // "enough" packets from the current layer, expire the previous // layer. if (next != null) { seenNext++; // NOTE(gp) not unexpectedly we have observed that 250 high // quality packets make 5 seconds to arrive (approx), then 250 // low quality packets will make 10 seconds to arrive (approx), // If we don't take that fact into account, then the immediate // lower layer makes twice as much to expire. // Assuming that each upper layer doubles the number of packets // it sends in a given interval, we normalize the MAX_NEXT_SEEN // to reflect the different relative rates of incoming packets // of the different simulcast layers we receive. if (seenNext > MAX_NEXT_SEEN * Math.pow(2, next.getOrder())) { this.sendSimulcastLayersChangedEvent(next); this.weakCurrent = weakNext; this.weakNext = null; if (logger.isDebugEnabled()) { Map<String, Object> map = new HashMap<String, Object>(3); map.put("self", getSelf()); map.put("peer", getPeer()); map.put("next", next); StringCompiler sc = new StringCompiler(map); logger.debug(sc.c("The simulcast receiver of " + "{self.id} for {peer.id} has now switched to " + "the next layer of order {next.order} " + "({next.primarySSRC}).")); } } } } } private Endpoint getPeer() { // TODO(gp) maybe add expired checks (?) SimulcastManager sm; VideoChannel vc; Endpoint peer; peer = ((sm = getPeerSM()) != null && (vc = sm.getVideoChannel()) != null) ? vc.getEndpoint() : null; if (peer == null) { logger.warn("Peer is null!"); if (logger.isDebugEnabled()) { logger.debug(Arrays.toString( Thread.currentThread().getStackTrace())); } } return peer; } private SimulcastManager getPeerSM() { WeakReference<SimulcastManager> wr = this.weakPeerSM; SimulcastManager peerSM = (wr != null) ? wr.get() : null; if (peerSM == null) { logger.warn("The peer simulcast manager is null!"); if (logger.isDebugEnabled()) { logger.debug( Arrays.toString( Thread.currentThread().getStackTrace())); } } return peerSM; } private Endpoint getSelf() { // TODO(gp) maybe add expired checks (?) SimulcastManager sm = this.mySM; VideoChannel vc; Endpoint self; self = (sm != null && (vc = sm.getVideoChannel()) != null) ? vc.getEndpoint() : null; if (self == null) { logger.warn("Self is null!"); if (logger.isDebugEnabled()) { logger.debug(Arrays.toString( Thread.currentThread().getStackTrace())); } } return self; } /** * Sets the receiving simulcast substream for the peers in the endpoints * parameter. * * @param options */ protected void configure(SimulcastReceiverOptions options) { if (options == null) { if (logger.isWarnEnabled()) { Map<String, Object> map = new HashMap<String, Object>(1); map.put("self", getSelf()); StringCompiler sc = new StringCompiler(map); logger.warn(sc.c("{self.id} cannot set receiving simulcast " + "options because the parameter is null.")); } return; } SimulcastManager peerSM = this.getPeerSM(); if (peerSM == null || !peerSM.hasLayers()) { if (logger.isWarnEnabled()) { Map<String, Object> map = new HashMap<String, Object>(1); map.put("self", getSelf()); StringCompiler sc = new StringCompiler(map); logger.warn(sc.c("{self.id} hasn't any simulcast layers.")); } return; } SimulcastLayer next = peerSM.getSimulcastLayer(options.getTargetOrder()); // Do NOT switch to hq if it's not streaming. if (next == null || (next.getOrder() != SimulcastManager.SIMULCAST_LAYER_ORDER_LQ && !next.isStreaming())) { if (logger.isDebugEnabled()) { Map<String, Object> map = new HashMap<String, Object>(1); map.put("self", getSelf()); StringCompiler sc = new StringCompiler(map); logger.debug(sc.c("{self.id} ignoring request to switch to " + "higher order layer because it is not currently " + "being streamed.")); } return; } synchronized (receiveLayersSyncRoot) { SimulcastLayer current = getCurrent(); // Do NOT switch to an already receiving layer. if (current == next) { // and forget "previous" next, we're sticking with current. this.weakNext = null; this.seenNext = 0; if (logger.isDebugEnabled()) { Map<String, Object> map = new HashMap<String, Object>(4); map.put("self", getSelf()); map.put("peer", getPeer()); map.put("current", current); map.put("next", next); StringCompiler sc = new StringCompiler(map); logger.debug(sc.c("The simulcast receiver of {self.id} for " + "{peer.id} already receives layer {next.order} " + "({next.primarySSRC}).")); } return; } else { // If current has changed, request an FIR, notify the parent // endpoint and change the receiving streams. if (options.isHardSwitch() && next != getNext()) { // XXX(gp) run these in the event dispatcher thread? // Send FIR requests first. this.askForKeyframe(next); } if (options.isUrgent() || current == null) { // Receiving simulcast layers have brutally changed. Create // and send an event through data channels to the receiving // endpoint. this.sendSimulcastLayersChangedEvent(next); this.weakCurrent = new WeakReference<SimulcastLayer>(next); this.weakNext = null; // Since the currently received layer has changed, reset the // seenCurrent counter. this.seenNext = 0; if (logger.isDebugEnabled()) { Map<String, Object> map = new HashMap<String, Object>(4); map.put("self", getSelf()); map.put("peer", getPeer()); map.put("next", next); map.put("urgently", options.isUrgent() ? "urgently" : ""); StringCompiler sc = new StringCompiler(map); logger.debug(sc.c("The simulcast receiver " + "of {self.id} for {peer.id} has {urgently} " + "switched to layer {next.order} " + "({next.primarySSRC}).").toString() .replaceAll("\\s+", " ")); } } else { // Receiving simulcast layers are changing, create and send // an event through data channels to the receiving endpoint. this.sendSimulcastLayersChangingEvent(next); // If the layer we receive has changed (hasn't dropped), // then continue streaming the previous layer for a short // period of time while the client receives adjusts its // video. this.weakNext = new WeakReference<SimulcastLayer>(next); // Since the currently received layer has changed, reset the // seenCurrent counter. this.seenNext = 0; if (logger.isDebugEnabled()) { Map<String, Object> map = new HashMap<String, Object>(3); map.put("self", getSelf()); map.put("peer", getPeer()); map.put("next", next); StringCompiler sc = new StringCompiler(map); logger.debug(sc.c("The simulcast receiver of " + "{self.id} for {peer.id} is going to switch " + "to layer {next.order} ({next.primarySSRC}) " + "in a few moments..")); } } } } } private void askForKeyframe(SimulcastLayer layer) { if (layer == null) { logger.warn("Requested a key frame for null layer!"); return; } SimulcastManager peerSM = getPeerSM(); if (peerSM == null) { logger.warn("Requested a key frame but the peer simulcast " + "manager is null!"); return; } peerSM.getVideoChannel().askForKeyframes( new int[]{(int) layer.getPrimarySSRC()}); if (logger.isDebugEnabled()) { Map<String, Object> map = new HashMap<String, Object>(3); map.put("self", getSelf()); map.put("peer", getPeer()); map.put("layer", layer); StringCompiler sc = new StringCompiler(map); logger.debug(sc.c("The simulcast receiver of {self.id} for " + "{peer.id} has asked for a key frame for layer " + "{layer.order} ({layer.primarySSRC}).")); } } private void sendSimulcastLayersChangedEvent(SimulcastLayer layer) { if (layer == null) { logger.warn("Requested to send a simulcast layers changed event" + "but layer is null!"); return; } Endpoint self, peer; if ((self = getSelf()) != null && (peer = getPeer()) != null) { logger.debug("Sending a simulcast layers changed event to " + self.getID() + "."); // XXX(gp) it'd be nice if we could remove the // SimulcastLayersChangedEvent event. Ideally, receivers should // listen for MediaStreamTrackActivity instead. Unfortunately, // such an event does not exist in WebRTC. // Receiving simulcast layers changed, create and send // an event through data channels to the receiving endpoint. SimulcastLayersChangedEvent ev = new SimulcastLayersChangedEvent(); ev.endpointSimulcastLayers = new EndpointSimulcastLayer[]{ new EndpointSimulcastLayer(peer.getID(), layer) }; String json = mapper.toJson(ev); try { // FIXME(gp) sendMessageOnDataChannel may silently fail to // send a data message. We want to be able to handle those // errors ourselves. self.sendMessageOnDataChannel(json); } catch (IOException e) { logger.error(self.getID() + " failed to send message on " + "data channel.", e); } } else { logger.warn("Didn't send simulcast layers changed event " + "because self == null || peer == null " + "|| current == null"); } } private void sendSimulcastLayersChangingEvent(SimulcastLayer layer) { if (layer == null) { logger.warn("Requested to send a simulcast layers changing event" + "but layer is null!"); return; } Endpoint self, peer; if ((self = getSelf()) != null && (peer = getPeer()) != null) { logger.debug("Sending a simulcast layers changing event to " + self.getID() + "."); // XXX(gp) it'd be nice if we could remove the // SimulcastLayersChangedEvent event. Ideally, receivers should // listen for MediaStreamTrackActivity instead. Unfortunately, // such an event does not exist in WebRTC. // Receiving simulcast layers changed, create and send // an event through data channels to the receiving // endpoint. SimulcastLayersChangingEvent ev = new SimulcastLayersChangingEvent(); ev.endpointSimulcastLayers = new EndpointSimulcastLayer[]{ new EndpointSimulcastLayer(peer.getID(), layer) }; String json = mapper.toJson(ev); try { // FIXME(gp) sendMessageOnDataChannel may silently fail to // send a data message. We want to be able to handle those // errors ourselves. self.sendMessageOnDataChannel(json); } catch (IOException e) { logger.error(self.getID() + " failed to send message on " + "data channel.", e); } } else { logger.warn("Didn't send simulcast layers changing event " + "because self == null || peer == null " + "|| current == null"); } } @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (SimulcastLayer.IS_STREAMING_PROPERTY .equals(propertyChangeEvent.getPropertyName())) { // A remote simulcast layer has either started or stopped // streaming. Deal with it. SimulcastLayer layer = (SimulcastLayer) propertyChangeEvent.getSource(); onPeerLayerChanged(layer); } else if (Endpoint .SELECTED_ENDPOINT_PROPERTY_NAME.equals( propertyChangeEvent.getPropertyName())) { // endpoint == this.manager.getVideoChannel().getEndpoint() is // implied. String oldValue = (String) propertyChangeEvent.getOldValue(); String newValue = (String) propertyChangeEvent.getNewValue(); onSelectedEndpointChanged(oldValue, newValue); } else if (VideoChannel.ENDPOINT_PROPERTY_NAME.equals( propertyChangeEvent.getPropertyName())) { // Listen for property changes from self. Endpoint newValue = (Endpoint) propertyChangeEvent.getNewValue(); Endpoint oldValue = (Endpoint) propertyChangeEvent.getOldValue(); onEndpointChanged(newValue, oldValue); } else if (SimulcastManager.SIMULCAST_LAYERS_PROPERTY.equals( propertyChangeEvent.getPropertyName())) { // The simulcast layers of the peer have changed, (re)attach. SimulcastManager peerSM = (SimulcastManager) propertyChangeEvent.getSource(); onPeerLayersChanged(peerSM); } } private void onPeerLayersChanged(SimulcastManager peerSM) { if (peerSM != null && peerSM.hasLayers()) { for (SimulcastLayer layer : peerSM.getSimulcastLayers()) { // Add listener from the current receiving simulcast layers. layer.addPropertyChangeListener(weakPropertyChangeListener); } // normally getPeer() == peerSM.getVideoChannel().getEndpoint() // holds. if (logger.isDebugEnabled()) { Map<String, Object> map = new HashMap<String, Object>(2); map.put("self", getSelf()); map.put("peer", getPeer()); StringCompiler sc = new StringCompiler(map); logger.debug(sc.c("{self.id} listens on layer changes from " + "{peer.id}.")); } } } private void onPeerLayerChanged(SimulcastLayer layer) { if (!layer.isStreaming()) { // HQ stream has stopped, switch to a lower quality stream. SimulcastReceiverOptions options = new SimulcastReceiverOptions(); options.setTargetOrder(SimulcastManager.SIMULCAST_LAYER_ORDER_LQ); options.setHardSwitch(true); options.setUrgent(true); configure(options); maybeForgetNext(); } else { Endpoint self = getSelf(); Endpoint peer = getPeer(); if (peer != null && self != null && peer.getID().equals(self.getSelectedEndpointID())) { SimulcastReceiverOptions options = new SimulcastReceiverOptions(); options.setTargetOrder( SimulcastManager.SIMULCAST_LAYER_ORDER_HQ); options.setHardSwitch(false); options.setUrgent(false); configure(options); } } } private void onSelectedEndpointChanged( String oldValue, String newValue) { synchronized (receiveLayersSyncRoot) { // Rule 1: send an hq stream only for the selected endpoint. if (this.maybeReceiveHighFrom(newValue)) { // Rule 1.1: if the new endpoint is being watched by any of the // receivers, the bridge tells it to start streaming its hq // stream. this.maybeSendStartHighQualityStreamCommand(newValue); } // Rule 2: send an lq stream only for the previously selected // endpoint. if (this.maybeReceiveLowFrom(oldValue)) { // Rule 2.1: if the old endpoint is not being watched by any of // the receivers, the bridge tells it to stop streaming its hq // stream. this.maybeSendStopHighQualityStreamCommand(oldValue); } } } private void onEndpointChanged(Endpoint newValue, Endpoint oldValue) { if (newValue != null) { newValue.addPropertyChangeListener(weakPropertyChangeListener); } else { logger.warn("Cannot listen on self, it's null!"); if (logger.isDebugEnabled()) { logger.debug(Arrays.toString( Thread.currentThread().getStackTrace())); } } if (oldValue != null) { oldValue.removePropertyChangeListener(weakPropertyChangeListener); } } /** * * @param id */ private boolean maybeReceiveHighFrom(String id) { Endpoint peer; if (!StringUtils.isNullOrEmpty(id) && (peer = getPeer()) != null && id.equals(peer.getID())) { SimulcastReceiverOptions options = new SimulcastReceiverOptions(); options.setTargetOrder(SimulcastManager.SIMULCAST_LAYER_ORDER_HQ); options.setHardSwitch(true); options.setUrgent(false); configure(options); return true; } else { return false; } } /** * Configures the simulcast manager of the receiver to receive a high * quality stream only from the designated sender. * * @param id */ private boolean maybeReceiveLowFrom(String id) { Endpoint peer; if (!StringUtils.isNullOrEmpty(id) && (peer = getPeer()) != null && id.equals(peer.getID())) { SimulcastReceiverOptions options = new SimulcastReceiverOptions(); options.setTargetOrder(SimulcastManager.SIMULCAST_LAYER_ORDER_LQ); options.setHardSwitch(true); options.setUrgent(false); configure(options); return true; } else { return false; } } /** * Sends a data channel command to a simulcast enabled video sender to make * it stop streaming its hq stream, if it's not being watched by any * receiver. * * @param id */ private void maybeSendStopHighQualityStreamCommand(String id) { Endpoint oldEndpoint = null; if (!StringUtils.isNullOrEmpty(id) && id != Endpoint.SELECTED_ENDPOINT_NOT_WATCHING_VIDEO) { oldEndpoint = this.mySM.getVideoChannel() .getContent() .getConference() .getEndpoint(id); } List<RtpChannel> oldVideoChannels = null; if (oldEndpoint != null) { oldVideoChannels = oldEndpoint.getChannels(MediaType.VIDEO); } VideoChannel oldVideoChannel = null; if (oldVideoChannels != null && oldVideoChannels.size() != 0) { oldVideoChannel = (VideoChannel) oldVideoChannels.get(0); } SortedSet<SimulcastLayer> oldSimulcastLayers = null; if (oldVideoChannel != null) { oldSimulcastLayers = oldVideoChannel.getSimulcastManager() .getSimulcastLayers(); } if (oldSimulcastLayers != null && oldSimulcastLayers.size() > 1 /* oldEndpoint != null is implied*/ && oldEndpoint.getSctpConnection().isReady() && !oldEndpoint.getSctpConnection().isExpired()) { // we have an old endpoint and it has an SCTP connection that is // ready and not expired. if nobody else is watching the old // endpoint, stop its hq stream. boolean stopHighQualityStream = true; for (Endpoint e : this.mySM.getVideoChannel() .getContent().getConference().getEndpoints()) { // TODO(gp) need some synchronization here. What if the selected // endpoint changes while we're in the loop? if (oldEndpoint != e && (oldEndpoint.getID().equals(e.getSelectedEndpointID()) || StringUtils.isNullOrEmpty(e.getSelectedEndpointID())) ) { // somebody is watching the old endpoint or somebody has not // yet signaled its selected endpoint to the bridge, don't // stop the hq stream. stopHighQualityStream = false; break; } } if (stopHighQualityStream) { // TODO(gp) this assumes only a single hq stream. logger.debug(this.mySM.getVideoChannel().getEndpoint().getID() + " notifies " + oldEndpoint.getID() + " to stop " + "its HQ stream."); SimulcastLayer hqLayer = oldSimulcastLayers.last(); StopSimulcastLayerCommand command = new StopSimulcastLayerCommand(hqLayer); String json = mapper.toJson(command); try { oldEndpoint.sendMessageOnDataChannel(json); } catch (IOException e1) { logger.error(oldEndpoint.getID() + " failed to send " + "message on data channel.", e1); } } } } /** * Sends a data channel command to a simulcast enabled video sender to make * it start streaming its hq stream, if it's being watched by some receiver. * * @param id */ private void maybeSendStartHighQualityStreamCommand(String id) { Endpoint newEndpoint = null; if (!StringUtils.isNullOrEmpty(id) && id != Endpoint.SELECTED_ENDPOINT_NOT_WATCHING_VIDEO) { newEndpoint = this.mySM.getVideoChannel() .getContent().getConference().getEndpoint(id); } List<RtpChannel> newVideoChannels = null; if (newEndpoint != null) { newVideoChannels = newEndpoint.getChannels(MediaType.VIDEO); } VideoChannel newVideoChannel = null; if (newVideoChannels != null && newVideoChannels.size() != 0) { newVideoChannel = (VideoChannel) newVideoChannels.get(0); } SortedSet<SimulcastLayer> newSimulcastLayers = null; if (newVideoChannel != null) { newSimulcastLayers = newVideoChannel.getSimulcastManager() .getSimulcastLayers(); } if (newSimulcastLayers != null && newSimulcastLayers.size() > 1 /* newEndpoint != null is implied*/ && newEndpoint.getSctpConnection().isReady() && !newEndpoint.getSctpConnection().isExpired()) { // we have a new endpoint and it has an SCTP connection that is // ready and not expired. if somebody else is watching the new // endpoint, start its hq stream. boolean startHighQualityStream = false; for (Endpoint e : this.mySM.getVideoChannel() .getContent().getConference().getEndpoints()) { // TODO(gp) need some synchronization here. What if the // selected endpoint changes while we're in the loop? if (newEndpoint != e && (newEndpoint.getID().equals( e.getSelectedEndpointID()) || (SimulcastManager.SIMULCAST_LAYER_ORDER_INIT > SimulcastManager.SIMULCAST_LAYER_ORDER_LQ && StringUtils.isNullOrEmpty( e.getSelectedEndpointID()))) ) { // somebody is watching the new endpoint or somebody has not // yet signaled its selected endpoint to the bridge, start // the hq stream. if (logger.isDebugEnabled()) { Map<String, Object> map = new HashMap<String, Object>(3); map.put("e", e); map.put("newEndpoint", newEndpoint); map.put("maybe", StringUtils.isNullOrEmpty( e.getSelectedEndpointID()) ? "(maybe) " : ""); StringCompiler sc = new StringCompiler(map); logger.debug(sc.c("{e.id} is {maybe} watching " + "{newEndpoint.id}.") .toString().replaceAll("\\s+", " ")); } startHighQualityStream = true; break; } } if (startHighQualityStream) { // TODO(gp) this assumes only a single hq stream. logger.debug(this.mySM.getVideoChannel().getEndpoint().getID() + " notifies " + newEndpoint.getID() + " to start " + "its HQ stream."); SimulcastLayer hqLayer = newSimulcastLayers.last(); StartSimulcastLayerCommand command = new StartSimulcastLayerCommand(hqLayer); String json = mapper.toJson(command); try { newEndpoint.sendMessageOnDataChannel(json); } catch (IOException e1) { logger.error(newEndpoint.getID() + " failed to send " + "message on data channel.", e1); } } } } }
package com.microsoft.office365.profile; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; public class BaseActivity extends ActionBarActivity { protected static final String TAG = "BaseActivity"; protected static final String PREFERENCES_NAME = "ProfilePreferences"; protected ProfileApplication mApplication; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApplication = (ProfileApplication)getApplication(); mApplication.mSharedPreferences = getSharedPreferences(PREFERENCES_NAME, MODE_APPEND); } /** * This activity gets notified about the completion of the ADAL activity through this method. * @param requestCode The integer request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its * setResult(). * @param data An Intent, which can return result data to the caller (various data * can be attached to Intent "extras"). */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "onActivityResult - AuthenticationActivity has come back with results"); super.onActivityResult(requestCode, resultCode, data); AuthenticationManager .getInstance() .getAuthenticationContext() .onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_base, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.sign_out) { //Clear tokens. AuthenticationManager .getInstance() .getAuthenticationContext() .getCache() .removeAll(); AuthenticationManager.resetInstance(); RequestManager.resetInstance(); mApplication.resetDisplayName(); mApplication.resetDisplayableId(); mApplication.resetTenant(); mApplication.resetUserId(); //Clear cookies. if(Build.VERSION.SDK_INT >= 21){ CookieManager.getInstance().removeSessionCookies(null); CookieManager.getInstance().flush(); } else { CookieSyncManager.createInstance(this); CookieManager.getInstance().removeSessionCookie(); CookieSyncManager.getInstance().sync(); } final Intent userListIntent = new Intent(this, UserListActivity.class); startActivity(userListIntent); return true; } return super.onOptionsItemSelected(item); } }
package org.strategoxt.imp.runtime.services; import static org.spoofax.interpreter.terms.IStrategoTerm.*; import static org.strategoxt.imp.runtime.dynamicloading.TermReader.*; import java.io.FileNotFoundException; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import lpg.runtime.IAst; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; 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.core.runtime.jobs.ISchedulingRule; import org.eclipse.imp.parser.IModelListener; import org.eclipse.imp.parser.IParseController; import org.spoofax.interpreter.core.Interpreter; import org.spoofax.interpreter.core.InterpreterException; import org.spoofax.interpreter.library.LoggingIOAgent; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.strategoxt.imp.runtime.Debug; import org.strategoxt.imp.runtime.Environment; import org.strategoxt.imp.runtime.dynamicloading.Descriptor; import org.strategoxt.imp.runtime.parser.ast.AstMessageHandler; import org.strategoxt.imp.runtime.stratego.EditorIOAgent; import org.strategoxt.imp.runtime.stratego.StrategoTermPath; import org.strategoxt.imp.runtime.stratego.adapter.IStrategoAstNode; import org.strategoxt.imp.runtime.stratego.adapter.IWrappedAstNode; import org.strategoxt.imp.runtime.stratego.adapter.WrappedAstNode; /** * Basic Stratego feedback (i.e., errors and warnings) provider. * This service may also be used as a basis for other semantic services * such as reference resolving. * * @author Lennart Kats <lennart add lclnet.nl> */ public class StrategoFeedback implements IModelListener { private final Descriptor descriptor; private final Interpreter interpreter; private final String feedbackFunction; private final AstMessageHandler messages = new AstMessageHandler(); private final ExecutorService asyncExecutor = Executors.newSingleThreadExecutor(); private boolean asyncExecuterEnqueued = false; public StrategoFeedback(Descriptor descriptor, Interpreter resolver, String feedbackFunction) { this.descriptor = descriptor; this.interpreter = resolver; this.feedbackFunction = feedbackFunction; } public final AnalysisRequired getAnalysisRequired() { return AnalysisRequired.TYPE_ANALYSIS; } /** * Starts a new update() operation, asynchronously. */ public synchronized void asyncUpdate(final IParseController parseController, final IProgressMonitor monitor) { // TODO: Properly integrate this asynchronous job into the Eclipse environment? // e.g. (ab)using Workspace.run() if (!asyncExecuterEnqueued && feedbackFunction != null) { asyncExecuterEnqueued = true; asyncExecutor.execute(new Runnable() { public void run() { synchronized (StrategoFeedback.this) { asyncExecuterEnqueued = false; update(parseController, monitor); } } }); } } public synchronized void update(IParseController parseController, IProgressMonitor monitor) { if (feedbackFunction != null) { ITermFactory factory = Environment.getTermFactory(); IStrategoAstNode ast = (IStrategoAstNode) parseController.getCurrentAst(); if (ast == null) return; IStrategoTerm[] inputParts = { ast.getTerm(), factory.makeString(ast.getResourcePath().toOSString()), factory.makeString(ast.getRootPath().toOSString()) }; IStrategoTerm input = factory.makeTuple(inputParts); IStrategoTerm feedback = invoke(feedbackFunction, input, ast.getResourcePath().removeLastSegments(1)); asyncPresentToUser(parseController, feedback); } } private void asyncPresentToUser(final IParseController parseController, final IStrategoTerm feedback) { try { ResourcesPlugin.getWorkspace().run( new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { presentToUser(parseController, feedback); } } , new ISchedulingRule() { public boolean contains(ISchedulingRule rule) { return false; } public boolean isConflicting(ISchedulingRule rule) { return true; } } , IWorkspace.AVOID_UPDATE , null ); } catch (CoreException e) { // TODO: Handle exceptions, particularly workspace locked ones // (assuming these still occur with the scheduling rule) // (see also LoaderPreferences#updateDescriptors(IWorkspaceRunnable)) Environment.logException("Could not update feedback", e); } } private void presentToUser(IParseController parseController, IStrategoTerm feedback) { messages.clearAllMarkers(); if (feedback != null && feedback.getTermType() == TUPLE && termAt(feedback, 0).getTermType() == LIST && termAt(feedback, 1).getTermType() == LIST && termAt(feedback, 2).getTermType() == LIST) { IStrategoList errors = termAt(feedback, 0); IStrategoList warnings = termAt(feedback, 1); feedbackToMarkers(parseController, errors, IMarker.SEVERITY_ERROR); feedbackToMarkers(parseController, warnings, IMarker.SEVERITY_WARNING); } else { Environment.logException("Illegal output from " + feedbackFunction + ": " + feedback); } } private final void feedbackToMarkers(IParseController parseController, IStrategoList feedbacks, int severity) { for (IStrategoTerm feedback : feedbacks.getAllSubterms()) { feedbackToMarker(parseController, feedback, severity); } } private void feedbackToMarker(IParseController parseController, IStrategoTerm feedback, int severity) { IStrategoTerm term = termAt(feedback, 0); IStrategoString message = termAt(feedback, 1); IAst node = getClosestAstNode(term); if (node == null) { Environment.logException("ATerm is not associated with an AST node, cannot report feedback message: " + term + " - " + message); } else { messages.addMarker(node, message.stringValue(), severity); } } /** * Given an stratego term, give the first AST node associated * with any of its subterms, doing a depth-first search. */ private static IAst getClosestAstNode(IStrategoTerm term) { if (term instanceof IWrappedAstNode) { return ((IWrappedAstNode) term).getNode(); } else { for (int i = 0; i < term.getSubtermCount(); i++) { IAst result = getClosestAstNode(termAt(term, i)); if (result != null) return result; } return null; } } /** * Invoke a Stratego function with a specific AST node as its input. * * @see #getAstNode(IStrategoTerm) To retrieve the AST node associated with the resulting term. */ public synchronized IStrategoTerm invoke(String function, IStrategoAstNode node) { ITermFactory factory = Environment.getTermFactory(); IStrategoTerm[] inputParts = { getRoot(node).getTerm(), factory.makeString(node.getResourcePath().toOSString()), node.getTerm(), StrategoTermPath.createPath(node) }; IStrategoTerm input = factory.makeTuple(inputParts); return invoke(function, input, node.getResourcePath().removeLastSegments(1)); } public synchronized IStrategoTerm invoke(String function, IStrategoTerm term, IPath workingDir) { Debug.startTimer(); try { interpreter.setCurrent(term); initInterpreterPath(workingDir); ((LoggingIOAgent) interpreter.getIOAgent()).clearLog(); boolean success = interpreter.invoke(function); if (!success) { Environment.logStrategyFailure("Failure reported during evaluation of function " + function, interpreter); return null; } } catch (InterpreterException e) { Environment.logException("Internal error evaluating function " + function, e); return null; } Debug.stopTimer("Invoked Stratego strategy " + function); return interpreter.current(); } public IAst getAstNode(IStrategoTerm term) { if (term == null) return null; if (term instanceof WrappedAstNode) { return ((WrappedAstNode) term).getNode(); } else { Environment.logException("Resolved reference is not associated with an AST node " + interpreter.current()); return null; } } private void initInterpreterPath(IPath workingDir) { try { interpreter.getIOAgent().setWorkingDir(workingDir.toOSString()); ((EditorIOAgent) interpreter.getIOAgent()).setDescriptor(descriptor); } catch (FileNotFoundException e) { Environment.logException("Could not set Stratego working directory", e); throw new RuntimeException(e); } } private static IStrategoAstNode getRoot(IStrategoAstNode node) { while (node.getParent() != null) node = node.getParent(); return node; } }
/* * $Id: ConfigurationPropTreeImpl.java,v 1.10 2010-04-06 18:09:48 pgust Exp $ */ package org.lockss.config; import java.io.*; import java.util.*; import org.lockss.util.*; /** <code>ConfigurationPropTreeImpl</code> represents the config parameters * as a {@link org.lockss.util.PropertyTree} */ public class ConfigurationPropTreeImpl extends Configuration { private PropertyTree props; private boolean isSealed = false; ConfigurationPropTreeImpl() { super(); props = new PropertyTree(); } private ConfigurationPropTreeImpl(PropertyTree tree) { super(); props = tree; } PropertyTree getPropertyTree() { return props; } public boolean store(OutputStream ostr, String header) throws IOException { SortedProperties.fromProperties(props).store(ostr, header); // props.store(ostr, header); return true; } /** * Reset this instance. */ void reset() { super.reset(); props.clear(); } /** Return true iff the Configurations are equal. * Equality is based on the equality of their property * trees and Tdbs. * <p> * This implementation is more efficient if the other * object is an instance of ConfigurationPropertyTreeImpl. * Otherwise it falls back on Configuration.equals(). * * @param o the other object * @return <code>true</code> iff the configurations are equal */ public boolean equals(Object o) { if (o instanceof ConfigurationPropTreeImpl) { // compare configuration properties ConfigurationPropTreeImpl config = (ConfigurationPropTreeImpl)o; if (!PropUtil.equalProps(props, (config.getPropertyTree()))) { return false; } // compare Tdbs Tdb thisTdb = getTdb(); Tdb otherTdb = config.getTdb(); if (thisTdb == null) { return (otherTdb == null); } return thisTdb.equals(otherTdb); } return super.equals(o); } /** Return the set of keys whose values differ. * This operation is transitive: c1.differentKeys(c2) yields the same * result as c2.differentKeys(c1). * * @param otherConfig the config to compare with. May be null. */ public Set<String> differentKeys(Configuration otherConfig) { if (this == otherConfig) { return Collections.EMPTY_SET; } PropertyTree otherTree = (otherConfig == null) ? new PropertyTree() : ((ConfigurationPropTreeImpl)otherConfig).getPropertyTree(); return PropUtil.differentKeysAndPrefixes(getPropertyTree(), otherTree); } public boolean containsKey(String key) { return props.containsKey(key); } public String get(String key) { return (String)props.get(key); } /** * Return a list of values for the given key. */ public List getList(String key) { List propList = null; try { Object o = props.get(key); if (o != null) { if (o instanceof List) { propList = (List)o; } else { propList = StringUtil.breakAt((String)o, ';', 0, true); } } else { propList = Collections.EMPTY_LIST; } } catch (ClassCastException ex) { // The client requested a list of something that wasn't actually a list. // Throw an exception throw new IllegalArgumentException("Key does not hold a list value: " + key); } return propList; } public void put(String key, String val) { if (isSealed) { throw new IllegalStateException("Can't modify sealed configuration"); } props.setProperty(key, val); } /** Remove the value associated with <code>key</code>. * @param key the config key to remove */ public void remove(String key) { if (isSealed) { throw new IllegalStateException("Can't modify sealed configuration"); } props.remove(key); } public void seal() { isSealed = true; // also seal the title database Tdb tdb = getTdb(); if (tdb != null) { tdb.seal(); } } public boolean isSealed() { return isSealed; } public Configuration getConfigTree(String key) { PropertyTree tree = props.getTree(key); if (tree == null) { return null; } Configuration res = new ConfigurationPropTreeImpl(tree); if (isSealed()) { res.seal(); } return res; } public Set keySet() { return Collections.unmodifiableSet(props.keySet()); } public Iterator keyIterator() { return keySet().iterator(); } public Iterator nodeIterator() { return possiblyEmptyIterator(props.getNodes()); } public Iterator nodeIterator(String key) { return possiblyEmptyIterator(props.getNodes(key)); } private Iterator possiblyEmptyIterator(Enumeration en) { if (en != null) { return new EnumerationIterator(en); } else { return CollectionUtil.EMPTY_ITERATOR; } } public String toString() { return getPropertyTree().toString(); } }
package com.suwonsmartapp.tourlist.list; import com.suwonsmartapp.tourlist.InputActivity; import com.suwonsmartapp.tourlist.R; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; public class ListActivity extends ActionBarActivity implements AdapterView.OnItemClickListener { public static final String TAG = ListActivity.class.getSimpleName(); private ListView mListAdapter; private ArrayList<TourList> tourList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); mListAdapter = (ListView) findViewById(R.id.lv_list_adapter); tourListLoad(); // Adapter ListAdapter adapter = new ListAdapter(getApplicationContext(), 0, tourList); // View mListAdapter.setAdapter(adapter); mListAdapter.setOnItemClickListener(this); } void tourListLoad() { tourList = new ArrayList<>(); tourList.add(new TourList(R.drawable.car, " 1", "2015-01-01", " ", R.drawable.gold_apple, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.girl, " 2", "2015-02-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.gold_apple, " 3", "2015-03-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.car, " 4", "2015-04-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.girl, " 5", "2015-05-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.gold_apple, " 6", "2015-06-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.car, " 7", "2015-07-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.girl, " 8", "2015-08-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.gold_apple, " 9", "2015-09-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); tourList.add(new TourList(R.drawable.car, " 10", "2015-10-01", " ", R.drawable.car, R.drawable.girl, R.drawable.gold_apple, R.drawable.car, R.drawable.car)); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { startActivity(new Intent(getApplicationContext(), InputActivity.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_first, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. // int id = item.getItemId(); Intent intent = new Intent(this, InputActivity.class); startActivity(intent); return true; } }
package org.lwjgl.vulkan.awt; import org.lwjgl.PointerBuffer; import org.lwjgl.system.Library; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.jawt.JAWT; import org.lwjgl.system.jawt.JAWTDrawingSurface; import org.lwjgl.system.jawt.JAWTDrawingSurfaceInfo; import org.lwjgl.system.macosx.ObjCRuntime; import org.lwjgl.vulkan.VkMetalSurfaceCreateInfoEXT; import org.lwjgl.vulkan.VkPhysicalDevice; import javax.swing.*; import java.awt.*; import java.nio.LongBuffer; import static org.lwjgl.system.JNI.invokePPP; import static org.lwjgl.system.jawt.JAWTFunctions.*; import static org.lwjgl.system.macosx.ObjCRuntime.objc_getClass; import static org.lwjgl.system.macosx.ObjCRuntime.sel_getUid; import static org.lwjgl.vulkan.EXTMetalSurface.VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT; import static org.lwjgl.vulkan.EXTMetalSurface.vkCreateMetalSurfaceEXT; import static org.lwjgl.vulkan.VK10.VK_SUCCESS; public class PlatformMacOSXVKCanvas implements PlatformVKCanvas { private static final JAWT awt; private static final long objc_msgSend; private static final long CATransaction; static { awt = JAWT.callocStack(); awt.version(JAWT_VERSION_1_7); if (!JAWT_GetAWT(awt)) throw new AssertionError("GetAWT failed"); Library.loadSystem("org.lwjgl.awt","lwjgl3awt"); objc_msgSend = ObjCRuntime.getLibrary().getFunctionAddress("objc_msgSend"); CATransaction = objc_getClass("CATransaction"); } // core animation flush public static void caFlush() { invokePPP(CATransaction, sel_getUid("flush"), objc_msgSend); } private native long createMTKView(long platformInfo, int x, int y, int width, int height); public long create(Canvas canvas, VKData data) throws AWTException { MemoryStack stack = MemoryStack.stackGet(); JAWTDrawingSurface ds = JAWT_GetDrawingSurface(canvas, awt.GetDrawingSurface()); try { int lock = JAWT_DrawingSurface_Lock(ds, ds.Lock()); if ((lock & JAWT_LOCK_ERROR) != 0) throw new AWTException("JAWT_DrawingSurface_Lock() failed"); try { JAWTDrawingSurfaceInfo dsi = JAWT_DrawingSurface_GetDrawingSurfaceInfo(ds, ds.GetDrawingSurfaceInfo()); try { // if the canvas is inside e.g. a JSplitPane, the dsi coordinates are wrong and need to be corrected JRootPane rootPane = SwingUtilities.getRootPane(canvas); if(rootPane!=null) { Point point = SwingUtilities.convertPoint(canvas, new Point(), rootPane); dsi.bounds().x(point.x); dsi.bounds().y(point.y); } long metalLayer = createMTKView(dsi.platformInfo(), dsi.bounds().x(), dsi.bounds().y(), dsi.bounds().width(), dsi.bounds().height()); caFlush(); PointerBuffer pLayer = PointerBuffer.create(metalLayer, 1); VkMetalSurfaceCreateInfoEXT sci = VkMetalSurfaceCreateInfoEXT.callocStack(stack) .sType(VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT) .flags(0) .pLayer(pLayer); LongBuffer pSurface = stack.mallocLong(1); int err = vkCreateMetalSurfaceEXT(data.instance, sci, null, pSurface); if (err != VK_SUCCESS) { throw new AWTException("Calling vkCreateMetalSurfaceEXT failed with error: " + err); } return pSurface.get(0); } finally { JAWT_DrawingSurface_FreeDrawingSurfaceInfo(dsi, ds.FreeDrawingSurfaceInfo()); } } finally { JAWT_DrawingSurface_Unlock(ds, ds.Unlock()); } } finally { JAWT_FreeDrawingSurface(ds, awt.FreeDrawingSurface()); } } // On macOS, all physical devices and queue families must be capable of presentation with any layer. As a result there is no macOS-specific query for these capabilities. public boolean getPhysicalDevicePresentationSupport(VkPhysicalDevice physicalDevice, int queueFamily) { return true; } }
package org.xwiki.extension.job.internal; import java.util.ArrayList; import java.util.Collection; import java.util.NavigableSet; import java.util.TreeSet; import javax.inject.Named; import org.xwiki.component.annotation.Component; import org.xwiki.extension.ExtensionId; import org.xwiki.extension.InstallException; import org.xwiki.extension.InstalledExtension; import org.xwiki.extension.ResolveException; import org.xwiki.extension.job.InstallRequest; import org.xwiki.extension.job.plan.internal.DefaultExtensionPlanTree; import org.xwiki.extension.repository.result.IterableResult; import org.xwiki.extension.version.Version; import org.xwiki.job.Request; /** * Create an Extension upgrade plan. * * @version $Id$ * @since 4.1M1 */ @Component @Named(UpgradePlanJob.JOBTYPE) public class UpgradePlanJob extends AbstractInstallPlanJob<InstallRequest> { /** * The id of the job. */ public static final String JOBTYPE = "upgradeplan"; private static final String FAILED_INSTALL_MESSAGE = "Can't install extension [{}] on namespace [{}]."; @Override public String getType() { return JOBTYPE; } @Override protected InstallRequest castRequest(Request request) { InstallRequest installRequest; if (request instanceof InstallRequest) { installRequest = (InstallRequest) request; } else { installRequest = new InstallRequest(request); } return installRequest; } private boolean isSkipped(InstalledExtension extension, String namespace) { // Explicitly skipped extensions if (getRequest().getExcludedExtensions().contains(extension.getId())) { return true; } // Extensions with no backward dependencies Collection<ExtensionId> requestExtensions = getRequest().getExtensions(); boolean filterDependencies = requestExtensions == null || requestExtensions.isEmpty(); if (filterDependencies) { // Don't skip if the extension has not been installed as dependency if (!extension.isDependency(namespace)) { return false; } // Don't skip if the extension "lost" its backward dependencies try { boolean hasBackwardDependencies; if (extension.getNamespaces() == null) { hasBackwardDependencies = !this.installedExtensionRepository.getBackwardDependencies(extension.getId()).isEmpty(); } else { hasBackwardDependencies = !extension.isDependency(namespace) && !this.installedExtensionRepository .getBackwardDependencies(extension.getId().getId(), namespace).isEmpty(); } return hasBackwardDependencies; } catch (ResolveException e) { // Should never happen this.logger.error("Failed to gather backward dependencies for extension [{}]", extension.getId(), e); } } return false; } /** * @param extension the extension currently installed * @param namespace the namespace where the extension is installed */ protected void upgradeExtension(InstalledExtension extension, String namespace) { if (!isSkipped(extension, namespace)) { NavigableSet<Version> versions = getVersions(extension, namespace); // Useless to continue if the extension does not have any available version if (!versions.isEmpty()) { upgradeExtension(extension, namespace, versions.descendingSet()); } } } private NavigableSet<Version> getVersions(InstalledExtension extension, String namespace) { NavigableSet<Version> versionList = new TreeSet<>(); // Search local versions try { IterableResult<Version> versions = this.localExtensionRepository.resolveVersions(extension.getId().getId(), 0, -1); for (Version version : versions) { versionList.add(version); } } catch (ResolveException e) { this.logger.debug("Failed to resolve local versions for extension id [{}]", extension.getId().getId(), e); } // Search remote versions try { IterableResult<Version> versions = this.repositoryManager.resolveVersions(extension.getId().getId(), 0, -1); for (Version version : versions) { versionList.add(version); } } catch (ResolveException e) { this.logger.debug("Failed to resolve remote versions for extension id [{}]", extension.getId().getId(), e); } // Make sure the current version is included if the extension is invalid (it's possible this version does // not exist on any repository) if (!extension.isValid(namespace)) { versionList.add(extension.getId().getVersion()); } return versionList; } protected void upgradeExtension(InstalledExtension extension, String namespace, Collection<Version> versionList) { for (Version version : versionList) { // Don't try to upgrade for lower versions but try to repair same version of the extension is invalid int compare = extension.getId().getVersion().compareTo(version); if (compare > 0 || (compare == 0 && extension.isValid(namespace))) { break; } // Only upgrade beta if the current is beta etc. if (extension.getId().getVersion().getType().ordinal() <= version.getType().ordinal()) { if (tryInstallExtension(new ExtensionId(extension.getId().getId(), version), namespace)) { break; } } } } /** * Try to install the provided extension and update the plan if it's working. * * @param extensionId the extension version to install * @param namespace the namespace where to install the extension * @return true if the installation would succeed, false otherwise */ protected boolean tryInstallExtension(ExtensionId extensionId, String namespace) { DefaultExtensionPlanTree currentTree = this.extensionTree.clone(); try { installExtension(extensionId, namespace, currentTree); setExtensionTree(currentTree); return true; } catch (InstallException e) { if (getRequest().isVerbose()) { this.logger.info(FAILED_INSTALL_MESSAGE, extensionId, namespace, e); } else { this.logger.debug(FAILED_INSTALL_MESSAGE, extensionId, namespace, e); } } return false; } protected void upgrade(String namespace, Collection<InstalledExtension> installedExtensions) { this.progressManager.pushLevelProgress(installedExtensions.size(), this); try { for (InstalledExtension installedExtension : installedExtensions) { this.progressManager.startStep(this); if (namespace == null || !installedExtension.isInstalled(null)) { upgradeExtension(installedExtension, namespace); } this.progressManager.endStep(this); } } finally { this.progressManager.popLevelProgress(this); } } protected void upgrade(Collection<InstalledExtension> installedExtensions) { this.progressManager.pushLevelProgress(installedExtensions.size(), this); try { for (InstalledExtension installedExtension : installedExtensions) { this.progressManager.startStep(this); if (installedExtension.getNamespaces() == null) { upgradeExtension(installedExtension, null); } else { this.progressManager.pushLevelProgress(installedExtension.getNamespaces().size(), this); try { for (String namespace : installedExtension.getNamespaces()) { this.progressManager.startStep(this); upgradeExtension(installedExtension, namespace); this.progressManager.endStep(this); } } finally { this.progressManager.popLevelProgress(this); } } this.progressManager.endStep(this); } } finally { this.progressManager.popLevelProgress(this); } } protected Collection<InstalledExtension> getInstalledExtensions(String namespace) { Collection<ExtensionId> requestExtensions = getRequest().getExtensions(); Collection<InstalledExtension> installedExtensions; if (requestExtensions != null && !requestExtensions.isEmpty()) { installedExtensions = new ArrayList<>(requestExtensions.size()); for (ExtensionId requestExtension : requestExtensions) { InstalledExtension installedExtension = this.installedExtensionRepository.getInstalledExtension(requestExtension); if (installedExtension.isInstalled(namespace)) { installedExtensions.add(installedExtension); } } } else { installedExtensions = this.installedExtensionRepository.getInstalledExtensions(namespace); } return installedExtensions; } protected Collection<InstalledExtension> getInstalledExtensions() { Collection<ExtensionId> requestExtensions = getRequest().getExtensions(); Collection<InstalledExtension> installedExtensions; if (requestExtensions != null && !requestExtensions.isEmpty()) { installedExtensions = new ArrayList<>(requestExtensions.size()); for (ExtensionId requestExtension : requestExtensions) { InstalledExtension installedExtension = this.installedExtensionRepository.getInstalledExtension(requestExtension); installedExtensions.add(installedExtension); } } else { installedExtensions = this.installedExtensionRepository.getInstalledExtensions(); } return installedExtensions; } @Override protected void runInternal() throws Exception { Collection<String> namespaces = getRequest().getNamespaces(); if (namespaces == null) { Collection<InstalledExtension> installedExtensions = getInstalledExtensions(); upgrade(installedExtensions); } else { this.progressManager.pushLevelProgress(namespaces.size(), this); try { for (String namespace : namespaces) { this.progressManager.startStep(this); upgrade(namespace, getInstalledExtensions(namespace)); this.progressManager.endStep(this); } } finally { this.progressManager.popLevelProgress(this); } } } }
package com.vdocipher.sampleapp; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.util.Pair; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.vdocipher.aegis.media.ErrorDescription; import com.vdocipher.aegis.media.Track; import com.vdocipher.aegis.player.VdoPlayer; import com.vdocipher.aegis.player.VdoPlayerFragment; import org.json.JSONException; import java.io.IOException; public class OnlinePlayerActivity extends AppCompatActivity implements VdoPlayer.InitializationListener { private final String TAG = "OnlinePlayerActivity"; private VdoPlayer player; private VdoPlayerFragment playerFragment; private ImageButton playPauseButton, replayButton, errorButton; private TextView currTime, duration; private SeekBar seekBar; private ProgressBar bufferingIcon; private Button speedControlButton; private boolean playWhenReady = false; private boolean controlsShowing = false; private boolean isLandscape = false; private int mLastSystemUiVis; private volatile String mOtp; private volatile String mPlaybackInfo; private static final float allowedSpeedList[] = new float[]{0.5f, 0.75f, 1f, 1.25f, 1.5f, 1.75f, 2f}; private static final CharSequence allowedSpeedStrList[] = new CharSequence[]{"0.5x", "0.75x", "1x", "1.25x", "1.5x", "1.75x", "2x"}; private int chosenSpeedIndex = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.v(TAG, "onCreate called"); setContentView(R.layout.activity_online_player); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(uiVisibilityListener); if (getSupportActionBar() != null) { getSupportActionBar().hide(); } if (savedInstanceState != null) { mOtp = savedInstanceState.getString("otp"); mPlaybackInfo = savedInstanceState.getString("playbackInfo"); } seekBar = (SeekBar)findViewById(R.id.seekbar); seekBar.setEnabled(false); currTime = (TextView)findViewById(R.id.current_time); duration = (TextView)findViewById(R.id.duration); playerFragment = (VdoPlayerFragment)getFragmentManager().findFragmentById(R.id.online_vdo_player_fragment); playPauseButton = (ImageButton)findViewById(R.id.play_pause_button); replayButton = (ImageButton)findViewById(R.id.replay_button); replayButton.setVisibility(View.INVISIBLE); errorButton = (ImageButton)findViewById(R.id.error_icon); errorButton.setEnabled(false); errorButton.setVisibility(View.INVISIBLE); bufferingIcon = (ProgressBar) findViewById(R.id.loading_icon); speedControlButton = (Button) findViewById(R.id.speed_control_button); showLoadingIcon(false); showControls(false); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } @Override protected void onStart() { Log.v(TAG, "onStart called"); super.onStart(); initializePlayer(); } @Override protected void onStop() { Log.v(TAG, "onStop called"); disablePlayerUI(); player = null; super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { Log.v(TAG, "onSaveInstanceState called"); super.onSaveInstanceState(outState); if (mOtp != null && mPlaybackInfo != null) { outState.putString("otp", mOtp); outState.putString("playbackInfo", mPlaybackInfo); } } private void initializePlayer() { if (mOtp != null && mPlaybackInfo != null) { // initialize the playerFragment; a VdoPlayer instance will be received // in onInitializationSuccess() callback playerFragment.initialize(OnlinePlayerActivity.this); } else { // lets get otp and playbackInfo before creating the player obtainOtpAndPlaybackInfo(); } } /** * Fetch (otp + playbackInfo) and initialize VdoPlayer * here we're fetching a sample (otp + playbackInfo) * TODO you need to generate/fetch (otp + playbackInfo) OR (signature + playbackInfo) for the * video you wish to play */ private void obtainOtpAndPlaybackInfo() { // todo use asynctask new Thread(new Runnable() { @Override public void run() { try { Pair<String, String> pair = Utils.getSampleOtpAndPlaybackInfo(); mOtp = pair.first; mPlaybackInfo = pair.second; Log.i(TAG, "obtained new otp and playbackInfo"); runOnUiThread(new Runnable() { @Override public void run() { initializePlayer(); } }); } catch (IOException | JSONException e) { e.printStackTrace(); showToast("Error fetching otp and playbackInfo: " + e.getClass().getSimpleName()); } } }).start(); } private void showToast(final String message) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(OnlinePlayerActivity.this, message, Toast.LENGTH_SHORT).show(); } }); } private View.OnClickListener playPauseListener = new View.OnClickListener() { @Override public void onClick(View view) { if (player == null) return; if (playWhenReady) { player.setPlayWhenReady(false); } else { player.setPlayWhenReady(true); } } }; private View.OnClickListener playerTapListener = new View.OnClickListener() { @Override public void onClick(View v) { showControls(!controlsShowing); // controlsShowing changed in this method if (isLandscape) { // show/hide system ui as well showSystemUi(controlsShowing); } } }; private void showControls(boolean show) { Log.v(TAG, (show ? "show " : "hide ") + "controls"); int visibility = show ? View.VISIBLE : View.INVISIBLE; playPauseButton.setVisibility(visibility); (findViewById(R.id.bottom_panel)).setVisibility(visibility); controlsShowing = show; } private void showSpeedControlDialog() { new AlertDialog.Builder(this) .setSingleChoiceItems(allowedSpeedStrList, chosenSpeedIndex, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (player != null) { float speed = allowedSpeedList[which]; player.setPlaybackSpeed(speed); } dialog.dismiss(); } }) .setTitle("Choose playback speed") .show(); } private void disablePlayerUI() { showControls(false); showLoadingIcon(false); playPauseButton.setEnabled(false); currTime.setEnabled(false); seekBar.setEnabled(false); replayButton.setEnabled(false); replayButton.setVisibility(View.INVISIBLE); (findViewById(R.id.player_region)).setOnClickListener(null); } @Override public void onInitializationSuccess(VdoPlayer.PlayerHost playerHost, VdoPlayer player, boolean wasRestored) { Log.i(TAG, "onInitializationSuccess"); this.player = player; player.addPlaybackEventListener(playbackListener); showLoadingIcon(false); (findViewById(R.id.player_region)).setOnClickListener(playerTapListener); (findViewById(R.id.fullscreen_toggle_button)).setOnClickListener(fullscreenToggleListener); showControls(true); // load a media to the player VdoPlayer.VdoInitParams vdoParams = VdoPlayer.VdoInitParams.createParamsWithOtp(mOtp, mPlaybackInfo); player.load(vdoParams); } @Override public void onInitializationFailure(VdoPlayer.PlayerHost playerHost, ErrorDescription errorDescription) { Log.e(TAG, "onInitializationFailure: errorCode = " + errorDescription.errorCode + ": " + errorDescription.errorMsg); Toast.makeText(OnlinePlayerActivity.this, "initialization failure: " + errorDescription.errorMsg, Toast.LENGTH_LONG).show(); showLoadingIcon(false); errorButton.setVisibility(View.VISIBLE); } private VdoPlayer.PlaybackEventListener playbackListener = new VdoPlayer.PlaybackEventListener() { @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { OnlinePlayerActivity.this.playWhenReady = playWhenReady; if (playWhenReady) { playPauseButton.setImageResource(R.drawable.ic_pause_white_48dp); } else { playPauseButton.setImageResource(R.drawable.ic_play_arrow_white_48dp); } switch (playbackState) { case VdoPlayer.STATE_READY: { showLoadingIcon(false); break; } case VdoPlayer.STATE_BUFFERING: { showLoadingIcon(true); break; } case VdoPlayer.STATE_ENDED: { playPauseButton.setEnabled(false); playPauseButton.setVisibility(View.INVISIBLE); replayButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { replayButton.setVisibility(View.INVISIBLE); if (OnlinePlayerActivity.this.player != null) { OnlinePlayerActivity.this.player.seekTo(0); playPauseButton.setEnabled(true); } } }); replayButton.setEnabled(true); replayButton.setVisibility(View.VISIBLE); break; } default: break; } } @Override public void onTracksChanged(Track[] tracks, Track[] tracks1) { Log.i(TAG, "onTracksChanged"); } @Override public void onBufferUpdate(long bufferTime) { seekBar.setSecondaryProgress((int)bufferTime); } @Override public void onSeekTo(long millis) { Log.i(TAG, "onSeekTo: " + String.valueOf(millis)); } @Override public void onProgress(long millis) { seekBar.setProgress((int)millis); currTime.setText(Utils.digitalClockTime((int)millis)); } @Override public void onPlaybackSpeedChanged(float speed) { Log.i(TAG, "onPlaybackSpeedChanged " + speed); chosenSpeedIndex = Utils.getClosestFloatIndex(allowedSpeedList, speed); ((TextView)(findViewById(R.id.speed_control_button))).setText(allowedSpeedStrList[chosenSpeedIndex]); } @Override public void onLoading(VdoPlayer.VdoInitParams vdoInitParams) { Log.i(TAG, "onLoading"); showLoadingIcon(true); } @Override public void onLoadError(VdoPlayer.VdoInitParams vdoInitParams, ErrorDescription errorDescription) { Log.i(TAG, "onLoadError"); showLoadingIcon(false); } @Override public void onLoaded(VdoPlayer.VdoInitParams vdoInitParams) { Log.i(TAG, "onLoaded"); showLoadingIcon(false); duration.setText(Utils.digitalClockTime((int)player.getDuration())); seekBar.setMax((int)player.getDuration()); seekBar.setEnabled(true); seekBar.setOnSeekBarChangeListener(seekbarChangeListener); playPauseButton.setEnabled(true); playPauseButton.setOnClickListener(playPauseListener); speedControlButton.setOnClickListener(speedButtonListener); } @Override public void onError(VdoPlayer.VdoInitParams vdoParams, ErrorDescription errorDescription) { Log.e(TAG, "onError code " + errorDescription.errorCode + ": " + errorDescription.errorMsg); showLoadingIcon(false); } @Override public void onMediaEnded(VdoPlayer.VdoInitParams vdoInitParams) { Log.i(TAG, "onMediaEnded"); } }; private void showLoadingIcon(final boolean showIcon) { if (showIcon) { bufferingIcon.setVisibility(View.VISIBLE); bufferingIcon.bringToFront(); } else { bufferingIcon.setVisibility(View.INVISIBLE); bufferingIcon.requestLayout(); } } private SeekBar.OnSeekBarChangeListener seekbarChangeListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) { // nothing much to do here } @Override public void onStartTrackingTouch(SeekBar seekBar) { // nothing much to do here } @Override public void onStopTrackingTouch(SeekBar seekBar) { player.seekTo(seekBar.getProgress()); } }; private View.OnClickListener fullscreenToggleListener = new View.OnClickListener() { @Override public void onClick(View v) { showFullScreen(!isLandscape); isLandscape = !isLandscape; int fsButtonResId = isLandscape ? R.drawable.ic_action_return_from_full_screen : R.drawable.ic_action_full_screen; ((ImageButton)(findViewById(R.id.fullscreen_toggle_button))).setImageResource(fsButtonResId); } }; private View.OnClickListener speedButtonListener = new View.OnClickListener() { @Override public void onClick(View v) { showSpeedControlDialog(); } }; private void showFullScreen(boolean show) { Log.v(TAG, show ? "go fullscreen" : "return from fullscreen"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (show) { // go to landscape orientation setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); // hide other views (findViewById(R.id.title_text)).setVisibility(View.GONE); (findViewById(R.id.online_vdo_player_fragment)).setLayoutParams(new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); findViewById(R.id.player_region).setFitsSystemWindows(true); // hide system windows showSystemUi(false); showControls(false); } else { // go to portrait orientation setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); // show other views (findViewById(R.id.title_text)).setVisibility(View.VISIBLE); (findViewById(R.id.online_vdo_player_fragment)).setLayoutParams(new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT)); findViewById(R.id.player_region).setFitsSystemWindows(false); findViewById(R.id.player_region).setPadding(0,0,0,0); // show system windows showSystemUi(true); } } } private void showSystemUi(boolean show) { Log.v(TAG, (show ? "show " : "hide ") + "system ui"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (!show) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } else { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE); } } } private View.OnSystemUiVisibilityChangeListener uiVisibilityListener = new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { Log.v(TAG, "onSystemUiVisibilityChange"); // show player controls when system ui is showing int diff = mLastSystemUiVis ^ visibility; mLastSystemUiVis = visibility; if ((diff & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0 && (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { Log.v(TAG, "system ui visible, making controls visible"); showControls(true); } } }; }
package de.melvil.stacksrs.view; import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.Header; import de.melvil.stacksrs.model.Card; import de.melvil.stacksrs.model.Deck; public class DeckDownloadActivity extends AppCompatActivity { private final String SERVER_URL = "http://stacksrs.droppages.com/"; private class DownloadableDeckInfo { public String name; public String file; public String front; public String back; public String description; @Override public String toString() { return name + "\n" + description; } } private ListView deckListView; private ArrayAdapter<DownloadableDeckInfo> deckListAdapter; private List<DownloadableDeckInfo> deckNames = new ArrayList<>(); private ProgressBar circle; private AsyncHttpClient httpClient = new AsyncHttpClient(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_deck_download); setTitle(getString(R.string.download_deck)); deckListView = (ListView) findViewById(R.id.deck_list); deckListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, deckNames); deckListView.setAdapter(deckListAdapter); deckListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final DownloadableDeckInfo deckInfo = deckNames.get(position); AlertDialog.Builder builder = new AlertDialog.Builder(DeckDownloadActivity.this); builder.setTitle(getString(R.string.download_deck)); builder.setMessage(getString(R.string.really_download_deck, deckInfo.name)); builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNeutralButton(getString(R.string.yes_level_0), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { downloadDeck(deckInfo.file, 0); dialog.dismiss(); } }); builder.setPositiveButton(getString(R.string.yes_level_2), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { downloadDeck(deckInfo.file, 2); dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } }); circle = (ProgressBar) findViewById(R.id.circle); } @Override protected void onResume() { super.onResume(); circle.setVisibility(View.VISIBLE); reloadDeckList(); } public void reloadDeckList() { httpClient.get(SERVER_URL + "decks.txt", null, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { deckNames.clear(); try { JSONArray deckListArray = response.getJSONArray("decks"); for (int i = 0; i < deckListArray.length(); ++i) { JSONObject deckInfoObject = deckListArray.getJSONObject(i); DownloadableDeckInfo deckInfo = new DownloadableDeckInfo(); deckInfo.name = deckInfoObject.getString("name"); deckInfo.file = deckInfoObject.getString("file"); deckInfo.front = deckInfoObject.getString("front"); deckInfo.back = deckInfoObject.getString("back"); deckInfo.description = deckInfoObject.getString("description"); deckNames.add(deckInfo); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), getString(R.string.could_not_load_deck_list_from_server), Toast.LENGTH_SHORT).show(); } deckListAdapter.notifyDataSetChanged(); circle.setVisibility(View.INVISIBLE); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { Toast.makeText(getApplicationContext(), getString(R.string.could_not_connect_to_server), Toast.LENGTH_SHORT).show(); } }); } public void downloadDeck(final String file, final int level) { httpClient.get(SERVER_URL + file + ".txt", null, new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { String deckName = response.getString("name"); Deck newDeck = new Deck(deckName, response.getString("front"), response.getString("back")); JSONArray cardArray = response.getJSONArray("cards"); List<Card> cards = new ArrayList<>(); for(int i = 0; i < cardArray.length(); ++i) { JSONObject cardObject = cardArray.getJSONObject(i); Card c = new Card(cardObject.getString("front"), cardObject.getString("back"), level); cards.add(c); } newDeck.fillWithCards(cards); Toast.makeText(getApplicationContext(), getString(R.string.downloaded_deck, deckName), Toast.LENGTH_SHORT).show(); } catch(JSONException e) { Toast.makeText(getApplicationContext(), getString(R.string.could_not_load_deck), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { Toast.makeText(getApplicationContext(), getString(R.string.downloading_deck_failed), Toast.LENGTH_SHORT).show(); } }); } }
package org.objectweb.proactive.core.mop; import org.apache.log4j.Logger; import sun.rmi.server.MarshalInputStream; import sun.rmi.server.MarshalOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Instances of this class represent method calls performed on reified * objects. They are generated by a <I>stub object</I>, whose role is to act * as a representative for the reified object. * * @author Julien Vayssi&egrave;re */ public final class MethodCall implements java.io.Serializable { // COMPONENTS added a tag for identification of component requests private String tag; // COMPONENTS added a field for the Fractal interface name // (the name of the interface containing the method called) private String fcFunctionalInterfaceName; public static Logger logger = Logger.getLogger(MethodCall.class.getName()); /** * The size of the pool we use for recycling MethodCall objects. */ private static int RECYCLE_POOL_SIZE = 30; /** * The pool of recycled methodcall objects */ private static MethodCall[] recyclePool; /** * Position inside the pool */ private static int index; /** Indicates if the recycling of MethodCall object is on. */ private static boolean recycleMethodCallObject; private static java.util.Hashtable reifiedMethodsTable = new java.util.Hashtable(); //tag for component calls public static final String COMPONENT_TAG = "component-methodCall"; /** * Initializes the recycling of MethodCall objects to be enabled by default. */ static { MethodCall.setRecycleMethodCallObject(true); } /** * The array holding the argments of the method call */ private Object[] effectiveArguments; /** * The method corresponding to the call */ private transient Method reifiedMethod; /** * The internal ID of the methodcall */ private long methodCallID; private String key; /** * byte[] to store effectiveArguments. Requiered to optimize multiple serialization * in some case (such as group communication) or to create a stronger * asynchronism (serialization of parameters then return to the thread of * execution before the end of the rendez-vous). */ private byte[] serializedEffectiveArguments = null; /** * transform the effectiveArguments into a byte[] * */ public void transformEffectiveArgumentsIntoByteArray() { if ((serializedEffectiveArguments == null) && (effectiveArguments != null)) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); MarshalOutputStream objectOutputStream = new MarshalOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(effectiveArguments); objectOutputStream.flush(); objectOutputStream.close(); byteArrayOutputStream.close(); serializedEffectiveArguments = byteArrayOutputStream.toByteArray(); } catch (Exception e) { e.printStackTrace(); } effectiveArguments = null; } } /** * Sets recycling of MethodCall objects on/off. Note that turning the recycling * off and on again results in the recycling pool being flushed, thus damaging * performances. * @param value sets the recycling on if <code>true</code>, otherwise turns it off. */ public static synchronized void setRecycleMethodCallObject(boolean value) { if (recycleMethodCallObject == value) { return; } else { recycleMethodCallObject = value; if (value) { // Creates the recycle poll for MethodCall objects recyclePool = new MethodCall[RECYCLE_POOL_SIZE]; index = 0; } else { // If we do not want to recycle MethodCall objects anymore, // let's free some memory by permitting the reyclePool to be // garbage-collecting recyclePool = null; } } } /** * Indicates if the recycling of MethodCall objects is currently running or not. * * @return <code>true</code> if recycling is on, <code>false</code> otherwise */ public static synchronized boolean getRecycleMethodCallObject() { return MethodCall.recycleMethodCallObject; } /** * Factory method for getting MethodCall objects * * @param reifiedMethod a <code>Method</code> object that represents * the method whose invocation is reified * @param effectiveArguments the effective arguments of the call. Arguments * that are of primitive type need to be wrapped * within an instance of the corresponding wrapper * class (like <code>java.lang.Integer</code> for * primitive type <code>int</code> for example). * @return a MethodCall object representing an invocation of method * <code>reifiedMethod</code> with arguments <code>effectiveArguments</code> */ public synchronized static MethodCall getMethodCall(Method reifiedMethod, Object[] effectiveArguments) { if (MethodCall.getRecycleMethodCallObject()) { // Finds a recycled MethodCall object in the pool, cleans it and // eventually returns it if (MethodCall.index > 0) { // gets the object from the pool MethodCall.index MethodCall result = MethodCall.recyclePool[MethodCall.index]; MethodCall.recyclePool[MethodCall.index] = null; // Refurbishes the object result.reifiedMethod = reifiedMethod; result.effectiveArguments = effectiveArguments; result.key = buildKey(reifiedMethod); return result; } else { return new MethodCall(reifiedMethod, effectiveArguments); } } else { return new MethodCall(reifiedMethod, effectiveArguments); } } /** * Returns a MethodCall object with extra info for component calls (the * possible name of the functional interface invoked). * @param reifiedMethod * @param effectiveArguments * @param fcFunctionalInterfaceName fractal interface name, whose value is : * - null if the call is non-functional * - the name of the functional interface otherwise * @return MethodCall */ public synchronized static MethodCall getComponentMethodCall( Method reifiedMethod, Object[] effectiveArguments, String fcFunctionalInterfaceName) { // COMPONENTS MethodCall mc = MethodCall.getMethodCall(reifiedMethod, effectiveArguments); mc.setTag(COMPONENT_TAG); mc.setFcFunctionalInterfaceName(fcFunctionalInterfaceName); return mc; } /** * Tells the recyclying process that the MethodCall object passed as parameter * is ready for recycling. It is the responsibility of the caller of this * method to make sure that this object can safely be disposed of. */ public synchronized static void setMethodCall(MethodCall mc) { if (MethodCall.getRecycleMethodCallObject()) { // If there's still one slot left in the pool if (MethodCall.recyclePool[MethodCall.index] == null) { // Cleans up a MethodCall object // It is prefereable to do it here rather than at the moment // the object is picked out of the pool, because it allows // garbage-collecting the objects referenced in here mc.fcFunctionalInterfaceName = null; mc.tag = null; mc.reifiedMethod = null; mc.effectiveArguments = null; mc.key = null; // Inserts the object in the pool MethodCall.recyclePool[MethodCall.index] = mc; MethodCall.index++; if (MethodCall.index == RECYCLE_POOL_SIZE) { MethodCall.index = RECYCLE_POOL_SIZE - 1; } } } } /** * Builds a new MethodCall object. * Please, consider use the factory method <code>getMethodCall</code> * instead of build a new MethodCall object. */ // This constructor is private to this class // because we want to enforce the use of factory methods for getting fresh // instances of this class (see <I>Factory</I> pattern in GoF). public MethodCall(Method reifiedMethod, Object[] effectiveArguments) { this.reifiedMethod = reifiedMethod; this.effectiveArguments = effectiveArguments; this.key = buildKey(reifiedMethod); } /** * Builds a new MethodCall object. This constructor is a copy constructor. * Fields of the object are also copied. * Please, consider use the factory method <code>getMethodCall</code> * instead of build a new MethodCall object. */ public MethodCall(MethodCall mc) { try { this.fcFunctionalInterfaceName = mc.getFcFunctionalInterfaceName(); this.reifiedMethod = mc.getReifiedMethod(); this.tag = mc.getTag(); if (mc.serializedEffectiveArguments == null) { serializedEffectiveArguments = null; } else { // array copy byte[] source = mc.serializedEffectiveArguments; serializedEffectiveArguments = new byte[source.length]; for (int i = 0; i < serializedEffectiveArguments.length; i++) { serializedEffectiveArguments[i] = source[i]; } } if (mc.effectiveArguments == null) { effectiveArguments = null; } else { // je crois que c'est bon ... effectiveArguments = (Object[]) Utils.makeDeepCopy(mc.effectiveArguments); } this.key = MethodCall.buildKey(mc.getReifiedMethod()); // methodcallID? } catch (java.io.IOException e) { e.printStackTrace(); } } /** * Executes the instance method call represented by this object. * * @param targetObject the Object the method is called on * @throws MethodCallExecutionFailedException thrown if the refleciton of the * call failed. * @throws InvocationTargetException thrown if the execution of the reified * method terminates abruptly by throwing an exception. The exception * thrown by the execution of the reified method is placed inside the * InvocationTargetException object. * @return the result of the invocation of the method. If the method returns * <code>void</code>, then <code>null</code> is returned. If the method * returned a primitive type, then it is wrapped inside the appropriate * wrapper object. */ public Object execute(Object targetObject) throws InvocationTargetException, MethodCallExecutionFailedException { // A test at how non-public methods can be reflected if ((serializedEffectiveArguments != null) && (effectiveArguments == null)) { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serializedEffectiveArguments); //ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); MarshalInputStream objectInputStream = new MarshalInputStream(byteArrayInputStream); effectiveArguments = (Object[]) objectInputStream.readObject(); objectInputStream.close(); byteArrayInputStream.close(); } catch (Exception e) { e.printStackTrace(); } serializedEffectiveArguments = null; } if (logger.isDebugEnabled()) { logger.debug("MethodCall.execute() name = " + this.getName()); logger.debug("MethodCall.execute() reifiedMethod = " + reifiedMethod); logger.debug( "MethodCall.execute() reifiedMethod.getDeclaringClass() = " + reifiedMethod.getDeclaringClass()); logger.debug("MethodCall.execute() targetObject " + targetObject); } if (reifiedMethod.getParameterTypes().length > 0) { reifiedMethod.setAccessible(true); } try { return reifiedMethod.invoke(targetObject, effectiveArguments); } catch (IllegalAccessException e) { throw new MethodCallExecutionFailedException( "Access rights to the method denied: " + e); } } protected void finalize() { MethodCall.setMethodCall(this); } public Method getReifiedMethod() { return reifiedMethod; } public String getName() { return reifiedMethod.getName(); } public int getNumberOfParameter() { return this.effectiveArguments.length; } public Object getParameter(int index) { return this.effectiveArguments[index]; } public void setEffectiveArguments(Object[] o) { effectiveArguments = o; } /** * Make a deep copy of all arguments of the constructor */ public void makeDeepCopyOfArguments() throws java.io.IOException { effectiveArguments = (Object[]) Utils.makeDeepCopy(effectiveArguments); } /** * accessor for the functional name ot the invoked Fractal interface * @return the functional name of the invoked Fractal interface */ public String getFcFunctionalInterfaceName() { return fcFunctionalInterfaceName; } /** * setter for the functional name of the invoked Fractal interface * @param the functional name of the invoked Fractal interface */ public void setFcFunctionalInterfaceName(String string) { fcFunctionalInterfaceName = string; } /** * setter for the tag of the method call */ public void setTag(String string) { tag = string; } /** * accessor for the tag of the method call * @return the tag of the method call */ public String getTag() { return tag; } private Class[] fixBugRead(FixWrapper[] para) { Class[] tmp = new Class[para.length]; for (int i = 0; i < para.length; i++) { // System.out.println("fixBugRead for " + i + " value is " +para[i]); tmp[i] = para[i].getWrapped(); } return tmp; } private FixWrapper[] fixBugWrite(Class[] para) { FixWrapper[] tmp = new FixWrapper[para.length]; for (int i = 0; i < para.length; i++) { // System.out.println("fixBugWrite for " + i + " out of " + para.length + " value is " +para[i] ); tmp[i] = new FixWrapper(para[i]); } return tmp; } private static String buildKey(Method reifiedMethod) { StringBuffer sb = new StringBuffer(); sb.append(reifiedMethod.getDeclaringClass().getName()); sb.append(reifiedMethod.getName()); Class[] parameters = reifiedMethod.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { sb.append(parameters[i].getName()); } return sb.toString(); } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.defaultWriteObject(); // The Method object needs to be converted out.writeObject(reifiedMethod.getDeclaringClass()); out.writeObject(reifiedMethod.getName()); out.writeObject(fixBugWrite(reifiedMethod.getParameterTypes())); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); reifiedMethod = (Method) reifiedMethodsTable.get(key); if (reifiedMethod == null) { // Reads several pieces of data that we need for looking up the method Class declaringClass = (Class) in.readObject(); String simpleName = (String) in.readObject(); Class[] parameters = this.fixBugRead((FixWrapper[]) in.readObject()); // Looks up the method try { reifiedMethod = declaringClass.getMethod(simpleName, parameters); reifiedMethodsTable.put(key, reifiedMethod); } catch (NoSuchMethodException e) { throw new InternalException("Lookup for method failed: " + e + ". This may be caused by having different versions of the same class on different VMs. Check your CLASSPATH settings."); } } else { //added to avoid an ibis bug in.readObject(); in.readObject(); in.readObject(); } if ((serializedEffectiveArguments != null) && (effectiveArguments == null)) { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serializedEffectiveArguments); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); MarshalInputStream objectInputStream = new MarshalInputStream(byteArrayInputStream); effectiveArguments = (Object[]) objectInputStream.readObject(); objectInputStream.close(); byteArrayInputStream.close(); } catch (Exception e) { e.printStackTrace(); } serializedEffectiveArguments = null; } } public class FixWrapper implements java.io.Serializable { public boolean isPrimitive; public Class encapsulated; public FixWrapper() { } /** * Encapsulate primitives types into Class */ public FixWrapper(Class c) { if (!c.isPrimitive()) { encapsulated = c; return; } isPrimitive = true; if (c.equals(Boolean.TYPE)) { encapsulated = Boolean.class; } else if (c.equals(Byte.TYPE)) { encapsulated = Byte.class; } else if (c.equals(Character.TYPE)) { encapsulated = Character.class; } else if (c.equals(Double.TYPE)) { encapsulated = Double.class; } else if (c.equals(Float.TYPE)) { encapsulated = Float.class; } else if (c.equals(Integer.TYPE)) { encapsulated = Integer.class; } else if (c.equals(Long.TYPE)) { encapsulated = Long.class; } else if (c.equals(Short.TYPE)) { encapsulated = Short.class; } } /** * Give back the original class */ public Class getWrapped() { if (!isPrimitive) { return encapsulated; } if (encapsulated.equals(Boolean.class)) { return Boolean.TYPE; } if (encapsulated.equals(Byte.class)) { return Byte.TYPE; } if (encapsulated.equals(Character.class)) { return Character.TYPE; } if (encapsulated.equals(Double.class)) { return Double.TYPE; } if (encapsulated.equals(Float.class)) { return Float.TYPE; } if (encapsulated.equals(Integer.class)) { return Integer.TYPE; } if (encapsulated.equals(Long.class)) { return Long.TYPE; } if (encapsulated.equals(Short.class)) { return Short.TYPE; } throw new InternalException("FixWrapper encapsulated class unkown " + encapsulated); } public String toString() { return "FixWrapper: " + encapsulated.toString(); } } // end inner class FixWrapper }
package org.objectweb.proactive.core.mop; /** * References on an active object are indirect link to the active object. There * is some interposition objects between the caller and the targetted active * object like a StubObject and a Proxy object. It is possible to know if an * object is a reference onto an active object by checking if the object * implements StubObject. A reference can be either on a local (on the same * runtime) or on a distant (on a remote runtime) active object. if an object is * a reference onto an active object, it implements StubObject but also the * class of the active object allowing to perform method call as if the method * call was made on the active object */ public interface StubObject { /** * set the proxy to the active object */ public void setProxy(Proxy p); /** * return the proxy to the active object */ public Proxy getProxy(); }
package me.devsaki.hentoid.activities; import static android.content.Intent.ACTION_SEND; import static android.content.Intent.ACTION_VIEW; import static android.content.Intent.EXTRA_TEXT; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import me.devsaki.hentoid.core.AppStartup; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.util.ContentHelper; import timber.log.Timber; public class IntentActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); new AppStartup().initApp(this, this::onMainProgress, this::onSecondaryProgress, this::onInitComplete); } private void onMainProgress(float f) { Timber.i("Init @ IntentActivity (main) : %s%%", f); } private void onSecondaryProgress(float f) { Timber.i("Init @ IntentActivity (secondary) : %s%%", f); } private void onInitComplete() { Intent intent = getIntent(); String action = intent.getAction(); Uri data = intent.getData(); if (ACTION_VIEW.equals(action) && data != null) { processIntent(data); } else if (ACTION_SEND.equals(action) && intent.hasExtra(EXTRA_TEXT)) { processIntent(Uri.parse(intent.getStringExtra(EXTRA_TEXT))); } else { Timber.d("Unrecognized intent. Cannot process."); } finish(); } private void processIntent(Uri data) { Timber.d("Uri: %s", data); Site site = Site.searchByUrl(data.toString()); if (site == null) { Timber.d("Invalid URL"); return; } if (site.equals(Site.NONE)) { Timber.d("Unrecognized host : %s", data.getHost()); return; } String parsedPath = parsePath(site, data); if (parsedPath == null) { Timber.d("Cannot parse path"); return; } // Cleanup double /'s if (site.getUrl().endsWith("/") && parsedPath.startsWith("/") && parsedPath.length() > 1) parsedPath = parsedPath.substring(1); Content content = new Content(); content.setSite(site); content.setUrl(parsedPath); ContentHelper.viewContentGalleryPage(this, content, true); } @Nullable private static String parsePath(Site site, Uri data) { String toParse = data.getPath(); if (null == toParse) return null; switch (site) { case HITOMI: int titleIdSeparatorIndex = toParse.lastIndexOf('-'); if (-1 == titleIdSeparatorIndex) { return toParse.substring(toParse.lastIndexOf('/')); // Input uses old gallery URL format } else return "/" + toParse.substring(toParse.lastIndexOf('-') + 1); // Reconstitute old gallery URL format case NHENTAI: return toParse.replace("/g", ""); case TSUMINO: return toParse.replace("/entry", ""); case ASMHENTAI: case ASMHENTAI_COMICS: return toParse.replace("/g", "") + "/"; // '/' required case HENTAICAFE: String path = data.toString(); return path.contains("/?p=") ? path.replace(Site.HENTAICAFE.getUrl(), "") : toParse; case PURURIN: return toParse.replace("/gallery", "") + "/"; case EHENTAI: case EXHENTAI: return toParse.replace("g/", ""); case FAKKU2: return toParse.replace("/hentai", ""); case NEXUS: return toParse.replace("/view", ""); case HBROWSE: return toParse.substring(1); case IMHENTAI: case HENTAIFOX: return toParse.replace("/gallery", ""); case PORNCOMIX: return data.toString(); case MUSES: case DOUJINS: case LUSCIOUS: case HENTAI2READ: case MRM: case MANHWA: case TOONILY: case ALLPORNCOMIC: case PIXIV: return toParse; default: return null; } } }
package org.phenoscape.view; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JToolBar; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.obo.app.swing.BugWorkaroundTable; import org.obo.app.swing.PlaceholderRenderer; import org.obo.app.swing.SortDisabler; import org.obo.app.swing.TableColumnPrefsSaver; import org.phenoscape.controller.PhenexController; import org.phenoscape.model.Character; import org.phenoscape.model.DataSet; import org.phenoscape.model.MultipleState; import org.phenoscape.model.MultipleState.MODE; import org.phenoscape.model.State; import org.phenoscape.model.Taxon; import ca.odell.glazedlists.GlazedLists; import ca.odell.glazedlists.gui.AdvancedTableFormat; import ca.odell.glazedlists.gui.WritableTableFormat; import ca.odell.glazedlists.swing.EventTableModel; import ca.odell.glazedlists.swing.TableComparatorChooser; import com.eekboom.utils.Strings; public class CharacterTableComponent extends PhenoscapeGUIComponent { private JButton addCharacterButton; private JButton deleteCharacterButton; public CharacterTableComponent(String id, PhenexController controller) { super(id, controller); } @Override public void init() { super.init(); this.initializeInterface(); } public void consolidateSelectedCharacters() { //FIXME some of this logic should be moved down into the model final List<Character> characters = Collections.unmodifiableList(this.getSelectedCharacters()); if (characters.size() > 1) { final DataSet data = this.getController().getDataSet(); final Character newCharacter = data.newCharacter();; final List<String> labels = new ArrayList<String>(); final List<String> comments = new ArrayList<String>(); final List<String> figures = new ArrayList<String>(); final List<String> discussions = new ArrayList<String>(); for (Character character : characters) { labels.add(character.getLabel()); comments.add(character.getComment()); figures.add(character.getFigure()); discussions.add(character.getDiscussion()); newCharacter.addStates(character.getStates()); } newCharacter.setLabel(StringUtils.stripToNull(org.obo.app.util.Collections.join(labels, "; "))); newCharacter.setComment(StringUtils.stripToNull(org.obo.app.util.Collections.join(comments, "; "))); newCharacter.setFigure(StringUtils.stripToNull(org.obo.app.util.Collections.join(figures, "; "))); newCharacter.setDiscussion(StringUtils.stripToNull(org.obo.app.util.Collections.join(discussions, "; "))); for (Taxon taxon : data.getTaxa()) { final Set<State> statesForTaxon = new HashSet<State>(); for (Character character : characters) { final State stateValue = data.getStateForTaxon(taxon, character); if (stateValue instanceof MultipleState) { statesForTaxon.addAll(((MultipleState)stateValue).getStates()); } else if (stateValue != null) { statesForTaxon.add(stateValue); } } final State newStateValue; if (statesForTaxon.size() > 1) { if (statesForTaxon.contains(null)) { log().debug("We created a null state?"); log().debug(statesForTaxon); } newStateValue = new MultipleState(statesForTaxon, MODE.POLYMORPHIC); } else if (statesForTaxon.size() == 1) { newStateValue = statesForTaxon.iterator().next(); } else { newStateValue = null; } data.setStateForTaxon(taxon, newCharacter, newStateValue); } data.removeCharacters(characters); int i = 0; for (State state : newCharacter.getStates()) { state.setSymbol("" + i); i += 1; } } } private void initializeInterface() { this.setLayout(new BorderLayout()); final EventTableModel<Character> charactersTableModel = new EventTableModel<Character>(this.getController().getSortedCharacters(), new CharactersTableFormat()); final JTable charactersTable = new BugWorkaroundTable(charactersTableModel); charactersTable.setSelectionModel(this.getController().getCharactersSelectionModel()); charactersTable.setDefaultRenderer(Object.class, new PlaceholderRenderer("None")); charactersTable.putClientProperty("Quaqua.Table.style", "striped"); new TableColumnPrefsSaver(charactersTable, this.getClass().getName()); final TableComparatorChooser<Character> sortChooser = new TableComparatorChooser<Character>(charactersTable, this.getController().getSortedCharacters(), false); sortChooser.addSortActionListener(new SortDisabler()); this.add(new JScrollPane(charactersTable), BorderLayout.CENTER); this.add(this.createToolBar(), BorderLayout.NORTH); this.getController().getCharactersSelectionModel().addListSelectionListener(new CharacterSelectionListener()); } private void addCharacter() { this.getController().getDataSet().newCharacter(); } private void deleteSelectedCharacter() { final List<Character> characters = Collections.unmodifiableList(this.getSelectedCharacters()); final DataSet data = this.getController().getDataSet(); data.getCharacters().removeAll(characters); } private List<Character> getSelectedCharacters() { return this.getController().getCharactersSelectionModel().getSelected(); } private void updateButtonStates() { this.deleteCharacterButton.setEnabled(!this.getSelectedCharacters().isEmpty()); } private void selectFirstState() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!getController().getStatesForCurrentCharacterSelection().isEmpty()) { getController().getCurrentStatesSelectionModel().setSelectionInterval(0, 0); } } }); } private JToolBar createToolBar() { final JToolBar toolBar = new JToolBar(); this.addCharacterButton = new JButton(new AbstractAction(null, new ImageIcon(this.getClass().getResource("/org/phenoscape/view/images/list-add.png"))) { @Override public void actionPerformed(ActionEvent e) { addCharacter(); } }); this.addCharacterButton.setToolTipText("Add Character"); toolBar.add(this.addCharacterButton); this.deleteCharacterButton = new JButton(new AbstractAction(null, new ImageIcon(this.getClass().getResource("/org/phenoscape/view/images/list-remove.png"))) { @Override public void actionPerformed(ActionEvent e) { deleteSelectedCharacter(); } }); this.deleteCharacterButton.setToolTipText("Delete Character"); toolBar.add(this.deleteCharacterButton); toolBar.setFloatable(false); return toolBar; } private class CharactersTableFormat implements WritableTableFormat<Character>, AdvancedTableFormat<Character> { @Override public boolean isEditable(Character character, int column) { return column != 0; } @Override public Character setColumnValue(Character character, Object editedValue, int column) { switch(column) { case 0: break; case 1: character.setLabel(editedValue.toString()); break; case 2: character.setComment(editedValue.toString()); break; case 3: character.setFigure(editedValue.toString()); break; case 4: character.setDiscussion(editedValue.toString()); break; } return character; } @Override public int getColumnCount() { return 5; } @Override public String getColumnName(int column) { switch(column) { case 0: return " "; case 1: return "Character Description"; case 2: return "Comment"; case 3: return "Figure"; case 4: return "Discussion"; default: return null; } } @Override public Object getColumnValue(Character character, int column) { switch(column) { case 0: return getController().getDataSet().getCharacters().indexOf(character) + 1; case 1: return character.getLabel(); case 2: return character.getComment(); case 3: return character.getFigure(); case 4: return character.getDiscussion(); default: return null; } } @Override public Class<?> getColumnClass(int column) { switch(column) { case 0: return Integer.class; case 1: return String.class; case 2: return String.class; case 3: return String.class; case 4: return String.class; default: return null; } } @Override public Comparator<?> getColumnComparator(int column) { switch(column) { case 0: return GlazedLists.comparableComparator(); case 1: return Strings.getNaturalComparator(); case 2: return Strings.getNaturalComparator(); case 3: return Strings.getNaturalComparator(); case 4: return Strings.getNaturalComparator(); default: return null; } } } private class CharacterSelectionListener implements ListSelectionListener { public CharacterSelectionListener() { updateButtonStates(); } @Override public void valueChanged(ListSelectionEvent e) { updateButtonStates(); selectFirstState(); } } @Override protected Logger log() { return Logger.getLogger(this.getClass()); } }
package mobapptut.com.imageviewer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.net.Uri; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.widget.ImageView; import java.io.IOException; public class PinchZoomImageView extends ImageView { private Bitmap mBitmap; private int mImageWidth; private int mImageHeight; private final static float mMinZoom = 1.f; private final static float mMaxZoom = 3.f; private float mScaleFactor = 1.f; private ScaleGestureDetector mScaleGestureDetector; private final static int NONE = 0; private final static int PAN = 1; private final static int ZOOM = 2; private int mEventState; private float mStartX = 0; private float mStartY = 0; private float mTranslateX = 0; private float mTranslateY = 0; private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); mScaleFactor = Math.max(mMinZoom, Math.min(mMaxZoom, mScaleFactor)); // invalidate(); // requestLayout(); return super.onScale(detector); } } public PinchZoomImageView(Context context, AttributeSet attrs) { super(context, attrs); mScaleGestureDetector = new ScaleGestureDetector(getContext(), new ScaleListener()); } @Override public boolean onTouchEvent(MotionEvent event) { switch(event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mEventState = PAN; mStartX = event.getX(); mStartY = event.getY(); break; case MotionEvent.ACTION_UP: mEventState = NONE; break; case MotionEvent.ACTION_MOVE: mTranslateX = event.getX() - mStartX; mTranslateY = event.getY() - mStartY; break; case MotionEvent.ACTION_POINTER_DOWN: mEventState = ZOOM; break; } mScaleGestureDetector.onTouchEvent(event); if((mEventState == PAN && mScaleFactor != mMinZoom) || mEventState == ZOOM) { invalidate(); requestLayout(); } return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int imageWidth = MeasureSpec.getSize(widthMeasureSpec); int imageHeight = MeasureSpec.getSize(heightMeasureSpec); int scaledWidth = Math.round(mImageWidth * mScaleFactor); int scaledHeight = Math.round(mImageHeight * mScaleFactor); setMeasuredDimension( Math.min(imageWidth, scaledWidth), Math.min(imageHeight, scaledHeight) ); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); canvas.scale(mScaleFactor, mScaleFactor); // canvas.scale(mScaleFactor, mScaleFactor, mScaleGestureDetector.getFocusX(), mScaleGestureDetector.getFocusY()); canvas.translate(mTranslateX/mScaleFactor, mTranslateY/mScaleFactor); canvas.drawBitmap(mBitmap, 0, 0, null); canvas.restore(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } public void setImageUri(Uri uri) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri); float aspecRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth(); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); mImageWidth = displayMetrics.widthPixels; mImageHeight = Math.round(mImageWidth * aspecRatio); mBitmap = Bitmap.createScaledBitmap(bitmap, mImageWidth, mImageHeight, false); invalidate(); requestLayout(); } catch (IOException e) { e.printStackTrace(); } } }
package org.royaldev.royalcommands.rcommands; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.royaldev.royalcommands.RUtils; import org.royaldev.royalcommands.RoyalCommands; public class CmdLag implements CommandExecutor { RoyalCommands plugin; public CmdLag(RoyalCommands instance) { plugin = instance; } // HEAVILY influenced by commandbook's lag measuring // Give them most credit @Override public boolean onCommand(final CommandSender cs, Command cmd, String label, String[] args) { if (!plugin.isAuthorized(cs, "rcmds.lag")) { RUtils.dispNoPerms(cs); return true; } int tps = 20; int runfor = 5; if (args.length > 0) { try { runfor = Integer.valueOf(args[0]); } catch (Exception e) { cs.sendMessage(ChatColor.RED + "Please input the amount of whole seconds you would like to run the test for."); return true; } } final long expms = runfor * 1000; final long expsecs = runfor; final long expticks = tps * expsecs; final World world = plugin.getServer().getWorlds().get(0); final long started = System.currentTimeMillis(); final long startedticks = world.getFullTime(); cs.sendMessage(ChatColor.YELLOW + "This measures in-game time, so please do not change the time for " + ChatColor.GRAY + expsecs + ChatColor.YELLOW + " seconds."); Runnable getlag = new Runnable() { public void run() { long ran = System.currentTimeMillis(); long ranticks = world.getFullTime(); long ranforms = ran - started; long ranforsecs = ranforms / 1000; long currentticks = ranticks - startedticks; long error = ((expms - ranforms) / ranforms) * 100; long rtps = currentticks / ranforsecs; if (expticks != currentticks) cs.sendMessage(ChatColor.RED + "Got " + ChatColor.GRAY + currentticks + "ticks" + ChatColor.RED + " instead of " + ChatColor.GRAY + expticks + "ticks" + ChatColor.RED + "; Bukkit scheduling may be off."); if (Math.round(rtps) == 20) cs.sendMessage(ChatColor.GREEN + "Full throttle" + ChatColor.WHITE + " - " + ChatColor.GREEN + 20 + ChatColor.WHITE + "/20 TPS"); else if (rtps < 5) cs.sendMessage(ChatColor.DARK_RED + "Inefficient" + ChatColor.WHITE + " - " + ChatColor.DARK_RED + rtps + ChatColor.WHITE + "/20 TPS"); else if (rtps < 10) cs.sendMessage(ChatColor.RED + "Severe lag" + ChatColor.WHITE + " - " + ChatColor.RED + rtps + ChatColor.WHITE + "/20 TPS"); else if (rtps < 15) cs.sendMessage(ChatColor.RED + "Big lag" + ChatColor.WHITE + " - " + ChatColor.RED + rtps + ChatColor.WHITE + "/20 TPS"); else if (rtps < 19) cs.sendMessage(ChatColor.YELLOW + "Small lag" + ChatColor.WHITE + " - " + ChatColor.YELLOW + rtps + ChatColor.WHITE + "/20 TPS"); else if (rtps > 20) cs.sendMessage(ChatColor.GOLD + "Overboard" + ChatColor.WHITE + " - " + ChatColor.GOLD + rtps + ChatColor.WHITE + "/20 TPS"); cs.sendMessage(ChatColor.BLUE + "Margin of error: " + ChatColor.GRAY + error + "%"); } }; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, getlag, expticks); return true; } }
package nerd.tuxmobil.fahrplan.congress; import android.annotation.SuppressLint; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ActivityNotFoundException; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.provider.CalendarContract; import android.support.v4.app.FragmentActivity; import android.text.format.Time; import android.widget.Toast; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import nerd.tuxmobil.fahrplan.congress.FahrplanContract.AlarmsTable; import nerd.tuxmobil.fahrplan.congress.FahrplanContract.HighlightsTable; import nerd.tuxmobil.fahrplan.congress.FahrplanContract.LecturesTable; import nerd.tuxmobil.fahrplan.congress.FahrplanContract.MetasTable; public class FahrplanMisc { private static final String LOG_TAG = "FahrplanMisc"; private static final int ALL_DAYS = -1; static void loadDays(Context context) { MyApp.dateInfos = new DateInfos(); LecturesDBOpenHelper lecturesDB = new LecturesDBOpenHelper(context); SQLiteDatabase lecturedb = lecturesDB.getReadableDatabase(); Cursor cursor; try { cursor = lecturedb.query(LecturesTable.NAME, LecturesDBOpenHelper.allcolumns, null, null, null, null, null); } catch (SQLiteException e) { e.printStackTrace(); lecturedb.close(); lecturesDB.close(); return; } if (cursor.getCount() == 0) { cursor.close(); lecturesDB.close(); lecturedb.close(); return; } cursor.moveToFirst(); while (!cursor.isAfterLast()) { int day = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.DAY)); String date = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.DATE)); DateInfo dateItem = new DateInfo(day, date); if (!MyApp.dateInfos.contains(dateItem)) { MyApp.dateInfos.add(dateItem); } cursor.moveToNext(); } cursor.close(); for (DateInfo dateInfo : MyApp.dateInfos) { MyApp.LogDebug(LOG_TAG, "DateInfo: " + dateInfo); } lecturesDB.close(); lecturedb.close(); } static void loadMeta(Context context) { MetaDBOpenHelper metaDB = new MetaDBOpenHelper(context); SQLiteDatabase metadb = metaDB.getReadableDatabase(); Cursor cursor; try { cursor = metadb.query(MetasTable.NAME, MetaDBOpenHelper.allcolumns, null, null, null, null, null); } catch (SQLiteException e) { e.printStackTrace(); metaDB.close(); metadb.close(); metadb = null; return; } MyApp.numdays = MetasTable.Defaults.NUM_DAYS_DEFAULT; MyApp.version = ""; MyApp.title = ""; MyApp.subtitle = ""; MyApp.dayChangeHour = MetasTable.Defaults.DAY_CHANGE_HOUR_DEFAULT; MyApp.dayChangeMinute = MetasTable.Defaults.DAY_CHANGE_MINUTE_DEFAULT; MyApp.eTag = null; if (cursor.getCount() > 0) { cursor.moveToFirst(); int columnIndexNumDays = cursor.getColumnIndex(MetasTable.Columns.NUM_DAYS); if (cursor.getColumnCount() > columnIndexNumDays) { MyApp.numdays = cursor.getInt(columnIndexNumDays); } int columIndexVersion = cursor.getColumnIndex(MetasTable.Columns.VERSION); if (cursor.getColumnCount() > columIndexVersion) { MyApp.version = cursor.getString(columIndexVersion); } int columnIndexTitle = cursor.getColumnIndex(MetasTable.Columns.TITLE); if (cursor.getColumnCount() > columnIndexTitle) { MyApp.title = cursor.getString(columnIndexTitle); } int columnIndexSubTitle = cursor.getColumnIndex(MetasTable.Columns.SUBTITLE); if (cursor.getColumnCount() > columnIndexSubTitle) { MyApp.subtitle = cursor.getString(columnIndexSubTitle); } int columnIndexDayChangeHour = cursor .getColumnIndex(MetasTable.Columns.DAY_CHANGE_HOUR); if (cursor.getColumnCount() > columnIndexDayChangeHour) { MyApp.dayChangeHour = cursor.getInt(columnIndexDayChangeHour); } int columnIndexDayChangeMinute = cursor .getColumnIndex(MetasTable.Columns.DAY_CHANGE_MINUTE); if (cursor.getColumnCount() > columnIndexDayChangeMinute) { MyApp.dayChangeMinute = cursor.getInt(columnIndexDayChangeMinute); } int columnIndexEtag = cursor.getColumnIndex(MetasTable.Columns.ETAG); if (cursor.getColumnCount() > columnIndexEtag) { MyApp.eTag = cursor.getString(columnIndexEtag); } } MyApp.LogDebug(LOG_TAG, "loadMeta: numdays=" + MyApp.numdays + " version:" + MyApp.version + " " + MyApp.title + " " + MyApp.eTag); cursor.close(); metadb.close(); metaDB.close(); } public static void share(Context context, Lecture l) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); StringBuilder sb = new StringBuilder(); Time time = l.getTime(); sb.append(l.title).append("\n").append(SimpleDateFormat .getDateTimeInstance(SimpleDateFormat.FULL, SimpleDateFormat.SHORT) .format(new Date(time.toMillis(true)))); sb.append(", ").append(l.room).append("\n\n"); final String eventUrl = getEventUrl(context, l.lecture_id); sb.append(eventUrl); sendIntent.putExtra(Intent.EXTRA_TEXT, sb.toString()); sendIntent.setType("text/plain"); context.startActivity(sendIntent); } public static String getEventUrl(final Context context, final String eventId) { StringBuilder sb = new StringBuilder(); sb.append(BuildConfig.SCHEDULE_DOMAIN_PART); sb.append(BuildConfig.SCHEDULE_PART); // TODO The event url can be localized by providing individual values // for `schedule_event_part` in `values` and `values-de`. String eventPart = String.format(BuildConfig.SCHEDULE_EVENT_PART, eventId); sb.append(eventPart); return sb.toString(); } public static String getCalendarDescription(final Context context, final Lecture lecture) { StringBuilder sb = new StringBuilder(); sb.append(lecture.description); sb.append("\n\n"); final String eventOnline = context.getString(R.string.event_online); sb.append(eventOnline + ": "); sb.append(getEventUrl(context, lecture.lecture_id)); return sb.toString(); } @SuppressLint("NewApi") public static void addToCalender(Context context, Lecture l) { Intent intent = new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI); intent.putExtra(CalendarContract.Events.TITLE, l.title); intent.putExtra(CalendarContract.Events.EVENT_LOCATION, l.room); long when; if (l.dateUTC > 0) { when = l.dateUTC; } else { Time time = l.getTime(); when = time.normalize(true); } intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, when); intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, when + (l.duration * 60000)); final String description = getCalendarDescription(context, l); intent.putExtra(CalendarContract.Events.DESCRIPTION, description); try { context.startActivity(intent); return; } catch (ActivityNotFoundException e) { } intent.setAction(Intent.ACTION_EDIT); try { context.startActivity(intent); return; } catch (ActivityNotFoundException e) { Toast.makeText(context, R.string.add_to_calendar_failed, Toast.LENGTH_LONG).show(); } } public static void deleteAlarm(Context context, Lecture lecture) { AlarmsDBOpenHelper alarmDB = new AlarmsDBOpenHelper(context); SQLiteDatabase db = alarmDB.getWritableDatabase(); Cursor cursor; try { cursor = db.query( AlarmsTable.NAME, AlarmsDBOpenHelper.allcolumns, AlarmsTable.Columns.EVENT_ID + "=?", new String[]{lecture.lecture_id}, null, null, null); } catch (SQLiteException e) { e.printStackTrace(); MyApp.LogDebug("delete alarm", "failure on alarm query"); db.close(); return; } if (cursor.getCount() == 0) { db.close(); cursor.close(); MyApp.LogDebug("delete_alarm", "alarm for " + lecture.lecture_id + " not found"); lecture.has_alarm = false; return; } cursor.moveToFirst(); Intent intent = new Intent(context, AlarmReceiver.class); String lecture_id = cursor.getString(cursor.getColumnIndex(AlarmsTable.Columns.EVENT_ID)); intent.putExtra(BundleKeys.ALARM_LECTURE_ID, lecture_id); int day = cursor.getInt(cursor.getColumnIndex(AlarmsTable.Columns.DAY)); intent.putExtra(BundleKeys.ALARM_DAY, day); String title = cursor.getString(cursor.getColumnIndex(AlarmsTable.Columns.EVENT_TITLE)); intent.putExtra(BundleKeys.ALARM_TITLE, title); long startTime = cursor.getLong(cursor.getColumnIndex(AlarmsTable.Columns.TIME)); intent.putExtra(BundleKeys.ALARM_START_TIME, startTime); // delete any previous alarms of this lecture db.delete(AlarmsTable.NAME, AlarmsTable.Columns.EVENT_ID + "=?", new String[]{lecture.lecture_id}); db.close(); intent.setAction("de.machtnix.fahrplan.ALARM"); intent.setData(Uri.parse("alarm://" + lecture.lecture_id)); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingintent = PendingIntent .getBroadcast(context, Integer.parseInt(lecture.lecture_id), intent, 0); // Cancel any existing alarms for this lecture alarmManager.cancel(pendingintent); lecture.has_alarm = false; } public static void addAlarm(Context context, Lecture lecture, int alarmTimesIndex) { String[] alarm_times = context.getResources().getStringArray(R.array.alarm_time_values); List<String> alarmTimeStrings = new ArrayList<String>(Arrays.asList(alarm_times)); List<Integer> alarmTimes = new ArrayList<Integer>(alarmTimeStrings.size()); for (String alarmTimeString : alarmTimeStrings) { alarmTimes.add(Integer.parseInt(alarmTimeString)); } long when; Time time; long startTime; long startTimeInSeconds = lecture.dateUTC; if (startTimeInSeconds > 0) { when = startTimeInSeconds; startTime = startTimeInSeconds; time = new Time(); } else { time = lecture.getTime(); startTime = time.normalize(true); when = time.normalize(true); } long alarmTimeDiffInSeconds = alarmTimes.get(alarmTimesIndex) * 60 * 1000; when -= alarmTimeDiffInSeconds; // DEBUG // when = System.currentTimeMillis() + (30 * 1000); time.set(when); MyApp.LogDebug("addAlarm", "Alarm time: " + time.format("%Y-%m-%dT%H:%M:%S%z") + ", in seconds: " + when); Intent intent = new Intent(context, AlarmReceiver.class); intent.putExtra(BundleKeys.ALARM_LECTURE_ID, lecture.lecture_id); intent.putExtra(BundleKeys.ALARM_DAY, lecture.day); intent.putExtra(BundleKeys.ALARM_TITLE, lecture.title); intent.putExtra(BundleKeys.ALARM_START_TIME, startTime); intent.setAction(AlarmReceiver.ALARM_LECTURE); intent.setData(Uri.parse("alarm://" + lecture.lecture_id)); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingintent = PendingIntent .getBroadcast(context, Integer.parseInt(lecture.lecture_id), intent, 0); // Cancel any existing alarms for this lecture alarmManager.cancel(pendingintent); // Set new alarm alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingintent); int alarmTimeInMin = alarmTimes.get(alarmTimesIndex); // write to DB AlarmsDBOpenHelper alarmDB = new AlarmsDBOpenHelper(context); SQLiteDatabase db = alarmDB.getWritableDatabase(); // delete any previous alarms of this lecture try { db.beginTransaction(); db.delete(AlarmsTable.NAME, AlarmsTable.Columns.EVENT_ID + "=?", new String[]{lecture.lecture_id}); ContentValues values = new ContentValues(); values.put(AlarmsTable.Columns.EVENT_ID, Integer.parseInt(lecture.lecture_id)); values.put(AlarmsTable.Columns.EVENT_TITLE, lecture.title); values.put(AlarmsTable.Columns.ALARM_TIME_IN_MIN, alarmTimeInMin); values.put(AlarmsTable.Columns.TIME, when); DateFormat df = SimpleDateFormat .getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); values.put(AlarmsTable.Columns.TIME_TEXT, df.format(new Date(when))); values.put(AlarmsTable.Columns.DISPLAY_TIME, startTime); values.put(AlarmsTable.Columns.DAY, lecture.day); db.insert(AlarmsTable.NAME, null, values); db.setTransactionSuccessful(); } catch (SQLException e) { } finally { db.endTransaction(); db.close(); } lecture.has_alarm = true; } public static void writeHighlight(Context context, Lecture lecture) { HighlightDBOpenHelper highlightDB = new HighlightDBOpenHelper(context); SQLiteDatabase db = highlightDB.getWritableDatabase(); try { db.beginTransaction(); db.delete(HighlightsTable.NAME, HighlightsTable.Columns.EVENT_ID + "=?", new String[]{lecture.lecture_id}); ContentValues values = new ContentValues(); values.put(HighlightsTable.Columns.EVENT_ID, Integer.parseInt(lecture.lecture_id)); int highlightState = lecture.highlight ? HighlightsTable.Values.HIGHLIGHT_STATE_ON : HighlightsTable.Values.HIGHLIGHT_STATE_OFF; values.put(HighlightsTable.Columns.HIGHLIGHT, highlightState); db.insert(HighlightsTable.NAME, null, values); db.setTransactionSuccessful(); } catch (SQLException e) { } finally { db.endTransaction(); db.close(); } } public static long setUpdateAlarm(Context context, boolean initial) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent alarmintent = new Intent(context, AlarmReceiver.class); alarmintent.setAction(AlarmReceiver.ALARM_UPDATE); PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, alarmintent, 0); MyApp.LogDebug(LOG_TAG, "set update alarm"); long next_fetch; long interval; Time t = new Time(); t.setToNow(); long now = t.toMillis(true); if ((now >= MyApp.first_day_start) && (now < MyApp.last_day_end)) { interval = 2 * AlarmManager.INTERVAL_HOUR; next_fetch = now + interval; } else if (now >= MyApp.last_day_end) { MyApp.LogDebug(LOG_TAG, "cancel alarm post congress"); alarmManager.cancel(pendingintent); return 0; } else { interval = AlarmManager.INTERVAL_DAY; next_fetch = now + interval; } if ((now < MyApp.first_day_start) && ((now + AlarmManager.INTERVAL_DAY) >= MyApp.first_day_start)) { next_fetch = MyApp.first_day_start; interval = 2 * AlarmManager.INTERVAL_HOUR; if (!initial) { MyApp.LogDebug(LOG_TAG, "update alarm to interval " + interval + ", next in " + (next_fetch - now)); alarmManager.cancel(pendingintent); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next_fetch, interval, pendingintent); } } if (initial) { MyApp.LogDebug(LOG_TAG, "set initial alarm to interval " + interval + ", next in " + (next_fetch - now)); alarmManager.cancel(pendingintent); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next_fetch, interval, pendingintent); } return interval; } public static void clearUpdateAlarm(Context context) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent alarmintent = new Intent(context, AlarmReceiver.class); alarmintent.setAction(AlarmReceiver.ALARM_UPDATE); PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, alarmintent, 0); MyApp.LogDebug(LOG_TAG, "clear update alarm"); alarmManager.cancel(pendingintent); } public static LectureList loadLecturesForAllDays(Context context) { return loadLecturesForDayIndex(context, ALL_DAYS); } /** * Load all Lectures from the DB on the day specified * * @param context The Android Context * @param day The day to load lectures for (0..), or -1 for all days * @return ArrayList of Lecture objects */ public static LectureList loadLecturesForDayIndex(Context context, int day) { MyApp.LogDebug(LOG_TAG, "load lectures of day " + day); SQLiteDatabase lecturedb = null; LecturesDBOpenHelper lecturesDB = new LecturesDBOpenHelper(context); lecturedb = lecturesDB.getReadableDatabase(); HighlightDBOpenHelper highlightDB = new HighlightDBOpenHelper(context); SQLiteDatabase highlightdb = highlightDB.getReadableDatabase(); LectureList lectures = new LectureList(); Cursor cursor, hCursor; boolean allDays; if (day == ALL_DAYS) { allDays = true; } else { allDays = false; } try { cursor = lecturedb.query( LecturesTable.NAME, LecturesDBOpenHelper.allcolumns, allDays ? null : (LecturesTable.Columns.DAY + "=?"), allDays ? null : (new String[]{String.format("%d", day)}), null, null, LecturesTable.Columns.DATE_UTC); } catch (SQLiteException e) { e.printStackTrace(); lecturedb.close(); highlightdb.close(); lecturesDB.close(); return null; } try { hCursor = highlightdb.query( HighlightsTable.NAME, HighlightDBOpenHelper.allcolumns, null, null, null, null, null); } catch (SQLiteException e) { e.printStackTrace(); lecturedb.close(); highlightdb.close(); lecturesDB.close(); return null; } MyApp.LogDebug(LOG_TAG, "Got " + cursor.getCount() + " rows."); MyApp.LogDebug(LOG_TAG, "Got " + hCursor.getCount() + " highlight rows."); if (cursor.getCount() == 0) { cursor.close(); lecturedb.close(); highlightdb.close(); lecturesDB.close(); return null; } cursor.moveToFirst(); while (!cursor.isAfterLast()) { Lecture lecture = new Lecture(cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.EVENT_ID))); lecture.title = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.TITLE)); lecture.subtitle = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.SUBTITLE)); lecture.day = cursor.getInt( cursor.getColumnIndex(LecturesTable.Columns.DAY)); lecture.room = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.ROOM)); lecture.startTime = cursor.getInt( cursor.getColumnIndex(LecturesTable.Columns.START)); lecture.duration = cursor.getInt( cursor.getColumnIndex(LecturesTable.Columns.DURATION)); lecture.speakers = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.SPEAKERS)); lecture.track = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.TRACK)); lecture.type = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.TYPE)); lecture.lang = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.LANG)); lecture.abstractt = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.ABSTRACT)); lecture.description = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.DESCR)); lecture.relStartTime = cursor.getInt( cursor.getColumnIndex(LecturesTable.Columns.REL_START)); lecture.date = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.DATE)); lecture.links = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.LINKS)); lecture.dateUTC = cursor.getLong( cursor.getColumnIndex(LecturesTable.Columns.DATE_UTC)); lecture.room_index = cursor.getInt( cursor.getColumnIndex(LecturesTable.Columns.ROOM_IDX)); lecture.recordingLicense = cursor.getString( cursor.getColumnIndex(LecturesTable.Columns.REC_LICENSE)); lecture.recordingOptOut = cursor.getInt( cursor.getColumnIndex(LecturesTable.Columns.REC_OPTOUT)) == LecturesTable.Values.REC_OPTOUT_OFF ? Lecture.RECORDING_OPTOUT_OFF : Lecture.RECORDING_OPTOUT_ON; lecture.changedTitle = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_TITLE)) != 0; lecture.changedSubtitle = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_SUBTITLE)) != 0; lecture.changedRoom = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_ROOM)) != 0; lecture.changedDay = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_DAY)) != 0; lecture.changedSpeakers = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_SPEAKERS)) != 0; lecture.changedRecordingOptOut = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_RECORDING_OPTOUT)) != 0; lecture.changedLanguage = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_LANGUAGE)) != 0; lecture.changedTrack = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_TRACK)) != 0; lecture.changedIsNew = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_IS_NEW)) != 0; lecture.changedTime = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_TIME)) != 0; lecture.changedDuration = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_DURATION)) != 0; lecture.changedIsCanceled = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_IS_CANCELED)) != 0; lectures.add(lecture); cursor.moveToNext(); } cursor.close(); hCursor.moveToFirst(); while (!hCursor.isAfterLast()) { String lecture_id = hCursor.getString( hCursor.getColumnIndex(HighlightsTable.Columns.EVENT_ID)); int highlightState = hCursor.getInt( hCursor.getColumnIndex(HighlightsTable.Columns.HIGHLIGHT)); MyApp.LogDebug(LOG_TAG, "lecture " + lecture_id + " is hightlighted:" + highlightState); for (Lecture lecture : lectures) { if (lecture.lecture_id.equals(lecture_id)) { lecture.highlight = (highlightState == HighlightsTable.Values.HIGHLIGHT_STATE_ON ? true : false); } } hCursor.moveToNext(); } hCursor.close(); highlightdb.close(); lecturedb.close(); lecturesDB.close(); return lectures; } public static int getChangedLectureCount(LectureList list, boolean favsOnly) { int count = 0; if (list == null) return 0; for (int lectureIndex = 0; lectureIndex < list.size(); lectureIndex++) { Lecture l = list.get(lectureIndex); if (l.isChanged() && ((!favsOnly) || (l.highlight))) { count++; } } MyApp.LogDebug(LOG_TAG, "getChangedLectureCount " + favsOnly + ":" + count); return count; } public static int getNewLectureCount(LectureList list, boolean favsOnly) { int count = 0; if (list == null) return 0; for (int lectureIndex = 0; lectureIndex < list.size(); lectureIndex++) { Lecture l = list.get(lectureIndex); if ((l.changedIsNew) && ((!favsOnly) || (l.highlight))) count++; } MyApp.LogDebug(LOG_TAG, "getNewLectureCount " + favsOnly + ":" + count); return count; } public static int getCancelledLectureCount(LectureList list, boolean favsOnly) { int count = 0; if (list == null) return 0; for (int lectureIndex = 0; lectureIndex < list.size(); lectureIndex++) { Lecture l = list.get(lectureIndex); if ((l.changedIsCanceled) && ((!favsOnly) || (l.highlight))) count++; } MyApp.LogDebug(LOG_TAG, "getCancelledLectureCount " + favsOnly + ":" + count); return count; } public static LectureList readChanges(Context context) { MyApp.LogDebug(LOG_TAG, "readChanges"); LectureList changesList = FahrplanMisc.loadLecturesForAllDays(context); if (changesList == null) return null; int lectureIndex = changesList.size() - 1; while (lectureIndex >= 0) { Lecture l = changesList.get(lectureIndex); if (!l.isChanged() && !l.changedIsCanceled && !l.changedIsNew) { changesList.remove(l); } lectureIndex } MyApp.LogDebug(LOG_TAG, changesList.size() + " lectures changed."); return changesList; } public static LectureList getStarredLectures(Context context) { LectureList starredList = FahrplanMisc.loadLecturesForAllDays(context); if (starredList == null) return null; int lectureIndex = starredList.size() - 1; while (lectureIndex >= 0) { Lecture l = starredList.get(lectureIndex); if (!l.highlight) { starredList.remove(l); } lectureIndex } MyApp.LogDebug(LOG_TAG, starredList.size() + " lectures starred."); return starredList; } }
package org.fossasia.phimpme.accounts; import android.os.Build; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SwitchCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import org.fossasia.phimpme.R; import org.fossasia.phimpme.data.local.AccountDatabase; import org.fossasia.phimpme.gallery.util.ThemeHelper; import butterknife.BindView; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmQuery; import static org.fossasia.phimpme.data.local.AccountDatabase.HIDEINACCOUNTS; import static org.fossasia.phimpme.utilities.ActivitySwitchHelper.context; import static org.fossasia.phimpme.utilities.ActivitySwitchHelper.getContext; import java.util.ArrayList; public class AccountAdapter extends RecyclerView.Adapter<AccountAdapter.ViewHolder> { private Realm realm = Realm.getDefaultInstance(); private RealmQuery<AccountDatabase> realmResult = realm.where(AccountDatabase.class); public int switchAccentColor; public int switchBackgroundColor; private ThemeHelper themeHelper; private ArrayList<String> databaseoptions = new ArrayList<>(); public AccountAdapter() { themeHelper = new ThemeHelper(getContext()); updateTheme(); getdatabaseAccounts(); this.switchAccentColor = themeHelper.getAccentColor(); this.switchBackgroundColor = themeHelper.getPrimaryColor(); } public void updateTheme() { themeHelper.updateTheme(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.accounts_item_view, null, false); view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { realmResult = realm.where(AccountDatabase.class); // themeHelper.updateSwitchColor(holder.signInSignOutSwitch, switchBackgroundColor); String name = databaseoptions.get(position); if (realmResult.equalTo("name", name).count() > 0){ holder.accountName.setText(realmResult .equalTo("name", name).findAll() .first().getUsername()); holder.signInSignOutSwitch.setChecked(true); themeHelper.updateSwitchColor(holder.signInSignOutSwitch, switchAccentColor); } else { holder.accountName.setText(name); } Integer id = getContext().getResources().getIdentifier(context.getString(R.string.ic_) + (name.toLowerCase()) + "_black" , context.getString(R.string.drawable) , getContext().getPackageName()); holder.accountAvatar.setImageResource(id); id = getContext().getResources().getIdentifier((name.toLowerCase()) + "_color" , context.getString(R.string.color) , getContext().getPackageName()); if (themeHelper.getBaseTheme() == ThemeHelper.LIGHT_THEME){ holder.accountName.setTextColor(ContextCompat.getColor(getContext(), id)); holder.accountAvatar.setColorFilter(ContextCompat.getColor(getContext(), id)); } else { id = getContext().getResources().getIdentifier((name.toLowerCase()) + "_color_darktheme" , context.getString(R.string.color) , getContext().getPackageName()); holder.accountName.setTextColor(ContextCompat.getColor(getContext(), id)); holder.accountAvatar.setColorFilter(ContextCompat.getColor(getContext(), id)); } holder.cardView.setCardBackgroundColor(themeHelper.getCardBackgroundColor()); } @Override public int getItemCount() { /** * We are using the enum from the AccountDatabase model class, (-HIDEINACCOUNTS) from the length because * whatsapp, Instagram , googleplus and others option is only required in the Sharing activity. */ //return AccountDatabase.AccountName.values().length - HIDEINACCOUNTS; return databaseoptions.size() - HIDEINACCOUNTS; } public void getdatabaseAccounts(){ for(int i = 0; i < AccountDatabase.AccountName.values().length; i++){ if(AccountDatabase.AccountName.values()[i].toString().equals("BOX")){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ databaseoptions.add(AccountDatabase.AccountName.values()[i].toString()); } } else{ databaseoptions.add(AccountDatabase.AccountName.values()[i].toString()); } } } public void setResults(RealmQuery<AccountDatabase> results) { realmResult = results; notifyDataSetChanged(); } public static class ViewHolder extends RecyclerView.ViewHolder{ @BindView(R.id.account_avatar) ImageView accountAvatar; @BindView(R.id.account_logo_indicator) ImageView accountLogoIndicator; @BindView(R.id.account_username) TextView accountName; @BindView(R.id.sign_in_sign_out_switch) SwitchCompat signInSignOutSwitch; @BindView(R.id.card_view) CardView cardView; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
package org.innovateuk.ifs.project.core.repository; import org.innovateuk.ifs.BaseRepositoryIntegrationTest; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.finance.domain.ProjectFinance; import org.innovateuk.ifs.finance.repository.ProjectFinanceRepository; import org.innovateuk.ifs.finance.repository.ProjectFinanceRowRepository; import org.innovateuk.ifs.organisation.domain.Organisation; import org.innovateuk.ifs.organisation.domain.OrganisationAddress; import org.innovateuk.ifs.organisation.repository.OrganisationAddressRepository; import org.innovateuk.ifs.organisation.repository.OrganisationRepository; import org.innovateuk.ifs.project.bankdetails.domain.BankDetails; import org.innovateuk.ifs.project.bankdetails.repository.BankDetailsRepository; import org.innovateuk.ifs.project.core.domain.PartnerOrganisation; import org.innovateuk.ifs.project.core.domain.Project; import org.innovateuk.ifs.project.core.domain.ProjectUser; import org.innovateuk.ifs.project.resource.ApprovalType; import org.innovateuk.ifs.threads.repository.NoteRepository; import org.innovateuk.ifs.threads.repository.QueryRepository; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.repository.UserRepository; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import javax.transaction.Transactional; import java.time.ZonedDateTime; import java.util.List; import static java.time.LocalDate.now; import static org.innovateuk.ifs.address.builder.AddressBuilder.newAddress; import static org.innovateuk.ifs.address.builder.AddressTypeBuilder.newAddressType; import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication; import static org.innovateuk.ifs.finance.domain.builder.ProjectFinanceBuilder.newProjectFinance; import static org.innovateuk.ifs.organisation.builder.OrganisationAddressBuilder.newOrganisationAddress; import static org.innovateuk.ifs.project.bankdetails.builder.BankDetailsBuilder.newBankDetails; import static org.innovateuk.ifs.project.core.builder.PartnerOrganisationBuilder.newPartnerOrganisation; import static org.innovateuk.ifs.project.core.builder.ProjectBuilder.newProject; import static org.innovateuk.ifs.project.core.builder.ProjectUserBuilder.newProjectUser; import static org.innovateuk.ifs.project.core.domain.ProjectParticipantRole.PROJECT_MANAGER; import static org.innovateuk.ifs.project.core.domain.ProjectParticipantRole.PROJECT_PARTNER; import static org.junit.Assert.assertEquals; @Transactional @Rollback public class PartnerOrganisationRepositoryIntegrationTest extends BaseRepositoryIntegrationTest<PartnerOrganisationRepository> { @Autowired private UserRepository userRepository; @Autowired private ApplicationRepository applicationRepository; @Autowired private ProjectUserRepository projectUserRepository; @Autowired private ProjectRepository projectRepository; @Autowired private OrganisationRepository organisationRepository; @Autowired private ProjectFinanceRepository projectFinanceRepository; @Autowired private BankDetailsRepository bankDetailsRepository; @Autowired private ProjectFinanceRowRepository projectFinanceRowRepository; @Autowired private NoteRepository noteRepository; @Autowired private QueryRepository queryRepository; @Autowired private OrganisationAddressRepository organisationAddressRepository; private User projectManager; private User projectPartner; private Project project; private Organisation empire; private Organisation ludlow; List<ProjectUser> projectUsers; List<PartnerOrganisation> partnerOrganisations; private ProjectFinance projectFinanceEmpire; private ProjectFinance projectFinanceLudlow; private BankDetails bankDetailsEmpire; private BankDetails bankDetailsLudlow; private OrganisationAddress organisationAddress; private OrganisationAddress organisationAddress2; @Autowired @Override protected void setRepository(final PartnerOrganisationRepository repository) { this.repository = repository; } @Before public void setup() { projectManager = userRepository.findByEmail("steve.smith@empire.com").get(); projectPartner = userRepository.findByEmail("jessica.doe@ludlow.co.uk").get(); empire = organisationRepository.findOneByName("Empire Ltd"); ludlow = organisationRepository.findOneByName("Ludlow"); projectUsers = newProjectUser() .withRole(PROJECT_MANAGER, PROJECT_PARTNER) .withUser(projectManager, projectPartner) .build(2); project = newProject() .withApplication(newApplication().withId(1L).build()) .withDateSubmitted(ZonedDateTime.now()) .withDuration(6L) .withName("My test project") .withAddress(newAddress().withAddressLine1("2 Polaris House").withAddressLine2("Swindon").withPostcode("SN2 1EU").build()) .withOtherDocumentsApproved(ApprovalType.APPROVED) .withTargetStartDate(now()) .withProjectUsers(projectUsers) .build(); projectRepository.save(project); partnerOrganisations = newPartnerOrganisation() .withProject(project) .withId(30L, 40L) .withOrganisation(empire, ludlow) .withLeadOrganisation(true, false) .build(2); repository.save(partnerOrganisations.get(0)); repository.save(partnerOrganisations.get(1)); projectFinanceEmpire = newProjectFinance() .withProject(project) .withOrganisation(empire) .build(); projectFinanceLudlow = newProjectFinance() .withProject(project) .withOrganisation(ludlow) .build(); projectFinanceRepository.save(projectFinanceEmpire); projectFinanceRepository.save(projectFinanceLudlow); organisationAddress = newOrganisationAddress() .withOrganisation(empire) .withAddress(newAddress() .withAddressLine1("45 Friendly Street").withAddressLine2("SN2 1UR").build()) .withAddressType(newAddressType().build()) .build(); organisationAddress2 = newOrganisationAddress() .withOrganisation(empire) .withAddress(newAddress() .withAddressLine1("817 Union Street").withAddressLine2("SN2 5SL").build()) .withAddressType(newAddressType().build()) .build(); bankDetailsEmpire = newBankDetails() .withOrganisation(empire) .withSortCode("100006") .withAccountNumber("98765432") .withOrganiationAddress(organisationAddress) .withProject(project) .build(); bankDetailsLudlow = newBankDetails() .withOrganisation(ludlow) .withSortCode("120034") .withAccountNumber("1200146") .withOrganiationAddress(organisationAddress2) .withProject(project) .build(); bankDetailsRepository.save(bankDetailsEmpire); bankDetailsRepository.save(bankDetailsLudlow); } @Test public void getProjectPartnerOrganisations() { List<PartnerOrganisation> partners = repository.findByProjectId(project.getId()); assertEquals(empire, partners.get(0).getOrganisation()); assertEquals(ludlow, partners.get(1).getOrganisation()); } @Test public void deleteOneByProjectIdAndOrganisationId() { repository.deleteOneByProjectIdAndOrganisationId(project.getId(), ludlow.getId()); assertEquals(1, repository.findByProjectId(project.getId()).size()); } }
/* * $Id: $ * $URL: $ */ package org.subethamail.core.queue; import javax.ejb.MessageDriven; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Current; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subethamail.common.NotFoundException; import org.subethamail.core.deliv.i.Deliverator; /** * Processes delivery queue messages by creating an actual STMP message * using JavaMail, relaying it through the deliverator. */ @MessageDriven @TransactionAttribute(TransactionAttributeType.REQUIRED) public class DeliveryListener implements MessageListener { private final static Logger log = LoggerFactory.getLogger(DeliveryListener.class); @Current Deliverator deliverator; public void onMessage(Message qMsg) { try { DeliveryQueueItem umdd = (DeliveryQueueItem)((ObjectMessage)qMsg).getObject(); Long mailId = umdd.getMailId(); Long personId = umdd.getPersonId(); if (log.isDebugEnabled()) log.debug("Delivering mailId:" + mailId + " to personId:" + personId); try { this.deliverator.deliver(mailId, personId); } catch (NotFoundException ex) { // Just log a warning and accept the JMS message; this is a legit case // when mail gets deleted. if (log.isWarnEnabled()) log.warn("Unknown mailId(" + mailId + ") or personId(" + personId + ")", ex); } // This is not supposed to be relevant for MDBs //qMsg.acknowledge(); } catch (JMSException ex) { if (log.isErrorEnabled()) log.error("Error getting data out of message.", ex); throw new RuntimeException(ex); } } }
package org.mozilla.focus.widget; import android.content.Context; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import android.util.AttributeSet; import android.view.View; import android.view.accessibility.AccessibilityManager; import android.view.animation.AnimationUtils; import org.mozilla.focus.R; public class FloatingEraseButton extends FloatingActionButton { private boolean keepHidden = true; public FloatingEraseButton(Context context) { super(context); } public FloatingEraseButton(Context context, AttributeSet attrs) { super(context, attrs); } public FloatingEraseButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void updateSessionsCount(int tabCount) { final CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) getLayoutParams(); final FloatingActionButtonBehavior behavior = (FloatingActionButtonBehavior) params.getBehavior(); AccessibilityManager accessibilityManager = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); keepHidden = tabCount != 1; if (behavior != null) { if (accessibilityManager != null && accessibilityManager.isTouchExplorationEnabled()) { // Always display erase button if Talk Back is enabled behavior.setEnabled(false); } else { behavior.setEnabled(!keepHidden); } } if (keepHidden) { setVisibility(View.GONE); } } @Override protected void onFinishInflate() { if (!keepHidden) { this.setVisibility(View.VISIBLE); this.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.fab_reveal)); } super.onFinishInflate(); } @Override public void setVisibility(int visibility) { if (keepHidden && visibility == View.VISIBLE) { // There are multiple callbacks updating the visibility of the button. Let's make sure // we do not show the button if we do not want to. return; } if (visibility == View.VISIBLE) { show(); } else { hide(); } } }
package wikipod.vpm.fr.wikipodcasts; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import fr.vpm.wikipod.location.Localisation; import fr.vpm.wikipod.location.LocalisationListener; import fr.vpm.wikipod.location.LocationProvider; import wikipod.vpm.fr.wikipodcasts.search.LocalisationSearcher; import wikipod.vpm.fr.wikipodcasts.util.ProgressBarListener; /** * A placeholder fragment containing a simple view. */ public class LocationFragment extends Fragment implements LocalisationListener { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; private AbsListView locationsView; private ProgressBarListener progressListener; private List<Localisation> localisations = new ArrayList<>(); private ArrayAdapter<Localisation> locationsAdapter; /** * Returns a new instance of this fragment for the given section * number. */ public static LocationFragment newInstance(int sectionNumber) { LocationFragment fragment = new LocationFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public LocationFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_locations, container, false); ProgressBar progressBar = (ProgressBar) rootView.findViewById(R.id.processing); progressListener = new ProgressBarListener(progressBar); locationsView = (AbsListView) rootView.findViewById(R.id.locations); final EditText searchField = (EditText) rootView.findViewById(R.id.searchField); filterLocations(searchField); // manage search button clicks ImageButton searchButton = (ImageButton) rootView.findViewById(R.id.searchButton); searchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String searchText = searchField.getText().toString(); searchField.setText(""); new LocalisationSearcher(getActivity(), LocationFragment.this, progressListener).searchLocalisationByName(searchText); } }); // manage locate button clicks ImageButton locateButton = (ImageButton) rootView.findViewById(R.id.locateButton); locateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LocationProvider.Status status = new LocalisationSearcher(getActivity(), LocationFragment.this, progressListener).searchLocalisation(); Toast.makeText(getActivity(), "tried acquiring location, resulted in " + status.name(), Toast.LENGTH_SHORT).show(); } }); return rootView; } /** * Adds filtering from search field over the locations in the list * @param searchField the text field for searching locations */ private void filterLocations(EditText searchField) {searchField.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence searchText, int start, int before, int count) { if (locationsAdapter != null) { locationsAdapter.getFilter().filter(searchText.toString()); } } @Override public void afterTextChanged(Editable s) { } }); } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((FramingActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } @Override public void onLocalisationChanged(Localisation localisation) { localisations.add(localisation); locationsAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item, localisations); locationsView.setAdapter(locationsAdapter); } }
package util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; import models.Program; import org.json.JSONObject; public class FileSystem { private static String path = "/home/andy/codeweb/data/"; private static String assnStr = "1_3"; private static String programPath = ""; public static void setProgramPath(String newPath) { programPath = newPath; } public static void setPath(String newPath){ path = newPath; } public static void setAssignment(String assnStr) {FileSystem.assnStr = assnStr;} public static String getEquivalenceOutDir() { return path + "equivalence/equivalence_" + assnStr + "/"; } public static String getNodeMappingDir() { return path + "equivalence/nodeMapping_" + assnStr + "/"; } public static String getReducedOutDir() { return path + "equivalence/reduced_" + assnStr + "/"; } public static String getReducedAllDir() { return path + "equivalence/reduced_" + assnStr + "_all/"; } public static String getSubtreeDir() { return path + "equivalence/subtree_" + assnStr + "/"; } public static String getUnitTestOutputDir() { return path + "DumpOutputs" + "/"; } public static String getDiscoveriesDir() { return path + "equivalence/discoveries_" + assnStr + "/"; } public static String getSeedDir() { return path + "equivalence/seed_" + assnStr + "/"; } public static String getExpandedDir() { return path + "equivalence/expanded_" + assnStr + "/"; } public static void saveToIgnore(Set<Integer> toIgnore) { String fileString = ""; for(Integer id : toIgnore ) { fileString += id + "\n"; } createFile(path+ "equivalence" , "toIgnore.txt", fileString); } public static Set<Integer> loadToIgnore() { Set<Integer> toIgnore = new HashSet<Integer>(); String filePath = path+ "equivalence/toIgnore.txt"; try { Scanner keywordsIn = new Scanner(new File(filePath)); while (keywordsIn.hasNext()) { String line = keywordsIn.next(); int id = Integer.parseInt(line); toIgnore.add(id); } keywordsIn.close(); return toIgnore; } catch (FileNotFoundException e) { return toIgnore; } } public static String getNumSubmissionsDir() { return path + "DumpNumSubmissions" + "/"; } public static void clearEquivalences() { String dir = getEquivalenceOutDir(); File folder = new File(dir); File[] files = folder.listFiles(); if(files!=null) { //some JVMs return null for empty dirs for(File f: files) { if (f.listFiles()!= null) { for(File c: f.listFiles()) { c.delete(); } } f.delete(); } } } public static int getNumAsts() { return new File(path + "ast/ast_" + assnStr).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".json"); } }).length; } private static Set<Integer> getIncorrects() { return getAstSet("incorrects", "incorrects"); } public static Set<Integer> getCorrects() { return getAstSet("incorrects", "corrects"); } private static Set<Integer> getAstSet(String dir, String name) { Set<Integer> correctSet = new HashSet<Integer>(); Scanner correctIn; try { String fileName = dir + "/" + name + "_" + assnStr + ".txt"; String filePath = path + fileName; correctIn = new Scanner(new File(filePath)); while (correctIn.hasNextInt()) { correctSet.add(correctIn.nextInt()); } correctIn.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } return correctSet; } public static Set<Integer> getCorrupts() { try { Set<Integer> corruptSet = new HashSet<Integer>(); Scanner corruptIn = new Scanner(new File(path + "matching/dist_" + assnStr + ".txt")); String firstLine = corruptIn.nextLine(); Scanner firstLineScanner = new Scanner(firstLine); int index = 0; while (firstLineScanner.hasNextInt()) { boolean isCorrupt = firstLineScanner.nextInt() == -1; if (isCorrupt) { corruptSet.add(index); } index += 1; } corruptIn.close(); return corruptSet; } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file",e); } } private static String getProgramDir() { String dir = programPath; if(programPath.isEmpty()) { dir = path + "ast/ast_" + assnStr + "/"; } return dir; } public static void copyFile(String from, String to) { File source = new File(from); File dest = new File(to); FileChannel inputChannel = null; FileChannel outputChannel = null; try { dest.createNewFile(); inputChannel = new FileInputStream(source).getChannel(); outputChannel = new FileOutputStream(dest).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); inputChannel.close(); outputChannel.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void setConfig(String configPath) { try{ Scanner configIn = new Scanner(new File(configPath)); while (configIn.hasNextLine()){ String line = configIn.nextLine(); String[] tokens = line.split(" "); if (tokens[0].equals("DATA")){ path = tokens[1]; } if (tokens[0].equals("ASSIGNMENT")){ assnStr = tokens[1]; } } configIn.close(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file",e); } } public static HashSet<String> loadKeywords() { try { Scanner keywordsIn = new Scanner(new File(path + "starter/starter_" + assnStr + ".txt")); HashSet<String> ans = new HashSet<String>(); while (keywordsIn.hasNext()) ans.add(keywordsIn.next()); keywordsIn.close(); return ans; } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file",e); } } public static JSONObject loadJson(String path) { Scanner astIn; try { astIn = new Scanner(new File(path)); StringBuffer astStr = new StringBuffer(); while (astIn.hasNextLine()) astStr.append(astIn.nextLine()); astIn.close(); return new JSONObject(astStr.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file",e); } } public static JSONObject loadAst(int astId) { Scanner astIn; try { String dir = getProgramDir(); String fullPath = dir + "ast_" + astId + ".json"; astIn = new Scanner(new File(fullPath)); StringBuffer astStr = new StringBuffer(); while (astIn.hasNextLine()) astStr.append(astIn.nextLine()); astIn.close(); return new JSONObject(astStr.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file",e); } } public static ArrayList<String> loadCode(int astId) { try { String dir = getProgramDir(); String fullPath = dir + "ast_" + astId + ".code"; Scanner codeIn = new Scanner(new File(fullPath)); ArrayList<String> code = new ArrayList<String>(); while (codeIn.hasNextLine()) code.add(codeIn.nextLine()); codeIn.close(); return code; } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file",e); } } public static int[][] loadMap(int astId) { try { String dir = getProgramDir(); String fullPath = dir + "ast_" + astId + ".map"; Scanner mapIn = new Scanner(new File(fullPath)); int mapN = mapIn.nextInt(); int[][] map = new int[mapN][]; for (int j = 0; j < mapN; j++) { int mapC = mapIn.nextInt(); map[j] = new int[mapC]; for (int k = 0; k < mapC; k++) map[j][k] = mapIn.nextInt(); } mapIn.close(); return map; } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file",e); } } public static ArrayList<Integer> loadOutputs() { try { Scanner outputsIn = new Scanner(new File(getUnitTestOutputDir() + "outputClasses_" + assnStr + ".txt")); ArrayList<Integer> outputs = new ArrayList<Integer>(); while (outputsIn.hasNextLine()){ String line = outputsIn.nextLine(); outputs.add(Integer.parseInt(line)); } outputsIn.close(); return outputs; } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file", e); } } public static ArrayList<Integer> loadNumSubmissions() { try { Scanner numSubmissionsIn = new Scanner(new File(getNumSubmissionsDir() + "NumSubmissions_" + assnStr + ".txt")); ArrayList<Integer> numSubmissions = new ArrayList<Integer>(); while (numSubmissionsIn.hasNextLine()) { String line = numSubmissionsIn.nextLine(); String[] parts = line.split(", "); //int astId = Integer.parseInt(parts[0]); int num = Integer.parseInt(parts[1]); numSubmissions.add(num); } numSubmissionsIn.close(); return numSubmissions; } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("could not open file", e); } } public static void createEmptyFile(String dir, String fileName) { new File(dir).mkdirs(); try { String path = dir + "/" + fileName; FileWriter file = new FileWriter(path); file.write(""); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } } public static void createFile(String dir, String fileName, String text) { new File(dir).mkdirs(); try { String path = dir + "/" + fileName; FileWriter file = new FileWriter(path); file.write(text); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } } }
package ua.com.fielden.platform.entity.meta; import static java.lang.String.format; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.getEntityTitleAndDesc; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.getTitleAndDesc; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.processReqErrorMsg; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.DynamicEntityKey; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.proxy.StrictProxyException; import ua.com.fielden.platform.entity.validation.FinalValidator; import ua.com.fielden.platform.entity.validation.IBeforeChangeEventHandler; import ua.com.fielden.platform.entity.validation.StubValidator; import ua.com.fielden.platform.entity.validation.annotation.Final; import ua.com.fielden.platform.entity.validation.annotation.ValidationAnnotation; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.error.Warning; import ua.com.fielden.platform.reflection.Reflector; import ua.com.fielden.platform.utils.EntityUtils; public final class MetaPropertyFull<T> extends MetaProperty<T> { private final Class<?> propertyAnnotationType; private final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> validators; private final Set<Annotation> validationAnnotations = new HashSet<Annotation>(); private final IAfterChangeEventHandler<T> aceHandler; private final boolean collectional; private final boolean shouldAssignBeforeSave; /** * This property indicates whether a corresponding property was modified. This is similar to <code>dirty</code> property at the entity level. */ private boolean dirty; public static final Number ORIGINAL_VALUE_NOT_INIT_COLL = -1; /// Holds an original value of the property. /** * Original value is always the value retrieved from a data storage. This means that new entities, which have not been persisted yet, have original values of their properties * equal to <code>null</code> * <p> * In case of properties with default values such definition might be unintuitive at first. However, the whole notion of default property values specified as an assignment * during property field definition does not fit naturally into the proposed modelling paradigm. Any property value should be validated before being assigned. This requires * setter invocation, and should be a deliberate act enforced as part of the application logic. Enforcing validation for default values is not technically difficult, but would * introduce a maintenance hurdle for application developers, where during an evolution of the system the validation logic might change, but default values not updated * accordingly. This would lead to entity instantiation failure. * * A much preferred approach is to provide a custom entity constructor or instantiation factories in case default property values support is required, where property values * should be set via setters. The use of factories would provide additional flexibility, where default values could be governed by business logic and a place of entity * instantiation. */ private T originalValue; private T prevValue; private T lastInvalidValue; private int valueChangeCount = 0; /** * Indicates whether this property has an assigned value. * This flag is requited due to the fact that the value of null could be assigned making it impossible to identify the * fact of value assignment in light of the fact that the original property value could, and in most cases is, be <code>null</code>. */ private boolean assigned = false; // The following properties are more related to UI controls rather than to actual property value modification. // // Some external to meta-property logic may define whether the value of <code>editable</code>. // private boolean editable = true; private boolean visible = true; private boolean required = false; private final boolean calculated; private final boolean upperCase; // if the value is present then a corresponding property has annotation {@link Final} // the boolean value captures the value of attribute persistentOnly private final Optional<Boolean> persistentOnlySettingForFinalAnnotation; private final PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); private final Logger logger = Logger.getLogger(this.getClass()); /** Enforced mutation happens as part of the error recovery to indicate processing of dependent properties. */ private boolean enforceMutator = false; /** * Property supports specification of the precise type. For example, property <code>key</code> in entity classes is recognised by reflection API as Comparable. Therefore, it * might be desirable to specify type more accurately. * * @param entity * @param field * @param type * @param isKey * @param isCollectional * @param propertyAnnotationType * @param calculated * @param upperCase * @param validationAnnotations * @param validators * @param aceHandler * @param dependentPropertyNames */ public MetaPropertyFull( final AbstractEntity<?> entity, final Field field, final Class<?> type, final boolean isProxy, final boolean isKey, final boolean isCollectional, final boolean shouldAssignBeforeSave, final Class<?> propertyAnnotationType, final boolean calculated, final boolean upperCase, final Set<Annotation> validationAnnotations, final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> validators, final IAfterChangeEventHandler<T> aceHandler, final String[] dependentPropertyNames) { super(entity, field, type, isKey, isProxy, dependentPropertyNames); this.validationAnnotations.addAll(validationAnnotations); this.validators = validators; this.aceHandler = aceHandler; this.collectional = isCollectional; this.shouldAssignBeforeSave = shouldAssignBeforeSave; this.propertyAnnotationType = propertyAnnotationType; this.calculated = calculated; this.upperCase = upperCase; final Final finalAnnotation = field.getAnnotation(Final.class); persistentOnlySettingForFinalAnnotation = finalAnnotation == null ? Optional.empty() : Optional.of(finalAnnotation.persistentOnly()); } /** * Perform sequential validation. * * Stops validation at the first violation. This is preferred since subsequent validators may depend on success of preceding ones. * * Please note that collectional properties may have up to three mutators having different annotations. Thus, a special logic is used to ensure that only validators associated * with the mutator being processed are applied. * * @return */ @Override public synchronized final Result validate(final T newValue, final Set<Annotation> applicableValidationAnnotations, final boolean ignoreRequiredness) { setLastInvalidValue(null); if (!ignoreRequiredness && isRequired() && isNull(newValue, getValue())) { final Map<IBeforeChangeEventHandler<T>, Result> requiredHandler = getValidators().get(ValidationAnnotation.REQUIRED); if (requiredHandler == null || requiredHandler.size() > 1) { throw new IllegalArgumentException("There are no or there is more than one REQUIRED validation handler for required property!"); } final Result result = mkRequiredError(); setValidationResultNoSynch(ValidationAnnotation.REQUIRED, requiredHandler.keySet().iterator().next(), result); return result; } else { // refresh REQUIRED validation result if REQUIRED validation annotation pair exists final Map<IBeforeChangeEventHandler<T>, Result> requiredHandler = getValidators().get(ValidationAnnotation.REQUIRED); if (requiredHandler != null && requiredHandler.size() == 1) { setValidationResultNoSynch(ValidationAnnotation.REQUIRED, requiredHandler.keySet().iterator().next(), new Result(getEntity(), "Requiredness updated by successful result.")); } // process all registered validators (that have its own annotations) return processValidators(newValue, applicableValidationAnnotations); } } private Result mkRequiredError() { // obtain custom error message in case it has been provided at the domain level final String reqErrorMsg = processReqErrorMsg(name, getEntity().getType()); final Result result; if (!StringUtils.isEmpty(reqErrorMsg)) { result = Result.failure(getEntity(), reqErrorMsg); } else { final String msg = format("Required property [%s] is not specified for entity [%s].", getTitleAndDesc(name, getEntity().getType()).getKey(), getEntityTitleAndDesc(getEntity().getType()).getKey()); result = Result.failure(getEntity(), msg); } return result; } /** * Convenient method to determine if the newValue is "null" or is empty in terms of value. * * @param newValue * @param oldValue * @return */ private boolean isNull(final T newValue, final T oldValue) { // IMPORTANT : need to check NotNullValidator usage on existing logic. There is the case, when // should not to pass the validation : setRotable(null) in AdvicePosition when getRotable() == null!!! // that is why - - "&& (oldValue != null)" - - was removed!!!!! // The current condition is essential for UI binding logic. return (newValue == null) || /* && (oldValue != null) */ (newValue instanceof String && StringUtils.isBlank(newValue.toString())); } /** * Revalidates this property using {@link #getLastAttemptedValue()} value as the input for the property. Revalidation occurs only if this property has an assigned value (null * could also be an assigned value). * * @param ignoreRequiredness * when true then isRequired value is ignored during revalidation, this is currently used for re-validating dependent properties where there is no need to mark * properties as invalid only because they are empty. * @return revalidation result */ @Override public synchronized final Result revalidate(final boolean ignoreRequiredness) { // revalidation is required only is there is an assigned value if (assigned) { return validate(getLastAttemptedValue(), validationAnnotations, ignoreRequiredness); } return Result.successful(this); } /** * Processes all registered validators (that have its own annotations) by iterating over validators associated with corresponding validation annotations (va). * * @param newValue * @param applicableValidationAnnotations * @param mutatorType * @return */ private Result processValidators(final T newValue, final Set<Annotation> applicableValidationAnnotations) { // iterate over registered validations for (final ValidationAnnotation va : validators.keySet()) { // requiredness falls outside of processing logic for other validators, so simply ignore it if (va == ValidationAnnotation.REQUIRED) { continue; } final Set<Entry<IBeforeChangeEventHandler<T>, Result>> pairs = validators.get(va).entrySet(); for (final Entry<IBeforeChangeEventHandler<T>, Result> pair : pairs) { // if validator exists ...and it should... then validated and set validation result final IBeforeChangeEventHandler<T> handler = pair.getKey(); if (handler != null && isValidatorApplicable(applicableValidationAnnotations, va.getType())) { final Result result = pair.getKey().handle(this, newValue, applicableValidationAnnotations); setValidationResultNoSynch(va, handler, result); // important to call setValidationResult as it fires property change event listeners if (!result.isSuccessful()) { // 1. isCollectional() && newValue instance of Collection : previously the size of "newValue" collection was set as LastInvalidValue, but now, // if we need to update bounded component by the lastInvalidValue then we set it as a collectional value // 2. if the property is not collectional then simply set LastInvalidValue as newValue setLastInvalidValue(newValue); return result; } } else { pair.setValue(null); } } } return new Result(this, "Validated successfully."); } /** * Checks whether annotation identified by parameter <code>key</code> is amongst applicable validation annotations. * * @param applicableValidationAnnotations * @param validationAnnotationEnumValue * @return */ private boolean isValidatorApplicable(final Set<Annotation> applicableValidationAnnotations, final Class<? extends Annotation> validationAnnotationType) { for (final Annotation annotation : applicableValidationAnnotations) { if (annotation.annotationType() == validationAnnotationType) { return true; } } return false; } @Override public final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> getValidators() { return validators; } @Override public final String toString() { return format(format("Meta-property for property [%s] in entity [%s] wiht validators [%s].", getName(), getEntity().getType().getName(), validators)); } /** * Sets the result for validator with index. * * @param key * -- annotation representing validator * @param validationResult */ private void setValidationResultNoSynch(final ValidationAnnotation key, final IBeforeChangeEventHandler<T> handler, final Result validationResult) { // fire validationResults change event!! if (validators.get(key) != null) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(key); final Result oldValue = annotationHandlers.get(handler);// getValue(); annotationHandlers.put(handler, validationResult); final Result firstFailure = getFirstFailure(); if (firstFailure != null) { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, firstFailure); } else { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, validationResult); } } } /** * Same as {@link #setValidationResultNoSynch(Annotation, IBeforeChangeEventHandler, Result)}, but with synchronization block. * * @param key * @param handler * @param validationResult */ @Override public synchronized final void setValidationResult(final ValidationAnnotation key, final IBeforeChangeEventHandler<T> handler, final Result validationResult) { setValidationResultNoSynch(key, handler, validationResult); } /** * Sets validation result specifically for {@link ValidationAnnotation.REQUIRED}; * * @param validationResult */ @Override public synchronized final void setRequiredValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.REQUIRED); } /** * Sets validation result specifically for {@link ValidationAnnotation.ENTITY_EXISTS}; * * @param validationResult */ @Override public synchronized final void setEntityExistsValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.ENTITY_EXISTS); } /** * Sets validation result specifically for {@link ValidationAnnotation.REQUIRED}; * * @param validationResult */ @Override public synchronized final void setDomainValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.DOMAIN); } /** * Sets validation result for the first of the annotation handlers designated by the validation annotation value. * * @param validationResult * @param annotationHandlers */ private void setValidationResultForFirtsValidator(final Result validationResult, final ValidationAnnotation va) { Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); if (annotationHandlers == null) { annotationHandlers = new HashMap<>(); annotationHandlers.put(StubValidator.singleton, null); validators.put(va, annotationHandlers); } final IBeforeChangeEventHandler<T> handler = annotationHandlers.keySet().iterator().next(); final Result oldValue = annotationHandlers.get(handler); annotationHandlers.put(handler, validationResult); final Result firstFailure = getFirstFailure(); if (firstFailure != null) { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, firstFailure); } else { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, validationResult); } } /** * Returns the last result of the first validator associated with {@link ValidationAnnotation} value in a synchronised manner if all validators for this annotation succeeded, * or the last result of the first failed validator. Most validation annotations are associated with a single validator. But some, such as * {@link ValidationAnnotation#BEFORE_CHANGE} may have more than one validator associated with it. * * @param va * -- validation annotation. * @return */ @Override public synchronized final Result getValidationResult(final ValidationAnnotation va) { final Result failure = getFirstFailureFor(va); return failure != null ? failure : validators.get(va).values().iterator().next(); } /** * Returns false if there is at least one unsuccessful result. Evaluation of the validation results happens in a synchronised manner. * * @return */ @Override public synchronized final boolean isValid() { final Result failure = getFirstFailure(); return failure == null; } @Override public synchronized final boolean hasWarnings() { final Result failure = getFirstWarning(); return failure != null; } /** * Returns the first warning associated with property validators. * * @return */ @Override public synchronized final Warning getFirstWarning() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Result result : annotationHandlers.values()) { if (result != null && result.isWarning()) { return (Warning) result; } } } return null; } /** * Removes all validation warnings (not errors) from the property. */ @Override public synchronized final void clearWarnings() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Entry<IBeforeChangeEventHandler<T>, Result> handlerAndResult : annotationHandlers.entrySet()) { if (handlerAndResult.getValue() != null && handlerAndResult.getValue().isWarning()) { annotationHandlers.put(handlerAndResult.getKey(), null); } } } } /** * This method invokes {@link #isValid()} and if its result is <code>true</code> (i.e. valid) then additional check kicks in to ensure requiredness validation. * * @return */ @Override public synchronized final boolean isValidWithRequiredCheck() { final boolean result = isValid(); if (result) { // if valid check whether it's requiredness sound final Object value = ((AbstractEntity<?>) getEntity()).get(getName()); // this is a potential alternative approach to validating requiredness for proxied properties // leaving it here for future reference // if (isRequired() && isProxy()) { // throw new StrictProxyException(format("Required property [%s] in entity [%s] is proxied and thus cannot be checked.", getName(), getEntity().getType().getName())); if (isRequired() && !isProxy() && (value == null || isEmpty(value))) { if (!getValidators().containsKey(ValidationAnnotation.REQUIRED)) { throw new IllegalArgumentException("There are no REQUIRED validation annotation pair for required property!"); } final Result result1 = mkRequiredError(); setValidationResultNoSynch(ValidationAnnotation.REQUIRED, StubValidator.singleton, result1); return false; } } return result; } /** * A convenient method, which ensures that only string values are tested for empty when required. This prevents accidental and redundant lazy loading when invoking * values.toString() on entity instances. * * @param value * @return */ private boolean isEmpty(final Object value) { return value instanceof String ? StringUtils.isEmpty(value.toString()) : false; } /** * Return the first failed validation result. If there is no failure then returns null. * * @return */ @Override public synchronized final Result getFirstFailure() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Result result : annotationHandlers.values()) { if (result != null && !result.isSuccessful()) { return result; } } } return null; } /** * Returns the first failure associated with <code>annotation</code> value. * * @param annotation * @return */ private final Result getFirstFailureFor(final ValidationAnnotation annotation) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(annotation); for (final Result result : annotationHandlers.values()) { if (result != null && !result.isSuccessful()) { return result; } } return null; } /** * Returns the number of property validators. Can be zero. * * @return */ @Override public final int numberOfValidators() { return validators.size(); } /** * Registers property change listener to validationResults. This listener fires when setValidationResult(..) method invokes. * * @param propertyName * @param listener */ @Override public final synchronized void addValidationResultsChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(VALIDATION_RESULTS_PROPERTY_NAME, listener); } /** * Removes validationResults change listener. */ @Override public synchronized final void removeValidationResultsChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(VALIDATION_RESULTS_PROPERTY_NAME, listener); } /** * Registers property change listener for property <code>editable</code>. * * @param propertyName * @param listener */ @Override public final synchronized void addEditableChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(EDITABLE_PROPERTY_NAME, listener); } /** * Removes change listener for property <code>editable</code>. */ @Override public final synchronized void removeEditableChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(EDITABLE_PROPERTY_NAME, listener); } /** * Registers property change listener for property <code>required</code>. * * @param propertyName * @param listener */ @Override public final synchronized void addRequiredChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(REQUIRED_PROPERTY_NAME, listener); } /** * Removes change listener for property <code>required</code>. */ @Override public final synchronized void removeRequiredChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(REQUIRED_PROPERTY_NAME, listener); } @Override public final PropertyChangeSupport getChangeSupport() { return changeSupport; } @Override public final T getOriginalValue() { return originalValue; } /** * Sets the original value. * * <p> * VERY IMPORTANT : the method should not cause proxy initialisation!!! * * @param value -- new originalValue for the property */ @Override public final MetaPropertyFull<T> setOriginalValue(final T value) { // when original property value is set then the previous value should be the same // the previous value setter is not used deliberately since it has some logic not needed here if (isCollectional()) { // set the shallow copy of collection into originalValue to be able to perform comparison between actual value and original value of the collection originalValue = EntityUtils.copyCollectionalValue(value).flatMap(copy -> copy).orElse(null); // set the shallow copy of collection into prevValue to be able to perform comparison between actual value and prevValue value of the collection prevValue = EntityUtils.copyCollectionalValue(originalValue).flatMap(copy -> copy).orElse(null); } else { // The single property (proxied or not!!!) originalValue = value; prevValue = originalValue; } // reset value change counter resetValueChageCount(); assigned = true; return this; } @Override public final int getValueChangeCount() { return valueChangeCount; } private void incValueChangeCount() { valueChangeCount++; } private void resetValueChageCount() { valueChangeCount = 0; } @Override public final T getPrevValue() { return prevValue; } /** * Returns the current (last successful) value of the property. * * @return */ @Override public final T getValue() { return entity.<T> get(name); } /** * A convenient method to set property value, which in turn accesses entity to set the propery. * * @param value */ @Override public final void setValue(final Object value) { entity.set(name, value); } /** * Updates the previous value for the entity property. Increments the update counter and check if the original value should be updated as well. * * @param value -- new prevValue for the property * @return */ @Override public final MetaPropertyFull<T> setPrevValue(final T value) { incValueChangeCount(); // just in case cater for correct processing of collection properties if (isCollectional()) { // set the shallow copy of collection into this.prevValue to be able to perform comparison between actual value and previous value of the collection EntityUtils.copyCollectionalValue(value).map(copy -> this.prevValue = copy.orElse(null)); } else { this.prevValue = value; } return this; } /** * Checks if the current value is changed from the original one. * * @return */ @Override public final boolean isChangedFromOriginal() { return isChangedFrom(getOriginalValue()); } /** * Checks if the current value is changed from the specified one by means of equality. <code>null</code> value is permitted. * <p> * Please, note that property accessor (aka getter) is used to get current value. If exception occurs during current value getting -- * this method returns <code>false</code> and silently ignores this exception (with some debugging logging). * * @param value * @return */ private final boolean isChangedFrom(final T value) { try { final Method getter = Reflector.obtainPropertyAccessor(entity.getClass(), getName()); final Object currValue = getter.invoke(entity); return !EntityUtils.equalsEx(currValue, value); } catch (final Exception e) { logger.debug(e.getMessage(), e); } return false; } /** * Checks if the current value is changed from the previous one. * * @return */ @Override public final boolean isChangedFromPrevious() { return isChangedFrom(getPrevValue()); } @Override public final boolean isEditable() { return editable && getEntity().isEditable().isSuccessful() && !isFinalised(); } private boolean isFinalised() { if (persistentOnlySettingForFinalAnnotation.isPresent()) { return FinalValidator.isPropertyFinalised(this, persistentOnlySettingForFinalAnnotation.get()); } return false; } @Override public final void setEditable(final boolean editable) { final boolean oldValue = this.editable; this.editable = editable; changeSupport.firePropertyChange(EDITABLE_PROPERTY_NAME, oldValue, editable); } /** * Invokes {@link IAfterChangeEventHandler#handle(MetaPropertyFull, Object)} if it has been provided. * * @param entityPropertyValue * @return */ @Override public final MetaPropertyFull<T> define(final T entityPropertyValue) { if (aceHandler != null) { aceHandler.handle(this, entityPropertyValue); } return this; } @Override public final MetaPropertyFull<T> defineForOriginalValue() { if (aceHandler != null) { aceHandler.handle(this, getOriginalValue()); } return this; } /** * Returns true if MetaProperty represents a collectional property. * * @return */ @Override public final boolean isCollectional() { return collectional; } /** * Returns a type provided as part of the annotation {@link IsProperty} when defining property. It is provided, for example, in cases where meta-property represents a * collection property -- the provided type indicates the type collection elements. * * @return */ @Override public final Class<?> getPropertyAnnotationType() { return propertyAnnotationType; } @Override public final boolean isVisible() { return visible; } @Override public final void setVisible(final boolean visible) { this.visible = visible; } @Override public final T getLastInvalidValue() { return lastInvalidValue; } @Override public final void setLastInvalidValue(final T lastInvalidValue) { this.lastInvalidValue = lastInvalidValue; } /** * A convenient method for determining whether there are validators associated a the corresponding property. * * @return */ @Override public final boolean hasValidators() { return getValidators().size() > 0; } /** * Convenient method that returns either property value (if property validation passed successfully) or {@link #getLastInvalidValue()} (if property validation idn't pass). * <p> * A special care is taken for properties with default values assigned at the field level. This method returns <code>original value</code> for properties that are valid and not * assigned. * * @return */ @Override public final T getLastAttemptedValue() { return isValid() ? (isAssigned() ? getValue() : getOriginalValue()) : getLastInvalidValue(); } @Override public final boolean isRequired() { return required; } /** * This setter change the 'required' state for metaProperty. Also it puts RequiredValidator to the list of validators if it does not exist. And if 'required' became false -> it * clears REQUIRED validation result by successful result. * * @param required */ @Override public final void setRequired(final boolean required) { if (required && !getEntity().isInitialising() && isProxy()) { throw new StrictProxyException(format("Property [%s] in entity [%s] is proxied and should not be made required.", getName(), getEntity().getType().getName())); } final boolean oldRequired = this.required; this.required = required; // if requirement changed from false to true, and REQUIRED validator does not exist in the list of validators -> then put REQUIRED validator to the list of validators if (required && !oldRequired && !containsRequiredValidator()) { putRequiredValidator(); } // if requirement changed from true to false, then update REQUIRED validation result to be successful if (!required && oldRequired) { if (containsRequiredValidator()) { final Result result = getValidationResult(ValidationAnnotation.REQUIRED); if (result != null && !result.isSuccessful()) { setEnforceMutator(true); try { setValue(getLastAttemptedValue()); } finally { setEnforceMutator(false); } } else { // associated a successful result with requiredness validator setValidationResultNoSynch(ValidationAnnotation.REQUIRED, StubValidator.singleton, new Result(this.getEntity(), "'Required' became false. The validation result cleared.")); } } else { throw new IllegalStateException("The metaProperty was required but RequiredValidator didn't exist."); } } changeSupport.firePropertyChange(REQUIRED_PROPERTY_NAME, oldRequired, required); } @Override public final void resetState() { setOriginalValue(entity.get(name)); setDirty(false); } @Override public final void resetValues() { setOriginalValue(entity.get(name)); } @Override public final boolean isCalculated() { return calculated; } /** * Checks if REQUIRED validator were ever put to the list of validators. * * @return */ @Override public final boolean containsRequiredValidator() { return getValidators().containsKey(ValidationAnnotation.REQUIRED); } /** * Checks if DYNAMIC validator were ever put to the list of validators. * * @return */ @Override public final boolean containsDynamicValidator() { return getValidators().containsKey(ValidationAnnotation.DYNAMIC); } /** * Creates and puts EMPTY validator related to DYNAMIC validation annotation. Validation result for DYNAMIC validator can be set only from the outside logic, for e.g. using * method MetaProperty.setValidationResult(). */ @Override public final void putDynamicValidator() { putValidator(ValidationAnnotation.DYNAMIC); } /** * Creates and puts EMPTY validator related to REQUIRED validation annotation. Validation result for REQURED validator can be set only from the outside logic, for e.g. using * method MetaProperty.setValidationResult(). */ @Override public final void putRequiredValidator() { putValidator(ValidationAnnotation.REQUIRED); } /** * Used to create and put new validator (without any validation logic!) to validators list related to <code>valAnnotation</code>. * * This method should be used ONLY for DYNAMIC, REQUIRED and all validators that cannot change its result from its own "validate" method, but only from the outside method * MetaProperty.setValidationResult(). * * @param valAnnotation */ private void putValidator(final ValidationAnnotation valAnnotation) { final Map<IBeforeChangeEventHandler<T>, Result> map = new HashMap<>(2); // optimised with 2 as default value for this map -- not to create map with unnecessary 16 elements map.put(StubValidator.singleton, null); getValidators().put(valAnnotation, map); } @Override public boolean isDirty() { return dirty || !entity.isPersisted(); } @Override public MetaPropertyFull<T> setDirty(final boolean dirty) { this.dirty = dirty; return this; } @Override public boolean isUpperCase() { return upperCase; } /** * Restores property state to original if possible, which includes setting the original value and removal of all validation errors. */ @Override public final void restoreToOriginal() { resetValidationResult(); // need to ignore composite key instance resetting if (!DynamicEntityKey.class.isAssignableFrom(type)) { try { entity.set(name, getOriginalValue()); } catch (final Exception ex) { logger.debug("Could not restore to original property " + name + "#" + entity.getType().getName() + "."); } } resetState(); } /** * Resets validation results for all validators by setting their value to <code>null</code>. */ @Override public synchronized final void resetValidationResult() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final IBeforeChangeEventHandler<T> handler : annotationHandlers.keySet()) { annotationHandlers.put(handler, null); } } } @Override public boolean isEnforceMutator() { return enforceMutator; } @Override public void setEnforceMutator(final boolean enforceMutator) { this.enforceMutator = enforceMutator; } @Override public boolean isAssigned() { return assigned; } @Override public void setAssigned(final boolean hasAssignedValue) { this.assigned = hasAssignedValue; } /** * Returns a list of validation annotations associated with this property. * * @return */ @Override public Set<Annotation> getValidationAnnotations() { return Collections.unmodifiableSet(validationAnnotations); } /** * Returns property ACE handler. * * @return */ @Override public IAfterChangeEventHandler<T> getAceHandler() { return aceHandler; } @Override public boolean shouldAssignBeforeSave() { return shouldAssignBeforeSave; } }