answer
stringlengths
17
10.2M
package hex.tree; import hex.*; import static hex.ModelCategory.Binomial; import static hex.genmodel.GenModel.createAuxKey; import hex.genmodel.algos.tree.SharedTreeMojoModel; import hex.genmodel.algos.tree.SharedTreeSubgraph; import hex.glm.GLMModel; import hex.util.LinearAlgebraUtils; import water.*; import water.codegen.CodeGenerator; import water.codegen.CodeGeneratorPipeline; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.JCodeSB; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.parser.BufferedString; import water.util.*; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; public abstract class SharedTreeModel< M extends SharedTreeModel<M, P, O>, P extends SharedTreeModel.SharedTreeParameters, O extends SharedTreeModel.SharedTreeOutput > extends Model<M, P, O> implements Model.LeafNodeAssignment, Model.GetMostImportantFeatures { @Override public String[] getMostImportantFeatures(int n) { if (_output == null) return null; TwoDimTable vi = _output._variable_importances; if (vi==null) return null; n = Math.min(n, vi.getRowHeaders().length); String[] res = new String[n]; System.arraycopy(vi.getRowHeaders(), 0, res, 0, n); return res; } @Override public ToEigenVec getToEigenVec() { return LinearAlgebraUtils.toEigen; } public abstract static class SharedTreeParameters extends Model.Parameters { public int _ntrees=50; // Number of trees in the final model. Grid Search, comma sep values:50,100,150,200 public int _max_depth = 5; // Maximum tree depth. Grid Search, comma sep values:5,7 public double _min_rows = 10; // Fewest allowed observations in a leaf (in R called 'nodesize'). Grid Search, comma sep values public int _nbins = 20; // Numerical (real/int) cols: Build a histogram of this many bins, then split at the best point public int _nbins_cats = 1024; // Categorical (factor) cols: Build a histogram of this many bins, then split at the best point public double _min_split_improvement = 1e-5; // Minimum relative improvement in squared error reduction for a split to happen public enum HistogramType { AUTO, UniformAdaptive, Random, QuantilesGlobal, RoundRobin } public HistogramType _histogram_type = HistogramType.AUTO; // What type of histogram to use for finding optimal split points public double _r2_stopping = Double.MAX_VALUE; // Stop when the r^2 metric equals or exceeds this value public int _nbins_top_level = 1<<10; //hardcoded maximum top-level number of bins for real-valued columns public boolean _build_tree_one_node = false; public int _score_tree_interval = 0; // score every so many trees (no matter what) public int _initial_score_interval = 4000; //Adding this parameter to take away the hard coded value of 4000 for scoring the first 4 secs public int _score_interval = 4000; //Adding this parameter to take away the hard coded value of 4000 for scoring each iteration every 4 secs public double _sample_rate = 0.632; //fraction of rows to sample for each tree public double[] _sample_rate_per_class; //fraction of rows to sample for each tree, per class public boolean _calibrate_model = false; // Use Platt Scaling public Key<Frame> _calibration_frame; public Frame calib() { return _calibration_frame == null ? null : _calibration_frame.get(); } @Override public long progressUnits() { return _ntrees + (_histogram_type==HistogramType.QuantilesGlobal || _histogram_type==HistogramType.RoundRobin ? 1 : 0); } public double _col_sample_rate_change_per_level = 1.0f; //relative change of the column sampling rate for every level public double _col_sample_rate_per_tree = 1.0f; //fraction of columns to sample for each tree /** Fields which can NOT be modified if checkpoint is specified. * FIXME: should be defined in Schema API annotation */ private static String[] CHECKPOINT_NON_MODIFIABLE_FIELDS = { "_build_tree_one_node", "_sample_rate", "_max_depth", "_min_rows", "_nbins", "_nbins_cats", "_nbins_top_level"}; protected String[] getCheckpointNonModifiableFields() { return CHECKPOINT_NON_MODIFIABLE_FIELDS; } /** This method will take actual parameters and validate them with parameters of * requested checkpoint. In case of problem, it throws an API exception. * * @param checkpointParameters checkpoint parameters */ public void validateWithCheckpoint(SharedTreeParameters checkpointParameters) { for (Field fAfter : this.getClass().getFields()) { // only look at non-modifiable fields if (ArrayUtils.contains(getCheckpointNonModifiableFields(),fAfter.getName())) { for (Field fBefore : checkpointParameters.getClass().getFields()) { if (fBefore.equals(fAfter)) { try { if (!PojoUtils.equals(this, fAfter, checkpointParameters, checkpointParameters.getClass().getField(fAfter.getName()))) { throw new H2OIllegalArgumentException(fAfter.getName(), "TreeBuilder", "Field " + fAfter.getName() + " cannot be modified if checkpoint is specified!"); } } catch (NoSuchFieldException e) { throw new H2OIllegalArgumentException(fAfter.getName(), "TreeBuilder", "Field " + fAfter.getName() + " is not supported by checkpoint!"); } } } } } } } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { switch(_output.getModelCategory()) { case Binomial: return new ModelMetricsBinomial.MetricBuilderBinomial(domain); case Multinomial: return new ModelMetricsMultinomial.MetricBuilderMultinomial(_output.nclasses(),domain); case Regression: return new ModelMetricsRegression.MetricBuilderRegression(); default: throw H2O.unimpl(); } } public abstract static class SharedTreeOutput extends Model.Output { /** InitF value (for zero trees) * f0 = mean(yi) for gaussian * f0 = log(yi/1-yi) for bernoulli * * For GBM bernoulli, the initial prediction for 0 trees is * p = 1/(1+exp(-f0)) * * From this, the mse for 0 trees (null model) can be computed as follows: * mean((yi-p)^2) * */ public double _init_f; /** Number of trees actually in the model (as opposed to requested) */ public int _ntrees; /** More indepth tree stats */ public final TreeStats _treeStats; /** Trees get big, so store each one separately in the DKV. */ public Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _treeKeys; public Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _treeKeysAux; public ScoreKeeper[/*ntrees+1*/] _scored_train; public ScoreKeeper[/*ntrees+1*/] _scored_valid; public ScoreKeeper[] scoreKeepers() { ArrayList<ScoreKeeper> skl = new ArrayList<>(); ScoreKeeper[] ska = _validation_metrics != null ? _scored_valid : _scored_train; for( ScoreKeeper sk : ska ) if (!sk.isEmpty()) skl.add(sk); return skl.toArray(new ScoreKeeper[skl.size()]); } /** Training time */ public long[/*ntrees+1*/] _training_time_ms = {System.currentTimeMillis()}; /** * Variable importances computed during training */ public TwoDimTable _variable_importances; public VarImp _varimp; public GLMModel _calib_model; public SharedTreeOutput( SharedTree b) { super(b); _ntrees = 0; // No trees yet _treeKeys = new Key[_ntrees][]; // No tree keys yet _treeKeysAux = new Key[_ntrees][]; // No tree keys yet _treeStats = new TreeStats(); _scored_train = new ScoreKeeper[]{new ScoreKeeper(Double.NaN)}; _scored_valid = new ScoreKeeper[]{new ScoreKeeper(Double.NaN)}; _modelClassDist = _priorClassDist; } // Append next set of K trees public void addKTrees( DTree[] trees) { // DEBUG: Print the generated K trees //SharedTree.printGenerateTrees(trees); assert nclasses()==trees.length; // Compress trees and record tree-keys _treeKeys = Arrays.copyOf(_treeKeys ,_ntrees+1); _treeKeysAux = Arrays.copyOf(_treeKeysAux ,_ntrees+1); Key[] keys = _treeKeys[_ntrees] = new Key[trees.length]; Key[] keysAux = _treeKeysAux[_ntrees] = new Key[trees.length]; Futures fs = new Futures(); for( int i=0; i<nclasses(); i++ ) if( trees[i] != null ) { CompressedTree ct = trees[i].compress(_ntrees,i,_domains); DKV.put(keys[i]=ct._key,ct,fs); _treeStats.updateBy(trees[i]); // Update tree shape stats CompressedTree ctAux = new CompressedTree(trees[i]._abAux.buf(),-1,-1,-1); keysAux[i] = ctAux._key = Key.make(createAuxKey(ct._key.toString())); DKV.put(ctAux,fs); } _ntrees++; // 1-based for errors; _scored_train[0] is for zero trees, not 1 tree _scored_train = ArrayUtils.copyAndFillOf(_scored_train, _ntrees+1, new ScoreKeeper()); _scored_valid = _scored_valid != null ? ArrayUtils.copyAndFillOf(_scored_valid, _ntrees+1, new ScoreKeeper()) : null; _training_time_ms = ArrayUtils.copyAndFillOf(_training_time_ms, _ntrees+1, System.currentTimeMillis()); fs.blockForPending(); } public CompressedTree ctree( int tnum, int knum ) { return _treeKeys[tnum][knum].get(); } public String toStringTree ( int tnum, int knum ) { return ctree(tnum,knum).toString(this); } } public SharedTreeModel(Key<M> selfKey, P parms, O output) { super(selfKey, parms, output); } protected String[] makeAllTreeColumnNames() { int classTrees = 0; for (int i = 0; i < _output._treeKeys[0].length; ++i) { if (_output._treeKeys[0][i] != null) classTrees++; } final int outputcols = _output._treeKeys.length * classTrees; final String[] names = new String[outputcols]; int col = 0; for (int tidx = 0; tidx < _output._treeKeys.length; tidx++) { Key[] keys = _output._treeKeys[tidx]; for (int c = 0; c < keys.length; c++) { if (keys[c] != null) { names[col++] = "T" + (tidx + 1) + (keys.length == 1 ? "" : (".C" + (c + 1))); } } } return names; } @Override public Frame scoreLeafNodeAssignment(Frame frame, LeafNodeAssignmentType type, Key<Frame> destination_key) { Frame adaptFrm = new Frame(frame); adaptTestForTrain(adaptFrm, true, false); final String[] names = makeAllTreeColumnNames(); AssignLeafNodeTaskBase task = AssignLeafNodeTaskBase.make(_output, type); return task.execute(adaptFrm, names, destination_key); } public static class BufStringDecisionPathTracker implements SharedTreeMojoModel.DecisionPathTracker<BufferedString> { private final byte[] _buf = new byte[64]; private final BufferedString _bs = new BufferedString(_buf, 0, 0); private int _pos = 0; @Override public boolean go(int depth, boolean right) { _buf[depth] = right ? (byte) 'R' : (byte) 'L'; if (right) _pos = depth; return true; } @Override public BufferedString terminate() { _bs.setLen(_pos); _pos = 0; return _bs; } } private static abstract class AssignLeafNodeTaskBase extends MRTask<AssignLeafNodeTaskBase> { final Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _treeKeys; final String _domains[][]; AssignLeafNodeTaskBase(SharedTreeOutput output) { _treeKeys = output._treeKeys; _domains = output._domains; } protected abstract void initMap(); protected abstract void assignNode(final int tidx, final int cls, final CompressedTree tree, final double[] input, final NewChunk out); @Override public void map(Chunk chks[], NewChunk[] idx) { double[] input = new double[chks.length]; initMap(); for (int row = 0; row < chks[0]._len; row++) { for (int i = 0; i < chks.length; i++) input[i] = chks[i].atd(row); int col = 0; for (int tidx = 0; tidx < _treeKeys.length; tidx++) { Key[] keys = _treeKeys[tidx]; for (int cls = 0; cls < keys.length; cls++) { Key key = keys[cls]; if (key != null) { CompressedTree tree = DKV.get(key).get(); assignNode(tidx, cls, tree, input, idx[col++]); } } } assert (col == idx.length); } } protected abstract Frame execute(Frame adaptFrm, String[] names, Key<Frame> destKey); private static AssignLeafNodeTaskBase make(SharedTreeOutput modelOutput, LeafNodeAssignmentType type) { switch (type) { case Path: return new AssignTreePathTask(modelOutput); case Node_ID: return new AssignLeafNodeIdTask(modelOutput); default: throw new UnsupportedOperationException("Unknown leaf node assignment type: " + type); } } } private static class AssignTreePathTask extends AssignLeafNodeTaskBase { private transient BufStringDecisionPathTracker _tr; private AssignTreePathTask(SharedTreeOutput output) { super(output); } @Override protected void initMap() { _tr = new BufStringDecisionPathTracker(); } @Override protected void assignNode(int tidx, int cls, CompressedTree tree, double[] input, NewChunk out) { BufferedString pred = tree.getDecisionPath(input, _domains, _tr); out.addStr(pred); } @Override protected Frame execute(Frame adaptFrm, String[] names, Key<Frame> destKey) { Frame res = doAll(names.length, Vec.T_STR, adaptFrm).outputFrame(destKey, names, null); // convert to categorical Vec vv; Vec[] nvecs = new Vec[res.vecs().length]; for(int c=0;c<res.vecs().length;++c) { vv = res.vec(c); try { nvecs[c] = vv.toCategoricalVec(); } catch (Exception e) { VecUtils.deleteVecs(nvecs, c); throw e; } } res.delete(); res = new Frame(destKey, names, nvecs); DKV.put(res); return res; } } private static class AssignLeafNodeIdTask extends AssignLeafNodeTaskBase { private final Key<CompressedTree>[/*_ntrees*/][/*_nclass*/] _auxTreeKeys; private final int _nclasses; private transient BufStringDecisionPathTracker _tr; private AssignLeafNodeIdTask(SharedTreeOutput output) { super(output); _auxTreeKeys = output._treeKeysAux; _nclasses = output.nclasses(); } @Override protected void initMap() { _tr = new BufStringDecisionPathTracker(); } @Override protected void assignNode(int tidx, int cls, CompressedTree tree, double[] input, NewChunk out) { CompressedTree auxTree = _auxTreeKeys[tidx][cls].get(); assert auxTree != null; final double d = SharedTreeMojoModel.scoreTree(tree._bits, input, true, _domains); final int nodeId = SharedTreeMojoModel.getLeafNodeId(d, auxTree._bits); out.addNum(nodeId, 0); } @Override protected Frame execute(Frame adaptFrm, String[] names, Key<Frame> destKey) { return doAll(names.length, Vec.T_NUM, adaptFrm).outputFrame(destKey, names, null); } } @Override protected Frame postProcessPredictions(Frame adaptedFrame, Frame predictFr, Job j) { if (_output._calib_model == null) return predictFr; if (_output.getModelCategory() == Binomial) { Key<Job> jobKey = j != null ? j._key : null; Key<Frame> calibInputKey = Key.make(); Frame calibOutput = null; try { Frame calibInput = new Frame(calibInputKey, new String[]{"p"}, new Vec[]{predictFr.vec(1)}); calibOutput = _output._calib_model.score(calibInput); assert calibOutput._names.length == 3; Vec[] calPredictions = calibOutput.remove(new int[]{1, 2}); // append calibrated probabilities to the prediction frame predictFr.write_lock(jobKey); for (int i = 0; i < calPredictions.length; i++) predictFr.add("cal_" + predictFr.name(1 + i), calPredictions[i]); return predictFr.update(jobKey); } finally { predictFr.unlock(jobKey); DKV.remove(calibInputKey); if (calibOutput != null) calibOutput.remove(); } } else throw H2O.unimpl("Calibration is only supported for binomial models"); } protected double[] score0Incremental(Score.ScoreIncInfo sii, Chunk chks[], double offset, int row_in_chunk, double[] tmp, double[] preds) { return score0(chks, offset, row_in_chunk, tmp, preds); // by default delegate to non-incremental implementation } @Override protected double[] score0(double[] data, double[] preds, double offset) { return score0(data, preds, offset, _output._treeKeys.length); } @Override protected double[] score0(double[/*ncols*/] data, double[/*nclasses+1*/] preds) { return score0(data, preds, 0.0); } protected double[] score0(double[] data, double[] preds, double offset, int ntrees) { Arrays.fill(preds,0); return score0(data, preds, offset, 0, ntrees); } protected double[] score0(double[] data, double[] preds, double offset, int startTree, int ntrees) { // Prefetch trees into the local cache if it is necessary // Invoke scoring for( int tidx=startTree; tidx<ntrees; tidx++ ) score0(data, preds, tidx); return preds; } // Score per line per tree private void score0(double[] data, double[] preds, int treeIdx) { Key[] keys = _output._treeKeys[treeIdx]; for( int c=0; c<keys.length; c++ ) { if (keys[c] != null) { double pred = DKV.get(keys[c]).<CompressedTree>get().score(data,_output._domains); assert (!Double.isInfinite(pred)); preds[keys.length == 1 ? 0 : c + 1] += pred; } } } /** Performs deep clone of given model. */ protected M deepClone(Key<M> result) { M newModel = IcedUtils.deepCopy(self()); newModel._key = result; // Do not clone model metrics newModel._output.clearModelMetrics(); newModel._output._training_metrics = null; newModel._output._validation_metrics = null; // Clone trees Key[][] treeKeys = newModel._output._treeKeys; for (int i = 0; i < treeKeys.length; i++) { for (int j = 0; j < treeKeys[i].length; j++) { if (treeKeys[i][j] == null) continue; CompressedTree ct = DKV.get(treeKeys[i][j]).get(); CompressedTree newCt = IcedUtils.deepCopy(ct); newCt._key = CompressedTree.makeTreeKey(i, j); DKV.put(treeKeys[i][j] = newCt._key,newCt); } } // Clone Aux info Key[][] treeKeysAux = newModel._output._treeKeysAux; if (treeKeysAux!=null) { for (int i = 0; i < treeKeysAux.length; i++) { for (int j = 0; j < treeKeysAux[i].length; j++) { if (treeKeysAux[i][j] == null) continue; CompressedTree ct = DKV.get(treeKeysAux[i][j]).get(); CompressedTree newCt = IcedUtils.deepCopy(ct); newCt._key = Key.make(createAuxKey(treeKeys[i][j].toString())); DKV.put(treeKeysAux[i][j] = newCt._key,newCt); } } } return newModel; } @Override protected Futures remove_impl( Futures fs ) { for (Key[] ks : _output._treeKeys) for (Key k : ks) if( k != null ) k.remove(fs); for (Key[] ks : _output._treeKeysAux) for (Key k : ks) if( k != null ) k.remove(fs); if (_output._calib_model != null) _output._calib_model.remove(fs); return super.remove_impl(fs); } /** Write out K/V pairs */ @Override protected AutoBuffer writeAll_impl(AutoBuffer ab) { for (Key<CompressedTree>[] ks : _output._treeKeys) for (Key<CompressedTree> k : ks) ab.putKey(k); for (Key<CompressedTree>[] ks : _output._treeKeysAux) for (Key<CompressedTree> k : ks) ab.putKey(k); return super.writeAll_impl(ab); } @Override protected Keyed readAll_impl(AutoBuffer ab, Futures fs) { for (Key<CompressedTree>[] ks : _output._treeKeys) for (Key<CompressedTree> k : ks) ab.getKey(k,fs); for (Key<CompressedTree>[] ks : _output._treeKeysAux) for (Key<CompressedTree> k : ks) ab.getKey(k,fs); return super.readAll_impl(ab,fs); } @SuppressWarnings("unchecked") // `M` is really the type of `this` private M self() { return (M)this; } /** * Converts a given tree of the ensemble to a user-understandable representation. * @param tidx tree index * @param cls tree class * @return instance of SharedTreeSubgraph */ public SharedTreeSubgraph getSharedTreeSubgraph(final int tidx, final int cls) { if (tidx < 0 || tidx >= _output._ntrees) { throw new IllegalArgumentException("Invalid tree index: " + tidx + ". Tree index must be in range [0, " + (_output._ntrees -1) + "]."); } final CompressedTree auxCompressedTree = _output._treeKeysAux[tidx][cls].get(); return _output._treeKeys[tidx][cls].get().toSharedTreeSubgraph(auxCompressedTree, _output._names, _output._domains); } // Serialization into a POJO // Override in subclasses to provide some top-level model-specific goodness @Override protected boolean toJavaCheckTooBig() { // If the number of leaves in a forest is more than N, don't try to render it in the browser as POJO code. return _output==null || _output._treeStats._num_trees * _output._treeStats._mean_leaves > 1000000; } protected boolean binomialOpt() { return true; } @Override protected SBPrintStream toJavaInit(SBPrintStream sb, CodeGeneratorPipeline fileCtx) { if (_parms._categorical_encoding != Parameters.CategoricalEncodingScheme.AUTO && _parms._categorical_encoding != Parameters.CategoricalEncodingScheme.Enum) { throw new IllegalArgumentException("Only default categorical_encoding scheme is supported for POJO/MOJO"); } sb.nl(); sb.ip("public boolean isSupervised() { return true; }").nl(); sb.ip("public int nfeatures() { return " + _output.nfeatures() + "; }").nl(); sb.ip("public int nclasses() { return " + _output.nclasses() + "; }").nl(); return sb; } @Override protected void toJavaPredictBody(SBPrintStream body, CodeGeneratorPipeline classCtx, CodeGeneratorPipeline fileCtx, final boolean verboseCode) { final int nclass = _output.nclasses(); body.ip("java.util.Arrays.fill(preds,0);").nl(); final String mname = JCodeGen.toJavaId(_key.toString()); // One forest-per-GBM-tree, with a real-tree-per-class for (int t=0; t < _output._treeKeys.length; t++) { // Generate score method for given tree toJavaForestName(body.i(),mname,t).p(".score0(data,preds);").nl(); final int treeIdx = t; fileCtx.add(new CodeGenerator() { @Override public void generate(JCodeSB out) { try { // Generate a class implementing a tree out.nl(); toJavaForestName(out.ip("class "), mname, treeIdx).p(" {").nl().ii(1); out.ip("public static void score0(double[] fdata, double[] preds) {").nl().ii(1); for (int c = 0; c < nclass; c++) { if (_output._treeKeys[treeIdx][c] == null) continue; if (!(binomialOpt() && c == 1 && nclass == 2)) // Binomial optimization toJavaTreeName(out.ip("preds[").p(nclass == 1 ? 0 : c + 1).p("] += "), mname, treeIdx, c).p(".score0(fdata);").nl(); } out.di(1).ip("}").nl(); // end of function out.di(1).ip("}").nl(); // end of forest class // Generate the pre-tree classes afterwards for (int c = 0; c < nclass; c++) { if (_output._treeKeys[treeIdx][c] == null) continue; if (!(binomialOpt() && c == 1 && nclass == 2)) { // Binomial optimization String javaClassName = toJavaTreeName(new SB(), mname, treeIdx, c).toString(); CompressedTree ct = _output.ctree(treeIdx, c); SB sb = new SB(); new TreeJCodeGen(SharedTreeModel.this, ct, sb, javaClassName, verboseCode).generate(); out.p(sb); } } } catch (Throwable t) { t.printStackTrace(); throw new IllegalArgumentException("Internal error creating the POJO.", t); } } }); } toJavaUnifyPreds(body); } protected abstract void toJavaUnifyPreds(SBPrintStream body); protected <T extends JCodeSB> T toJavaTreeName(T sb, String mname, int t, int c ) { return (T) sb.p(mname).p("_Tree_").p(t).p("_class_").p(c); } protected <T extends JCodeSB> T toJavaForestName(T sb, String mname, int t ) { return (T) sb.p(mname).p("_Forest_").p(t); } }
package org.jgroups.blocks; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.ChannelException; import java.io.Serializable; import java.util.HashMap; /** * Distributed lock manager is responsible for maintaining the lock information * consistent on all participating nodes. * * @author Roman Rokytskyy (rrokytskyy@acm.org) */ public class DistributedLockManager implements TwoPhaseVotingListener, LockManager { /** * This parameter means that lock acquisition expires after 5 seconds. * If there were no "commit" operation on prepared lock, then it * is treated as expired and is removed from the prepared locks table. */ private static final long ACQUIRE_EXPIRATION = 5000; /** * This parameter is used during lock releasing. If group fails to release * the lock during the specified period of time, unlocking fails. */ private static final long VOTE_TIMEOUT = 10000; // list of all prepared locks private final HashMap preparedLocks = new HashMap(); // list of all prepared releases private final HashMap preparedReleases = new HashMap(); // list of locks on the node private final HashMap heldLocks = new HashMap(); private final TwoPhaseVotingAdapter votingAdapter; private final Object id; protected final Log log=LogFactory.getLog(getClass()); /** * Create instance of this class. * * @param voteChannel instance of {@link VotingAdapter} that will be used * for voting purposes on the lock decrees. <tt>voteChannel()</tt> will * be wrapped by the instance of the {@link TwoPhaseVotingAdapter}. * * @param id the unique identifier of this lock manager. * * @todo check if the node with the same id is already in the group. */ public DistributedLockManager(VotingAdapter voteChannel, Object id) { this(new TwoPhaseVotingAdapter(voteChannel), id); } /** * Constructor for the DistributedLockManager_cl object. * * @param channel instance of {@link TwoPhaseVotingAdapter} * that will be used for voting purposes on the lock decrees. * * @param id the unique identifier of this lock manager. * * @todo check if the node with the same id is already in the group. */ public DistributedLockManager(TwoPhaseVotingAdapter channel, Object id) { this.id = id; this.votingAdapter = channel; this.votingAdapter.addListener(this); } /** * Performs local lock. This method also performs the clean-up of the lock * table, all expired locks are removed. */ private boolean localLock(LockDecree lockDecree) { // remove expired locks removeExpired(lockDecree); LockDecree localLock = (LockDecree) heldLocks.get(lockDecree.getKey()); if (localLock == null) { // promote lock into commited state lockDecree.commit(); // no lock exist, perform local lock, note: // we do not store locks that were requested by other manager. if (lockDecree.managerId.equals(id)) heldLocks.put(lockDecree.getKey(), lockDecree); // everything is fine :) return true; } else if (localLock.requester.equals(lockDecree.requester)) // requester already owns the lock return true; else // lock does not belong to requester return false; } /** * Returns <code>true</code> if the requested lock can be granted by the * current node. * * @param decree instance of <code>LockDecree</code> containing information * about the lock. */ private boolean canLock(LockDecree decree) { // clean expired locks removeExpired(decree); LockDecree lock = (LockDecree)heldLocks.get(decree.getKey()); if (lock == null) return true; else return lock.requester.equals(decree.requester); } /** * Returns <code>true</code> if the requested lock can be released by the * current node. * * @param decree instance of {@link LockDecree} containing information * about the lock. */ private boolean canRelease(LockDecree decree) { // clean expired locks removeExpired(decree); // we need to check only hold locks, because // prepared locks cannot contain the lock LockDecree lock = (LockDecree)heldLocks.get(decree.getKey()); if (lock == null) // check if this holds... return true; else if (!decree.managerId.equals(id)) { // If another manager tries to release the decree it is possible // that a merge of two splitted nets occured. // In this case, we tell the other manager to release the lock return true; } else return lock.requester.equals(decree.requester); } /** * Removes expired locks. * * @param decree instance of {@link LockDecree} describing the lock. */ private void removeExpired(LockDecree decree) { // remove the invalid (expired) lock LockDecree localLock = (LockDecree)heldLocks.get(decree.getKey()); if (localLock != null && !localLock.isValid()) heldLocks.remove(localLock.getKey()); } /** * Releases lock locally. * * @param lockDecree instance of {@link LockDecree} describing the lock. */ private boolean localRelease(LockDecree lockDecree) { // remove expired locks removeExpired(lockDecree); LockDecree localLock= (LockDecree) heldLocks.get(lockDecree.getKey()); if(localLock == null) { // no lock exist return true; } else if (!lockDecree.managerId.equals(id)) { // If another manager tries to release the decree it is possible // that a merge of two splitted nets occured. // In this case, we tell the other manager to release the lock, // but don't release our local version return true; } else if(localLock.requester.equals(lockDecree.requester)) { // requester owns the lock, release the lock heldLocks.remove(lockDecree.getKey()); return true; } else // lock does not belong to requester return false; } /** * Locks an object with <code>lockId</code> on behalf of the specified * <code>owner</code>. * * @param lockId <code>Object</code> representing the object to be locked. * @param owner object that requests the lock. * @param timeout time during which group members should decide * whether to grant a lock or not. * * @throws LockNotGrantedException when the lock cannot be granted. * * @throws ClassCastException if lockId or owner are not serializable. * * @throws ChannelException if something bad happened to underlying channel. */ public void lock(Object lockId, Object owner, int timeout) throws LockNotGrantedException, ChannelException { if (!(lockId instanceof Serializable) || !(owner instanceof Serializable)) throw new ClassCastException("DistributedLockManager " + "works only with serializable objects."); boolean acquired = votingAdapter.vote( new AcquireLockDecree(lockId, owner, id), timeout); if (!acquired) throw new LockNotGrantedException("Lock cannot be granted."); } /** * Unlocks an object with <code>lockId</code> on behalf of the specified * <code>owner</code>. * @param lockId <code>long</code> representing the object to be unlocked. * @param owner object that releases the lock. * * @throws LockNotReleasedException when the lock cannot be released. * @throws ClassCastException if lockId or owner are not serializable. */ public void unlock(Object lockId, Object owner) throws LockNotReleasedException, ChannelException { if (!(lockId instanceof Serializable) || !(owner instanceof Serializable)) throw new ClassCastException("DistributedLockManager " + "works only with serializable objects."); boolean released = votingAdapter.vote( new ReleaseLockDecree(lockId, owner, id), VOTE_TIMEOUT); if (!released) throw new LockNotReleasedException("Lock cannot be unlocked."); } /** * Checks the list of prepared locks/unlocks to determine if we are in the * middle of the two-phase commit process for the lock acqusition/release. * Here we do not tolerate if the request comes from the same node on behalf * of the same owner. * * @param preparedContainer either <code>preparedLocks</code> or * <code>preparedReleases</code> depending on the situation. * * @param requestedDecree instance of <code>LockDecree</code> representing * the lock. */ private boolean checkPrepared(HashMap preparedContainer, LockDecree requestedDecree) { LockDecree preparedDecree = (LockDecree)preparedContainer.get(requestedDecree.getKey()); // if prepared lock is not valid, remove it from the list if ((preparedDecree != null) && !preparedDecree.isValid()) { preparedContainer.remove(preparedDecree.getKey()); preparedDecree = null; } if (preparedDecree != null) { if (requestedDecree.requester.equals(preparedDecree.requester)) return true; else return false; } else // it was not prepared... sorry... return true; } /** * Prepare phase for the lock acquisition or release. * * @param decree should be an instance <code>LockDecree</code>, if not, * we throw <code>VoteException</code> to be ignored by the * <code>VoteChannel</code>. * * @return <code>true</code> when preparing the lock operation succeeds. * * @throws VoteException if we should be ignored during voting. */ public synchronized boolean prepare(Object decree) throws VoteException { if (!(decree instanceof LockDecree)) throw new VoteException("Uknown decree type. Ignore me."); if (decree instanceof AcquireLockDecree) { AcquireLockDecree acquireDecree = (AcquireLockDecree)decree; if(log.isDebugEnabled()) log.debug("Preparing to acquire decree " + acquireDecree.lockId); if (!checkPrepared(preparedLocks, acquireDecree)) // there is a prepared lock owned by third party return false; if (canLock(acquireDecree)) { preparedLocks.put(acquireDecree.getKey(), acquireDecree); return true; } else // we are unable to aquire local lock return false; } else if (decree instanceof ReleaseLockDecree) { ReleaseLockDecree releaseDecree = (ReleaseLockDecree)decree; if(log.isDebugEnabled()) log.debug("Preparing to release decree " + releaseDecree.lockId); if (!checkPrepared(preparedReleases, releaseDecree)) // there is a prepared release owned by third party return false; if (canRelease(releaseDecree)) { preparedReleases.put(releaseDecree.getKey(), releaseDecree); // we have local lock and the prepared lock return true; } else // we were unable to aquire local lock return false; } // we should not be here return false; } /** * Commit phase for the lock acquisition or release. * * @param decree should be an instance <code>LockDecree</code>, if not, * we throw <code>VoteException</code> to be ignored by the * <code>VoteChannel</code>. * * @return <code>true</code> when commiting the lock operation succeeds. * * @throws VoteException if we should be ignored during voting. */ public synchronized boolean commit(Object decree) throws VoteException { if (!(decree instanceof LockDecree)) throw new VoteException("Uknown decree type. Ignore me."); if (decree instanceof AcquireLockDecree) { if(log.isDebugEnabled()) log.debug("Committing decree acquisition " + ((LockDecree)decree).lockId); if (!checkPrepared(preparedLocks, (LockDecree)decree)) // there is a prepared lock owned by third party return false; if (localLock((LockDecree)decree)) { preparedLocks.remove(((LockDecree)decree).getKey()); return true; } else return false; } else if (decree instanceof ReleaseLockDecree) { if(log.isDebugEnabled()) log.debug("Committing decree release " + ((LockDecree)decree).lockId); if (!checkPrepared(preparedReleases, (LockDecree)decree)) // there is a prepared release owned by third party return false; if (localRelease((LockDecree)decree)) { preparedReleases.remove(((LockDecree)decree).getKey()); return true; } else return false; } // we should not be here return false; } /** * Abort phase for the lock acquisition or release. * * @param decree should be an instance <code>LockDecree</code>, if not, * we throw <code>VoteException</code> to be ignored by the * <code>VoteChannel</code>. * * @throws VoteException if we should be ignored during voting. */ public synchronized void abort(Object decree) throws VoteException { if (!(decree instanceof LockDecree)) throw new VoteException("Uknown decree type. Ignore me."); if (decree instanceof AcquireLockDecree) { if(log.isDebugEnabled()) log.debug("Aborting decree acquisition " + ((LockDecree)decree).lockId); if (!checkPrepared(preparedLocks, (LockDecree)decree)) // there is a prepared lock owned by third party return; preparedLocks.remove(((LockDecree)decree).getKey()); } else if (decree instanceof ReleaseLockDecree) { if(log.isDebugEnabled()) log.debug("Aborting decree release " + ((LockDecree)decree).lockId); if (!checkPrepared(preparedReleases, (LockDecree)decree)) // there is a prepared release owned by third party return; preparedReleases.remove(((LockDecree)decree).getKey()); } } /** * This class represents the lock */ public static class LockDecree implements Serializable { protected final Object lockId; protected final Object requester; protected final Object managerId; protected boolean commited; private LockDecree(Object lockId, Object requester, Object managerId) { this.lockId = lockId; this.requester = requester; this.managerId = managerId; } /** * Returns the key that should be used for Map lookup. */ public Object getKey() { return lockId; } /** * This is a place-holder for future lock expiration code. */ public boolean isValid() { return true; } public void commit() { this.commited = true; } /** * This is hashcode from the java.lang.Long class. */ public int hashCode() { return lockId.hashCode(); } public boolean equals(Object other) { if (other instanceof LockDecree) { return ((LockDecree)other).lockId.equals(this.lockId); } else { return false; } } } /** * This class represents the lock to be released. */ public static class AcquireLockDecree extends LockDecree { private final long creationTime; private AcquireLockDecree(LockDecree lockDecree) { this(lockDecree.lockId, lockDecree.requester, lockDecree.managerId); } private AcquireLockDecree(Object lockId, Object requester, Object managerId) { super(lockId, requester, managerId); this.creationTime = System.currentTimeMillis(); } /** * Lock aquire decree is valid for a <code>ACQUIRE_EXPIRATION</code> * time after creation and if the lock is still valid (in the * future locks will be leased for a predefined period of time). */ public boolean isValid() { boolean result = super.isValid(); if (!commited && result) result = ((creationTime + ACQUIRE_EXPIRATION) > System.currentTimeMillis()); return result; } } /** * This class represents the lock to be released. */ public static class ReleaseLockDecree extends LockDecree { ReleaseLockDecree(Object lockId, Object requester, Object managerId) { super(lockId, requester, managerId); } } }
package hex.schemas; import java.util.ArrayList; import java.util.List; import hex.Model; import hex.grid.Grid; import water.DKV; import water.Key; import water.api.API; import water.api.KeyV3; import water.api.ModelParametersSchema; import water.api.Schema; /** * REST endpoint representing single grid object. * * FIXME: Grid should contain also grid definition - model parameters * and definition of hyper parameters. */ public class GridSchemaV99 extends Schema<Grid, GridSchemaV99> { // Inputs @API(help = "Grid id") public KeyV3.GridKeyV3 grid_id; // Outputs @API(help = "Model IDs build by a grid search") public KeyV3.ModelKeyV3[] model_ids; @API(help = "Used hyper parameters.", direction = API.Direction.OUTPUT) public String[] hyper_names; @API(help = "List of failed parameters", direction = API.Direction.OUTPUT) public ModelParametersSchema[] failed_params; // Using common ancestor of XXXParamsV3 @API(help = "List of detailed failure messages", direction = API.Direction.OUTPUT) public String[] failure_details; @API(help = "List of detailed failure stack traces", direction = API.Direction.OUTPUT) public String[] failure_stack_traces; @API(help = "List of raw parameters causing model building failure", direction = API.Direction.OUTPUT) public String[][] failed_raw_params; @Override public Grid createImpl() { return Grid.GRID_PROTO; } @Override public GridSchemaV99 fillFromImpl(Grid grid) { Key<Model>[] gridModelKeys = grid.getModelKeys(); // Return only keys which are referencing to existing objects in DKV // However, here is still implicit race, since we are sending // keys to client, but referenced models can be deleted in meantime // Hence, client has to be responsible for handling this situation // - call getModel and check for null model List<Key> modelKeys = new ArrayList<>(gridModelKeys.length); // pre-allocate for (Key k : gridModelKeys) { if (k != null && DKV.get(k) != null) { modelKeys.add(k); } } KeyV3.ModelKeyV3[] modelIds = new KeyV3.ModelKeyV3[modelKeys.size()]; for (int i = 0; i < modelIds.length; i++) { modelIds[i] = new KeyV3.ModelKeyV3(modelKeys.get(i)); } grid_id = new KeyV3.GridKeyV3(grid._key); model_ids = modelIds; hyper_names = grid.getHyperNames(); failed_params = toModelParametersSchema(grid.getFailedParameters()); failure_details = grid.getFailureDetails(); failure_stack_traces = grid.getFailureStackTraces(); failed_raw_params = grid.getFailedRawParameters(); return this; } private ModelParametersSchema[] toModelParametersSchema(Model.Parameters[] modelParameters) { if (modelParameters==null) return null; ModelParametersSchema[] result = new ModelParametersSchema[modelParameters.length]; for (int i = 0; i < modelParameters.length; i++) { if (modelParameters[i] != null) { result[i] = (ModelParametersSchema) Schema.schema(Schema.getLatestVersion(), modelParameters[i]) .fillFromImpl(modelParameters[i]); } else { result[i] = null; } } return result; } }
package water; import java.net.*; import water.util.Log; /** * The Thread that looks for Multicast UDP Cloud requests. * * This thread just spins on reading multicast UDP packets from the kernel and * either dispatching on them directly itself (if the request is known short) * or queuing them up for worker threads. Multicast *Channels* are available * Java 7, but we are writing to Java 6 JDKs. SO back to the old-school * MulticastSocket. * @author <a href="mailto:cliffc@0xdata.com"></a> * @version 1.0 */ class MultiReceiverThread extends Thread { MultiReceiverThread() { super("Multi-UDP-R"); } // The Run Method. // Started by main() on a single thread, this code manages reading UDP packets @SuppressWarnings("resource") @Override public void run() { // No multicast? Then do not bother with listening for them if( H2O.STATIC_H2OS != null ) return; Thread.currentThread().setPriority(Thread.MAX_PRIORITY); MulticastSocket sock = null, errsock = null; InetAddress group = null, errgroup = null; boolean saw_error = false; // Loop forever accepting Cloud Management requests while( true ) { try { // Cleanup from any prior socket failures. Rare unless we're really sick. if( errsock != null && errgroup != null ) { // socket error AND group present final InetAddress tmp = errgroup; errgroup = null; errsock.leaveGroup(tmp); // Could throw, but errgroup cleared for next pass } if( errsock != null ) { // One time attempt a socket close final MulticastSocket tmp2 = errsock; errsock = null; tmp2.close(); // Could throw, but errsock cleared for next pass } if( saw_error ) Thread.sleep(1000); // prevent deny-of-service endless socket-creates saw_error = false; // Actually do the common-case setup of Inet multicast group if( group == null ) group = H2O.CLOUD_MULTICAST_GROUP; // More common-case setup of a MultiCast socket if( sock == null ) { sock = new MulticastSocket(H2O.CLOUD_MULTICAST_PORT); if( H2O.CLOUD_MULTICAST_IF != null ) sock.setNetworkInterface(H2O.CLOUD_MULTICAST_IF); sock.joinGroup(group); } // Receive a packet & handle it byte[] buf = new byte[AutoBuffer.MTU]; DatagramPacket pack = new DatagramPacket(buf,buf.length); sock.receive(pack); UDPReceiverThread.basic_packet_handling(new AutoBuffer(pack)); } catch( SocketException e ) { Log.err("Trying Multicast Interface, Group, Port - "+ H2O.CLOUD_MULTICAST_IF+" "+H2O.CLOUD_MULTICAST_GROUP+":"+H2O.CLOUD_MULTICAST_PORT, e); throw new RuntimeException(e); } catch( Exception e ) { Log.err("Trying Multicast Interface, Group, Port - "+ H2O.CLOUD_MULTICAST_IF+" "+H2O.CLOUD_MULTICAST_GROUP+":"+H2O.CLOUD_MULTICAST_PORT, e); // On any error from anybody, close all sockets & re-open saw_error = true; errsock = sock ; sock = null; // Signal error recovery on the next loop errgroup = group; group = null; } } } }
package org.nschmidt.csg; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.nschmidt.ldparteditor.data.GColour; import org.nschmidt.ldparteditor.data.GData1; import org.nschmidt.ldparteditor.data.GData3; import org.nschmidt.ldparteditor.data.Vertex; import org.nschmidt.ldparteditor.helpers.math.Vector3d; enum CSGOptimizerEdgeCollapse { INSTANCE; // TODO This epsilon should be accessible by the user! public static volatile double epsilon = 0.9999; public static boolean optimize(Random rnd, Map<Plane, List<GData3>> trianglesPerPlane, Map<GData3, IdAndPlane> optimization) { boolean result = false; for (List<GData3> triangles : trianglesPerPlane.values()) { final Set<VectorCSGd> verticesToProcess = new TreeSet<>(); final Map<VectorCSGd, List<GData3>> linkedSurfaceMap = new TreeMap<>(); final Map<GData3, VectorCSGd[]> trimap = new HashMap<>(); for (GData3 tri : triangles) { final VectorCSGd[] triverts = new VectorCSGd[]{ new VectorCSGd(tri.x1, tri.y1, tri.z1), new VectorCSGd(tri.x2, tri.y2, tri.z2), new VectorCSGd(tri.x3, tri.y3, tri.z3)}; verticesToProcess.add(triverts[0]); verticesToProcess.add(triverts[1]); verticesToProcess.add(triverts[2]); if (!linkedSurfaceMap.containsKey(triverts[0])) linkedSurfaceMap.put(triverts[0], new ArrayList<>()); if (!linkedSurfaceMap.containsKey(triverts[1])) linkedSurfaceMap.put(triverts[1], new ArrayList<>()); if (!linkedSurfaceMap.containsKey(triverts[2])) linkedSurfaceMap.put(triverts[2], new ArrayList<>()); linkedSurfaceMap.get(triverts[0]).add(tri); linkedSurfaceMap.get(triverts[1]).add(tri); linkedSurfaceMap.get(triverts[2]).add(tri); trimap.put(tri, triverts); } boolean foundOptimization = false; for (final VectorCSGd v : verticesToProcess) { if (foundOptimization) break; List<GData3> surfs = linkedSurfaceMap.get(v); // 1.1 Ist es ein eindeutiger Eckpunkt? if (surfs.size() == 1) { continue; } // 2. Ermittle alle angrenzenden Punkte final TreeSet<VectorCSGd> verts = new TreeSet<VectorCSGd>(); for (final GData3 g : surfs) { verts.addAll(Arrays.asList(trimap.get(g))); } // 3.2 Ist das Polygon geschlossen? final int delta = ((verts.size() - 1) - surfs.size()); final boolean polygonLoop = delta == 0; // 4. Entferne den Ursprungspunkt aus der Menge verts.remove(v); for (final VectorCSGd t : verts) { if (foundOptimization) break; final List<GData3> tsurfs = new ArrayList<>(linkedSurfaceMap.get(t)); final int oldcount = tsurfs.size(); tsurfs.removeAll(surfs); int vexp = 2; final int ds = oldcount - tsurfs.size(); if (ds == 1) { vexp = 1; } else if (ds != 2 || !polygonLoop) { continue; } // 5.2 t darf nur zwei angrenzende Punkte mit v teilen { final TreeSet<VectorCSGd> verts2 = new TreeSet<>(); for (final GData3 gData : new ArrayList<>(linkedSurfaceMap.get(t))) { verts2.addAll(Arrays.asList(trimap.get(gData))); } verts2.remove(t); verts2.retainAll(verts); if (verts2.size() != vexp) { continue; } } if (!polygonLoop) { boolean noInterpolation = true; VectorCSGd ref = t.minus(v); double m; if (delta == 1 && (m = ref.magnitude()) > 0.0) { ref = ref.dividedBy(m); for (VectorCSGd r : verts) { if (r != t) { VectorCSGd ref2 = v.minus(r); double m2 = ref2.magnitude(); if (m2 > 0.0) { ref2 = ref2.dividedBy(m2); double diskr = ref.dot(ref2); if (diskr > epsilon) { { final TreeSet<VectorCSGd> verts2 = new TreeSet<>(); for (final GData3 gData : new ArrayList<>(linkedSurfaceMap.get(r))) { verts2.addAll(Arrays.asList(trimap.get(gData))); } verts2.remove(r); verts2.retainAll(verts); if (verts2.size() != 1) { continue; } } noInterpolation = false; break; } } } } } if (noInterpolation) { continue; } } { boolean cont = false; final int surfcount = surfs.size(); VectorCSGd[][] surfsv = new VectorCSGd[surfcount][4]; Vector3d[] oldNormals = new Vector3d[surfcount]; Vector3d[] newNormals = new Vector3d[surfcount]; int s = 0; for (final GData3 gData : surfs) { int i = 0; for (VectorCSGd tv : trimap.get(gData)) { surfsv[s][i] = tv; i++; } oldNormals[s] = Vector3d.getNormal(new Vector3d(surfsv[s][0]), new Vector3d(surfsv[s][1]), new Vector3d(surfsv[s][2])); s++; } HashSet<Integer> ignoreSet = new HashSet<Integer>(); for (s = 0; s < surfcount; s++) { for (int i = 0; i < 3; i++) { if (surfsv[s][i].compareTo(t) == 0) { ignoreSet.add(s); } if (surfsv[s][i].compareTo(v) == 0) { surfsv[s][i] = t; } } if (!ignoreSet.contains(s)) { newNormals[s] = Vector3d.getNormal(new Vector3d(surfsv[s][0]), new Vector3d(surfsv[s][1]), new Vector3d(surfsv[s][2])); double angle = Vector3d.angle(oldNormals[s], newNormals[s]); if (angle > 3.0) { cont = true; break; } } } if (cont) { continue; } } // Als letzten Schritt => Kante zusammenfallen lassen // v -> t doOptimize(v, t, optimization, linkedSurfaceMap, trimap); foundOptimization = true; result = true; break; } } } return result; } private static void doOptimize(VectorCSGd v, VectorCSGd t, Map<GData3, IdAndPlane> optimization, Map<VectorCSGd, List<GData3>> linkedSurfaceMap, Map<GData3, VectorCSGd[]> trimap) { final List<GData3> affectedSurfaces = linkedSurfaceMap.get(v); for (GData3 g : affectedSurfaces) { Set<VectorCSGd> verts = new TreeSet<>(Arrays.asList(trimap.get(g))); if (!verts.contains(t)) { List<VectorCSGd> nv = new ArrayList<>(Arrays.asList(trimap.get(g))); int i = -1; if (nv.get(0).compareTo(v) == 0) i = 0; if (nv.get(1).compareTo(v) == 0) i = 1; if (nv.get(2).compareTo(v) == 0) i = 2; if (i > -1) { nv.set(i, t); optimization.put(createTriangle(g, nv.get(0), nv.get(1), nv.get(2)), optimization.get(g)); // Purple } } optimization.remove(g); } } private static GData3 createTriangle(GData3 idol, VectorCSGd a, VectorCSGd b, VectorCSGd c) { Vertex v1 = new Vertex((float) a.x, (float) a.y, (float) a.z); Vertex v2 = new Vertex((float) b.x, (float) b.y, (float) b.z); Vertex v3 = new Vertex((float) c.x, (float) c.y, (float) c.z); GData1 parent = idol.parent; GColour colour = new GColour(idol.colourNumber, idol.r, idol.g, idol.b, idol.a); return new GData3(v1, v2, v3, parent, colour, true); } }
package water.parser; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.zip.*; import jsr166y.CountedCompleter; import jsr166y.ForkJoinTask; import jsr166y.RecursiveAction; import water.*; import water.exceptions.H2OIllegalArgumentException; import water.parser.Parser.ColType; import water.parser.Parser.ColTypeInfo; import water.fvec.*; import water.fvec.Vec.VectorGroup; import water.nbhm.NonBlockingHashMap; import water.nbhm.NonBlockingSetInt; import water.util.ArrayUtils; import water.util.FrameUtils; import water.util.PrettyPrint; import water.util.Log; public final class ParseDataset extends Job<Frame> { private MultiFileParseTask _mfpt; // Access to partially built vectors for cleanup after parser crash // Keys are limited to ByteVec Keys and Frames-of-1-ByteVec Keys public static Frame parse(Key okey, Key... keys) { return parse(okey,keys,true, false,0/*guess header*/); } // Guess setup from inspecting the first Key only, then parse. // Suitable for e.g. testing setups, where the data is known to be sane. // NOT suitable for random user input! public static Frame parse(Key okey, Key[] keys, boolean delete_on_done, boolean singleQuote, int checkHeader) { return parse(okey,keys,delete_on_done,setup(keys[0],singleQuote,checkHeader)); } public static Frame parse(Key okey, Key[] keys, boolean delete_on_done, ParseSetup globalSetup) { return parse(okey,keys,delete_on_done,globalSetup,true).get(); } public static ParseDataset parse(Key okey, Key[] keys, boolean delete_on_done, ParseSetup globalSetup, boolean blocking) { ParseDataset job = forkParseDataset(okey,keys,globalSetup,delete_on_done); try { if( blocking ) job.get(); return job; } catch( Throwable ex ) { // Took a crash/NPE somewhere in the parser. Attempt cleanup. Futures fs = new Futures(); if( job != null ) { Keyed.remove(job._dest,fs); // Find & remove all partially-built output vecs & chunks if( job._mfpt != null ) job._mfpt.onExceptionCleanup(fs); } // Assume the input is corrupt - or already partially deleted after // parsing. Nuke it all - no partial Vecs lying around. for( Key k : keys ) Keyed.remove(k,fs); fs.blockForPending(); assert DKV.<Job>getGet(job._key).isStopped(); throw ex; } } public static ParseSetup setup(Key k, boolean singleQuote, int checkHeader) { byte[] bits = ZipUtil.getFirstUnzippedBytes(getByteVec(k)); ParseSetup globalSetup = ParseSetup.guessSetup(bits, singleQuote, checkHeader); if( globalSetup._ncols <= 0 ) throw new UnsupportedOperationException(globalSetup.toString()); return globalSetup; } // Allow both ByteVec keys and Frame-of-1-ByteVec static ByteVec getByteVec(Key key) { Iced ice = DKV.getGet(key); if(ice == null) throw new H2OIllegalArgumentException("Missing data","Did not find any data under key " + key); return (ByteVec)(ice instanceof ByteVec ? ice : ((Frame)ice).vecs()[0]); } static String [] genericColumnNames(int ncols){ String [] res = new String[ncols]; for(int i = 0; i < res.length; ++i) res[i] = "C" + String.valueOf(i+1); return res; } // Same parse, as a backgroundable Job public static ParseDataset forkParseDataset(final Key dest, final Key[] keys, final ParseSetup setup, boolean delete_on_done) { HashSet<String> conflictingNames = setup.checkDupColumnNames(); for( String x : conflictingNames ) throw new IllegalArgumentException("Found duplicate column name "+x); // Some quick sanity checks: no overwriting your input key, and a resource check. long totalParseSize=0; ByteVec bv; float dcr, maxDecompRatio = 0; for( int i=0; i<keys.length; i++ ) { Key k = keys[i]; if( dest.equals(k) ) throw new IllegalArgumentException("Destination key "+dest+" must be different from all sources"); if( delete_on_done ) for( int j=i+1; j<keys.length; j++ ) if( k==keys[j] ) throw new IllegalArgumentException("Source key "+k+" appears twice, delete_on_done must be false"); // estimate total size in bytes bv = getByteVec(k); dcr = ZipUtil.decompressionRatio(bv); if (dcr > maxDecompRatio) maxDecompRatio = dcr; if (maxDecompRatio > 1.0) totalParseSize += bv.length() * maxDecompRatio; // Sum of all input filesizes else // numerical issues was distorting files sizes when no decompression totalParseSize += bv.length(); } // Calc chunk-size, and set into the incoming FileVecs Iced ice = DKV.getGet(keys[0]); if (ice instanceof Frame && ((Frame) ice).vec(0) instanceof UploadFileVec) { setup._chunkSize = FileVec.DFLT_CHUNK_SIZE; } else { setup._chunkSize = FileVec.DFLT_CHUNK_SIZE;//Vec.calcOptimalChunkSize(totalParseSize, setup._ncols); } Log.info("Chunk size " + setup._chunkSize); for( int i = 0; i < keys.length; ++i ) { ice = DKV.getGet(keys[i]); Vec update = (ice instanceof Vec) ? (Vec)ice : ((Frame)ice).vec(0); if(update instanceof FileVec) { // does not work for byte vec ((FileVec) update)._chunkSize = setup._chunkSize; DKV.put(update._key, update); } } long memsz = H2O.CLOUD.memsz(); if( totalParseSize > memsz*4 ) throw new IllegalArgumentException("Total input file size of "+PrettyPrint.bytes(totalParseSize)+" is much larger than total cluster memory of "+PrettyPrint.bytes(memsz)+", please use either a larger cluster or smaller data."); // Fire off the parse ParseDataset job = new ParseDataset(dest); new Frame(job.dest(),new String[0],new Vec[0]).delete_and_lock(job._key); // Write-Lock BEFORE returning for( Key k : keys ) Lockable.read_lock(k,job._key); // Read-Lock BEFORE returning ParserFJTask fjt = new ParserFJTask(job, keys, setup, delete_on_done); // Fire off background parse job.start(fjt, totalParseSize); return job; } // Setup a private background parse job private ParseDataset(Key dest) { super(dest,"Parse"); } // Simple internal class doing background parsing, with trackable Job status public static class ParserFJTask extends water.H2O.H2OCountedCompleter { final ParseDataset _job; final Key[] _keys; final ParseSetup _setup; final boolean _delete_on_done; public ParserFJTask( ParseDataset job, Key[] keys, ParseSetup setup, boolean delete_on_done) { _job = job; _keys = keys; _setup = setup; _delete_on_done = delete_on_done; } @Override public void compute2() { parse_impl(_job, _keys, _setup, _delete_on_done); tryComplete(); } // Took a crash/NPE somewhere in the parser. Attempt cleanup. @Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter caller){ if( _job != null ) _job.cancel2(ex); return true; } @Override public void onCompletion(CountedCompleter caller) { _job.done(); } } private static class EnumMapping extends Iced { final int [][] map; public EnumMapping(int[][] map){this.map = map;} } // Top-level parser driver private static void parse_impl(ParseDataset job, Key[] fkeys, ParseSetup setup, boolean delete_on_done) { assert setup._ncols > 0; if( setup._columnNames != null && ( (setup._columnNames.length == 0) || (setup._columnNames.length == 1 && setup._columnNames[0].isEmpty())) ) setup._columnNames = null; // // FIXME: annoyingly front end sends column names as String[] {""} even if setup returned null if( fkeys.length == 0) { job.cancel(); return; } VectorGroup vg = getByteVec(fkeys[0]).group(); MultiFileParseTask mfpt = job._mfpt = new MultiFileParseTask(vg,setup,job._key,fkeys,delete_on_done); mfpt.doAll(fkeys); AppendableVec [] avs = mfpt.vecs(); Frame fr = null; // Calculate enum domain // Filter down to columns with some enums int n = 0; int [] ecols = new int[avs.length]; for( int i = 0; i < ecols.length; ++i ) if( avs[i].shouldBeEnum() ) ecols[n++] = i; ecols = Arrays.copyOf(ecols, n); // If we have any, go gather unified enum domains if( n > 0 ) { EnumFetchTask eft = new EnumFetchTask(mfpt._eKey, ecols).doAllNodes(); Categorical[] enums = eft._gEnums; ValueString[][] ds = new ValueString[ecols.length][]; EnumMapping [] emaps = new EnumMapping[H2O.CLOUD.size()]; int k = 0; for( int ei : ecols) avs[ei].setDomain(ValueString.toString(ds[k++] = enums[ei].computeColumnDomain())); for(int nodeId = 0; nodeId < H2O.CLOUD.size(); ++nodeId) { if(eft._lEnums[nodeId] == null)continue; int[][] emap = new int[ecols.length][]; for (int i = 0; i < ecols.length; ++i) { final Categorical e = eft._lEnums[nodeId][ecols[i]]; if(e == null) continue; emap[i] = MemoryManager.malloc4(e.maxId() + 1); Arrays.fill(emap[i], -1); for (int j = 0; j < ds[i].length; ++j) { ValueString vs = ds[i][j]; if (e.containsKey(vs)) { assert e.getTokenId(vs) <= e.maxId() : "maxIdx = " + e.maxId() + ", got " + e.getTokenId(vs); emap[i][e.getTokenId(vs)] = j; } } } emaps[nodeId] = new EnumMapping(emap); } fr = new Frame(job.dest(), setup._columnNames,AppendableVec.closeAll(avs)); // Some cols with enums lose their enum status (because they have more // number chunks than enum chunks); these no longer need (or want) enum // updating. Vec[] vecs = fr.vecs(); int j=0; for( int i=0; i<ecols.length; i++ ) { if( vecs[ecols[i]].isEnum() ) { ecols[j] = ecols[i]; ds[j] = ds[i]; for( int l=0; l<emaps.length; l++ ) if( emaps[l] != null ) emaps[l].map[j] = emaps[l].map[i]; j++; } } // Update enums to the globally agreed numbering Vec[] evecs = new Vec[j]; for( int i = 0; i < evecs.length; ++i ) evecs[i] = fr.vecs()[ecols[i]]; new EnumUpdateTask(ds, emaps, mfpt._chunk2Enum).doAll(evecs); } else { // No enums case fr = new Frame(job.dest(), setup._columnNames,AppendableVec.closeAll(avs)); } // SVMLight is sparse format, there may be missing chunks with all 0s, fill them in new SVFTask(fr).doAllNodes(); // unify any vecs with enums and strings to strings only new UnifyStrVecTask().doAll(fr); // Log any errors if( mfpt._errors != null ) for( String err : mfpt._errors ) Log.warn(err); logParseResults(job, fr); // Release the frame for overwriting fr.update(job._key); Frame fr2 = DKV.getGet(fr._key); assert fr2._names.length == fr2.numCols(); fr.unlock(job._key); // Remove CSV files from H2O memory if( delete_on_done ) for( Key k : fkeys ) assert DKV.get(k) == null : "Input key "+k+" not deleted during parse"; } /** Task to update enum (categorical) values to match the global numbering scheme. * Performs update in place so that values originally numbered using * node-local unordered numbering will be numbered using global numbering. * @author tomasnykodym */ private static class EnumUpdateTask extends MRTask<EnumUpdateTask> { private final ValueString [][] _gDomain; private final EnumMapping [] _emaps; private final int [] _chunk2Enum; private EnumUpdateTask(ValueString [][] gDomain, EnumMapping [] emaps, int [] chunk2Enum) { _gDomain = gDomain; _emaps = emaps; _chunk2Enum = chunk2Enum; } private int[][] emap(int nodeId) {return _emaps[nodeId].map;} @Override public void map(Chunk [] chks){ int[][] emap = emap(_chunk2Enum[chks[0].cidx()]); final int cidx = chks[0].cidx(); for(int i = 0; i < chks.length; ++i) { Chunk chk = chks[i]; if(_gDomain[i] == null) // killed, replace with all NAs DKV.put(chk.vec().chunkKey(chk.cidx()),new C0DChunk(Double.NaN,chk._len)); else if (!(chk instanceof CStrChunk)) { for( int j = 0; j < chk._len; ++j){ if( chk.isNA(j) )continue; long l = chk.at8(j); if (l < 0 || l >= emap[i].length) chk.reportBrokenEnum(i, j, l, emap, _gDomain[i].length); if(emap[i][(int)l] < 0) throw new RuntimeException(H2O.SELF.toString() + ": missing enum at col:" + i + ", line: " + (chk.start() + j) + ", val = " + l + ", chunk=" + chk.getClass().getSimpleName() + ", map = " + Arrays.toString(emap[i])); chk.set(j, emap[i][(int) l]); } } chk.close(cidx, _fs); } } } private static class EnumFetchTask extends MRTask<EnumFetchTask> { private final Key _k; private final int[] _ecols; private Categorical[] _gEnums; // global enums per column public Categorical[][] _lEnums; // local enums per node per column private EnumFetchTask(Key k, int[] ecols){_k = k;_ecols = ecols;} @Override public void setupLocal() { _lEnums = new Categorical[H2O.CLOUD.size()][]; if( !MultiFileParseTask._enums.containsKey(_k) ) return; _lEnums[H2O.SELF.index()] = _gEnums = MultiFileParseTask._enums.get(_k); // Null out any empty Enum structs; no need to ship these around. for( int i=0; i<_gEnums.length; i++ ) if( _gEnums[i].size()==0 ) _gEnums[i] = null; // if we are the original node (i.e. there will be no sending over wire), // we have to clone the enums not to share the same object (causes // problems when computing column domain and renumbering maps). // if( H2O.SELF.index() == _homeNode ) { // fixme: looks like need to clone even if not on home node in h2o-dev _gEnums = _gEnums.clone(); for(int i = 0; i < _gEnums.length; ++i) if( _gEnums[i] != null ) _gEnums[i] = _gEnums[i].deepCopy(); MultiFileParseTask._enums.remove(_k); } @Override public void reduce(EnumFetchTask etk) { if(_gEnums == null) { _gEnums = etk._gEnums; _lEnums = etk._lEnums; } else if (etk._gEnums != null) { for( int i : _ecols ) { if( _gEnums[i] == null ) _gEnums[i] = etk._gEnums[i]; else if( etk._gEnums[i] != null ) _gEnums[i].merge(etk._gEnums[i]); } for( int i = 0; i < _lEnums.length; ++i ) if( _lEnums[i] == null ) _lEnums[i] = etk._lEnums[i]; else assert etk._lEnums[i] == null; } } } // Run once on all nodes; fill in missing zero chunks private static class SVFTask extends MRTask<SVFTask> { private final Frame _f; private SVFTask( Frame f ) { _f = f; } @Override public void setupLocal() { Vec v0 = _f.anyVec(); ArrayList<RecursiveAction> rs = new ArrayList<RecursiveAction>(); for( int i = 0; i < v0.nChunks(); ++i ) { if( !v0.chunkKey(i).home() ) continue; final int fi = i; rs.add(new RecursiveAction() { @Override protected void compute() { // First find the nrows as the # rows of non-missing chunks; done on // locally-homed chunks only - to keep the data distribution. int nlines = 0; for( Vec vec : _f.vecs() ) { Value val = H2O.get(vec.chunkKey(fi)); // Local-get only if( val != null ) { nlines = ((Chunk)val.get())._len; break; } } final int fnlines = nlines; // Now fill in appropriate-sized zero chunks for(int j = 0; j < _f.numCols(); ++j) { Vec vec = _f.vec(j); Key k = vec.chunkKey(fi); Value val = H2O.get(k); // Local-get only if( val == null ) // Missing? Fill in w/zero chunk H2O.putIfMatch(k, new Value(k, new C0DChunk(0, fnlines)), null); } } }); } ForkJoinTask.invokeAll(rs); } @Override public void reduce( SVFTask drt ) {} } // Run once on all nodes; switch enum chunks over to string chunks private static class UnifyStrVecTask extends MRTask<UnifyStrVecTask> { private UnifyStrVecTask() {} @Override public void map(Chunk[] chunks) { for (Chunk c : chunks) { Vec v = c.vec(); if (v.isString() && c instanceof C4Chunk) { Key k = v.chunkKey(c.cidx()); NewChunk nc = new NewChunk(v, c.cidx()); for (int j = 0; j < c._len; ++j) if (c.isNA(j)) nc.addNA(); else nc.addStr(new ValueString(v.domain()[(int) c.at8(j)])); H2O.putIfMatch(k, new Value(k, nc.new_close()), H2O.get(k)); } } } } // We want to do a standard MRTask with a collection of file-keys (so the // files are parsed in parallel across the cluster), but we want to throttle // the parallelism on each node. private static class MultiFileParseTask extends MRTask<MultiFileParseTask> { private final ParseSetup _setup; // The expected column layout private final VectorGroup _vg; // vector group of the target dataset private final int _vecIdStart; // Start of available vector keys // Shared against all concurrent unrelated parses, a map to the node-local // Enum lists for each concurrent parse. private static NonBlockingHashMap<Key, Categorical[]> _enums = new NonBlockingHashMap<>(); // The Key used to sort out *this* parse's Categorical[] private final Key _eKey = Key.make(); // Eagerly delete Big Data private final boolean _delete_on_done; // Mapping from Chunk# to cluster-node-number holding the enum mapping. // It is either self for all the non-parallel parses, or the Chunk-home for parallel parses. private int[] _chunk2Enum; // Job Key, to unlock & remove raw parsed data; to report progress private final Key _job_key; // A mapping of Key+ByteVec to rolling total Chunk counts. private final int[] _fileChunkOffsets; // OUTPUT fields: FVecDataOut [] _dout; String[] _errors; int _reservedKeys; MultiFileParseTask(VectorGroup vg, ParseSetup setup, Key job_key, Key[] fkeys, boolean delete_on_done ) { _vg = vg; _setup = setup; _vecIdStart = _vg.reserveKeys(_reservedKeys = _setup._pType == ParserType.SVMLight ? 100000000 : setup._ncols); _delete_on_done = delete_on_done; _job_key = job_key; // A mapping of Key+ByteVec to rolling total Chunk counts. _fileChunkOffsets = new int[fkeys.length]; int len = 0; for( int i = 0; i < fkeys.length; ++i ) { _fileChunkOffsets[i] = len; len += getByteVec(fkeys[i]).nChunks(); } // Mapping from Chunk# to cluster-node-number _chunk2Enum = MemoryManager.malloc4(len); Arrays.fill(_chunk2Enum, -1); } private AppendableVec [] _vecs; @Override public void postGlobal(){ int n = _dout.length-1; while(_dout[n] == null && n != 0)--n; for(int i = 0; i <= n; ++i) { if (_dout[i] == null) { _dout[i] = _dout[n]; n while (n > i && _dout[n] == null) n } } if(n < _dout.length-1) _dout = Arrays.copyOf(_dout,n+1); if(_dout.length == 1) { _vecs = _dout[0]._vecs; return; } int nCols = 0; for(FVecDataOut dout:_dout) nCols = Math.max(dout._vecs.length,nCols); AppendableVec [] res = new AppendableVec[nCols]; int nchunks = 0; for(FVecDataOut dout:_dout) nchunks += dout.nChunks(); long [] espc = MemoryManager.malloc8(nchunks); for(int i = 0; i < res.length; ++i) { res[i] = new AppendableVec(_vg.vecKey(_vecIdStart + i), espc, 0); res[i].setTypes(MemoryManager.malloc1(nchunks)); } for(int i = 0; i < _dout.length; ++i) for(int j = 0; j < _dout[i]._vecs.length; ++j) res[j].setSubRange(_dout[i]._vecs[j]); if((res.length + _vecIdStart) < _reservedKeys) { Future f = _vg.tryReturnKeys(_vecIdStart + _reservedKeys, _vecIdStart + res.length); if (f != null) try { f.get(); } catch (InterruptedException e) { } catch (ExecutionException e) {} } _vecs = res; } private AppendableVec[] vecs(){ return _vecs; } @Override public void setupLocal() { _dout = new FVecDataOut[_keys.length]; } // Fetch out the node-local Categorical[] using _eKey and _enums hashtable private static Categorical[] enums(Key eKey, int ncols) { Categorical[] enums = _enums.get(eKey); if( enums != null ) return enums; enums = new Categorical[ncols]; for( int i = 0; i < enums.length; ++i ) enums[i] = new Categorical(); _enums.putIfAbsent(eKey, enums); return _enums.get(eKey); // Re-get incase lost insertion race } // Flag all chunk enums as being on local (self) private void chunksAreLocal( Vec vec, int chunkStartIdx, Key key ) { for(int i = 0; i < vec.nChunks(); ++i) _chunk2Enum[chunkStartIdx + i] = H2O.SELF.index(); // For Big Data, must delete data as eagerly as possible. Iced ice = DKV.get(key).get(); if( ice==vec ) { if( _delete_on_done ) vec.remove(); } else { Frame fr = (Frame)ice; if( _delete_on_done ) fr.delete(_job_key,new Futures()).blockForPending(); else if( fr._key != null ) fr.unlock(_job_key); } } private FVecDataOut makeDout(ParseSetup localSetup, int chunkOff, int nchunks) { AppendableVec [] avs = new AppendableVec[localSetup._ncols]; long [] espc = MemoryManager.malloc8(nchunks); for(int i = 0; i < avs.length; ++i) avs[i] = new AppendableVec(_vg.vecKey(i + _vecIdStart), espc, chunkOff); return localSetup._pType == ParserType.SVMLight ?new SVMLightFVecDataOut(_vg, _vecIdStart,chunkOff,enums(_eKey,localSetup._ncols), _setup._chunkSize, avs) :new FVecDataOut(_vg, chunkOff, enums(_eKey,localSetup._ncols), localSetup._ctypes, _setup._chunkSize, avs); } // Called once per file @Override public void map( Key key ) { // Get parser setup info for this chunk ByteVec vec = getByteVec(key); final int chunkStartIdx = _fileChunkOffsets[_lo]; byte[] zips = vec.getFirstBytes(); ZipUtil.Compression cpr = ZipUtil.guessCompressionMethod(zips); byte[] bits = ZipUtil.unzipBytes(zips,cpr,_setup._chunkSize); ParseSetup localSetup = _setup.guessSetup(bits,0/*guess header in each file*/); localSetup._chunkSize = _setup._chunkSize; if( !localSetup._isValid ) { _errors = localSetup._errors; chunksAreLocal(vec,chunkStartIdx,key); return; } // Parse the file try { switch( cpr ) { case NONE: if( localSetup._pType._parallelParseSupported ) { DParse dp = new DParse(_vg, localSetup, _vecIdStart, chunkStartIdx, this, key, vec.nChunks()); addToPendingCount(1); dp.setCompleter(this); dp.asyncExec(vec); for( int i = 0; i < vec.nChunks(); ++i ) _chunk2Enum[chunkStartIdx + i] = vec.chunkKey(i).home_node().index(); } else { InputStream bvs = vec.openStream(_job_key); _dout[_lo] = streamParse(bvs, localSetup, makeDout(localSetup,chunkStartIdx,vec.nChunks()), bvs); chunksAreLocal(vec,chunkStartIdx,key); } break; case ZIP: { // Zipped file; no parallel decompression; InputStream bvs = vec.openStream(_job_key); ZipInputStream zis = new ZipInputStream(bvs); ZipEntry ze = zis.getNextEntry(); // Get the *FIRST* entry // There is at least one entry in zip file and it is not a directory. if( ze != null && !ze.isDirectory() ) _dout[_lo] = streamParse(zis,localSetup,makeDout(localSetup,chunkStartIdx,vec.nChunks()), bvs); else zis.close(); // Confused: which zipped file to decompress chunksAreLocal(vec,chunkStartIdx,key); break; } case GZIP: { InputStream bvs = vec.openStream(_job_key); // Zipped file; no parallel decompression; _dout[_lo] = streamParse(new GZIPInputStream(bvs),localSetup,makeDout(localSetup,chunkStartIdx,vec.nChunks()),bvs); // set this node as the one which processed all the chunks chunksAreLocal(vec,chunkStartIdx,key); break; } } } catch( IOException ioe ) { throw new RuntimeException(ioe); } } // Reduce: combine errors from across files. // Roll-up other meta data @Override public void reduce( MultiFileParseTask mfpt ) { assert this != mfpt; // Collect & combine columns across files // Collect & combine columns across files if( _dout == null ) _dout = mfpt._dout; else if(_dout != mfpt._dout) _dout = ArrayUtils.append(_dout,mfpt._dout); if( _chunk2Enum == null ) _chunk2Enum = mfpt._chunk2Enum; else if(_chunk2Enum != mfpt._chunk2Enum) { // we're sharing global array! for( int i = 0; i < _chunk2Enum.length; ++i ) { if( _chunk2Enum[i] == -1 ) _chunk2Enum[i] = mfpt._chunk2Enum[i]; else assert mfpt._chunk2Enum[i] == -1 : Arrays.toString(_chunk2Enum) + " :: " + Arrays.toString(mfpt._chunk2Enum); } } _errors = ArrayUtils.append(_errors,mfpt._errors); } // Zipped file; no parallel decompression; decompress into local chunks, // parse local chunks; distribute chunks later. // private FVecDataOut streamParse( final InputStream is, final ParseSetup localSetup, int vecIdStart, int chunkStartIdx, InputStream bvs) throws IOException { private FVecDataOut streamParse( final InputStream is, final ParseSetup localSetup, FVecDataOut dout, InputStream bvs) throws IOException { // All output into a fresh pile of NewChunks, one per column Parser p = localSetup.parser(); // assume 2x inflation rate if( localSetup._pType._parallelParseSupported ) p.streamParseZip(is, dout, bvs); else p.streamParse (is, dout); // Parse all internal "chunks", until we drain the zip-stream dry. Not // real chunks, just flipping between 32K buffers. Fills up the single // very large NewChunk. dout.close(_fs); return dout; } private static class DParse extends MRTask<DParse> { private final ParseSetup _setup; private final int _vecIdStart; private final int _startChunkIdx; // for multifile parse, offset of the first chunk in the final dataset private final VectorGroup _vg; private FVecDataOut _dout; private final Key _eKey; // Parse-local-Enums key private final Key _job_key; private transient final MultiFileParseTask _outerMFPT; private transient final Key _srckey; // Source/text file to delete on done private transient NonBlockingSetInt _visited; private transient long [] _espc; final int _nchunks; DParse(VectorGroup vg, ParseSetup setup, int vecIdstart, int startChunkIdx, MultiFileParseTask mfpt, Key srckey,int nchunks) { super(mfpt); _vg = vg; _setup = setup; _vecIdStart = vecIdstart; _startChunkIdx = startChunkIdx; _outerMFPT = mfpt; _eKey = mfpt._eKey; _job_key = mfpt._job_key; _srckey = srckey; _nchunks = nchunks; } @Override public void setupLocal(){ super.setupLocal(); _visited = new NonBlockingSetInt(); _espc = MemoryManager.malloc8(_nchunks); } @Override public void map( Chunk in ) { AppendableVec [] avs = new AppendableVec[_setup._ncols]; for(int i = 0; i < avs.length; ++i) avs[i] = new AppendableVec(_vg.vecKey(_vecIdStart + i), _espc, _startChunkIdx); Categorical [] enums = enums(_eKey,_setup._ncols); // Break out the input & output vectors before the parse loop FVecDataIn din = new FVecDataIn(in); FVecDataOut dout; Parser p; switch(_setup._pType) { case CSV: p = new CsvParser(_setup); dout = new FVecDataOut(_vg,_startChunkIdx + in.cidx(), enums, null,_setup._chunkSize, avs); break; case ARFF: p = new CsvParser(_setup); dout = new FVecDataOut(_vg,_startChunkIdx + in.cidx(), enums, _setup._ctypes, _setup._chunkSize, avs); //TODO: use _setup._domains instead of enums break; case SVMLight: p = new SVMLightParser(_setup); dout = new SVMLightFVecDataOut(_vg, _vecIdStart, in.cidx() + _startChunkIdx, enums, _setup._chunkSize, avs); break; default: throw H2O.unimpl(); } p.parallelParse(in.cidx(),din,dout); (_dout = dout).close(_fs); Job.update(in._len,_job_key); // Record bytes parsed // remove parsed data right away (each chunk is used by 2) freeMem(in,0); freeMem(in,1); } private void freeMem(Chunk in, int off) { final int cidx = in.cidx()+off; if( _visited.add(cidx) ) return; // First visit; expect a 2nd so no freeing yet Value v = H2O.get(in.vec().chunkKey(cidx)); if( v == null || !v.isPersisted() ) return; // Not found, or not on disk somewhere v.freePOJO(); // Eagerly toss from memory v.freeMem(); } @Override public void reduce(DParse dp) { _dout.reduce(dp._dout); } @Override public void postGlobal() { super.postGlobal(); _outerMFPT._dout[_outerMFPT._lo] = _dout; _dout = null; // Reclaim GC eagerly // For Big Data, must delete data as eagerly as possible. Value val = DKV.get(_srckey); if( val == null ) return; Iced ice = val.get(); if( ice instanceof ByteVec ) { if( _outerMFPT._delete_on_done ) ((ByteVec)ice).remove(); } else { Frame fr = (Frame)ice; if( _outerMFPT._delete_on_done ) fr.delete(_outerMFPT._job_key,new Futures()).blockForPending(); else if( fr._key != null ) fr.unlock(_outerMFPT._job_key); } } } // Find & remove all partially built output chunks & vecs private Futures onExceptionCleanup(Futures fs) { int nchunks = _chunk2Enum.length; int ncols = _setup._ncols; for( int i = 0; i < ncols; ++i ) { Key vkey = _vg.vecKey(_vecIdStart + i); Keyed.remove(vkey,fs); for( int c = 0; c < nchunks; ++c ) DKV.remove(Vec.chunkKey(vkey,c),fs); } cancel(true); return fs; } } /** Parsed data output specialized for fluid vecs. * @author tomasnykodym */ static class FVecDataOut extends Iced implements Parser.StreamDataOut { protected transient NewChunk [] _nvs; protected AppendableVec []_vecs; protected final Categorical [] _enums; protected transient ColTypeInfo [] _ctypes; long _nLines; int _nCols; int _col = -1; final int _cidx; final int _chunkSize; boolean _closedVecs = false; int _nChunks; private final VectorGroup _vg; public int nChunks(){return _nChunks;} static final byte UCOL = 0; // unknown col type static final byte NCOL = 1; // numeric col type static final byte ECOL = 2; // enum col type static final byte TCOL = 3; // time col type static final byte ICOL = 4; // UUID col type static final byte SCOL = 5; // String col type public FVecDataOut(VectorGroup vg, int cidx, Categorical [] enums, ColTypeInfo [] ctypes, int chunkSize, AppendableVec [] avs){ if (ctypes != null) _ctypes = ctypes; else { _ctypes = new ColTypeInfo[avs.length]; for (int i=0; i < _ctypes.length;i++) _ctypes[i] = new ColTypeInfo(); } _vecs = avs; _nvs = new NewChunk[avs.length]; for(int i = 0; i < avs.length; ++i) _nvs[i] = _vecs[i].chunkForChunkIdx(cidx); _enums = enums; _nCols = avs.length; _cidx = cidx; _vg = vg; _chunkSize = chunkSize; } @Override public FVecDataOut reduce(Parser.StreamDataOut sdout){ FVecDataOut dout = (FVecDataOut)sdout; if( dout == null ) return this; _nCols = Math.max(_nCols,dout._nCols); _nChunks += dout._nChunks; if( dout!=null && _vecs != dout._vecs) { if(dout._vecs.length > _vecs.length) { AppendableVec [] v = _vecs; _vecs = dout._vecs; for(int i = 1; i < _vecs.length; ++i) _vecs[i]._espc = _vecs[0]._espc; dout._vecs = v; } for(int i = 0; i < dout._vecs.length; ++i) { // unify string and enum chunks if (_vecs[i].isString() && !dout._vecs[i].isString()) dout.enumCol2StrCol(i); else if (!_vecs[i].isString() && dout._vecs[i].isString()) { enumCol2StrCol(i); _ctypes[i]._type = ColType.STR; } _vecs[i].reduce(dout._vecs[i]); } } return this; } @Override public FVecDataOut close(){ Futures fs = new Futures(); close(fs); fs.blockForPending(); return this; } @Override public FVecDataOut close(Futures fs){ ++_nChunks; if( _nvs == null ) return this; // Might call close twice for(NewChunk nv:_nvs) nv.close(_cidx, fs); _nvs = null; // Free for GC return this; } @Override public FVecDataOut nextChunk(){ return new FVecDataOut(_vg, _cidx+1, _enums, _ctypes, _chunkSize, _vecs); } private Vec [] closeVecs(){ Futures fs = new Futures(); _closedVecs = true; Vec [] res = new Vec[_vecs.length]; for(int i = 0; i < _vecs[0]._espc.length; ++i){ int j = 0; while(j < _vecs.length && _vecs[j]._espc[i] == 0)++j; if(j == _vecs.length)break; final long clines = _vecs[j]._espc[i]; for(AppendableVec v:_vecs) { if(v._espc[i] == 0)v._espc[i] = clines; else assert v._espc[i] == clines:"incompatible number of lines: " + v._espc[i] + " != " + clines; } } for(int i = 0; i < _vecs.length; ++i) res[i] = _vecs[i].close(fs); _vecs = null; // Free for GC fs.blockForPending(); return res; } @Override public void newLine() { if(_col >= 0){ ++_nLines; for(int i = _col+1; i < _nCols; ++i) addInvalidCol(i); } _col = -1; } @Override public void addNumCol(int colIdx, long number, int exp) { if( colIdx < _nCols ) { _nvs[_col = colIdx].addNum(number, exp); if(_ctypes[colIdx]._type == ColType.UNKNOWN ) _ctypes[colIdx]._type = ColType.NUM; } } @Override public final void addInvalidCol(int colIdx) { if(colIdx < _nCols) _nvs[_col = colIdx].addNA(); } @Override public boolean isString(int colIdx) { return (colIdx < _nCols) && (_ctypes[colIdx]._type == ColType.ENUM || _ctypes[colIdx]._type == ColType.STR);} @Override public void addStrCol(int colIdx, ValueString str) { if(colIdx < _nvs.length){ if(_ctypes[colIdx]._type == ColType.NUM){ // support enforced types addInvalidCol(colIdx); return; } if(_ctypes[colIdx]._type == ColType.UNKNOWN && ParseTime.attemptTimeParse(str) > 0) _ctypes[colIdx]._type = ColType.TIME; if( _ctypes[colIdx]._type == ColType.UNKNOWN ) { // Attempt UUID parse int old = str.get_off(); ParseTime.attemptUUIDParse0(str); ParseTime.attemptUUIDParse1(str); if( str.get_off() != -1 ) _ctypes[colIdx]._type = ColType.UUID; str.setOff(old); } if( _ctypes[colIdx]._type == ColType.TIME ) { long l = ParseTime.attemptTimeParse(str); if( l == Long.MIN_VALUE ) addInvalidCol(colIdx); else { int time_pat = ParseTime.decodePat(l); // Get time pattern l = ParseTime.decodeTime(l); // Get time addNumCol(colIdx, l, 0); // Record time in msec _nvs[_col]._timCnt[time_pat]++; // Count histo of time parse patterns } } else if( _ctypes[colIdx]._type == ColType.UUID ) { // UUID column? Only allow UUID parses long lo = ParseTime.attemptUUIDParse0(str); long hi = ParseTime.attemptUUIDParse1(str); if( str.get_off() == -1 ) { lo = C16Chunk._LO_NA; hi = C16Chunk._HI_NA; } if( colIdx < _nCols ) _nvs[_col = colIdx].addUUID(lo, hi); } else if( _ctypes[colIdx]._type == ColType.STR ) { _nvs[_col = colIdx].addStr(str); } else { if(!_enums[colIdx].isMapFull()) { int id = _enums[_col = colIdx].addKey(str); if (_ctypes[colIdx]._type == ColType.UNKNOWN && id > 1) _ctypes[colIdx]._type = ColType.ENUM; _nvs[colIdx].addEnum(id); } else { // maxed out enum map, convert col to string chunk _ctypes[_col = colIdx]._type = ColType.STR; enumCol2StrCol(colIdx); _nvs[colIdx].addStr(str); } } } } private void enumCol2StrCol(int colIdx) { //build local value2key map for enums Categorical enums = _enums[colIdx].deepCopy(); ValueString emap[] = new ValueString[enums.maxId()+1]; ValueString keys[] = enums._map.keySet().toArray(new ValueString[enums.size()]); for (ValueString str:keys) // adjust for enum ids using 1-based indexing emap[enums._map.get(str)-1] = str; //swap in string NewChunk in place of enum NewChunk _nvs[colIdx] = _nvs[colIdx].convertEnum2Str(emap); //Log.info("enumCol2StrCol"); } /** Adds double value to the column. */ @Override public void addNumCol(int colIdx, double value) { if (Double.isNaN(value)) { addInvalidCol(colIdx); } else { double d= value; int exp = 0; long number = (long)d; while (number != d) { d = d * 10; --exp; number = (long)d; } addNumCol(colIdx, number, exp); } } @Override public void setColumnNames(String [] names){} @Override public final void rollbackLine() {} @Override public void invalidLine(String err) { newLine(); } } private static class SVMLightFVecDataOut extends FVecDataOut { protected final VectorGroup _vg; int _vecIdStart; public SVMLightFVecDataOut(VectorGroup vg, int vecIdStart, int cidx, Categorical [] enums, int chunkSize, AppendableVec [] avs){ super(vg, cidx, enums, null, chunkSize, avs); _vg = vg; _vecIdStart = vecIdStart; _nvs = new NewChunk[avs.length]; for(int i = 0; i < _nvs.length; ++i) _nvs[i] = new NewChunk(_vecs[i], _cidx, true); _col = 0; } @Override public void addNumCol(int colIdx, long number, int exp) { assert colIdx >= _col; if(colIdx >= _vecs.length) addColumns(colIdx+1); _nvs[colIdx].addZeros((int)_nLines - _nvs[colIdx]._len); _nvs[colIdx].addNum(number, exp); _col = colIdx+1; } @Override public void newLine() { ++_nLines; _col = 0; } @Override public void addStrCol(int idx, ValueString str){addInvalidCol(idx);} @Override public boolean isString(int idx){return false;} @Override public FVecDataOut close(Futures fs) { for(NewChunk nc:_nvs) { nc.addZeros((int) _nLines - nc._len); assert nc._len == _nLines:"incompatible number of lines after parsing chunk, " + _nLines + " != " + nc._len; } _nCols = _nvs.length; return super.close(fs); } private void addColumns(int ncols){ if(ncols > _nvs.length){ int _nCols = _vecs.length; _nvs = Arrays.copyOf(_nvs , ncols); _vecs = Arrays.copyOf(_vecs , ncols); _ctypes= Arrays.copyOf(_ctypes, ncols); for(int i = _nCols; i < ncols; ++i) { _vecs[i] = new AppendableVec(_vg.vecKey(i+_vecIdStart),_vecs[0]._espc,_vecs[0]._chunkOff); _nvs[i] = new NewChunk(_vecs[i], _cidx, true); } } } } /** * Parser data in taking data from fluid vec chunk. * @author tomasnykodym */ private static class FVecDataIn implements Parser.DataIn { final Vec _vec; Chunk _chk; int _idx; final long _firstLine; public FVecDataIn(Chunk chk){ _chk = chk; _idx = _chk.cidx(); _firstLine = chk.start(); _vec = chk.vec(); } @Override public byte[] getChunkData(int cidx) { if(cidx != _idx) _chk = cidx < _vec.nChunks()?_vec.chunkForChunkIdx(_idx = cidx):null; return (_chk == null)?null:_chk.getBytes(); } @Override public int getChunkDataStart(int cidx) { return -1; } @Override public void setChunkDataStart(int cidx, int offset) { } } // Log information about the dataset we just parsed. private static void logParseResults(ParseDataset job, Frame fr) { try { long numRows = fr.anyVec().length(); Log.info("Parse result for " + job.dest() + " (" + Long.toString(numRows) + " rows):"); Futures fs = new Futures(); Vec[] vecArr = fr.vecs(); for(Vec v:vecArr) v.startRollupStats(fs); fs.blockForPending(); int namelen = 0; for (String s : fr.names()) namelen = Math.max(namelen, s.length()); String format = " %"+namelen+"s %11s %12s %12s %11s %8s %6s"; Log.info(String.format(format, "ColV2", "type", "min", "max", "NAs", "constant", "numLevels")); // get all rollups started in parallell, otherwise this takes ages! for( int i = 0; i < vecArr.length; i++ ) { Vec v = vecArr[i]; boolean isCategorical = v.isEnum(); boolean isConstant = v.isConst(); boolean isString = v.isString(); String CStr = String.format("%"+namelen+"s:", fr.names()[i]); String typeStr = String.format("%s", (v.isUUID() ? "UUID" : (isCategorical ? "categorical" : (isString ? "string" : "numeric")))); String minStr = isString ? "" : String.format("%g", v.min()); String maxStr = isString ? "" : String.format("%g", v.max()); long numNAs = v.naCnt(); String naStr = (numNAs > 0) ? String.format("%d", numNAs) : ""; String isConstantStr = isConstant ? "constant" : ""; String numLevelsStr = isCategorical ? String.format("%d", v.domain().length) : (isString ? String.format("%d", v.nzCnt()) : ""); boolean printLogSeparatorToStdout = false; boolean printColumnToStdout; { // Print information to stdout for this many leading columns. final int MAX_HEAD_TO_PRINT_ON_STDOUT = 10; // Print information to stdout for this many trailing columns. final int MAX_TAIL_TO_PRINT_ON_STDOUT = 10; if (vecArr.length <= (MAX_HEAD_TO_PRINT_ON_STDOUT + MAX_TAIL_TO_PRINT_ON_STDOUT)) { // For small numbers of columns, print them all. printColumnToStdout = true; } else if (i < MAX_HEAD_TO_PRINT_ON_STDOUT) { printColumnToStdout = true; } else if (i == MAX_HEAD_TO_PRINT_ON_STDOUT) { printLogSeparatorToStdout = true; printColumnToStdout = false; } else if ((i + MAX_TAIL_TO_PRINT_ON_STDOUT) < vecArr.length) { printColumnToStdout = false; } else { printColumnToStdout = true; } } if (printLogSeparatorToStdout) System.out.println("Additional column information only sent to log file..."); String s = String.format(format, CStr, typeStr, minStr, maxStr, naStr, isConstantStr, numLevelsStr); Log.info(s,printColumnToStdout); } Log.info(FrameUtils.chunkSummary(fr).toString()); } catch(Exception ignore) {} // Don't fail due to logging issues. Just ignore them. } }
package org.nschmidt.ldparteditor.data; import java.math.BigDecimal; import java.util.Set; import java.util.TreeSet; import org.eclipse.jface.dialogs.IDialogConstants; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.data.tools.IdenticalVertexRemover; import org.nschmidt.ldparteditor.data.tools.Merger; import org.nschmidt.ldparteditor.dialogs.direction.DirectionDialog; import org.nschmidt.ldparteditor.enums.MergeTo; import org.nschmidt.ldparteditor.enums.Threshold; import org.nschmidt.ldparteditor.helpers.Manipulator; import org.nschmidt.ldparteditor.helpers.composite3d.SelectorSettings; import org.nschmidt.ldparteditor.helpers.math.Rational; import org.nschmidt.ldparteditor.helpers.math.Vector3d; import org.nschmidt.ldparteditor.helpers.math.Vector3r; import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow; public class VM21Merger extends VM20Manipulator { protected VM21Merger(DatFile linkedDatFile) { super(linkedDatFile); } public void merge(MergeTo mode, boolean syncWithTextEditor, boolean directional) { if (linkedDatFile.isReadOnly()) return; final Vector3r dir; // Get a direction if necessary... if (directional) { if (linkedDatFile.getLastSelectedComposite() == null) { return; } Manipulator manipulator = linkedDatFile.getLastSelectedComposite().getManipulator(); if (new DirectionDialog(Editor3DWindow.getWindow().getShell(), manipulator).open() != IDialogConstants.OK_ID) { return; } if (!DirectionDialog.calculateDirection(manipulator)) { return; } dir = new Vector3r(new Vertex(DirectionDialog.getDirection())); } else { dir = null; } Vector3d newVertex = new Vector3d(); Set<Vertex> originVerts = new TreeSet<Vertex>(); if (mode != MergeTo.LAST_SELECTED) { originVerts.addAll(selectedVertices); for (GData2 g : selectedLines) { for (Vertex v : lines.get(g)) { originVerts.add(v); } } for (GData3 g : selectedTriangles) { for (Vertex v : triangles.get(g)) { originVerts.add(v); } } for (GData4 g : selectedQuads) { for (Vertex v : quads.get(g)) { originVerts.add(v); } } for (GData5 g : selectedCondlines) { for (Vertex v : condlines.get(g)) { originVerts.add(v); } } } switch (mode) { case AVERAGE: if (originVerts.size() == 0) return; for (Vertex v : originVerts) { newVertex = Vector3d.add(newVertex, new Vector3d(v)); } final BigDecimal size = new BigDecimal(originVerts.size()); newVertex.setX(newVertex.X.divide(size, Threshold.mc)); newVertex.setY(newVertex.Y.divide(size, Threshold.mc)); newVertex.setZ(newVertex.Z.divide(size, Threshold.mc)); break; case LAST_SELECTED: if (lastSelectedVertex == null || !vertexLinkedToPositionInFile.containsKey(lastSelectedVertex)) return; newVertex = new Vector3d(lastSelectedVertex); lastSelectedVertex = null; break; case NEAREST_EDGE: case NEAREST_EDGE_SPLIT: case NEAREST_FACE: if (originVerts.size() == 0) return; { // This is a little bit more complex. // First, I had to extend the selection to adjacent data, // so the nearest edge will not be adjacent to the (selected) origin vertex for (Vertex v : originVerts) { for (VertexManifestation mani : vertexLinkedToPositionInFile.get(v)) { GData gd = mani.getGdata(); switch (gd.type()) { case 2: selectedLines.add((GData2) gd); break; case 3: selectedTriangles.add((GData3) gd); break; case 4: selectedQuads.add((GData4) gd); break; case 5: selectedCondlines.add((GData5) gd); break; default: continue; } selectedData.add(gd); } // Then invert the selection, so that getMinimalDistanceVertexToLines() will snap on the target selectInverse(new SelectorSettings()); // And using changeVertexDirectFast() to do the merge boolean modified = false; if (mode == MergeTo.NEAREST_EDGE) { for (Vertex vertex : originVerts) { final Object[] target = getMinimalDistanceVerticesToLines(vertex, false); modified = changeVertexDirectFast(vertex, (Vertex) target[2], true) || modified; } } else if (mode == MergeTo.NEAREST_EDGE_SPLIT) { for (Vertex vertex : originVerts) { final Object[] target = getMinimalDistanceVerticesToLines(vertex, false); modified = changeVertexDirectFast(vertex, (Vertex) target[2], true) || modified; // And split at target position! modified = split((Vertex) target[0], (Vertex) target[1], (Vertex) target[2]) || modified; } } else { if (directional) { // FIXME NEEDS IMPLEMENTATION!!! for (Vertex vertex : originVerts) { } } else { for (Vertex vertex : originVerts) { final Vertex target = getMinimalDistanceVertexToSurfaces(vertex); modified = changeVertexDirectFast(vertex, target, true) || modified; } } } clearSelection(); if (modified) { IdenticalVertexRemover.removeIdenticalVertices(this, linkedDatFile, false, true); clearSelection(); setModified_NoSync(); } } } if (syncWithTextEditor) { syncWithTextEditors(true); } return; case NEAREST_VERTEX: if (originVerts.size() == 0) return; { float minDist = Float.MAX_VALUE; Set<Vertex> allVerticesMinusSelection = new TreeSet<Vertex>(); allVerticesMinusSelection.addAll(getVertices()); allVerticesMinusSelection.removeAll(originVerts); clearSelection(); for (Vertex vertex2 : originVerts) { selectedVertices.clear(); selectedVertices.add(vertex2); Vertex minVertex = new Vertex(0f, 0f, 0f); Vector4f next = vertex2.toVector4fm(); for (Vertex vertex : allVerticesMinusSelection) { Vector4f sub = Vector4f.sub(next, vertex.toVector4fm(), null); float d2 = sub.lengthSquared(); if (d2 < minDist) { minVertex = vertex; minDist = d2; } } newVertex = new Vector3d(minVertex); Merger.mergeTo(new Vertex(newVertex), this, linkedDatFile, false); } clearSelection(); setModified_NoSync(); } if (syncWithTextEditor) { syncWithTextEditors(true); } return; default: return; } Merger.mergeTo(new Vertex(newVertex), this, linkedDatFile, syncWithTextEditor); clearSelection(); validateState(); } private void projectRayOnTriangleWithDistance( Vector3r vector3r, Vector3r dirN, Vector3r tv, Vector3r tv2, Vector3r tv3, Vector3r r, Rational[] distance) { Rational diskr = Rational.ZERO; Vector3r vert0 = new Vector3r(tv); Vector3r vert1 = new Vector3r(tv2); Vector3r vert2 = new Vector3r(tv3); Vector3r corner1 = Vector3r.sub(vert1, vert0); Vector3r corner2 = Vector3r.sub(vert2, vert0); Vector3r orig2 = new Vector3r(vector3r); Vector3r dir2 = new Vector3r(dirN); Vector3r pvec = Vector3r.cross(dir2, corner2); diskr = Vector3r.dot(corner1, pvec); if (diskr.abs().compareTo(Rational.ZERO) == 0) return; Rational inv_diskr = Rational.ONE.divide(diskr); Vector3r tvec = Vector3r.sub(orig2, vert0); Rational u = Vector3r.dot(tvec, pvec).multiply(inv_diskr); if (u.compareTo(Rational.ZERO) < 0 || u.compareTo(Rational.ONE) > 1) return; Vector3r qvec = Vector3r.cross(tvec, corner1); Rational v = Vector3r.dot(dir2, pvec).multiply(inv_diskr); if (v.compareTo(Rational.ZERO) < 0 || u.add(v).compareTo(Rational.ONE) > 0) return; Rational t = Vector3r.dot(corner2, qvec).multiply(inv_diskr); if (distance[0] == null) { distance[0] = t; } if (t.compareTo(Rational.ZERO) < 0 || t.compareTo(distance[0]) > 0) return; distance[0] = t; r.setX(orig2.X.add(dir2.X.multiply(t))); r.setY(orig2.Y.add(dir2.Y.multiply(t))); r.setZ(orig2.Z.add(dir2.Z.multiply(t))); return; } }
package water.rapids; import water.DKV; import water.MRTask; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import java.util.*; public class ASTStringOps { //merp } class ASTStrSplit extends ASTUniPrefixOp { String _split; ASTStrSplit() { super(new String[]{"strsplit", "x", "split"}); } @Override String opStr() { return "strsplit"; } @Override ASTOp make() { return new ASTStrSplit(); } ASTStrSplit parse_impl(Exec E) { AST ary = E.parse(); _split = E.nextStr(); E.eatEnd(); ASTStrSplit res = (ASTStrSplit) clone(); res._asts = new AST[]{ary}; return res; } @Override void apply(Env env) { Frame fr = env.popAry(); if (fr.numCols() != 1) throw new IllegalArgumentException("strsplit requires a single column."); final String[] old_domains = fr.anyVec().domain(); final String[][] new_domains = newDomains(old_domains, _split); final String regex = _split; Frame fr2 = new MRTask() { @Override public void map(Chunk[] cs, NewChunk[] ncs) { Chunk c = cs[0]; for (int i = 0; i < c._len; ++i) { int idx = (int)c.at8(i); String s = old_domains[idx]; String[] ss = s.split(regex); int cnt = 0; for (String s1 : ss) { int n_idx = Arrays.asList(new_domains[cnt]).indexOf(s1); if (n_idx == -1) ncs[cnt++].addNA(); else ncs[cnt++].addNum(n_idx); } if (cnt < ncs.length) for (; cnt < ncs.length; ++cnt) ncs[cnt].addNA(); } } }.doAll(new_domains.length, fr).outputFrame(null,null,new_domains); env.pushAry(fr2); } // each domain level may split in its own uniq way. // hold onto a hashset of domain levels for each "new" column private String[][] newDomains(String[] domains, String regex) { ArrayList<HashSet<String>> strs = new ArrayList<>(); // loop over each level in the domain HashSet<String> x; // used all over for (String domain : domains) { String[] news = domain.split(regex); // split the domain on the regex for( int i = 0; i < news.length; ++i ) { // we have a "new" column, must add a new HashSet to the array list and start tracking levels for this "i" if( strs.size() == i ) { x = new HashSet<>(); x.add(news[i]); strs.add(x); } else { // ok not a new column // whip out the current set of levels and add the new one strs.get(i).add(news[i]); } } } // now loop over and create the String[][] result String[][] doms = new String[strs.size()][]; for (int i = 0; i < strs.size(); ++i) { x = strs.get(i); doms[i] = new String[x.size()]; for (int j = 0; j < x.size(); ++j) doms[i][j] = (String)x.toArray()[j]; } return doms; } } // mutating call class ASTToLower extends ASTUniPrefixOp { @Override String opStr() { return "tolower"; } @Override ASTOp make() { return new ASTToLower(); } @Override void apply(Env env) { if( !env.isAry() ) { throw new IllegalArgumentException("tolower only operates on a single vector!"); } Frame fr = env.popAry(); if (fr.numCols() != 1) throw new IllegalArgumentException("tolower only takes a single column of data. Got "+ fr.numCols()+" columns."); String[] dom = fr.anyVec().domain(); for (int i = 0; i < dom.length; ++i) dom[i] = dom[i].toLowerCase(Locale.ENGLISH); fr.anyVec().setDomain(dom); if( fr._key!=null && DKV.getGet(fr._key)!=null) DKV.put(fr._key, fr); env.pushAry(fr); } } class ASTToUpper extends ASTUniPrefixOp { @Override String opStr() { return "tolower"; } @Override ASTOp make() { return new ASTToUpper(); } @Override void apply(Env env) { if( !env.isAry() ) { throw new IllegalArgumentException("tolower only operates on a single vector!"); } Frame fr = env.popAry(); if (fr.numCols() != 1) throw new IllegalArgumentException("tolower only takes a single column of data. Got "+ fr.numCols()+" columns."); String[] dom = fr.anyVec().domain(); for (int i = 0; i < dom.length; ++i) dom[i] = dom[i].toUpperCase(Locale.ENGLISH); fr.anyVec().setDomain(dom); if( fr._key!=null && DKV.getGet(fr._key)!=null) DKV.put(fr._key, fr); env.pushAry(fr); } } class ASTStrSub extends ASTUniPrefixOp { String _pattern; String _replacement; boolean _ignoreCase; ASTStrSub() { super(new String[]{"sub", "pattern", "replacement", "x", "ignore.case"}); } @Override String opStr() { return "sub"; } @Override ASTOp make() { return new ASTStrSub(); } ASTStrSub parse_impl(Exec E) { _pattern = E.nextStr(); _replacement = E.nextStr(); AST ary = E.parse(); AST a = E.parse(); if( a instanceof ASTId ) _ignoreCase = ((ASTNum)E._env.lookup((ASTId)a))._d==1; E.eatEnd(); ASTStrSub res = (ASTStrSub) clone(); res._asts = new AST[]{ary}; return res; } @Override void apply(Env env) { Frame fr = env.popAry(); if (fr.numCols() != 1) throw new IllegalArgumentException("sub works on a single column at a time."); final String replacement = _replacement; final String pattern = _pattern; String[] doms = fr.anyVec().domain(); for (int i = 0; i < doms.length; ++i) doms[i] = _ignoreCase ? doms[i].toLowerCase(Locale.ENGLISH).replaceFirst(pattern, replacement) : doms[i].replaceFirst(pattern, replacement); fr.anyVec().setDomain(doms); if( fr._key!=null && DKV.getGet(fr._key)!=null) DKV.put(fr._key, fr); env.pushAry(fr); } } class ASTGSub extends ASTStrSub { ASTGSub() { super(); } @Override String opStr() { return "gsub"; } @Override ASTOp make() { return new ASTGSub(); } @Override void apply(Env env) { Frame fr = env.popAry(); if (fr.numCols() != 1) throw new IllegalArgumentException("sub works on a single column at a time."); final String replacement = _replacement; final String pattern = _pattern; String[] doms = fr.anyVec().domain(); for (int i = 0; i < doms.length; ++i) doms[i] = _ignoreCase ? doms[i].toLowerCase(Locale.ENGLISH).replaceAll(pattern, replacement) : doms[i].replaceAll(pattern, replacement); fr.anyVec().setDomain(doms); if( fr._key!=null && DKV.getGet(fr._key)!=null) DKV.put(fr._key, fr); env.pushAry(fr); } } class ASTTrim extends ASTUniPrefixOp { ASTTrim() { super(new String[]{"trim","x"}); } @Override String opStr() { return "trim"; } @Override ASTOp make() { return new ASTTrim(); } @Override void apply(Env env) { Frame fr = env.popAry(); if (fr.numCols() != 1) throw new IllegalArgumentException("trim works on a single column at a time."); String[] doms = fr.anyVec().domain(); for (int i = 0; i < doms.length; ++i) doms[i] = doms[i].trim(); fr.anyVec().setDomain(doms); if( fr._key!=null && DKV.getGet(fr._key)!=null) DKV.put(fr._key, fr); env.pushAry(fr); } } //class ASTPaste extends ASTUniPrefixOp { // ASTPaste() { super(); } // @Override String opStr() { return "paste"; } // @Override ASTOp make() { return new ASTPaste(); } // ASTPaste parse_impl(Exec E) { // @Override void apply(Env env) { // Frame fr = env.popAry(); //class ASTSample extends ASTOp { // ASTSample() { super(new String[]{"sample", "ary", "nobs", "seed"}, // new Type[]{Type.ARY, Type.ARY, Type.DBL, Type.DBL}, // OPF_PREFIX, OPP_PREFIX, OPA_RIGHT); } // @Override String opStr() { return "sample"; } // @Override ASTOp make() { return new ASTSample(); } // @Override void apply(Env env, int argcnt, ASTApply apply) { // final double seed = env.popDbl(); // final double nobs = env.popDbl(); // String skey = env.key(); // Frame fr = env.popAry(); // long[] espc = fr.anyVec()._espc; // long[] chk_sizes = new long[espc.length]; // final long[] css = new long[espc.length]; // for (int i = 0; i < espc.length-1; ++i) // chk_sizes[i] = espc[i+1] - espc[i]; // chk_sizes[chk_sizes.length-1] = fr.numRows() - espc[espc.length-1]; // long per_chunk_sample = (long) Math.floor(nobs / (double)espc.length); // long defecit = (long) (nobs - per_chunk_sample*espc.length) ; // // idxs is an array list of chunk indexes for adding to the sample size. Chunks with no defecit can not be "sampled" as candidates. // ArrayList<Integer> idxs = new ArrayList<Integer>(); // for (int i = 0; i < css.length; ++i) { // // get the max allowed rows to sample from the chunk // css[i] = Math.min(per_chunk_sample, chk_sizes[i]); // // if per_chunk_sample > css[i] => spread around the defecit to meet number of rows requirement. // long def = per_chunk_sample - css[i]; // // no more "room" in chunk `i` // if (def >= 0) { // defecit += def; // // else `i` has "room" // if (chk_sizes[i] > per_chunk_sample) idxs.add(i); // if (defecit > 0) { // Random rng = new Random(seed != -1 ? (long)seed : System.currentTimeMillis()); // while (defecit > 0) { // if (idxs.size() <= 0) break; // // select chunks at random and add to the number of rows they should sample, // // up to the number of rows in the chunk. // int rand = rng.nextInt(idxs.size()); // if (css[idxs.get(rand)] == chk_sizes[idxs.get(rand)]) { // idxs.remove(rand); // continue; // css[idxs.get(rand)]++; // defecit--; // Frame fr2 = new MRTask2() { // @Override public void map(Chunk[] chks, NewChunk[] nchks) { // int N = chks[0]._len; // int m = 0; // long n = css[chks[0].cidx()]; // int row = 0; // Random rng = new Random(seed != -1 ? (long)seed : System.currentTimeMillis()); // while( m < n) { // double u = rng.nextDouble(); // if ( (N - row)* u >= (n - m)) { // row++; // } else { // for (int i = 0; i < chks.length; ++i) nchks[i].addNum(chks[i].at0(row)); // row++; m++; // }.doAll(fr.numCols(), fr).outputFrame(fr.names(), fr.domains()); // env.subRef(fr, skey); // env.poppush(1, fr2, null); //class ASTRevalue extends ASTOp { // ASTRevalue(){ super(new String[]{"revalue", "x", "replace", "warn_missing"}, // new Type[]{Type.ARY, Type.ARY, Type.STR, Type.DBL}, // OPF_PREFIX, // OPP_PREFIX, OPA_RIGHT); } // @Override String opStr() { return "revalue"; } // @Override ASTOp make() { return new ASTRevalue(); } // @Override void apply(Env env, int argcnt, ASTApply apply) { // final boolean warn_missing = env.popDbl() == 1; // final String replace = env.popStr(); // String skey = env.key(); // Frame fr = env.popAry(); // String[] old_dom = fr.anyVec()._domain; // HashMap<String, String> dom_map = hashMap(replace); // for (int i = 0; i < old_dom.length; ++i) { // if (dom_map.containsKey(old_dom[i])) { // old_dom[i] = dom_map.get(old_dom[i]); // dom_map.remove(old_dom[i]); // if (dom_map.size() > 0 && warn_missing) { // for (String k : dom_map.keySet()) { // env._warnings = Arrays.copyOf(env._warnings, env._warnings.length + 1); // env._warnings[env._warnings.length - 1] = "Warning: old value " + k + " not a factor level."; // private HashMap<String, String> hashMap(String replace) { // HashMap<String, String> map = new HashMap<String, String>(); // //replace is a ';' separated string. Each piece after splitting is a key:value pair. // String[] maps = replace.split(";"); // for (String s : maps) { // String[] pair = s.split(":"); // String key = pair[0]; // String value = pair[1]; // map.put(key, value); // return map;
package org.nutz.mvc.impl.processor; import javax.servlet.http.HttpServletRequest; import org.nutz.lang.Lang; import org.nutz.lang.Strings; import org.nutz.lang.util.Context; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.mvc.ActionContext; import org.nutz.mvc.ActionInfo; import org.nutz.mvc.NutConfig; import org.nutz.mvc.View; import org.nutz.mvc.ViewMaker; import org.nutz.mvc.ViewMaker2; import org.nutz.mvc.view.ViewWrapper; import org.nutz.mvc.view.VoidView; public class ViewProcessor extends AbstractProcessor { protected View view; public static final String DEFAULT_ATTRIBUTE = "obj"; private static final Log log = Logs.get(); @Override public void init(NutConfig config, ActionInfo ai) throws Throwable { //jsonView,String!! if("json".equals(ai.getOkView()) && String.class.equals(ai.getMethod().getReturnType())) { log.warn("Not a good idea : Return String ,and using JsonView!! (Using @Ok(\"raw\") or return map/list/pojo)--> " + Lang.simpleMetodDesc(ai.getMethod())); } view = evalView(config, ai, ai.getOkView()); } public void process(ActionContext ac) throws Throwable { Object re = ac.getMethodReturn(); Object err = ac.getError(); if (re != null && re instanceof View) { if (re instanceof ViewWrapper) putRequestAttribute(ac.getRequest(), ((ViewWrapper)re).getData()); ((View) re).render(ac.getRequest(), ac.getResponse(), err); } else { putRequestAttribute(ac.getRequest(), null == re ? err : re); view.render(ac.getRequest(), ac.getResponse(), null == re ? err : re); } doNext(ac); } /** * attribute */ public static void putRequestAttribute(HttpServletRequest req, Object re){ if (null != re){ if(re instanceof Context){ Context context = (Context) re; for(String key : context.keys()){ req.setAttribute(key, context.get(key)); } } else { req.setAttribute(ViewProcessor.DEFAULT_ATTRIBUTE, re); } } } public static View evalView(NutConfig config, ActionInfo ai, String viewType) { if (Strings.isBlank(viewType)) return new VoidView(); String str = viewType; int pos = str.indexOf(':'); String type, value; if (pos > 0) { type = Strings.trim(str.substring(0, pos).toLowerCase()); value = Strings.trim(pos >= (str.length() - 1) ? null : str.substring(pos + 1)); } else { type = str; value = null; } for (ViewMaker maker : ai.getViewMakers()) { if (maker instanceof ViewMaker2) { View view = ((ViewMaker2)maker).make(config, ai, type, value); if (view != null) return view; } View view = maker.make(config.getIoc(), type, value); if (null != view) return view; } throw Lang.makeThrow("Can not eval %s(\"%s\") View for %s", viewType, str, ai.getMethod()); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyil.lang; import java.util.*; import wyil.util.*; public abstract class Code { // Bytecode Constructors public static Assert Assert(String label) { return get(new Assert(label)); } public static BinOp BinOp(Type type, BOp op) { return get(new BinOp(type,op)); } public static Const Const(Value constant) { return get(new Const(constant)); } public static Convert Convert(Type from, Type to) { return get(new Convert(from,to)); } public static final Debug debug = new Debug(); public static DictLoad DictLoad(Type.Dictionary type) { return get(new DictLoad(type)); } public static End End(String label) { return get(new End(label)); } public static ExternJvm ExternJvm(List<wyjvm.lang.Bytecode> bytecodes) { return get(new ExternJvm(bytecodes)); } public static Fail Fail(String label) { return get(new Fail(label)); } public static FieldLoad FieldLoad(Type.Record type, String field) { return get(new FieldLoad(type,field)); } public static Goto Goto(String label) { return get(new Goto(label)); } public static Invoke Invoke(Type.Fun fun, NameID name, boolean retval) { return get(new Invoke(fun,name,retval)); } public static Load Load(Type type, int reg) { return get(new Load(type,reg)); } public static ListLength ListLength(Type.List type) { return get(new ListLength(type)); } public static SubList SubList(Type.List type) { return get(new SubList(type)); } public static ListAppend ListAppend(Type.List type, OpDir dir) { return get(new ListAppend(type,dir)); } public static ListLoad ListLoad(Type.List type) { return get(new ListLoad(type)); } public static Loop Loop(String label, Collection<Integer> modifies) { return get(new Loop(label,modifies)); } public static ForAll ForAll(Type type, int var, String label, Collection<Integer> modifies) { return get(new ForAll(type, var, label,modifies)); } public static MultiStore MultiStore(Type type, Collection<Integer> regs) { return get(new MultiStore(type,regs)); } /** * Construct a <code>newdict</code> bytecode which constructs a new dictionary * and puts it on the stack. * * @param type * @return */ public static NewDict NewDict(Type.Dictionary type, int nargs) { return get(new NewDict(type,nargs)); } /** * Construct a <code>newset</code> bytecode which constructs a new set * and puts it on the stack. * * @param type * @return */ public static NewSet NewSet(Type.Set type, int nargs) { return get(new NewSet(type,nargs)); } /** * Construct a <code>newlist</code> bytecode which constructs a new list * and puts it on the stack. * * @param type * @return */ public static NewList NewList(Type.List type, int nargs) { return get(new NewList(type,nargs)); } /** * Construct a <code>newtuple</code> bytecode which constructs a new tuple * and puts it on the stack. * * @param type * @return */ public static NewTuple NewTuple(Type.Tuple type, int nargs) { return get(new NewTuple(type, nargs)); } /** * Construct a <code>newrecord</code> bytecode which constructs a new record * and puts it on the stack. * * @param type * @return */ public static NewRecord NewRecord(Type.Record type) { return get(new NewRecord(type)); } public static Return Return(Type t) { return get(new Return(t)); } public static IfGoto IfGoto(Type type, COp cop, String label) { return get(new IfGoto(type,cop,label)); } public static IfType IfType(Type type, int slot, Type test, String label) { return get(new IfType(type,slot,test,label)); } public static IndirectSend IndirectSend(Type.Fun fun, boolean synchronous, boolean retval) { return get(new IndirectSend(fun,synchronous,retval)); } public static IndirectInvoke IndirectInvoke(Type.Fun fun, boolean retval) { return get(new IndirectInvoke(fun,retval)); } public static Label Label(String label) { return get(new Label(label)); } public static final Skip Skip = new Skip(); public static SetLength SetLength(Type.Set type) { return get(new SetLength(type)); } public static SetUnion SetUnion(Type.Set type, OpDir dir) { return get(new SetUnion(type,dir)); } public static SetIntersect SetIntersect(Type.Set type, OpDir dir) { return get(new SetIntersect(type,dir)); } public static SetDifference SetDifference(Type.Set type, OpDir dir) { return get(new SetDifference(type,dir)); } public static StringAppend StringAppend(OpDir dir) { return get(new StringAppend(dir)); } public static SubString SubString() { return get(new SubString()); } public static StringLength StringLength() { return get(new StringLength()); } public static StringLoad StringLoad() { return get(new StringLoad()); } public static Send Send(Type.Fun fun, NameID name, boolean synchronous, boolean retval) { return get(new Send(fun,name,synchronous,retval)); } public static Store Store(Type type, int reg) { return get(new Store(type,reg)); } public static Switch Switch(Type type, String defaultLabel, Collection<Pair<Value, String>> cases) { return get(new Switch(type,defaultLabel,cases)); } public static Throw Throw(Type t) { return get(new Throw(t)); } public static Negate Negate(Type type) { return get(new Negate(type)); } public static Spawn Spawn(Type.Process type) { return get(new Spawn(type)); } public static ProcLoad ProcLoad(Type.Process type) { return get(new ProcLoad(type)); } public static Update Update(Type type, int slot, int level, Collection<String> fields) { return get(new Update(type,slot,level,fields)); } // Bytecode Implementations public static final class Assert extends Code { public final String target; private Assert(String target) { this.target = target; } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Assert) { return target.equals(((Assert)o).target); } return false; } public String toString() { return "assert " + target; } } public enum BOp { ADD{ public String toString() { return "add"; } }, SUB{ public String toString() { return "sub"; } }, MUL{ public String toString() { return "mul"; } }, DIV{ public String toString() { return "div"; } }, REM{ public String toString() { return "rem"; } } }; /** * A binary operation (e.g. +,-,*,/) takes two items off the stack and * pushes a single result. * * @author djp * */ public static final class BinOp extends Code { public final BOp bop; public final Type type; private BinOp(Type type, BOp bop) { if(bop == null) { throw new IllegalArgumentException("BinOp bop argument cannot be null"); } this.bop = bop; this.type = type; } public int hashCode() { if(type == null) { return bop.hashCode(); } else { return type.hashCode() + bop.hashCode(); } } public boolean equals(Object o) { if(o instanceof BinOp) { BinOp bo = (BinOp) o; return (type == bo.type || (type != null && type .equals(bo.type))) && bop.equals(bo.bop); } return false; } public String toString() { return toString(bop.toString(),type); } } /** * A catch bytecode is similar to a switch. It identifies a block within * which exception handlers are active. * * @author djp * */ public static final class Catch extends Code { } /** * A convert operation represents a conversion from a value of one type to * another. The purpose of the conversion bytecode is to make it easy for * implementations which have different representations of data types to * convert between them. */ public static final class Convert extends Code { public final Type from; public final Type to; private Convert(Type from, Type to) { if(to == null) { throw new IllegalArgumentException("Convert to argument cannot be null"); } this.from = from; this.to = to; } public int hashCode() { if(from == null) { return to.hashCode(); } else { return from.hashCode() + to.hashCode(); } } public boolean equals(Object o) { if(o instanceof Convert) { Convert c = (Convert) o; return (from == c.from || (from != null && from.equals(c.from))) && to.equals(c.to); } return false; } public String toString() { return "convert " + from + " to " + to; } } /** * A const bytecode pushes a constant value onto the stack. This includes * integer constants, rational constants, list constants, set constants, * dictionary constants, function constants, etc. * * @author djp * */ public static final class Const extends Code { public final Value constant; private Const(Value constant) { this.constant = constant; } public int hashCode() { return constant.hashCode(); } public boolean equals(Object o) { if(o instanceof Const) { Const c = (Const) o; return constant.equals(c.constant); } return false; } public String toString() { return toString("const " + constant,constant.type()); } } public static final class Debug extends Code { Debug() {} public int hashCode() { return 101; } public boolean equals(Object o) { return o instanceof Debug; } public String toString() { return "debug"; } } public static final class DictLoad extends Code { public final Type.Dictionary type; private DictLoad(Type.Dictionary type) { this.type = type; } public int hashCode() { if(type == null) { return 235; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof DictLoad) { DictLoad i = (DictLoad) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("dictload",type); } } public static final class End extends Label { End(String label) { super(label); } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if(o instanceof End) { End e = (End) o; return e.label.equals(label); } return false; } public String toString() { return "end " + label; } } public static final class ExternJvm extends Code { public final List<wyjvm.lang.Bytecode> bytecodes; ExternJvm(List<wyjvm.lang.Bytecode> bytecodes) { this.bytecodes = new ArrayList(bytecodes); } public int hashCode() { return bytecodes.hashCode(); } public boolean equals(Object o) { if(o instanceof ExternJvm) { ExternJvm e = (ExternJvm) o; return e.bytecodes.equals(bytecodes); } return false; } public String toString() { return "externjvm"; } } public static final class Fail extends Code { public final String msg; private Fail(String msg) { this.msg = msg; } public int hashCode() { return msg.hashCode(); } public boolean equals(Object o) { if(o instanceof Fail) { return msg.equals(((Fail)o).msg); } return false; } public String toString() { return "fail " + msg; } } /** * The fieldload bytecode pops a record alias from the stack and reads the * value from the given field, pusing it back onto the stack. * * @author djp * */ public static final class FieldLoad extends Code { public final Type.Record type; public final String field; private FieldLoad(Type.Record type, String field) { if (field == null) { throw new IllegalArgumentException( "FieldLoad field argument cannot be null"); } this.type = type; this.field = field; } public int hashCode() { if(type != null) { return type.hashCode() + field.hashCode(); } else { return field.hashCode(); } } public Type fieldType() { return type.fields().get(field); } public boolean equals(Object o) { if(o instanceof FieldLoad) { FieldLoad i = (FieldLoad) o; return (i.type == type || (type != null && type.equals(i.type))) && field.equals(i.field); } return false; } public String toString() { return toString("fieldload " + field,type); } } public static final class Goto extends Code { public final String target; private Goto(String target) { this.target = target; } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Goto) { return target.equals(((Goto)o).target); } return false; } public String toString() { return "goto " + target; } } public static final class IfGoto extends Code { public final Type type; public final COp op; public final String target; private IfGoto(Type type, COp op, String target) { if(op == null) { throw new IllegalArgumentException("IfGoto op argument cannot be null"); } if(target == null) { throw new IllegalArgumentException("IfGoto target argument cannot be null"); } this.type = type; this.op = op; this.target = target; } public int hashCode() { if(type == null) { return op.hashCode() + target.hashCode(); } else { return type.hashCode() + op.hashCode() + target.hashCode(); } } public boolean equals(Object o) { if(o instanceof IfGoto) { IfGoto ig = (IfGoto) o; return op == ig.op && target.equals(ig.target) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { return toString("if" + op + " goto " + target,type); } } public enum COp { EQ() { public String toString() { return "eq"; } }, NEQ{ public String toString() { return "ne"; } }, LT{ public String toString() { return "lt"; } }, LTEQ{ public String toString() { return "le"; } }, GT{ public String toString() { return "gt"; } }, GTEQ{ public String toString() { return "ge"; } }, ELEMOF{ public String toString() { return "in"; } }, SUBSET{ public String toString() { return "sb"; } }, SUBSETEQ{ public String toString() { return "sbe"; } } }; public static final class IfType extends Code { public final Type type; public final int slot; public final Type test; public final String target; private IfType(Type type, int slot, Type test, String target) { if(test == null) { throw new IllegalArgumentException("IfGoto op argument cannot be null"); } if(target == null) { throw new IllegalArgumentException("IfGoto target argument cannot be null"); } this.type = type; this.slot = slot; this.test = test; this.target = target; } public int hashCode() { if(type == null) { return test.hashCode() + target.hashCode(); } else { return type.hashCode() + test.hashCode() + target.hashCode(); } } public boolean equals(Object o) { if(o instanceof IfType) { IfType ig = (IfType) o; return test.equals(ig.test) && slot == ig.slot && target.equals(ig.target) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { if(slot >= 0) { return toString("if" + test + " " + slot + " goto " + target,type); } else { return toString("if" + test + " goto " + target,type); } } } public static final class IndirectInvoke extends Code { public final Type.Fun type; public final boolean retval; private IndirectInvoke(Type.Fun type, boolean retval) { this.type = type; this.retval = retval; } public int hashCode() { if(type != null) { return type.hashCode(); } else { return 123; } } public boolean equals(Object o) { if(o instanceof IndirectInvoke) { IndirectInvoke i = (IndirectInvoke) o; return retval == i.retval && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { if(retval) { return toString("indirectinvoke",type); } else { return toString("vindirectinvoke",type); } } } public static final class IndirectSend extends Code { public final boolean synchronous; public final boolean retval; public final Type.Fun type; private IndirectSend(Type.Fun type, boolean synchronous, boolean retval) { this.type = type; this.synchronous = synchronous; this.retval = retval; } public int hashCode() { if(type != null) { return type.hashCode(); } else { return 123; } } public boolean equals(Object o) { if(o instanceof IndirectSend) { IndirectSend i = (IndirectSend) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { if(synchronous) { if(retval) { return toString("isend",type); } else { return toString("ivsend",type); } } else { return toString("iasend",type); } } } public static final class Invoke extends Code { public final Type.Fun type; public final NameID name; public final boolean retval; private Invoke(Type.Fun type, NameID name, boolean retval) { this.type = type; this.name = name; this.retval = retval; } public int hashCode() { if(type == null) { return name.hashCode(); } else { return type.hashCode() + name.hashCode(); } } public boolean equals(Object o) { if (o instanceof Invoke) { Invoke i = (Invoke) o; return name.equals(i.name) && retval == i.retval && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { if(retval) { return toString("invoke " + name,type); } else { return toString("vinvoke " + name,type); } } } public static class Label extends Code { public final String label; private Label(String label) { this.label = label; } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof Label) { return label.equals(((Label) o).label); } return false; } public String toString() { return "." + label; } } public static final class ListAppend extends Code { public final OpDir dir; public final Type.List type; private ListAppend(Type.List type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("ListAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof ListAppend) { ListAppend setop = (ListAppend) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("listappend" + dir.toString(),type); } } public static final class ListLength extends Code { public final Type.List type; private ListLength(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 124987; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof ListLength) { ListLength setop = (ListLength) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("listlength",type); } } public static final class SubList extends Code { public final Type.List type; private SubList(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 124987; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof SubList) { SubList setop = (SubList) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("sublist",type); } } public static final class ListLoad extends Code { public final Type.List type; private ListLoad(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 235; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof ListLoad) { ListLoad i = (ListLoad) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("listload",type); } } public static final class Load extends Code { public final Type type; public final int slot; private Load(Type type, int slot) { this.type = type; this.slot = slot; } public int hashCode() { if(type == null) { return slot; } else { return type.hashCode() + slot; } } public boolean equals(Object o) { if(o instanceof Load) { Load i = (Load) o; return slot == i.slot && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { return toString("load " + slot,type); } } public static class Loop extends Code { public final String target; public final HashSet<Integer> modifies; private Loop(String target, Collection<Integer> modifies) { this.target = target; this.modifies = new HashSet<Integer>(modifies); } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Loop) { Loop f = (Loop) o; return target.equals(f.target) && modifies.equals(f.modifies); } return false; } public String toString() { return "loop " + modifies; } } public static final class ForAll extends Loop { public final int slot; public final Type type; private ForAll(Type type, int slot, String target, Collection<Integer> modifies) { super(target,modifies); this.type = type; this.slot = slot; } public int hashCode() { return super.hashCode() + slot; } public boolean equals(Object o) { if(o instanceof ForAll) { ForAll f = (ForAll) o; return target.equals(f.target) && type.equals(f.type) && slot == f.slot && modifies.equals(f.modifies); } return false; } public String toString() { return toString("forall " + slot + " " + modifies,type); } } public static final class Update extends Code { public final Type type; public final int level; public final int slot; public final ArrayList<String> fields; private Update(Type type, int slot, int level, Collection<String> fields) { if (fields == null) { throw new IllegalArgumentException( "FieldStore fields argument cannot be null"); } this.type = type; this.slot = slot; this.level = level; this.fields = new ArrayList<String>(fields); } public int hashCode() { if(type == null) { return level + fields.hashCode(); } else { return type.hashCode() + slot + level + fields.hashCode(); } } public boolean equals(Object o) { if (o instanceof Update) { Update i = (Update) o; return (i.type == type || (type != null && type.equals(i.type))) && level == i.level && slot == i.slot && fields.equals(i.fields); } return false; } public String toString() { String fs = fields.isEmpty() ? "" : " "; boolean firstTime=true; for(String f : fields) { if(!firstTime) { fs += "."; } firstTime=false; fs += f; } return toString("multistore " + slot + " #" + level + fs,type); } } public static final class NewDict extends Code { public final Type.Dictionary type; public final int nargs; private NewDict(Type.Dictionary type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode() + nargs; } } public boolean equals(Object o) { if(o instanceof NewDict) { NewDict i = (NewDict) o; return (type == i.type || (type != null && type.equals(i.type))) && nargs == i.nargs; } return false; } public String toString() { return toString("newdict #" + nargs,type); } } public static final class NewRecord extends Code { public final Type.Record type; private NewRecord(Type.Record type) { this.type = type; } public int hashCode() { if(type == null) { return 952; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewRecord) { NewRecord i = (NewRecord) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("newrec",type); } } public static final class NewTuple extends Code { public final Type.Tuple type; public final int nargs; private NewTuple(Type.Tuple type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode() + nargs; } } public boolean equals(Object o) { if(o instanceof NewTuple) { NewTuple i = (NewTuple) o; return nargs == i.nargs && (type == i.type || (type != null && type.equals(i.type))); } return false; } public String toString() { return toString("newtuple #" + nargs,type); } } public static final class NewSet extends Code { public final Type.Set type; public final int nargs; private NewSet(Type.Set type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewSet) { NewSet i = (NewSet) o; return type == i.type || (type != null && type.equals(i.type)) && nargs == i.nargs; } return false; } public String toString() { return toString("newset #" + nargs,type); } } public static final class NewList extends Code { public final Type.List type; public final int nargs; private NewList(Type.List type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewList) { NewList i = (NewList) o; return type == i.type || (type != null && type.equals(i.type)) && nargs == i.nargs; } return false; } public String toString() { return toString("newlist #" + nargs,type); } } public static final class Nop extends Code { private Nop() {} public String toString() { return "nop"; } } /* removed as I don't think this bytecode is needed public static final class Pop extends Code { public final Type type; private Pop(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 996; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof Pop) { Pop i = (Pop) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("pop",type); } } */ public static final class Return extends Code { public final Type type; private Return(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 996; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Return) { Return i = (Return) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("return",type); } } public enum OpDir { UNIFORM { public String toString() { return ""; } }, LEFT { public String toString() { return "_l"; } }, RIGHT { public String toString() { return "_r"; } } } public static final class SetUnion extends Code { public final OpDir dir; public final Type.Set type; private SetUnion(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetUnion) { SetUnion setop = (SetUnion) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("union" + dir.toString(),type); } } public static final class SetIntersect extends Code { public final OpDir dir; public final Type.Set type; private SetIntersect(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetIntersect) { SetIntersect setop = (SetIntersect) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("intersect" + dir.toString(),type); } } public static final class SetDifference extends Code { public final OpDir dir; public final Type.Set type; private SetDifference(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetDifference) { SetDifference setop = (SetDifference) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("difference" + dir.toString(),type); } } public static final class SetLength extends Code { public final Type.Set type; private SetLength(Type.Set type) { this.type = type; } public int hashCode() { if(type == null) { return 558723; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetLength) { SetLength setop = (SetLength) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("setlength",type); } } public static final class StringAppend extends Code { public final OpDir dir; private StringAppend(OpDir dir) { if(dir == null) { throw new IllegalArgumentException("StringAppend direction cannot be null"); } this.dir = dir; } public int hashCode() { return dir.hashCode(); } public boolean equals(Object o) { if (o instanceof StringAppend) { StringAppend setop = (StringAppend) o; return dir.equals(setop.dir); } return false; } public String toString() { return toString("stringappend" + dir.toString(),Type.T_STRING); } } public static final class SubString extends Code { private SubString() { } public int hashCode() { return 983745; } public boolean equals(Object o) { return o instanceof SubString; } public String toString() { return toString("substring",Type.T_STRING); } } public static final class StringLength extends Code { private StringLength() { } public int hashCode() { return 982345; } public boolean equals(Object o) { return o instanceof StringLength; } public String toString() { return toString("stringlen",Type.T_STRING); } } public static final class StringLoad extends Code { private StringLoad() { } public int hashCode() { return 12387; } public boolean equals(Object o) { return o instanceof StringLoad; } public String toString() { return toString("stringload",Type.T_STRING); } } public static final class Skip extends Code { Skip() {} public int hashCode() { return 101; } public boolean equals(Object o) { return o instanceof Debug; } public String toString() { return "skip"; } } public static final class Store extends Code { public final Type type; public final int slot; private Store(Type type, int slot) { this.type = type; this.slot = slot; } public int hashCode() { if(type == null) { return slot; } else { return type.hashCode() + slot; } } public boolean equals(Object o) { if(o instanceof Store) { Store i = (Store) o; return (type == i.type || (type != null && type.equals(i.type))) && slot == i.slot; } return false; } public String toString() { return toString("store " + slot,type); } } public static final class Switch extends Code { public final Type type; public final ArrayList<Pair<Value,String>> branches; public final String defaultTarget; Switch(Type type, String defaultTarget, Collection<Pair<Value,String>> branches) { this.type = type; this.branches = new ArrayList<Pair<Value,String>>(branches); this.defaultTarget = defaultTarget; } public int hashCode() { if(type == null) { return defaultTarget.hashCode() + branches.hashCode(); } else { return type.hashCode() + defaultTarget.hashCode() + branches.hashCode(); } } public boolean equals(Object o) { if (o instanceof Switch) { Switch ig = (Switch) o; return defaultTarget.equals(ig.defaultTarget) && branches.equals(ig.branches) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Value, String> p : branches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } table += ", *->" + defaultTarget; return "switch " + table; } } public static final class Send extends Code { public final boolean synchronous; public final boolean retval; public final NameID name; public final Type.Fun type; private Send(Type.Fun type, NameID name, boolean synchronous, boolean retval) { this.type = type; this.name = name; this.synchronous = synchronous; this.retval = retval; } public int hashCode() { return type.hashCode() + name.hashCode(); } public boolean equals(Object o) { if(o instanceof Send) { Send i = (Send) o; return retval == i.retval && synchronous == i.synchronous && (type.equals(i.type) && name.equals(i.name)); } return false; } public String toString() { if(synchronous) { if(retval) { return toString("send " + name,type); } else { return toString("vsend " + name,type); } } else { return toString("asend " + name,type); } } } public static final class Throw extends Code { public final Type type; private Throw(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 98923; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Throw) { Throw i = (Throw) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("throw",type); } } public static final class Negate extends Code { public final Type type; private Negate(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Negate) { Negate bo = (Negate) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("neg",type); } } public static final class Spawn extends Code { public final Type.Process type; private Spawn(Type.Process type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Spawn) { Spawn bo = (Spawn) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("spawn",type); } } public static final class ProcLoad extends Code { public final Type.Process type; private ProcLoad(Type.Process type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof ProcLoad) { ProcLoad bo = (ProcLoad) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("procload",type); } } /** * The void bytecode is used to indicate that a given register is no longer live. * @author djp * */ public static class Void extends Code { public final Type type; public final int slot; private Void(Type type, int slot) { this.type = type; this.slot = slot; } public int hashCode() { return type.hashCode() + slot; } public boolean equals(Object o) { if(o instanceof Void) { Void i = (Void) o; return type.equals(i.type) && slot == i.slot; } return false; } public String toString() { return toString("void " + slot,type); } } public static String toString(String str, Type t) { if(t == null) { return str + " : ?"; } else { return str + " : " + t; } } private static final ArrayList<Code> values = new ArrayList<Code>(); private static final HashMap<Code,Integer> cache = new HashMap<Code,Integer>(); private static <T extends Code> T get(T type) { Integer idx = cache.get(type); if(idx != null) { return (T) values.get(idx); } else { cache.put(type, values.size()); values.add(type); return type; } } }
package water.cascade; import org.junit.BeforeClass; import org.junit.Test; import water.DKV; import water.Key; import water.TestUtil; import water.fvec.Frame; public class CascadeTest extends TestUtil { @BeforeClass public static void setup() { stall_till_cloudsize(1); } @Test public void test1() { // Checking `hex + 5` String tree = "(+ $a.hex checkTree(tree); } @Test public void test2() { // Checking `hex + 5 + 10` String tree = "(+ $a.hex (+ #5 #10))"; checkTree(tree); } @Test public void test3() { // Checking `hex + 5 - 1 * hex + 15 * (23 / hex)` String tree = "(+ (- (+ $a.hex #5) (* #1 $a.hex)) (* #15 (/ #23 $a.hex)))"; checkTree(tree); } @Test public void test4() { //Checking `hex == 5`, <=, >=, <, >, != String tree = "(n $a.hex checkTree(tree); tree = "(L $a.hex checkTree(tree); tree = "(G $a.hex #1.25132)"; checkTree(tree); tree = "(g $a.hex #112.341e-5)"; checkTree(tree); tree = "(l $a.hex #0.0123)"; checkTree(tree); tree = "(N $a.hex checkTree(tree); tree = "(n $a.hex \"hello\")"; checkTree(tree); } @Test public void test5() { // Checking `hex && hex`, ||, &, | String tree = "(&& $a.hex $a.hex)"; checkTree(tree); tree = "(|| $a.hex $a.hex)"; checkTree(tree); tree = "(& $a.hex $a.hex)"; checkTree(tree); tree = "(| $a.hex $a.hex)"; checkTree(tree); } @Test public void test6() { // Checking `hex[,1]` String tree = "([ $a.hex \"null\" checkTree(tree); // Checking `hex[1,5]` tree = "([ $a.hex #0 #5)"; checkTree(tree); // Checking `hex[c(1:5,7,9),6]` tree = "([ $a.hex {(: #0 #4);6;8} #5)"; checkTree(tree); // Checking `hex[1,c(1:5,7,8)]` tree = "([ $a.hex #0 {(: #0 #4);6;7})"; checkTree(tree); } private static void checkTree(String tree) { Frame r = frame(new double[]{-1,1,2,3,4,5,6,254}); Key ahex = Key.make("a.hex"); Frame fr = new Frame(ahex, null, r.vecs()); DKV.put(ahex, fr); Env env = Exec.exec(tree); System.out.println(env.toString()); Object result = env.pop(); if (result instanceof ValFrame) { Frame f2 = ((ValFrame)result)._fr; for (int i = 0; i < f2.numCols(); ++i) System.out.println(f2.vecs()[i].at(0)); f2.delete(); } if (result instanceof ValNum) { double d = ((ValNum)result)._d; System.out.println(d); } fr.delete(); r.delete(); } }
package ru.pinkponies.protocol; import java.io.IOException; import java.io.InvalidClassException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import org.msgpack.MessagePack; import org.msgpack.packer.BufferPacker; import org.msgpack.unpacker.BufferUnpacker; public final class Protocol { private static final byte LOGIN_PACKET = 0; private static final byte LOCATION_UPDATE_PACKET = 1; private static final byte SAY_PACKET = 2; private static final byte APPLE_UPDATE_PACKET = 3; private final MessagePack messagePack; public Protocol() { this.messagePack = new MessagePack(); this.messagePack.register(LocationUpdatePacket.class); this.messagePack.register(LoginPacket.class); this.messagePack.register(SayPacket.class); this.messagePack.register(AppleUpdatePacket.class); } public byte[] pack(final Packet packet) throws IOException { if (packet == null) { throw new NullPointerException("Packet can not be null."); } BufferPacker packer = this.messagePack.createBufferPacker(); if (packet instanceof LoginPacket) { packer.write(LOGIN_PACKET); packer.write(packet); } else if (packet instanceof LocationUpdatePacket) { packer.write(LOCATION_UPDATE_PACKET); packer.write(packet); } else if (packet instanceof SayPacket) { packer.write(SAY_PACKET); packer.write(packet); } else if (packet instanceof AppleUpdatePacket) { packer.write(APPLE_UPDATE_PACKET); packer.write(packet); } else { throw new InvalidClassException("Unknown packet type."); } return packer.toByteArray(); } public void pack(final Packet packet, final ByteBuffer buffer) throws IOException, BufferOverflowException { if (packet == null) { throw new NullPointerException("Packet can not be null."); } BufferPacker packer = this.messagePack.createBufferPacker(); if (packet instanceof LoginPacket) { packer.write(LOGIN_PACKET); packer.write(packet); } else if (packet instanceof LocationUpdatePacket) { packer.write(LOCATION_UPDATE_PACKET); packer.write(packet); } else if (packet instanceof SayPacket) { packer.write(SAY_PACKET); packer.write(packet); } else if (packet instanceof AppleUpdatePacket) { packer.write(APPLE_UPDATE_PACKET); packer.write(packet); } else { throw new InvalidClassException("Unknown packet type."); } buffer.put(packer.toByteArray()); } public Packet unpack(final byte[] data) throws IOException { BufferUnpacker unpacker = this.messagePack.createBufferUnpacker(data); byte type = unpacker.readByte(); if (type == LOGIN_PACKET) { return unpacker.read(LoginPacket.class); } else if (type == LOCATION_UPDATE_PACKET) { return unpacker.read(LocationUpdatePacket.class); } else if (type == SAY_PACKET) { return unpacker.read(SayPacket.class); } else if (type == APPLE_UPDATE_PACKET) { return unpacker.read(AppleUpdatePacket.class); } else { // FIXME(alexknvl): check if its the right type of exception throw new InvalidClassException("Unknown packet type."); } } public Packet unpack(final ByteBuffer buffer) throws IOException { // FIXME(alexknvl): wtf, there is no way to read directly from // ByteBuffer? BufferUnpacker unpacker = this.messagePack.createBufferUnpacker(buffer.array()); byte type = unpacker.readByte(); Packet result = null; if (type == LOGIN_PACKET) { result = unpacker.read(LoginPacket.class); } else if (type == LOCATION_UPDATE_PACKET) { result = unpacker.read(LocationUpdatePacket.class); } else if (type == SAY_PACKET) { result = unpacker.read(SayPacket.class); } else if (type == APPLE_UPDATE_PACKET) { result = unpacker.read(AppleUpdatePacket.class); } else { // FIXME(alexknvl): check if its the right type of exception throw new InvalidClassException("Unknown packet type."); } int totalRead = unpacker.getReadByteCount(); buffer.position(buffer.position() + totalRead); return result; } }
public class ArgumentsJava { public String a_0() { return "a_0"; } public String a_1(String arg) { return "a_1: " + arg; } public String a_3(String arg1, String arg2, String arg3) { return "a_3: " + arg1 + " " + arg2 + " " + arg3; } public String a_0_1() { return a_0_1("default"); } public String a_0_1(String arg) { return "a_0_1: " + arg; } public String a_1_3(String arg1) { return a_1_3(arg1, "default"); } public String a_1_3(String arg1, String arg2) { return a_1_3(arg1, arg2, "default"); } public String a_1_3(String arg1, String arg2, String arg3) { return "a_1_3: " + arg1 + " " + arg2 + " " + arg3; } public String a_0_n(String[] args) { String ret = "a_0_n:"; for (int i=0; i < args.length; i++) { ret += " " + args[i]; } return ret; } public String a_1_n(String arg, String[] args) { String ret = "a_1_n: " + arg; for (int i=0; i < args.length; i++) { ret += " " + args[i]; } return ret; } public String javaVarargs(String... args) { String ret = "javaVarArgs:"; for (String arg: args) ret += " " + arg; return ret; } }
package clasificadores; import datos.Datos; import datos.Elemento; import datos.ElementoFactory; import datos.TiposDeAtributos; import java.util.ArrayList; import java.util.HashMap; /** * * @author dani */ public class ClasificadorNaiveBayes extends Clasificador{ //el primer Array nos dice la columna //el primer HashMap nos dice el valor de la columna //el segundo hashmap cuenta por cada valor de la columna cuantas incidencias //tiene la clase, para hacer p(D|H) ArrayList<HashMap<Elemento, HashMap<Elemento, Integer>>> incidencias; //cuenta las incidencias totales de cada clase HashMap<Elemento, Integer> incidenciaClaseTotal; //filas totales de train int filasTrain = 0; @Override public void entrenamiento(Datos datosTrain) { this.incidencias = new ArrayList<>(); this.incidenciaClaseTotal = new HashMap<>(); //creacion de objetos for(String columna: datosTrain.getNombreCampos()){ HashMap<Elemento, HashMap<Elemento, Integer>> incidenciaColumna = new HashMap<>(); this.incidencias.add(incidenciaColumna); } for(Elemento fila[] : datosTrain.getDatos()){ this.filasTrain++; Elemento ultimoElemFila = fila[fila.length-1]; for(int i = 0; i < (fila.length - 1); i++){ HashMap<Elemento, HashMap<Elemento, Integer>> incidenciaColumna = this.incidencias.get(i); if(incidenciaColumna.containsKey(fila[i])){ //se ha encontrado el elemento HashMap<Elemento, Integer> incidenciaClase = incidenciaColumna.get(fila[i]); if(incidenciaClase.containsKey(ultimoElemFila)){ Integer contador = incidenciaClase.get(ultimoElemFila); contador++; incidenciaClase.put(ultimoElemFila, contador); }else{ Integer contador = 1; incidenciaClase.put(ultimoElemFila, contador); } }else{ //no se encontraba el elemento en la base de datos HashMap<Elemento, Integer> incidenciaClase = new HashMap<>(); Integer contador = 1; incidenciaClase.put(ultimoElemFila, contador); incidenciaColumna.put(fila[i], incidenciaClase); } } //sumar las incidencias de cada clase if(this.incidenciaClaseTotal.containsValue(ultimoElemFila)){ Integer nIncidencias = this.incidenciaClaseTotal.get(ultimoElemFila); nIncidencias++; this.incidenciaClaseTotal.put(ultimoElemFila, nIncidencias); }else{ Integer nIncidencias = 1; this.incidenciaClaseTotal.put(ultimoElemFila, nIncidencias); } } } @Override public ArrayList<Elemento> clasifica(Datos datosTest) { ArrayList<Elemento> clasificado = new ArrayList<>(); for(Elemento fila[] : datosTest.getDatos()){ Elemento mejorClase = null; //Elemento ultimoElemFila = fila[fila.length-1]; double mejorProb = 0; for(String clase : datosTest.getClases()){ //simulacion de la clase, decimos, si fuera esta clase, que prob da Elemento ultimoElemFila = ElementoFactory.crear(TiposDeAtributos.Continuo, clase); double prob = 0; for(int i = 0; i < (fila.length - 1); i++){ /* prob de el dato dada la hipotesis MULi (p(Di|H)) */ double probAux = this.incidencias.get(i).get(fila[i]).get(ultimoElemFila); probAux = probAux/this.incidenciaClaseTotal.get(ultimoElemFila); if(i == 0){ prob = probAux; }else{ prob = prob*probAux; } } /* prob de la hipotesis */ double probAux = this.incidenciaClaseTotal.get(ultimoElemFila); probAux = probAux/this.filasTrain; prob = prob*probAux; if(prob > mejorProb){ mejorProb = prob; mejorClase = ultimoElemFila; } } /*fin del iterador de las clases*/ clasificado.add(mejorClase); } /*fin del iterador de las filas*/ return clasificado; } }
package mathsquared.resultswizard2; /** * An immutable object that represents a proper fraction. Can support improper fractions intermittently as well. * * <p> * Note that any post-conditions on any methods of this class only apply after the constructor has successfully completed, as several clean-up methods are required to ensure that a Fraction is represented in a canonical form. * </p> * * <p> * Objects of this class may be marked as invalid at any time if they have zero denominators. If a Fraction is marked as invalid, subsequent operations will throw an {@link UnsupportedOperationException}. This is done on a best-effort basis; a Fraction with a zero denominator is not guaranteed to be marked invalid immediately. Note that the public constructors will disallow the creation of a Fraction with a zero denominator, so such Fractions should not be encountered in normal usage. * </p> * * @author MathSquared * */ public class Fraction { // TODO write unit tests private int unit; private boolean unitValid = false; // Turns true when a unit is calculated and false when it is extracted private int numerator; private int denominator; // If the denominator is detected as 0, this is false--prevents finalizer exploits from propagating 0 denominators private boolean valid = true; /** * Constructs a Fraction representing the given whole number. This is equivalent to <code>Fraction(num, 1)</code> and is provided as a convenience method. * * @param num the integer to represent */ public Fraction (int num) { this(num, 1); } /** * Constructs a Fraction representing the quotient of two integers. * * <p> * The Fraction is canonicalized as follows: * </p> * * <ul> * <li>If the denominator of the fraction is negative, both the numerator and denominator are multiplied by -1.</li> * <li>A whole-number unit is extracted from the fraction. Thus, {@link #getNumerator()} returns what the numerator would be if this quotient were expressed as a mixed number; {@link #getImproperNumerator()} returns what it would be as an improper fraction.</li> * <li>The sign of the unit and numerator are matched. If they don't match, the fraction takes on the value of (unit + (numerator / denominator)); thus, (6)u(-1/2) becomes (5)u(1/2).</li> * <li>The fraction is simplified to its lowest terms by dividing out the GCD of the numerator and denominator.</li> * </ul> * * @param num the numerator of the fraction * @param den the denominator of the fraction * @throws ArithmeticException if <code>den == 0</code> */ public Fraction (int num, int den) { if (den == 0) { valid = false; throw new ArithmeticException("Denominator must not be equal to 0"); } numerator = num; denominator = den; canonicalize(); } /** * Canonicalizes this fraction according to the criteria {@linkplain #Fraction(int, int) noted above}. This method may be invoked at any time. */ private void canonicalize () { canonicalizeDenominator(); calculateUnit(); matchUnitNumeratorSign(); simplify(); } /** * Marks this fraction as invalid and throws an {@link UnsupportedOperationException} if the denominator is 0. */ private void checkDenominatorNonzero () { if (!valid || denominator == 0) { valid = false; throw new UnsupportedOperationException("Fraction invalid; denominator is 0"); } } /** * If either this fraction or another given fraction have a zero denominator, throws an UnsupportedOperationException and marks the invalid fraction(s) as such. * * @param secondOperand the other fraction to check */ private void checkDenominatorNonzero (Fraction secondOperand) { String exceptionMessage = null; // tracks exception messages in case both fractions are invalid if (!valid || denominator == 0) { valid = false; exceptionMessage = "First operand invalid; denominator is 0"; } if (!secondOperand.valid || secondOperand.getDenominator() == 0) { secondOperand.valid = false; exceptionMessage = (exceptionMessage == null ? "Second operand invalid; denominator is 0" : "Both fractions invalid; denominators are 0"); } if (exceptionMessage != null) { throw new UnsupportedOperationException(exceptionMessage); } } // Setup methods // /* * Setup methods; called in constructor Before these methods are called, the Fraction may be in a non-canonical state. */ /** * If the denominator of a fraction is negative, switches the sign of both the numerator and denominator. This way, the denominator is always positive. */ private void canonicalizeDenominator () { if (denominator < 0) { numerator = -numerator; denominator = -denominator; } } /** * Calculates the unit of a fraction based on the numerator and denominator. This has the effect that the fraction represented by the numerator and denominator becomes proper. */ private void calculateUnit () { unit += numerator / denominator; // += in case there are already any other units that we want to remain valid--5u3/2 is 6u1/2 numerator %= denominator; // % picks sign based on numerator, so numerator keeps current sign unitValid = true; } /** * Ensures that the sign of the unit and numerator match. */ private void matchUnitNumeratorSign () { // If signs match, or if either quantity is 0 (which has no sign), we don't need to do anything if ((unit > 0 && numerator > 0) || (unit < 0 && numerator < 0) || (unit == 0 || numerator == 0)) { // last || is intentionally different return; } // Simply convert to improper and back numerator = getImproperNumerator(); unit = 0; unitValid = false; calculateUnit(); } /** * Simplifies a fraction to its lowest terms. */ private void simplify () { // Handle zero correctly to avoid BAD THINGS HAPPENING (like division by 0) if (numerator == 0) { denominator = 1; // 0/1 == 0/2 == 0/3.14159 == 0/-37 == ... return; } int gcd = GcdUtils.gcd(numerator, denominator); numerator /= gcd; denominator /= gcd; } // Accessors // /** * Returns the unit currently associated with this fraction. If the unit is {@linkplain #isUnitValid() invalid}, this method returns 0. If the fraction represents a negative quantity, the value returned by this method will be negative. * * @return the unit of this fraction */ public int getUnit () { return (unitValid ? unit : 0); } /** * Discards the unit of this fraction, returning the number discarded. After this method is called, {@link #getUnit()} returns 0 and {@link #isUnitValid()} returns false. If the fraction represents a negative quantity, the value returned by this method will be negative. * * @return the unit of this fraction */ public int extractUnit () { int temp = unit; unitValid = false; unit = 0; return temp; } /** * Returns whether the unit of this fraction will be used in future arithmetic calculations. * * <p> * The {@linkplain #getUnit() unit} mechanism was created to facilitate chaining of operations, especially additions. Since units are factored into calculations as long as they are valid, the unit can be disabled by the user when it is no longer needed. This method returns whether the unit will still be used in mathematical calculations. * </p> * * @return whether the current unit is valid */ public boolean isUnitValid () { return unitValid; } /** * Returns the numerator of the proper portion of this fraction. If the fraction represents a negative quantity, the value returned by this method will be negative. * * @return the numerator */ public int getNumerator () { return numerator; } /** * Returns the numerator of this fraction expressed as an improper fraction. If the unit is {@linkplain #isUnitValid() valid}, this is defined to be equal to <code>(numerator + unit*denominator)</code>; if the unit is invalid, this returns the same result as {@link #getNumerator()}. * * @return the improper numerator */ // USE THIS METHOD FOR ARITHMETIC TO SUPPORT OPERATION CHAINING; DO NOT DIRECTLY EMPLOY numerator public int getImproperNumerator () { return numerator + (unitValid ? unit : 0) * denominator; } /** * Returns the denominator of this fraction. This method always returns a positive quantity; the sign is unambiguously determined by the {@linkplain #getNumerator() numerator}. * * @return the denominator */ public int getDenominator () { return denominator; } // Arithmetic // /** * Negates a Fraction (finds its additive inverse). This is equivalent to multiplication by -1. * * @return a new Fraction representing the negative of this Fraction */ public Fraction negative () { checkDenominatorNonzero(); return new Fraction(-getImproperNumerator(), denominator); } /** * Multiplies a Fraction by an integer. * * @param multiplier the number by which to multiply * @return a new Fraction multiplied by the multiplier */ public Fraction multiply (int multiplier) { checkDenominatorNonzero(); return new Fraction(getImproperNumerator() * multiplier, denominator); } /** * Multiplies two Fractions together. * * @param multiplier the Fraction by which to multiply * @return a new Fraction multiplied by the multiplier */ public Fraction multiply (Fraction multiplier) { checkDenominatorNonzero(multiplier); return new Fraction(getImproperNumerator() * multiplier.getImproperNumerator(), denominator * multiplier.getDenominator()); } /** * Divides a Fraction by an integer. * * @param divisor the number by which to divide * @return a new Fraction divided by the divisor * @throws ArithmeticException if the divisor is 0 */ public Fraction divide (int divisor) { checkDenominatorNonzero(); if (divisor == 0) { throw new ArithmeticException("divisor must not be 0"); } return new Fraction(getImproperNumerator(), denominator * divisor); } /** * Divides a Fraction by another. This is equivalent to multiplication by the divisor's reciprocal. * * @param divisor the Fraction by which to divide * @return a new Fraction divided by the divisor * @throws ArithmeticException if the numerator of the divisor is 0 */ public Fraction divide (Fraction divisor) { checkDenominatorNonzero(divisor); if (divisor.getImproperNumerator() == 0) { throw new ArithmeticException("numerator of the divisor must not be 0"); } return new Fraction(getImproperNumerator() * divisor.getDenominator(), denominator * divisor.getImproperNumerator()); } /** * Raises a Fraction to a power. * * <p> * This method assumes that any fraction raised to the 0 power is equal to 1. If the given exponent is negative, this method acts as if <code>this.reciprocal().pow(-exponent)</code> was called. * * @param exponent the power to which to raise this Fraction * @return a new Fraction raised to the given power */ public Fraction pow (int exponent) { checkDenominatorNonzero(); // Math.pow will return non-integer results for negative exponents, so we take the reciprocal here first if (exponent < 0) { return reciprocal().pow(-exponent); } if (exponent == 0) { return new Fraction(1, 1); } // use integer power function for max precision (avoid floating-point round-off error) return new Fraction(GcdUtils.pow(getImproperNumerator(), exponent), GcdUtils.pow(denominator, exponent)); } /** * Finds the reciprocal (multiplicative inverse) of a Fraction. The new Fraction is canonicalized, so it may be the case that <code>fraction.getNumerator() != fraction.reciprocal().getDenominator()</code>. * * @return a new Fraction representing the denominator of this Fraction divided by the numerator * @throws ArithmeticException if the Fraction represents a zero quantity, i.e. if <code>(getImproperNumerator() == 0)</code> */ public Fraction reciprocal () { checkDenominatorNonzero(); if (getImproperNumerator() == 0) { throw new ArithmeticException("Cannot take the reciprocal of a zero fraction"); } return new Fraction(denominator, getImproperNumerator()); } /** * Adds an integer to a Fraction. * * @param augend the integer to add to this Fraction * @return a new Fraction representing the result of <code>(this + augend)</code> */ public Fraction add (int augend) { checkDenominatorNonzero(); return new Fraction(getImproperNumerator() + augend * denominator, denominator); } /** * Adds two Fractions together. * * @param augend the Fraction to which to add this one * @return a new Fraction representing the result of <code>(this + augend)</code> */ public Fraction add (Fraction augend) { checkDenominatorNonzero(augend); int lcm = GcdUtils.lcm(denominator, augend.getDenominator()); int multiplyA = lcm / denominator; int multiplyB = lcm / augend.getDenominator(); int numA = getImproperNumerator(); int numB = augend.getImproperNumerator(); return new Fraction(numA * multiplyA + numB * multiplyB, lcm); } /** * Subtracts an integer from a Fraction. * * @param subtrahend the integer to subtract from this Fraction * @return a new Fraction representing the result of <code>(this - subtrahend)</code> */ public Fraction subtract (int subtrahend) { checkDenominatorNonzero(); return add(-subtrahend); } /** * Subtracts two Fractions. * * @param subtrahend the Fraction to subtract from this Fraction * @return a new Fraction representing the result of <code>(this - subtrahend)</code> */ public Fraction subtract (Fraction subtrahend) { checkDenominatorNonzero(subtrahend); return add(subtrahend.negative()); } /** * Converts a Fraction to the double it represents. This is done as if returning <code>((double) {@link #getImproperNumerator()} / denominator)</code>. * * @return the double equivalent of this Fraction */ public double toDouble () { return (double) getImproperNumerator() / denominator; } /** * Tests whether a Fraction is equivalent to another object. * * <p> * A Fraction is considered equal to another object <code>other</code> if and only if: * </p> * * <ul> * <li><code>other</code> is a <code>Byte</code>, <code>Short</code>, <code>Integer</code>, or <code>Long</code> and this fraction represents a whole number that is precisely equal to the number represented by <code>other</code></li> * <li><code>other</code> is a <code>Float</code> or <code>Double</code> and <code>this.toDouble()</code> precisely equals the value represented by <code>other</code></li> * <li><code>other</code> is another <code>Fraction</code> and both fractions' {@linkplain #getImproperNumerator() improper numerators} and {@linkplain #getDenominator() denominators} are equal to each other when both fractions are in lowest terms</li> * </ul> */ public boolean equals (Object other) { canonicalize(); // Check some special cases if (other instanceof Byte || other instanceof Short || other instanceof Integer || other instanceof Long) { // ensure number is correct && fraction is a whole number (entire denominator can be divided out) return getImproperNumerator() / denominator == ((Number) other).intValue() && GcdUtils.gcd(getImproperNumerator(), denominator) == denominator; } else if (other instanceof Float || other instanceof Double) { return toDouble() == ((Number) other).doubleValue(); } else if (other instanceof Fraction) { Fraction fOther = (Fraction) other; fOther.canonicalize(); return unit == fOther.getUnit() && numerator == fOther.getNumerator() && denominator == fOther.getDenominator(); } else { return false; } } }
package yecheng; import org.json.JSONObject; import yecheng.music.database.Index; import yecheng.music.database.MysqlDB; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static yecheng.music.database.Index.Hash2id; @SuppressWarnings("WeakerAccess") public class Server { private final static int port = 1234; public static class ServerDataBase{ class Node{ int id; int time; } final HashMap<Integer,ArrayList<Node>> Database; final HashMap<Long,Integer> hashMap; public ServerDataBase() { super(); Database = new HashMap<>(2560000); hashMap = new HashMap<>(4000000); MysqlDB sqlDB = new MysqlDB(); ResultSet rs = sqlDB.listAll(); try { while(rs.next()){ int hash = rs.getInt(2); int id = rs.getInt(3); int time = rs.getInt(4); Node node = new Node(); node.id = id; node.time = time; ArrayList<Node> idList = Database.get(hash); if(idList == null){ idList = new ArrayList<>(); Database.put(hash,idList); } idList.add(node); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } private long maxId = -1; private int maxCount = -1; public int search(int[] linkTime,int[] linkHash, @SuppressWarnings("SameParameterValue") int minHit){ hashMap.clear(); for(int i = 0; i < linkHash.length; i ++){ final ArrayList<Node> list = Database.get(linkHash[i]); if(list == null) continue; final int time = linkTime[i]; list.forEach(node -> { long idHash = Index.idHash(node.id, node.time - time); Integer count = hashMap.get(idHash); if(count == null) count = 0; hashMap.put(idHash,count + 1); }); } maxId = -1; maxCount = -1; Map<Long,Integer> list = new HashMap<>(); hashMap.forEach((hash, integer) -> { if (integer > minHit) { list.put(hash,integer); } if (integer > minHit && integer > maxCount) { maxId = hash; maxCount = integer; } }); System.out.println(Hash2id(maxId) + ":" + maxCount); return Hash2id(maxId); } } public static void main(String[] arg) { System.out.println("Loading Database!"); ServerDataBase dataBase = new ServerDataBase(); System.gc(); System.out.println("Complete!"); MysqlDB mysqlDB = new MysqlDB(); try { ServerSocket serverSocket = new ServerSocket(port); Socket socket; while (true) { try { socket = serverSocket.accept(); InputStream is = socket.getInputStream(); ByteBuffer buf = ByteBuffer.allocate(4); byte[] a = new byte[4]; //noinspection ResultOfMethodCallIgnored is.read(a); buf.put(a); buf.rewind(); int size = buf.getInt(); buf.rewind(); int[] link = new int[size]; int[] time = new int[size]; int i = 0; while (is.read(a) != -1) { buf.put(a); buf.rewind(); if (i < size) { link[i] = buf.getInt(); } else { time[i - size] = buf.getInt(); } i++; buf.rewind(); } int id = dataBase.search(time, link, 18); JSONObject jsonObject = mysqlDB.getByID(id); PrintWriter writer = new PrintWriter(socket.getOutputStream()); if(jsonObject == null) writer.write(""); else writer.write(jsonObject.toString()); writer.close(); System.out.println(jsonObject.toString()); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } }
package ui.issuepanel; import java.lang.ref.WeakReference; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.input.KeyCode; import javafx.scene.layout.Priority; import javafx.stage.Stage; import javafx.util.Callback; import model.Model; import model.TurboIssue; import ui.UI; import ui.issuecolumn.Column; import ui.issuecolumn.ColumnControl; import ui.sidepanel.SidePanel; import util.events.IssueSelectedEvent; import command.TurboCommandExecutor; public class IssuePanel extends Column { private final Stage mainStage; private final Model model; private final ColumnControl parentColumnControl; private final int columnIndex; private final SidePanel sidePanel; private final UI ui; private ListView<TurboIssue> listView; public IssuePanel(UI ui, Stage mainStage, Model model, ColumnControl parentColumnControl, SidePanel sidePanel, int columnIndex, TurboCommandExecutor dragAndDropExecutor, boolean isSearchPanel) { super(mainStage, model, parentColumnControl, sidePanel, columnIndex, dragAndDropExecutor, isSearchPanel); this.mainStage = mainStage; this.model = model; this.parentColumnControl = parentColumnControl; this.columnIndex = columnIndex; this.sidePanel = sidePanel; this.ui = ui; listView = new ListView<>(); setupListView(); getChildren().add(listView); refreshItems(); } @Override public void deselect() { listView.getSelectionModel().clearSelection(); } @Override public void refreshItems() { super.refreshItems(); WeakReference<IssuePanel> that = new WeakReference<IssuePanel>(this); // Set the cell factory every time - this forces the list view to update listView.setCellFactory(new Callback<ListView<TurboIssue>, ListCell<TurboIssue>>() { @Override public ListCell<TurboIssue> call(ListView<TurboIssue> list) { if(that.get() != null){ return new IssuePanelCell(ui, mainStage, model, that.get(), columnIndex, sidePanel, parentColumnControl); } else{ return null; } } }); // Supposedly this also causes the list view to update - not sure // if it actually does on platforms other than Linux... listView.setItems(null); listView.setItems(getIssueList()); } private void setupListView() { setVgrow(listView, Priority.ALWAYS); setOnKeyReleased((e) -> { if (e.getCode().equals(KeyCode.ENTER)) { TurboIssue selectedIssue = listView.getSelectionModel().selectedItemProperty().get(); if (selectedIssue != null) { ui.triggerEvent(new IssueSelectedEvent(selectedIssue.getId())); } } }); } }
package jlibs.xml.xsd.display; import jlibs.graph.visitors.PathReflectionVisitor; import org.apache.xerces.xs.XSAttributeUse; import org.apache.xerces.xs.XSElementDeclaration; import org.apache.xerces.xs.XSWildcard; import java.awt.*; /** * @author Santhosh Kumar T */ public class XSColorVisitor extends PathReflectionVisitor<Object, Color>{ XSPathDiplayFilter filter; public XSColorVisitor(XSPathDiplayFilter filter){ this.filter = filter; } @Override protected Color getDefault(Object elem){ return COLOR_OTHER; } private static final Color COLOR_OTHER = Color.lightGray; private static final Color COLOR_ELEMENT = new Color(0, 0, 128); private static final Color COLOR_ATTRIBUTE = new Color(0, 128, 0); @SuppressWarnings({"UnusedDeclaration"}) protected Color process(XSElementDeclaration elem){ return COLOR_ELEMENT; } @SuppressWarnings({"UnusedDeclaration"}) protected Color process(XSWildcard wildcard){ return COLOR_ELEMENT; } @SuppressWarnings({"UnusedDeclaration"}) protected Color process(XSAttributeUse attrUse){ return COLOR_ATTRIBUTE; } }
package edu.wustl.query.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.factory.AbstractBizLogicFactory; import edu.wustl.common.querysuite.queryobject.IParameterizedQuery; import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.query.bizlogic.ValidateQueryBizLogic; import edu.wustl.query.util.global.Constants; import edu.wustl.query.util.global.Utility; /** * When the user searches or saves a query , the query is checked for the conditions like DAG should not be empty , is there * at least one node in view on define view page and does the query contain the main object. If all the conditions are satisfied * further process is done else corresponding error message is shown. * * @author shrutika_chintal * */ public class ValidateQueryAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String buttonClicked = request.getParameter(Constants.BUTTON_CLICKED); String dataQueryId= request.getParameter("dataQueryId"); // dataKey defines that ajax call from SimpleSearchDataView.jsp is made to get the updated message. String dataKey = request.getParameter(Constants.UPDATE_SESSION_DATA); HttpSession session = request.getSession(); //retrieve the Selected Project from the GetCounts.jsp and set it in session String selectedProject = request.getParameter(Constants.SELECTED_PROJECT); session.setAttribute(Constants.SELECTED_PROJECT,selectedProject); //Added By Baljeet //session.removeAttribute("allLimitExpressionIds"); String writeresponse= buttonClicked; if (dataKey != null && dataKey.equals(Constants.UPDATE_SESSION_DATA)) { //if dataKey is not null retrieve the data from the session and send it to the jsp writeresponse = updateSesionData(response, session); } else{ IParameterizedQuery parameterizedQuery=null; if(dataQueryId==null) { parameterizedQuery = (IParameterizedQuery)session .getAttribute(Constants.QUERY_OBJECT); } else{ IBizLogic bizLogic = AbstractBizLogicFactory.getBizLogic(ApplicationProperties .getValue("app.bizLogicFactory"), "getBizLogic", Constants.QUERY_INTERFACE_BIZLOGIC_ID); try{ parameterizedQuery =(ParameterizedQuery) bizLogic.retrieve(ParameterizedQuery.class .getName(),Long.valueOf(dataQueryId)); //request.setAttribute(Constants.DATA_QUERY_ID, dataQueryId); //request.setAttribute(Constants.COUNT_QUERY_ID, countQueryId); }catch (DAOException daoException) { ActionErrors errors = Utility.setActionError(daoException.getMessage(),"errors.item"); saveErrors(request, errors); } } if(parameterizedQuery!=null && dataQueryId==null) { parameterizedQuery.setName(request.getParameter("queyTitle")); } String validationMessage = ValidateQueryBizLogic.getValidationMessage(request,parameterizedQuery); if (validationMessage != null) { response.setContentType(Constants.CONTENT_TYPE_TEXT); writeresponse=validationMessage; } } response.getWriter().write(writeresponse); return null; } /** * This method retrieves the data from the session to send it to the jsp * @param response * @param session * @return */ private String updateSesionData(HttpServletResponse response, HttpSession session) { String message = (String) session .getAttribute(Constants.VALIDATION_MESSAGE_FOR_ORDERING); String isListEmpty = (String) session.getAttribute(Constants.IS_LIST_EMPTY); if ((isListEmpty != null && isListEmpty.equals(Constants.FALSE)) || message == null) { message = " "; //if empty string is returned mac+safari gives problem and if message is set to null mozilla gives problem. } response.setContentType("text/html"); return message; } }
package edu.wustl.query.querysuite; import junit.framework.Test; import junit.framework.TestSuite; import edu.wustl.common.query.impl.XQueryGeneratorTestCase; public class QueryTestSuite extends TestSuite { /** * @param args arg */ public static void main(String[] args) { try { junit.awtui.TestRunner.run(QueryTestSuite.class); } catch(Exception e) { e.printStackTrace(); } } /** * @return test */ public static Test suite() { TestSuite suite = new TestSuite("Test suite for QUERY business logic"); // For testing FAMEWORK for Query testing suite.addTestSuite(XQueryGeneratorTestCase.class); // For testing ASynchronous Queries // suite.addTestSuite(ASynchronousQueriesTestCases.class); return suite; } }
package radlab.rain.workload.scadr; import radlab.rain.Generator; import radlab.rain.LoadProfile; import radlab.rain.ObjectPool; import radlab.rain.Operation; import radlab.rain.RainConfig; import radlab.rain.ScenarioTrack; import radlab.rain.util.HttpTransport; import radlab.rain.util.NegativeExponential; import org.json.JSONObject; import org.json.JSONException; import java.util.LinkedHashSet; import java.util.Random; public class ScadrGenerator extends Generator { public static String CFG_USE_POOLING_KEY = "usePooling"; public static String CFG_DEBUG_KEY = "debug"; public static String CFG_ZOOKEEPER_CONN_STRING = "zookeeperConnString"; public static String CFG_ZOOKEEPER_APP_SERVER_PATH = "zookeeperAppServerPath"; public static int DEFAULT_APP_SERVER_PORT = 8080; protected static final String[] US_CITIES = { "New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose", "Detroit", "San Francisco", "Jacksonville", "Indianapolis", "Austin", "Columbus", "Fort Worth", "Charlotte", "Memphis", "Boston", "Baltimore", "El Paso", "Seattle", "Denver", "Nashville", "Milwaukee", "Washington", "Las Vegas", "Louisville", "Portland", "Oklahoma City", "Tucson", "Atlanta", "Albuquerque", "Kansas City", "Fresno", "Mesa", "Sacramento", "Long Beach", "Omaha", "Virginia Beach", "Miami", "Cleveland", "Oakland", "Raleigh", "Colorado Springs", "Tulsa", "Minneapolis", "Arlington", "Honolulu", "Wichita", "St. Louis", "New Orleans", "Tampa", "Santa Ana", "Anaheim", "Cincinnati", "Bakersfield", "Aurora", "Toledo", "Pittsburgh", "Riverside", "Lexington", "Stockton", "Corpus Christi", "Anchorage", "St. Paul", "Newark", "Plano", "Buffalo", "Henderson", "Fort Wayne", "Greensboro", "Lincoln", "Glendale", "Chandler", "St. Petersburg", "Jersey City", "Scottsdale", "Orlando", "Madison", "Norfolk", "Birmingham", "Winston-Salem", "Durham", "Laredo", "Lubbock", "Baton Rouge", "North Las Vegas", "Chula Vista", "Chesapeake", "Gilbert", "Garland", "Reno", "Hialeah", "Arlington", "Irvine", "Rochester", "Akron", "Boise", "Irving", "Fremont", "Richmond", "Spokane", "Modesto", "Montgomery", "Yonkers", "Des Moines", "Tacoma", "Shreveport", "San Bernardino", "Fayetteville", "Glendale", "Augusta", "Grand Rapids", "Huntington Beach", "Mobile", "Newport News", "Little Rock", "Moreno Valley", "Columbus", "Amarillo", "Fontana", "Oxnard", "Knoxville", "Fort Lauderdale", "Salt Lake City", "Worcester", "Huntsville", "Tempe", "Brownsville", "Jackson", "Overland Park", "Aurora", "Oceanside", "Tallahassee", "Providence", "Rancho Cucamonga", "Ontario", "Chattanooga", "Santa Clarita", "Garden Grove", "Vancouver", "Grand Prairie", "Peoria", "Sioux Falls", "Springfield", "Santa Rosa", "Rockford", "Springfield", "Salem", "Port St. Lucie", "Cape Coral", "Dayton", "Eugene", "Pomona", "Corona", "Alexandria", "Joliet", "Pembroke Pines", "Paterson", "Pasadena", "Lancaster", "Hayward", "Salinas", "Hampton ", "Palmdale", "Pasadena", "Naperville", "Kansas City", "Hollywood", "Lakewood", "Torrance", "Escondido", "Fort Collins", "Syracuse", "Bridgeport", "Orange", "Cary", "Elk Grove", "Savannah", "Sunnyvale", "Warren", "Mesquite", "Fullerton", "McAllen", "Columbia", "Carrollton", "Cedar Rapids", "McKinney", "Sterling Heights", "Bellevue", "Coral Springs", "Waco", "Elizabeth", "West Valley City", "Clarksville", "Topeka", "Hartford", "Thousand Oaks", "New Haven", "Denton", "Concord", "Visalia", "Olathe", "El Monte", "Independence", "Stamford", "Simi Valley", "Provo", "Killeen", "Springfield", "Thornton", "Abilene", "Gainesville", "Evansville", "Roseville", "Charleston", "Peoria", "Athens ", "Lafayette", "Vallejo", "Lansing", "Ann Arbor", "Inglewood", "Santa Clara", "Flint", "Victorville", "Costa Mesa", "Beaumont", "Miami Gardens", "Manchester", "Westminster", "Miramar", "Norman", "Cambridge", "Midland", "Arvada", "Allentown", "Elgin", "Waterbury", "Downey", "Clearwater", "Billings", "West Covina", "Round Rock", "Murfreesboro", "Lewisville", "West Jordan", "Pueblo", "San Buenaventura (Ventura)", "Lowell", "South Bend", "Fairfield", "Erie", "Rochester", "High Point", "Richardson", "Richmond", "Burbank", "Berkeley", "Pompano Beach", "Norwalk", "Frisco", "Columbia", "Gresham", "Daly City", "Green Bay", "Wilmington", "Davenport", "Wichita Falls", "Antioch", "Palm Bay", "Odessa", "Centennial", "Boulder", }; protected static final String[] HOMEPAGE_STATICS = { "/stylesheets/base.css?1296794014", "/javascripts/jquery.js?1296577051", "/javascripts/jquery-ui.js?1296577051", "/javascripts/jrails.js?1296577051", "/javascripts/application.js?1296577051" }; protected static final String[] LOGINPAGE_STATICS = { "/stylesheets/base.css?1296794014", "/javascripts/jquery.js?1296577051", "/javascripts/jquery-ui.js?1296577051", "/javascripts/jrails.js?1296577051", "/javascripts/application.js?1296577051" }; protected static final String[] CREATEUSERPAGE_STATICS = { "/stylesheets/base.css?1296794014", "/javascripts/jquery.js?1296577051", "/javascripts/jquery-ui.js?1296577051", "/javascripts/jrails.js?1296577051", "/javascripts/application.js?1296577051" }; protected static final String[] POSTTHOUGHTPAGE_STATICS = { "/stylesheets/base.css?1296794014", "/javascripts/jquery.js?1296577051", "/javascripts/jquery-ui.js?1296577051", "/javascripts/jrails.js?1296577051", "/javascripts/application.js?1296577051" }; // Statics URLs public String[] homepageStatics; public String[] loginpageStatics; public String[] createuserpageStatics; public String[] postthoughtpageStatics; // Operation indices - each operation has a unique index /* Test matrix 25 75 0 0 0 0 Home 0 0 100 0 0 0 Create user 0 0 20 5 55 20 Login 10 0 50 0 20 20 Logout 0 0 0 10 40 50 Post thought 0 0 0 20 50 30 Subscribe Should give us the following steady-state results: 0.015555301383965 Home (~2%) 0.011666476037974 Create user (~1%) 0.087498570284802 Login (~9%) 0.116664760379736 Logout (~12%) 0.414331465172151 Post thought (~41%) 0.354283426741404 Subscribe (~35%) */ public static final int HOME_PAGE = 0; public static final int CREATE_USER = 1; public static final int LOGIN = 2; public static final int LOGOUT = 3; public static final int POST_THOUGHT = 4; public static final int CREATE_SUBSCRIPTION = 5; public static final String HOSTNAME_PORT_SEPARATOR = ":"; private boolean _usePooling = false; private boolean _debug = false; private HttpTransport _http; private Random _rand; private NegativeExponential _thinkTimeGenerator = null; private NegativeExponential _cycleTimeGenerator = null; // App urls public String _baseUrl; public String _homeUrl; public String _createUserUrl; public String _createUserResultUrl; public String _loginUrl; public String _loginResultUrl; public String _postThoughtUrlTemplate; public String _postThoughtResultUrlTemplate; public String _createSubscriptionResultUrlTemplate; public String _logoutUrl; // Application-specific variables private boolean _isLoggedIn = false; private boolean _usingZookeeper = false; //private ZooKeeper _zconn = null; //private boolean _appServerListChanged = false; private String[] _appServers = null; private int _currentAppServer = 0; //private String _zkConnString = ""; //private String _zkPath = ""; public String _loginAuthToken; public String _username; public ScadrGenerator(ScenarioTrack track) { super(track); this._rand = new Random(); } public void initializeUrls( String targetHost, int port ) { this._baseUrl = "http://" + targetHost + ":" + port; this._homeUrl = this._baseUrl; this._createUserUrl = this._baseUrl + "/users/new"; this._createUserResultUrl = this._baseUrl + "/users"; this._loginUrl = this._baseUrl; this._loginResultUrl = this._baseUrl + "/user_session"; this._postThoughtUrlTemplate = this._baseUrl + "/users/%s"; this._postThoughtResultUrlTemplate = this._baseUrl + "/users/%s/thoughts"; this._createSubscriptionResultUrlTemplate = this._baseUrl + "/users/%s/subscriptions"; this._logoutUrl = this._baseUrl + "/logout"; this.initializeStaticUrls(); } public boolean getIsLoggedIn() { return this._isLoggedIn; } public void setIsLoggedIn( boolean val ) { this._isLoggedIn = val; } public boolean getIsDebugMode() { return this._debug; } @Override public void dispose() {} @Override public void initialize() { this._http = new HttpTransport(); // Initialize think/cycle time random number generators (if you need/want them) this._cycleTimeGenerator = new NegativeExponential( this._cycleTime ); this._thinkTimeGenerator = new NegativeExponential( this._thinkTime ); } @Override public void configure( JSONObject config ) throws JSONException { if( config.has(CFG_USE_POOLING_KEY) ) this._usePooling = config.getBoolean( CFG_USE_POOLING_KEY ); if( config.has( CFG_DEBUG_KEY) ) this._debug = config.getBoolean( CFG_DEBUG_KEY ); ScadrScenarioTrack scadrTrack = null; String zkConnString = ""; String zkPath = ""; // Get the zookeeper parameter from the RainConfig first. If that doesn't // exist then get it from the generator config parameters try { String zkString = RainConfig.getInstance()._zooKeeper; if( zkString != null && zkString.trim().length() > 0 ) zkConnString = zkString; else zkConnString = config.getString( CFG_ZOOKEEPER_CONN_STRING ); zkPath = RainConfig.getInstance()._zkPath; if( zkPath == null || zkPath.trim().length() == 0 ) zkPath = config.getString( CFG_ZOOKEEPER_APP_SERVER_PATH ); // Get the track - see whether it's the "right" kind of track if( this._loadTrack instanceof ScadrScenarioTrack ) { scadrTrack = (ScadrScenarioTrack) this._loadTrack; scadrTrack.configureZooKeeper( zkConnString, zkPath ); if( scadrTrack.isConfigured() ) this._usingZookeeper = true; } } catch( JSONException e ) { System.out.println( this + "Error obtaining ZooKeeper info from RainConfig instance or generator paramters. Falling back on targetHost and port." ); this._usingZookeeper = false; } if( this._usingZookeeper ) { this._appServers = scadrTrack.getAppServers(); // Pick an app server @ random and use that as the target host this._currentAppServer = this._rand.nextInt( this._appServers.length ); String[] appServerNamePort = this._appServers[this._currentAppServer].split( HOSTNAME_PORT_SEPARATOR ); if( appServerNamePort.length == 2 ) this.initializeUrls( appServerNamePort[0], Integer.parseInt( appServerNamePort[1]) ); else if( appServerNamePort.length == 1 ) this.initializeUrls( appServerNamePort[0], DEFAULT_APP_SERVER_PORT ); } else { String appServer = this.getTrack().getTargetHostName() + HOSTNAME_PORT_SEPARATOR + this.getTrack().getTargetHostPort(); this._appServers = new String[1]; this._appServers[0] = appServer; this._currentAppServer = 0; this.initializeUrls( this.getTrack().getTargetHostName(), this.getTrack().getTargetHostPort() ); } } public void initializeStaticUrls() { this.homepageStatics = joinStatics( HOMEPAGE_STATICS ); this.loginpageStatics = joinStatics( LOGINPAGE_STATICS ); this.createuserpageStatics = joinStatics( CREATEUSERPAGE_STATICS ); this.postthoughtpageStatics = joinStatics( POSTTHOUGHTPAGE_STATICS ); } /* Pass in index of the last operation */ @Override public Operation nextRequest(int lastOperation) { // Get the current load profile if we need to look inside of it to decide // what to do next LoadProfile currentLoad = this.getTrack().getCurrentLoadProfile(); this._latestLoadProfile = currentLoad; //if( true ) // return getOperation( 0 ); int nextOperation = -1; if( lastOperation == -1 ) { nextOperation = 0; } else { if( this._usingZookeeper ) { ScadrScenarioTrack scadrTrack = (ScadrScenarioTrack) this._loadTrack; if( scadrTrack.getAppServerListChanged() ) { // Get new data if( scadrTrack.updateAppServerList() ) this._currentAppServer = 0; // Reset the list } // Always get the list of app servers cached in the track - this doesn't cause a query to // ZooKeeper this._appServers = scadrTrack.getAppServers(); } if( this._appServers == null ) { String appServer = this.getTrack().getTargetHostName() + HOSTNAME_PORT_SEPARATOR + this.getTrack().getTargetHostPort(); this._appServers = new String[1]; this._appServers[0] = appServer; this._currentAppServer = 0; this.initializeUrls( this.getTrack().getTargetHostName(), this.getTrack().getTargetHostPort() ); } // Pick the new target based on the current app server value String nextAppServerHostPort[] = null; if( this._currentAppServer >= this._appServers.length ) this._currentAppServer = 0; // Reset the current application server if( this._appServers.length == 0 ) { System.out.println( "No app servers available to target. Executing no-op." ); return null; // no-op } nextAppServerHostPort = this._appServers[this._currentAppServer].split( HOSTNAME_PORT_SEPARATOR ); if( nextAppServerHostPort.length == 2 ) this.initializeUrls( nextAppServerHostPort[0], Integer.parseInt( nextAppServerHostPort[1] ) ); else if( nextAppServerHostPort.length == 1 ) this.initializeUrls( nextAppServerHostPort[0], DEFAULT_APP_SERVER_PORT ); // Update the current app server value this._currentAppServer = (this._currentAppServer + 1) % this._appServers.length; // Get the selection matrix double[][] selectionMix = this.getTrack().getMixMatrix( currentLoad.getMixName() ).getSelectionMix(); double rand = this._rand.nextDouble(); int j; for ( j = 0; j < selectionMix.length; j++ ) { if ( rand <= selectionMix[lastOperation][j] ) { break; } } nextOperation = j; } return getOperation( nextOperation ); } private ScadrOperation getOperation( int opIndex ) { switch( opIndex ) { case HOME_PAGE: return this.createHomePageOperation(); case CREATE_USER: return this.createNewUserOperation(); case LOGIN: return this.createLoginOperation(); case LOGOUT: return this.createLogoutOperation(); case CREATE_SUBSCRIPTION: return this.createSubscriptionOperation(); case POST_THOUGHT: return this.createPostThoughtOperation(); default: return null; } } // Factory methods for creating operations public HomePageOperation createHomePageOperation() { HomePageOperation op = null; if( this._usePooling ) { ObjectPool pool = this.getTrack().getObjectPool(); op = (HomePageOperation) pool.rentObject( HomePageOperation.NAME ); } if( op == null ) op = new HomePageOperation( this.getTrack().getInteractive(), this.getScoreboard() ); op.prepare( this ); return op; } public LoginOperation createLoginOperation() { LoginOperation op = null; if( this._usePooling ) { ObjectPool pool = this.getTrack().getObjectPool(); op = (LoginOperation) pool.rentObject( LoginOperation.NAME ); } if( op == null ) op = new LoginOperation( this.getTrack().getInteractive(), this.getScoreboard() ); op.prepare( this ); return op; } public CreateUserOperation createNewUserOperation() { CreateUserOperation op = null; if( this._usePooling ) { ObjectPool pool = this.getTrack().getObjectPool(); op = (CreateUserOperation) pool.rentObject( CreateUserOperation.NAME ); } if( op == null ) op = new CreateUserOperation( this.getTrack().getInteractive(), this.getScoreboard() ); op.prepare( this ); return op; } public CreateSubscriptionOperation createSubscriptionOperation() { CreateSubscriptionOperation op = null; if( this._usePooling ) { ObjectPool pool = this.getTrack().getObjectPool(); op = (CreateSubscriptionOperation) pool.rentObject( CreateSubscriptionOperation.NAME ); } if( op == null ) op = new CreateSubscriptionOperation( this.getTrack().getInteractive(), this.getScoreboard() ); op.prepare( this ); return op; } public PostThoughtOperation createPostThoughtOperation() { PostThoughtOperation op = null; if( this._usePooling ) { ObjectPool pool = this.getTrack().getObjectPool(); op = (PostThoughtOperation) pool.rentObject( PostThoughtOperation.NAME ); } if( op == null ) op = new PostThoughtOperation( this.getTrack().getInteractive(), this.getScoreboard() ); op.prepare( this ); return op; } public LogoutOperation createLogoutOperation() { LogoutOperation op = null; if( this._usePooling ) { ObjectPool pool = this.getTrack().getObjectPool(); op = (LogoutOperation) pool.rentObject( LogoutOperation.NAME ); } if( op == null ) op = new LogoutOperation( this.getTrack().getInteractive(), this.getScoreboard() ); op.prepare( this ); return op; } private String[] joinStatics( String[] ... staticsLists ) { LinkedHashSet<String> urlSet = new LinkedHashSet<String>(); for ( String[] staticList : staticsLists ) { for ( int i = 0; i < staticList.length; i++ ) { String url = ""; if( staticList[i].trim().startsWith( "http: url = staticList[i].trim(); else url = this._baseUrl + staticList[i].trim(); urlSet.add( url ); } } return (String[]) urlSet.toArray(new String[0]); } /** * Returns the pre-existing HTTP transport. * * @return An HTTP transport. */ public HttpTransport getHttpTransport() { return this._http; } @Override public long getCycleTime() { if( this._cycleTime == 0 ) return 0; else { // Example cycle time generator long nextCycleTime = (long) this._cycleTimeGenerator.nextDouble(); // Truncate at 5 times the mean (arbitrary truncation) return Math.min( nextCycleTime, (5*this._cycleTime) ); } } @Override public long getThinkTime() { if( this._thinkTime == 0 ) return 0; else { //Example think time generator long nextThinkTime = (long) this._thinkTimeGenerator.nextDouble(); // Truncate at 5 times the mean (arbitrary truncation) return Math.min( nextThinkTime, (5*this._thinkTime) ); } } }
package com.ibm.streamsx.rest; import java.io.IOException; import java.math.BigInteger; import java.util.List; import org.apache.http.client.fluent.Executor; import com.ibm.streamsx.topology.internal.streams.InvokeCancel; /** * Connection to IBM Streams. */ public class StreamsConnection { IStreamsConnection delegate; protected boolean allowInsecure; private String userName; private String authToken; private String url; /** * @deprecated No replacement {@code StreamsConnection} is not intended to be sub-classed. */ @Deprecated protected String apiKey; /** * @deprecated No replacement {@code StreamsConnection} is not intended to be sub-classed. */ @Deprecated protected Executor executor; StreamsConnection(IStreamsConnection delegate, boolean allowInsecure) { this.delegate = delegate; this.allowInsecure = allowInsecure; refreshState(); } /** * @deprecated No replacement {@code StreamsConnection} is not intended to be sub-classed. */ @Deprecated protected StreamsConnection(String userName, String authToken, String url) { this(createDelegate(userName, authToken, url), false); } /** * Connection to IBM Streams * * @param userName * String representing the userName to connect to the instance * @param authToken * String representing the password to connect to the instance * @param url * String representing the root url to the REST API * @return a connection to IBM Streams */ public static StreamsConnection createInstance(String userName, String authToken, String url) { IStreamsConnection delegate = createDelegate(userName, authToken, url); StreamsConnection sc = new StreamsConnection(delegate, false); sc.userName = userName; sc.authToken = authToken; sc.url = url; return sc; } /** * This function is used to disable checking the trusted certificate chain * and should never be used in production environments * * @param allowInsecure * <ul> * <li>true - disables checking</li> * <li>false - enables checking (default)</li> * </ul> * @return a boolean indicating the state of the connection after this * method was called. * <ul> * <li>true - if checking is disabled</li> * <li>false - if checking is enabled</li> * </ul> */ public boolean allowInsecureHosts(boolean allowInsecure) { refreshState(); if (allowInsecure != this.allowInsecure && null != userName && null != authToken && null != url) { try { StreamsConnectionImpl connection = new StreamsConnectionImpl(userName, StreamsRestUtils.createBasicAuth(userName, authToken), url, allowInsecure); connection.init(); delegate = connection; this.allowInsecure = allowInsecure; } catch (IOException e) { // Don't change current allowInsecure but update delegate in // case new exception is more informative. delegate = new InvalidStreamsConnection(e); } } return this.allowInsecure; } /** * Cancels a job at this streams connection identified by the jobId * * @param jobId * string identifying the job to be cancelled * @return a boolean indicating * <ul> * <li>true if the jobId is cancelled</li> * <li>false if the jobId did not get cancelled</li> * </ul> * @throws Exception */ public boolean cancelJob(String jobId) throws Exception { refreshState(); InvokeCancel cancelJob = new InvokeCancel(new BigInteger(jobId), userName); return cancelJob.invoke(false) == 0; } /** * Gets a specific {@link Instance instance} identified by the instanceId at * this IBM Streams connection * * @param instanceId * name of the instance to be retrieved * @return a single {@link Instance} * @throws IOException */ public Instance getInstance(String instanceId) throws IOException { refreshState(); return delegate.getInstance(instanceId); } /** * Gets a list of {@link Instance instances} that are available to this IBM * Streams connection * * @return List of {@link Instance IBM Streams Instances} available to this * connection * @throws IOException */ public List<Instance> getInstances() throws IOException { refreshState(); return delegate.getInstances(); } // Refresh protected members from the previous implementation void refreshState() { if (delegate instanceof AbstractStreamsConnection) { AbstractStreamsConnection asc = (AbstractStreamsConnection)delegate; apiKey = asc.getAuthorization(); executor = asc.getExecutor(); } } /** * @deprecated No replacement {@code StreamsConnection} is not intended to be sub-classed. */ @Deprecated protected void setStreamsRESTURL(String url) { delegate = createDelegate(userName, authToken, url); refreshState(); } private static IStreamsConnection createDelegate(String userName, String authToken, String url) { IStreamsConnection delegate = null; try { StreamsConnectionImpl connection = new StreamsConnectionImpl(userName, StreamsRestUtils.createBasicAuth(userName, authToken), url, false); connection.init(); delegate = connection; } catch (Exception e) { delegate = new InvalidStreamsConnection(e); } return delegate; } // Since the original class never threw on exception on creation, we need a // dummy class that will throw on use. static class InvalidStreamsConnection implements IStreamsConnection { private final static String MSG = "Invalid Streams connection"; private final Exception exception; InvalidStreamsConnection(Exception e) { exception = e; } @Override public Instance getInstance(String instanceId) throws IOException { throw new RESTException(MSG, exception); } @Override public List<Instance> getInstances() throws IOException { throw new RESTException(MSG, exception); } } }
package ai.onnxruntime; import ai.onnxruntime.OrtSession.SessionOptions; import java.io.IOException; import java.util.EnumSet; import java.util.logging.Logger; /** * The host object for the onnx-runtime system. Can create {@link OrtSession}s which encapsulate * specific models. * * <p>There can be at most one OrtEnvironment object created in a JVM lifetime. This class * implements {@link AutoCloseable} as before for backwards compatibility with 1.10 and earlier, but * the close method is a no-op. The environment is closed by a JVM shutdown hook registered on * construction. */ public final class OrtEnvironment implements AutoCloseable { private static final Logger logger = Logger.getLogger(OrtEnvironment.class.getName()); public static final String DEFAULT_NAME = "ort-java"; static { try { OnnxRuntime.init(); } catch (IOException e) { throw new RuntimeException("Failed to load onnx-runtime library", e); } } private static volatile OrtEnvironment INSTANCE; private static volatile OrtLoggingLevel curLogLevel; private static volatile String curLoggingName; /** * Gets the OrtEnvironment. If there is not an environment currently created, it creates one using * {@link OrtEnvironment#DEFAULT_NAME} and {@link OrtLoggingLevel#ORT_LOGGING_LEVEL_WARNING}. * * @return The OrtEnvironment singleton. */ public static synchronized OrtEnvironment getEnvironment() { if (INSTANCE == null) { // If there's no instance, create one. return getEnvironment(OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING, DEFAULT_NAME); } else { return INSTANCE; } } /** * Gets the OrtEnvironment. If there is not an environment currently created, it creates one using * the supplied name and {@link OrtLoggingLevel#ORT_LOGGING_LEVEL_WARNING}. * * <p>If the environment already exists then it returns the existing one and logs a warning if the * name or log level is different from the requested one. * * @param name The logging id of the environment. * @return The OrtEnvironment singleton. */ public static OrtEnvironment getEnvironment(String name) { return getEnvironment(OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING, name); } /** * Gets the OrtEnvironment. If there is not an environment currently created, it creates one using * the {@link OrtEnvironment#DEFAULT_NAME} and the supplied logging level. * * <p>If the environment already exists then it returns the existing one and logs a warning if the * name or log level is different from the requested one. * * @param logLevel The logging level to use. * @return The OrtEnvironment singleton. */ public static OrtEnvironment getEnvironment(OrtLoggingLevel logLevel) { return getEnvironment(logLevel, DEFAULT_NAME); } /** * Gets the OrtEnvironment. If there is not an environment currently created, it creates one using * the supplied name and logging level. If an environment already exists with a different name, * that environment is returned and a warning is logged. * * @param loggingLevel The logging level to use. * @param name The log id. * @return The OrtEnvironment singleton. */ public static synchronized OrtEnvironment getEnvironment( OrtLoggingLevel loggingLevel, String name) { if (INSTANCE == null) { try { INSTANCE = new OrtEnvironment(loggingLevel, name); curLogLevel = loggingLevel; curLoggingName = name; } catch (OrtException e) { throw new IllegalStateException("Failed to create OrtEnvironment", e); } } else { if ((loggingLevel.getValue() != curLogLevel.getValue()) || (!name.equals(curLoggingName))) { logger.warning( "Tried to change OrtEnvironment's logging level or name while a reference exists."); } } return INSTANCE; } public static synchronized OrtEnvironment getEnvironment( OrtLoggingLevel loggingLevel, String name, ThreadingOptions threadOptions) { if (INSTANCE == null) { try { INSTANCE = new OrtEnvironment(loggingLevel, name, threadOptions); curLogLevel = loggingLevel; curLoggingName = name; } catch (OrtException e) { throw new IllegalStateException("Failed to create OrtEnvironment", e); } return INSTANCE; } else { // As the thread pool state is unknown, and that's probably not what the user wanted. throw new IllegalStateException( "Tried to specify the thread pool when creating an OrtEnvironment, but one already exists."); } } final long nativeHandle; final OrtAllocator defaultAllocator; /** * Create an OrtEnvironment using a default name. * * @throws OrtException If the environment couldn't be created. */ private OrtEnvironment() throws OrtException { this(OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING, "java-default"); } /** * Create an OrtEnvironment using the specified name and log level. * * @param loggingLevel The logging level to use. * @param name The logging id of the environment. * @throws OrtException If the environment couldn't be created. */ private OrtEnvironment(OrtLoggingLevel loggingLevel, String name) throws OrtException { nativeHandle = createHandle(OnnxRuntime.ortApiHandle, loggingLevel.getValue(), name); defaultAllocator = new OrtAllocator(getDefaultAllocator(OnnxRuntime.ortApiHandle), true); Runtime.getRuntime() .addShutdownHook(new Thread(new OrtEnvCloser(OnnxRuntime.ortApiHandle, nativeHandle))); } /** * Create an OrtEnvironment using the specified name, log level and threading options. * * @param loggingLevel The logging level to use. * @param name The logging id of the environment. * @param threadOptions The global thread pool configuration. * @throws OrtException If the environment couldn't be created. */ private OrtEnvironment(OrtLoggingLevel loggingLevel, String name, ThreadingOptions threadOptions) throws OrtException { nativeHandle = createHandle( OnnxRuntime.ortApiHandle, loggingLevel.getValue(), name, threadOptions.nativeHandle); defaultAllocator = new OrtAllocator(getDefaultAllocator(OnnxRuntime.ortApiHandle), true); Runtime.getRuntime() .addShutdownHook(new Thread(new OrtEnvCloser(OnnxRuntime.ortApiHandle, nativeHandle))); } /** * Create a session using the default {@link SessionOptions}, model and the default memory * allocator. * * @param modelPath Path on disk to load the model from. * @return An {@link OrtSession} with the specified model. * @throws OrtException If the model failed to load, wasn't compatible or caused an error. */ public OrtSession createSession(String modelPath) throws OrtException { return createSession(modelPath, new OrtSession.SessionOptions()); } /** * Create a session using the specified {@link SessionOptions}, model and the default memory * allocator. * * @param modelPath Path on disk to load the model from. * @param options The session options. * @return An {@link OrtSession} with the specified model. * @throws OrtException If the model failed to load, wasn't compatible or caused an error. */ public OrtSession createSession(String modelPath, SessionOptions options) throws OrtException { return createSession(modelPath, defaultAllocator, options); } /** * Create a session using the specified {@link SessionOptions} and model. * * @param modelPath Path on disk to load the model from. * @param allocator The memory allocator to use. * @param options The session options. * @return An {@link OrtSession} with the specified model. * @throws OrtException If the model failed to load, wasn't compatible or caused an error. */ OrtSession createSession(String modelPath, OrtAllocator allocator, SessionOptions options) throws OrtException { return new OrtSession(this, modelPath, allocator, options); } /** * Create a session using the specified {@link SessionOptions}, model and the default memory * allocator. * * @param modelArray Byte array representing an ONNX model. * @param options The session options. * @return An {@link OrtSession} with the specified model. * @throws OrtException If the model failed to parse, wasn't compatible or caused an error. */ public OrtSession createSession(byte[] modelArray, SessionOptions options) throws OrtException { return createSession(modelArray, defaultAllocator, options); } /** * Create a session using the default {@link SessionOptions}, model and the default memory * allocator. * * @param modelArray Byte array representing an ONNX model. * @return An {@link OrtSession} with the specified model. * @throws OrtException If the model failed to parse, wasn't compatible or caused an error. */ public OrtSession createSession(byte[] modelArray) throws OrtException { return createSession(modelArray, new OrtSession.SessionOptions()); } /** * Create a session using the specified {@link SessionOptions} and model. * * @param modelArray Byte array representing an ONNX model. * @param allocator The memory allocator to use. * @param options The session options. * @return An {@link OrtSession} with the specified model. * @throws OrtException If the model failed to parse, wasn't compatible or caused an error. */ OrtSession createSession(byte[] modelArray, OrtAllocator allocator, SessionOptions options) throws OrtException { return new OrtSession(this, modelArray, allocator, options); } /** * Turns on or off the telemetry. * * @param sendTelemetry If true then send telemetry on onnxruntime usage. * @throws OrtException If the call failed. */ public void setTelemetry(boolean sendTelemetry) throws OrtException { setTelemetry(OnnxRuntime.ortApiHandle, nativeHandle, sendTelemetry); } @Override public String toString() { return "OrtEnvironment(name=" + curLoggingName + ",logLevel=" + curLogLevel + ")"; } /** * Gets the providers available in this environment. * * @return An enum set of the available execution providers. */ public static EnumSet<OrtProvider> getAvailableProviders() { return OnnxRuntime.providers.clone(); } /** * Creates the native object. * * @param apiHandle The API pointer. * @param loggingLevel The logging level. * @param name The name of the environment. * @return The pointer to the native object. * @throws OrtException If the creation failed. */ private static native long createHandle(long apiHandle, int loggingLevel, String name) throws OrtException; /** * Creates the native object with a global thread pool. * * @param apiHandle The API pointer. * @param loggingLevel The logging level. * @param name The name of the environment. * @param threadOptionsHandle The threading options handle. * @return The pointer to the native object. * @throws OrtException If the creation failed. */ private static native long createHandle( long apiHandle, int loggingLevel, String name, long threadOptionsHandle) throws OrtException; /** * Gets a reference to the default allocator. * * @param apiHandle The API handle to use. * @return A pointer to the default allocator. * @throws OrtException If it failed to get the allocator. */ private static native long getDefaultAllocator(long apiHandle) throws OrtException; /** * Closes the OrtEnvironment, frees the handle. * * @param apiHandle The API pointer. * @param nativeHandle The handle to free. * @throws OrtException If an error was caused by freeing the handle. */ private static native void close(long apiHandle, long nativeHandle) throws OrtException; /** * Enables or disables the telemetry. * * @param apiHandle The API pointer. * @param nativeHandle The native handle for the environment. * @param sendTelemetry Turn on or off the telemetry. * @throws OrtException If an error was caused when setting the telemetry status. */ private static native void setTelemetry(long apiHandle, long nativeHandle, boolean sendTelemetry) throws OrtException; /** Close is a no-op on OrtEnvironment since ORT 1.11. */ @Override public void close() {} /** * Controls the global thread pools in the environment. Only used if the session is constructed * using an options with {@link OrtSession.SessionOptions#disablePerSessionThreads()} set. */ public static final class ThreadingOptions implements AutoCloseable { static { try { OnnxRuntime.init(); } catch (IOException e) { throw new RuntimeException("Failed to load onnx-runtime library", e); } } private final long nativeHandle; private boolean closed = false; /** Create an empty threading options. */ public ThreadingOptions() { nativeHandle = createThreadingOptions(OnnxRuntime.ortApiHandle); } private void checkClosed() { if (closed) { throw new IllegalStateException("Trying to use a closed ThreadingOptions"); } } /** Closes the threading options. */ @Override public void close() { if (!closed) { closeThreadingOptions(OnnxRuntime.ortApiHandle, nativeHandle); closed = true; } else { throw new IllegalStateException("Trying to close a closed ThreadingOptions."); } } /** * Sets the number of threads available for inter-op parallelism (i.e. running multiple ops in * parallel). * * <p>Setting it to 0 will allow ORT to choose the number of threads, setting it to 1 will cause * the main thread to be used (i.e., no thread pools will be used). * * @param numThreads The number of threads. * @throws OrtException If there was an error in native code. */ public void setGlobalInterOpNumThreads(int numThreads) throws OrtException { checkClosed(); if (numThreads < 0) { throw new IllegalArgumentException("Number of threads must be non-negative."); } setGlobalInterOpNumThreads(OnnxRuntime.ortApiHandle, nativeHandle, numThreads); } /** * Sets the number of threads available for intra-op parallelism (i.e. within a single op). * * <p>Setting it to 0 will allow ORT to choose the number of threads, setting it to 1 will cause * the main thread to be used (i.e., no thread pools will be used). * * @param numThreads The number of threads. * @throws OrtException If there was an error in native code. */ public void setGlobalIntraOpNumThreads(int numThreads) throws OrtException { checkClosed(); if (numThreads < 0) { throw new IllegalArgumentException("Number of threads must be non-negative."); } setGlobalIntraOpNumThreads(OnnxRuntime.ortApiHandle, nativeHandle, numThreads); } /** * Allows spinning of thread pools when their queues are empty. This call sets the value for * both inter-op and intra-op thread pools. * * <p>If the CPU usage is very high then do not enable this. * * @param allowSpinning If true allow the thread pools to spin. * @throws OrtException If there was an error in native code. */ public void setGlobalSpinControl(boolean allowSpinning) throws OrtException { checkClosed(); setGlobalSpinControl(OnnxRuntime.ortApiHandle, nativeHandle, allowSpinning ? 1 : 0); } /** * When this is set it causes intra-op and inter-op thread pools to flush denormal values to * zero. * * @throws OrtException If there was an error in native code. */ public void setGlobalDenormalAsZero() throws OrtException { checkClosed(); setGlobalDenormalAsZero(OnnxRuntime.ortApiHandle, nativeHandle); } private static native long createThreadingOptions(long apiHandle); private native void setGlobalIntraOpNumThreads( long apiHandle, long nativeHandle, int numThreads) throws OrtException; private native void setGlobalInterOpNumThreads( long apiHandle, long nativeHandle, int numThreads) throws OrtException; private native void setGlobalSpinControl(long apiHandle, long nativeHandle, int allowSpinning) throws OrtException; private native void setGlobalDenormalAsZero(long apiHandle, long nativeHandle) throws OrtException; private native void closeThreadingOptions(long apiHandle, long nativeHandle); } private static final class OrtEnvCloser implements Runnable { private final long apiHandle; private final long nativeHandle; OrtEnvCloser(long apiHandle, long nativeHandle) { this.apiHandle = apiHandle; this.nativeHandle = nativeHandle; } @Override public void run() { try { OrtEnvironment.close(apiHandle, nativeHandle); } catch (OrtException e) { System.err.println("Error closing OrtEnvironment, " + e); } } } }
package tv.studer.smssync; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import com.android.email.mail.*; import com.android.email.mail.internet.BinaryTempFileBody; import org.apache.commons.io.IOUtils; import java.util.HashSet; import java.util.Set; import static tv.studer.smssync.CursorToMessage.Headers.*; import static tv.studer.smssync.ServiceBase.SmsSyncState.*; public class SmsRestoreService extends ServiceBase { public static final String TAG = "SmsRestoreService"; private static int currentRestoredItems; private static int itemsToRestoreCount; private static boolean sIsRunning = false; private static SmsSyncState sState; private static boolean sCanceled = false; public static void cancel() { sCanceled = true; } public static boolean isWorking() { return sIsRunning; } public static boolean isCancelling() { return sCanceled; } public static int getCurrentRestoredItems() { return currentRestoredItems; } public static int getItemsToRestoreCount() { return itemsToRestoreCount; } private class RestoreTask extends AsyncTask<Integer, Integer, Integer> { private Set<String> ids = new HashSet<String>(); private Set<String> uids = new HashSet<String>(); private int max; protected java.lang.Integer doInBackground(Integer... params) { this.max = params.length > 0 ? params[0] : -1; try { acquireWakeLock(); sIsRunning = true; updateState(LOGIN); Folder folder = getBackupFolder(); updateState(CALC); Message[] msgs = folder.getMessages(null); itemsToRestoreCount = msgs.length; long lastPublished = System.currentTimeMillis(); for (int i = 0; i < msgs.length; i++) { if (sCanceled) { Log.i(TAG, "Restore canceled by user."); updateState(CANCELED); updateAllThreads(); return ids.size(); } importMessage(msgs[i]); // help GC msgs[i] = null; if (System.currentTimeMillis() - lastPublished > 1000) { // don't publish too often or we get ANRs publishProgress(i); lastPublished = System.currentTimeMillis(); } } publishProgress(msgs.length); updateAllThreads(); updateState(IDLE); Log.d(TAG, "finished (" + ids.size() + "/" + uids.size() + ")"); return ids.size(); } catch (AuthenticationErrorException authError) { Log.e(TAG, "error", authError); updateState(AUTH_FAILED); return -1; } catch (MessagingException e) { Log.e(TAG, "error", e); updateState(GENERAL_ERROR); return -1; } finally { releaseWakeLock(); sCanceled = false; sIsRunning = false; } } protected void onProgressUpdate(Integer... progress) { currentRestoredItems = progress[0]; updateState(RESTORE); } protected void onPostExecute(Integer result) { } private void updateAllThreads() { // thread dates + states might be wrong, we need to force a full update // unfortunately there's no direct way to do that in the SDK, but passing a negative conversation // id to delete will to the trick if (ids.isEmpty()) return; // execute in background, might take some time new Thread() { @Override public void run() { Log.d(TAG, "updating threads"); getContentResolver().delete(Uri.parse("content://sms/conversations/-1"), null, null); Log.d(TAG, "finished"); } }.start(); } private void importMessage(Message message) { uids.add(message.getUid()); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); try { Log.d(TAG, "fetching message uid " + message.getUid()); message.getFolder().fetch(new Message[]{message}, fp, null); ContentValues values = messageToContentValues(message); Integer type = values.getAsInteger(SmsConsts.TYPE); if (type == null) return; // only restore inbox messages and sent messages - otherwise sms might get sent on restore if ((type == SmsConsts.MESSAGE_TYPE_INBOX || type == SmsConsts.MESSAGE_TYPE_SENT) && !smsExists(values)) { Uri uri = getContentResolver().insert(SMS_PROVIDER, values); ids.add(uri.getLastPathSegment()); Log.d(TAG, "inserted " + uri); } else { Log.d(TAG, "ignoring sms"); } } catch (java.io.IOException e) { Log.e(TAG, "error", e); } catch (MessagingException e) { Log.e(TAG, "error", e); } } } @Override public void onCreate() { BinaryTempFileBody.setTempDirectory(getCacheDir()); } @Override public void onStart(final Intent intent, int startId) { super.onStart(intent, startId); synchronized (this.getClass()) { if (!sIsRunning) { new RestoreTask().execute(-1); } } } private boolean smsExists(ContentValues values) { // just assume equality on date+address+type Cursor c = getContentResolver().query(SMS_PROVIDER, new String[]{"_id"}, "date = ? AND address = ? AND type = ?", new String[]{values.getAsString(SmsConsts.DATE), values.getAsString(SmsConsts.ADDRESS), values.getAsString(SmsConsts.TYPE)}, null ); boolean exists = c.getCount() > 0; c.close(); return exists; } private ContentValues messageToContentValues(Message message) throws java.io.IOException, MessagingException { ContentValues values = new ContentValues(); String body = IOUtils.toString(message.getBody().getInputStream()); values.put(SmsConsts.BODY, body); values.put(SmsConsts.ADDRESS, getHeader(message, ADDRESS)); values.put(SmsConsts.TYPE, getHeader(message, TYPE)); values.put(SmsConsts.PROTOCOL, getHeader(message, PROTOCOL)); values.put(SmsConsts.READ, getHeader(message, READ)); values.put(SmsConsts.SERVICE_CENTER, getHeader(message, SERVICE_CENTER)); values.put(SmsConsts.DATE, getHeader(message, DATE)); values.put(SmsConsts.STATUS, getHeader(message, STATUS)); return values; } private static void updateState(SmsSyncState newState) { SmsSyncState old = sState; sState = newState; smsSync.getStatusPreference().stateChanged(old, newState); } }
package com.microsoft.storageperf; import java.io.IOException; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import com.azure.storage.blob.BlobClientBuilder; import com.azure.storage.blob.BlockBlobAsyncClient; import org.apache.commons.cli.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public class App { private static final String _containerName = "testcontainer"; private static final String _blobName = "testblob"; public static void main(String[] args) throws InterruptedException, IOException { Options options = new Options(); Option durationOption = new Option("d", "duration", true, "Duration in seconds"); options.addOption(durationOption); Option parallelOption = new Option("p", "parallel", true, "Number of tasks to execute in parallel"); options.addOption(parallelOption); Option sizeOption = new Option("s", "size", true, "Size of message (in bytes)"); options.addOption(sizeOption); Option uploadOption = new Option("u", "upload", false, "Upload before download"); options.addOption(uploadOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("storageperf", options); System.exit(1); } int duration = Integer.parseInt(cmd.getOptionValue("duration", "10")); int parallel = Integer.parseInt(cmd.getOptionValue("parallel", "1")); int size = Integer.parseInt(cmd.getOptionValue("size", "10240")); boolean upload = cmd.hasOption("upload"); boolean debug = cmd.hasOption("debug"); String connectionString = System.getenv("STORAGE_CONNECTION_STRING"); if (connectionString == null || connectionString.isEmpty()) { System.out.println("Environment variable STORAGE_CONNECTION_STRING must be set"); System.exit(1); } Run(connectionString, debug, upload, duration, parallel, size); } static void Run(String connectionString, Boolean debug, Boolean upload, int duration, int parallel, int size) { BlockBlobAsyncClient client = new BlobClientBuilder().connectionString(connectionString) .containerName(_containerName).blobName(_blobName).buildBlockBlobAsyncClient(); if (upload) { UploadAndVerifyDownload(client, size).block(); } System.out.printf("Downloading blob '%s/%s' with %d parallel task(s) for %d second(s)...%n", _containerName, _blobName, parallel, duration); System.out.println(); AtomicInteger receivedSize = new AtomicInteger(-1); AtomicInteger counter = new AtomicInteger(); Flux.interval(Duration.ofSeconds(1)).subscribe(i -> System.out.println(counter.get())); long start = System.nanoTime(); Flux<Integer> downloads = downloadParallel(client, parallel) .take(Duration.ofSeconds(duration)) .doOnNext(i -> { if (receivedSize.get() == -1) { receivedSize.set(i); } counter.incrementAndGet(); }); downloads.blockLast(); long end = System.nanoTime(); double elapsedSeconds = 1.0 * (end - start) / 1000000000; double downloadsPerSecond = counter.get() / elapsedSeconds; double megabytesPerSecond = (downloadsPerSecond * receivedSize.get()) / (1024 * 1024); System.out.println(); System.out.printf("Downloaded %d blobs of size %d in %.2fs (%.2f blobs/s, %.2f MB/s)", counter.get(), receivedSize.get(), elapsedSeconds, downloadsPerSecond, megabytesPerSecond); } static Flux<Integer> downloadParallel(BlockBlobAsyncClient client, int parallel) { return Flux.just(1).repeat().flatMap(i -> downloadOneBlob(client), parallel); } static Mono<Integer> downloadOneBlob(BlockBlobAsyncClient client) { return client .download() // Mono<Flux<ByteBuffer>> .flatMap(f -> f .reduce(0, (i, b) -> { // System.out.println(Thread.currentThread().getName()); int remaining = b.remaining(); b.get(new byte[remaining]); return i + remaining; })); } static Mono<Void> UploadAndVerifyDownload(BlockBlobAsyncClient client, int size) { byte[] payload = new byte[size]; (new Random(0)).nextBytes(payload); Flux<ByteBuffer> payloadStream = Flux.just(ByteBuffer.wrap(payload)); client.upload(payloadStream, size).block(); return Mono.empty(); // TODO: Verify download } }
package restservices.publish; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.Map.Entry; import org.codehaus.jackson.annotate.JsonProperty; import org.json.JSONException; import org.json.JSONObject; import restservices.RestServices; import restservices.consume.JsonDeserializer; import restservices.consume.ObjectCache; import restservices.util.Utils; import com.google.common.collect.ImmutableMap; import com.mendix.core.Core; import com.mendix.core.CoreException; import com.mendix.m2ee.api.IMxRuntimeResponse; import com.mendix.systemwideinterfaces.connectionbus.requests.IRetrievalSchema; import com.mendix.systemwideinterfaces.connectionbus.requests.ISortExpression.SortDirection; import com.mendix.systemwideinterfaces.core.IContext; import com.mendix.systemwideinterfaces.core.IMendixIdentifier; import com.mendix.systemwideinterfaces.core.IMendixObject; import com.mendix.systemwideinterfaces.core.IMendixObject.ObjectState; import com.mendix.systemwideinterfaces.core.meta.IMetaAssociation; import com.mendix.systemwideinterfaces.core.meta.IMetaAssociation.AssociationType; import com.mendix.systemwideinterfaces.core.meta.IMetaObject; import com.mendix.systemwideinterfaces.core.meta.IMetaPrimitive; import com.sun.xml.internal.fastinfoset.stax.events.Util; import communitycommons.XPath; public class PublishedService { @JsonProperty private String servicename; @JsonProperty private String sourceentity; @JsonProperty private String constraint; public String getConstraint() { return constraint == null ? "" : constraint; } @JsonProperty private String idattribute; @JsonProperty private String publishentity; @JsonProperty private String publishmicroflow; private IMetaObject sourceMetaEntity; private IMetaObject publishMetaEntity; private ChangeManager changeManager = new ChangeManager(this); private String deletemicroflow; private boolean detectConflicts; private String updatemicroflow; public ChangeManager getChangeManager() { return changeManager; } public void consistencyCheck() { // source exists and persistent // keyattr exists // constraint is valid // name is a valid identifier // reserved attributes: _key, _etag } public String getName() { return servicename; } public String getSourceEntity() { return sourceentity; } public void serveListing(RestServiceRequest rsr) throws CoreException { IRetrievalSchema schema = Core.createRetrievalSchema(); schema.addSortExpression(this.idattribute, SortDirection.ASC); schema.addMetaPrimitiveName(this.idattribute); schema.setAmount(RestServices.BATCHSIZE); switch(rsr.getContentType()) { case HTML: rsr.startHTMLDoc(); break; case XML: rsr.startXMLDoc(); rsr.write("<items>"); break; case JSON: rsr.datawriter.array(); break; } long offset = 0; List<IMendixObject> result; rsr.datawriter.array(); do { schema.setOffset(offset); result = Core.retrieveXPathSchema(rsr.getContext(), "//" + this.sourceentity + this.getConstraint(), schema, false); for(IMendixObject item : result) { String key = item.getMember(rsr.getContext(), idattribute).parseValueToString(rsr.getContext()); if (!Utils.isValidKey(key)) continue; String url = this.getServiceUrl() + key; //TODO: url param encode key? rsr.datawriter.value(url); } offset += RestServices.BATCHSIZE; } while(!result.isEmpty()); rsr.datawriter.endArray(); switch(rsr.getContentType()) { case HTML: rsr.endHTMLDoc(); break; case XML: rsr.write("</items>"); break; case JSON: rsr.datawriter.endArray(); break; } rsr.close(); } public String getServiceUrl() { return Core.getConfiguration().getApplicationRootUrl() + "rest/" + this.servicename + "/"; } public void serveGet(RestServiceRequest rsr, String key) throws Exception { IMendixObject source = getObjectByKey(rsr.getContext(), key); if (source == null) { rsr.setStatus(keyExists(key)? 401 : IMxRuntimeResponse.NOT_FOUND); rsr.close(); return; } IMendixObject view = convertSourceToView(rsr.getContext(), source); JSONObject result = JsonSerializer.convertMendixObjectToJson(rsr.getContext(), view); String jsonString = result.toString(4); String eTag = Utils.getMD5Hash(jsonString); if (eTag.equals(rsr.getETag())) { rsr.setStatus(IMxRuntimeResponse.NOT_MODIFIED); rsr.close(); return; } rsr.response.setHeader(RestServices.ETAG_HEADER, eTag); result.put(RestServices.ETAG_ATTR, eTag); switch(rsr.getContentType()) { case JSON: rsr.write(jsonString); break; case HTML: rsr.startHTMLDoc(); rsr.write("<h1>").write(servicename).write("/").write(key).write("</h1>"); rsr.datawriter.value(result); rsr.endHTMLDoc(); break; case XML: rsr.startXMLDoc(); //TODO: doesnt JSON.org provide a toXML? rsr.write("<" + this.servicename + ">"); rsr.datawriter.value(result); rsr.write("</" + this.servicename + ">"); break; } rsr.close(); rsr.getContext().getSession().release(view.getId()); } private IMendixObject getObjectByKey(IContext context, String key) throws CoreException { String xpath = XPath.create(context, this.sourceentity).eq(this.idattribute, key).getXPath() + this.getConstraint(); List<IMendixObject> results = Core.retrieveXPathQuery(context, xpath, 1, 0, ImmutableMap.of("id", "ASC")); return results.size() == 0 ? null : results.get(0); } public void serveDelete(RestServiceRequest rsr, String key, String etag) throws Exception { //TODO: check delete api enabled? IMendixObject source = getObjectByKey(rsr.getContext(), key); if (source == null) { rsr.setStatus(keyExists(key) ? IMxRuntimeResponse.UNAUTHORIZED : IMxRuntimeResponse.NOT_FOUND); return; } verifyEtag(rsr.getContext(), source, etag); if (Utils.isNotEmpty(this.deletemicroflow)) Core.execute(rsr.getContext(), this.deletemicroflow, source); else Core.delete(rsr.getContext(), source); rsr.setStatus(204); //no content } public void servePost(RestServiceRequest rsr, JSONObject data) throws Exception { //TODO: if enabled String key = UUID.randomUUID().toString(); IMendixObject target = createNewObject(rsr.getContext(), key); updateObject(rsr.getContext(), target, data); rsr.setStatus(201); //created rsr.write(getObjecturl(rsr.getContext(), target)); rsr.close(); } public IMendixObject createNewObject(IContext context, String key) { IMendixObject target = Core.instantiate(context, getSourceEntity()); target.setValue(context, idattribute, key); return target; } public void servePut(RestServiceRequest rsr, String key, JSONObject data, String etag) throws Exception { IContext context = rsr.getContext(); IMendixObject target = getObjectByKey(context, key); if (target == null) { if (keyExists(key)){ rsr.setStatus(400); rsr.close(); return; } else { target = createNewObject(context, key); rsr.setStatus(201); } } else { //already existing target verifyEtag(rsr.getContext(), target, etag); rsr.setStatus(204); } updateObject(rsr.getContext(), target, data); rsr.close(); } private boolean keyExists(String key) throws CoreException { return getObjectByKey(Core.createSystemContext(), key) != null; } private void updateObject(IContext context, IMendixObject target, JSONObject data) throws Exception, Exception { Map<String, String> argtypes = Utils.getArgumentTypes(updatemicroflow); if (argtypes.size() != 2) throw new RuntimeException("Expected exactly two arguments for microflow " + updatemicroflow); //Determine argnames String viewArgName = null; String targetArgName = null; String viewArgType = null; for(Entry<String, String> e : argtypes.entrySet()) { if (e.getValue().equals(target.getType())) targetArgName = e.getKey(); else if (Core.getMetaObject(e.getValue()) != null) { viewArgName = e.getKey(); viewArgType = e.getValue(); } } if (targetArgName == null || viewArgName == null || Core.getMetaObject(viewArgType).isPersistable()) throw new RuntimeException("Microflow '" + updatemicroflow + "' should have one argument of type " + target.getType() + ", and one argument typed with an persistent entity"); IMendixObject view = Core.instantiate(context, viewArgType); JsonDeserializer.readJsonObjectIntoMendixObject(context, data, view, new ObjectCache(false)); Core.commit(context, view); Core.execute(context, updatemicroflow, ImmutableMap.of(targetArgName, (Object) target, viewArgName, (Object) view)); } private void verifyEtag(IContext context, IMendixObject source, String etag) throws Exception { if (!this.detectConflicts) return; IMendixObject view = convertSourceToView(context, source); JSONObject result = JsonSerializer.convertMendixObjectToJson(context, view); String jsonString = result.toString(4); String eTag = Utils.getMD5Hash(jsonString); if (!eTag.equals(etag)) throw new RuntimeException("Update conflict detected, expected change based on version '" + eTag + "', but found '" + etag + "'"); } public IMetaObject getSourceMetaEntity() { if (this.sourceMetaEntity == null) this.sourceMetaEntity = Core.getMetaObject(this.sourceentity); return this.sourceMetaEntity; } private IMetaObject getPublishMetaEntity() {//TODO: or not use property but reflect on convert microflow? if (this.publishMetaEntity == null) this.publishMetaEntity = Core.getMetaObject(this.publishentity); return this.publishMetaEntity; } public IMendixObject convertSourceToView(IContext context, IMendixObject source) throws CoreException { return (IMendixObject) Core.execute(context, this.publishmicroflow, source); } public boolean identifierInConstraint(IContext c, IMendixIdentifier id) throws CoreException { if (this.getConstraint().isEmpty()) return true; return Core.retrieveXPathQueryAggregate(c, "count(//" + this.sourceentity + "[id='" + id.toLong() + "']" + this.getConstraint()) == 1; } public String getObjecturl(IContext c, IMendixObject obj) { //Pre: inConstraint is checked!, obj is not null String key = getKey(c, obj); if (!Utils.isValidKey(key)) throw new IllegalStateException("Invalid key for object " + obj.toString()); return this.getServiceUrl() + key; } public String getKey(IContext c, IMendixObject obj) { return obj.getMember(c, idattribute).parseValueToString(c); } //TODO: replace with something recursive public Map<String, String> getPublishedMembers() { Map<String, String> res = new HashMap<String, String>(); for(IMetaPrimitive prim : this.getPublishMetaEntity().getMetaPrimitives()) res.put(prim.getName(), prim.getType().toString()); for(IMetaAssociation assoc : this.getPublishMetaEntity().getMetaAssociationsParent()) { PublishedService service = RestServices.getServiceForEntity(assoc.getChild().getName()); if (service == null) continue; String name = Utils.getShortMemberName(assoc.getName()); String type = assoc.getType() == AssociationType.REFERENCESET ? "[" + service.getServiceUrl() + "]" : service.getServiceUrl(); res.put(name, type); } return res; } public void serveServiceDescription(RestServiceRequest rsr) { rsr.datawriter.object() .key("name").value(this.servicename) .key("url").value(this.getServiceUrl()) .key("attributes").object(); for(Entry<String, String> e : getPublishedMembers().entrySet()) rsr.datawriter.key(e.getKey()).value(e.getValue()); rsr.datawriter.endObject().endObject(); } void debug(String msg) { if (RestServices.LOG.isDebugEnabled()) RestServices.LOG.debug(msg); } }
package com.sun.jna.examples; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.Calendar; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.event.MouseInputAdapter; /** Example which uses the {@link WindowUtils} class. Demonstrates the * definition of a cross-platform library with several platform-specific * implementations based on JNA native library definitions. */ public class ShapedWindowDemo { public static final int ICON_SIZE = 64; private static class ClockFace extends JComponent { private Stroke border; private Stroke secondHand; private Stroke minuteHand; private Stroke hourHand; private Stroke ticks; public ClockFace(Dimension size) { setPreferredSize(size); setSize(size); setOpaque(false); Timer timer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { repaint(); Window w = SwingUtilities.getWindowAncestor(ClockFace.this); while (!(w instanceof Frame)) { w = w.getOwner(); } if (w instanceof Frame) { ((Frame)w).setIconImage(getIconImage()); } } }); timer.setRepeats(true); timer.start(); } private String getRomanNumeral(int number) { switch(number) { case 1: return "I"; case 2: return "II"; case 3: return "III"; case 4: return "IV"; case 5: return "V"; case 6: return "VI"; case 7: return "VII"; case 8: return "VIII"; case 9: return "IX"; case 10: return "X"; case 11: return "XI"; case 12: default: return "XII"; } } protected void paintComponent(Graphics graphics) { paintFace(graphics, Math.min(getWidth(), getHeight())); } protected void paintFace(Graphics graphics, int size) { Point center = new Point(size/2, size/2); int radius = center.x; int margin = radius / 20; int w = size; border = new BasicStroke(Math.max(1f, w/150f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); secondHand = new BasicStroke(Math.max(1f, w/75f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); minuteHand = new BasicStroke(Math.max(1f, w/38f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); hourHand = new BasicStroke(Math.max(1.5f, w/20f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); ticks = new BasicStroke(1f); Graphics2D g = (Graphics2D)graphics.create(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Color bg = getBackground(); g.setColor(new Color(bg.getRed(), bg.getGreen(), bg.getBlue())); g.fill(new Ellipse2D.Float(0,0,size,size)); Font font = getFont(); g.setFont(font.deriveFont(Font.BOLD, size/12)); g.setColor(new Color(0,0,0,128)); g.setStroke(border); g.draw(new Ellipse2D.Float(0,0,size-1,size-1)); g.draw(new Ellipse2D.Float(margin,margin,size-margin*2-1,size-margin*2-1)); Calendar c = Calendar.getInstance(); int minute = c.get(Calendar.MINUTE); int hour = c.get(Calendar.HOUR); int second = c.get(Calendar.SECOND); g.translate(center.x, center.y); g.setColor(getForeground()); int numbers = radius * 3 / 4; for (int i=0;i < 12;i++) { double theta = Math.PI*2*i/12; String str = getRomanNumeral((i+2)%12+1); Rectangle2D rect = g.getFontMetrics().getStringBounds(str, g); g.drawString(str, Math.round(numbers*Math.cos(theta)-rect.getWidth()/2), Math.round(numbers*Math.sin(theta)+margin*2)); } for (int i=0;i < 60;i++) { g.setColor(getForeground()); g.setStroke(ticks); g.drawLine(radius-margin*2, 0, radius-margin, 0); if ((i % 5) == 0) { g.drawLine(radius-margin*3, 0, radius-margin, 0); } if ((i + 15) % 60 == minute) { g.setStroke(minuteHand); g.drawLine(0, 0, radius-margin*4, 0); } if ((i + 15) % 60 == (hour * 5 + minute * 5 / 60)) { g.setStroke(hourHand); g.drawLine(0, 0, radius/2, 0); } if ((i + 15) % 60 == second) { g.setColor(new Color(255, 0, 0, 128)); g.setStroke(secondHand); g.drawLine(0, 0, radius-margin*4, 0); } g.rotate(Math.PI*2/60); } g.dispose(); } public Image getIconImage() { BufferedImage image = new BufferedImage(ICON_SIZE, ICON_SIZE, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Composite old = g.getComposite(); g.setComposite(AlphaComposite.Clear); g.fillRect(0, 0, image.getWidth(), image.getHeight()); g.setComposite(old); paintFace(g, ICON_SIZE); return image; } } public static void main(String[] args) { try { System.setProperty("sun.java2d.noddraw", "true"); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { } final JFrame frame = new JFrame("Shaped Window Demo"); MouseInputAdapter handler = new MouseInputAdapter() { private Point offset; private void showPopup(MouseEvent e) { final JPopupMenu m = new JPopupMenu(); m.add(new AbstractAction("Hide") { public void actionPerformed(ActionEvent e) { frame.setState(JFrame.ICONIFIED); } }); m.add(new AbstractAction("Close") { public void actionPerformed(ActionEvent e) { System.exit(0); } }); m.pack(); m.show(e.getComponent(), e.getX(), e.getY()); } public void mousePressed(MouseEvent e) { offset = e.getPoint(); if (e.isPopupTrigger()) { showPopup(e); } } public void mouseDragged(MouseEvent e) { if (!SwingUtilities.isLeftMouseButton(e)) return; Point where = e.getPoint(); where.translate(-offset.x, -offset.y); Point loc = frame.getLocationOnScreen(); loc.translate(where.x, where.y); frame.setLocation(loc.x, loc.y); } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showPopup(e); } } }; frame.addMouseListener(handler); frame.addMouseMotionListener(handler); ClockFace face = new ClockFace(new Dimension(150, 150)); frame.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); frame.getContentPane().add(face); frame.setUndecorated(true); frame.pack(); frame.setLocation(100, 100); try { Shape mask = new Area(new Ellipse2D.Float(0, 0, 150, 150)); WindowUtils.setWindowMask(frame, mask); if (WindowUtils.isWindowAlphaSupported()) { WindowUtils.setWindowAlpha(frame, .7f); } frame.setIconImage(face.getIconImage()); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } catch(UnsatisfiedLinkError e) { e.printStackTrace(); String msg = e.getMessage() + "\nError loading the JNA library"; JTextArea area = new JTextArea(msg); area.setOpaque(false); area.setFont(UIManager.getFont("Label.font")); area.setEditable(false); area.setColumns(80); area.setRows(8); area.setWrapStyleWord(true); area.setLineWrap(true); JOptionPane.showMessageDialog(frame, new JScrollPane(area), "Library Load Error: " + System.getProperty("os.name") + "/" + System.getProperty("os.arch"), JOptionPane.ERROR_MESSAGE); System.exit(1); } } }
import java.io.BufferedWriter; 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.io.InputStream; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Set; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.coode.owlapi.obo.parser.OBOVocabulary; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom; import org.semanticweb.owlapi.model.OWLEquivalentObjectPropertiesAxiom; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.model.OWLOntologyStorageException; import org.semanticweb.owlapi.model.OWLSubObjectPropertyOfAxiom; public class ZP { static boolean verbose = true; static Logger log = Logger.getLogger(ZP.class.getName()); public static void main(String[] args) throws OWLOntologyCreationException, IOException, ParseException, InterruptedException { final CommandLineParser commandLineParser = new BasicParser(); HelpFormatter formatter = new HelpFormatter(); final Options options = new Options(); Option zfinFileOpt = new Option("z", "zfin-file", true, "The ZFIN file (e.g., http://zfin.org/data_transfer/Downloads/phenotype.txt)"); options.addOption(zfinFileOpt); Option ontoFileOpt = new Option("o","ontology-file", true, "Where the ontology file (e.g. ZP.owl) is written to."); options.addOption(ontoFileOpt); Option annotFileOpt = new Option("a", "annotation-file", true, "Where the annotation file (e.g. ZP.annot) is written to."); options.addOption(annotFileOpt); Option keepOpt = new Option("k", "keep-ids", false, "If the file on the output is already a valid ZP.owl file, keep the ids (ZP_nnnnnnn) stored in that file."); options.addOption(keepOpt); Option help = new Option( "h", "help",false, "Print this (help-)message."); options.addOption(help); final CommandLine commandLine = commandLineParser.parse(options, args); /* * Check if user wants help how to use this program */ if (commandLine.hasOption(help.getOpt()) || commandLine.hasOption(help.getLongOpt())) { formatter.printHelp( ZP.class.getSimpleName() , options ); return; } final String zfinFilePath = getOption(zfinFileOpt, commandLine); final String ontoFilePath = getOption(ontoFileOpt, commandLine); final String annotFilePath = getOption(annotFileOpt, commandLine); boolean keepIds = commandLine.hasOption(keepOpt.getOpt()); // check that required parameters are set String parameterError = null; if (zfinFilePath == null) parameterError = "Required zfin-file is missing!"; else if (ontoFilePath == null) parameterError = "Required option ontology-output-file is missing!"; else if (annotFilePath == null) parameterError = "Required option annotation-output-file missing!"; /* * Maybe something was wrong with the parameter. Print help for * the user and die here... */ if (parameterError != null) { String className = ZP.class.getSimpleName(); formatter.printHelp(className, options); throw new IllegalArgumentException(parameterError); } /* Create ontology manager and IRIs */ final OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); final IRI zpIRI = IRI.create("http://purl.obolibrary.org/obo/"); /* Load the previous zp, if requested */ final OWLOntology zp; if (keepIds) { File ontoFile = new File(ontoFilePath); if (ontoFile.exists()) { zp = manager.loadOntologyFromOntologyDocument(ontoFile); } else { log.info("Ignoring non-existent file \""+ ontoFilePath + "\" for keeping the ids"); zp = manager.createOntology(zpIRI); } } else { zp = manager.createOntology(zpIRI); } /* Instanciate the zpid db */ final ZPIDDB zpIdDB = new ZPIDDB(zp); /* Where to write the annotation file to */ final BufferedWriter annotationOut = new BufferedWriter(new FileWriter(annotFilePath)); /* Obtain the default data factory */ final OWLDataFactory factory = manager.getOWLDataFactory(); /* Open zfin input file */ File f = new File(zfinFilePath); if (f.isDirectory()) { System.err.println(String.format("Specified zfin parameter value \"%s\" must point to a file (as the name suggests) and not a directory.",zfinFilePath)); System.exit(-1); } if (!f.exists()) { System.err.println(String.format("Specified file \"%s\" doesn't exist!",zfinFilePath)); System.exit(-1); } File of = new File(ontoFilePath); final OWLObjectProperty towards = factory.getOWLObjectProperty(IRI.create(zpIRI + "BFO_0000070")); final OWLObjectProperty partOf = factory.getOWLObjectProperty(IRI.create(zpIRI + "BFO_0000050")); final OWLObjectProperty inheresIn = factory.getOWLObjectProperty(IRI.create(zpIRI + "BFO_0000052")); final OWLObjectProperty hasPart = factory.getOWLObjectProperty(IRI.create(zpIRI + "BFO_0000051")); // RO_0002180 = "qualifier" final OWLObjectProperty qualifier = factory.getOWLObjectProperty(IRI.create(zpIRI + "RO_0002180")); final OWLClass abnormal = factory.getOWLClass(IRI.create(zpIRI + "PATO_0000460")); /* Now walk the file and create instances on the fly */ try { InputStream is; /* Open input file. Try gzip compression first */ try { is = new GZIPInputStream(new FileInputStream(f)); if (is.markSupported()) is.mark(10); is.read(); if (is.markSupported()) is.reset(); else is = new GZIPInputStream(new FileInputStream(f)); } catch(IOException ex) { /* We did not succeed in open the file and reading in a byte. We assume that * the file is not compressed. */ is = new FileInputStream(f); } /* Constructs an OWLClass and Axioms for each zfin entry. We expect the reasoner to * collate the classes properly. We also emit the annotations here. */ ZFINWalker.walk(is, new ZFINVisitor() { /** * Returns an entity class for the given obo id. This is a simple wrapper * for OBOVocabulary.ID2IRI(id) but checks whether the term stems from * a supported ontology. * * @param id * @return */ private OWLClass getEntityClassForOBOID(String id) { if (id.startsWith("GO:") || id.startsWith("ZFA:") || id.startsWith("BSPO:") || id.startsWith("MPATH:")) return factory.getOWLClass(OBOVocabulary.ID2IRI(id)); throw new RuntimeException("Unknown ontology prefix for name \"" + id + "\""); } /** * Returns an quality class for the given obo id. This is a simple wrapper * for OBOVocabulary.ID2IRI(id) but checks whether the term stems from * a supported ontology. * * @param id * @return */ private OWLClass getQualiClassForOBOID(String id) { if (id.startsWith("PATO:")) return factory.getOWLClass(OBOVocabulary.ID2IRI(id)); throw new RuntimeException("Qualifier must be a pato term"); } public boolean visit(ZFINEntry entry) { // handle only abnormal entries if (! entry.isAbnormal) return true; // FIXME debug: exclude useless annotation that look like this // ...ZFA:0001439|anatomical system|||||||PATO:0000001|quality|abnormal| if ( entry.entity1SupertermId.equals("ZFA:0001439") && entry.patoID.equals("PATO:0000001") && entry.entity1SubtermId.equals("") && entry.entity2SupertermId.equals("") && entry.entity2SubtermId.equals("")) return true; OWLClass pato = getQualiClassForOBOID(entry.patoID); OWLClass cl1 = getEntityClassForOBOID(entry.entity1SupertermId); OWLClassExpression intersectionExpression; String label; Set<OWLClassExpression> intersectionList = new LinkedHashSet<OWLClassExpression>(); intersectionList.add(pato); intersectionList.add(factory.getOWLObjectSomeValuesFrom(qualifier, abnormal)); /* Entity 1: Create intersections */ if (entry.entity1SubtermId!= null && entry.entity1SubtermId.length() > 0) { /* Pattern is (all-some interpretation): <pato> inheres_in (<cl2> part of <cl1>) AND qualifier abnormal*/ OWLClass cl2 = getEntityClassForOBOID(entry.entity1SubtermId); intersectionList.add(factory.getOWLObjectSomeValuesFrom(inheresIn, factory.getOWLObjectIntersectionOf(cl2,factory.getOWLObjectSomeValuesFrom(partOf, cl1)))); /* Note that is language the last word is the more specific part of the composition, i.e., * we say swim bladder epithelium, which is the epithelium of the swim bladder */ label = "abnormal(ly) " + entry.patoName + " " + entry.entity1SupertermName + " " + entry.entity1SubtermName; } else { /* Pattern is (all-some interpretation): <pato> inheres_in <cl1> AND qualifier abnormal */ intersectionList.add(factory.getOWLObjectSomeValuesFrom(inheresIn, cl1)); label = "abnormal(ly) " + entry.patoName + " " + entry.entity1SupertermName; } /* Entity 2: Create intersections */ if (entry.entity2SupertermId!= null && entry.entity2SupertermId.length() > 0){ OWLClass cl3 = getEntityClassForOBOID(entry.entity2SupertermId); if (entry.entity2SubtermId!= null && entry.entity2SubtermId.length() > 0) { /* Pattern is (all-some interpretation): <pato> inheres_in (<cl2> part of <cl1>) AND qualifier abnormal*/ OWLClass cl4 = getEntityClassForOBOID(entry.entity2SubtermId); intersectionList.add(factory.getOWLObjectSomeValuesFrom(towards, factory.getOWLObjectIntersectionOf(cl4,factory.getOWLObjectSomeValuesFrom(partOf, cl3)))); /* Note that is language the last word is the more specific part of the composition, i.e., * we say swim bladder epithelium, which is the epithelium of the swim bladder */ label += " towards " + entry.entity2SupertermName + " " + entry.entity2SubtermName; } else{ intersectionList.add(factory.getOWLObjectSomeValuesFrom(towards, cl3)); label += " towards " + entry.entity2SupertermName; } } /* Create intersection */ intersectionExpression = factory.getOWLObjectIntersectionOf(intersectionList); OWLClassExpression owlSomeClassExp = factory.getOWLObjectSomeValuesFrom(hasPart,intersectionExpression); IRI zpIRI = zpIdDB.getZPId(owlSomeClassExp); String zpID = OBOVocabulary.IRI2ID(zpIRI); OWLClass zpTerm = factory.getOWLClass(zpIRI); /* Make term equivalent to the intersection */ OWLEquivalentClassesAxiom axiom = factory.getOWLEquivalentClassesAxiom(zpTerm, owlSomeClassExp); manager.addAxiom(zp,axiom); /* Add label */ OWLAnnotation labelAnno = factory.getOWLAnnotation(factory.getRDFSLabel(),factory.getOWLLiteral(label)); OWLAxiom labelAnnoAxiom = factory.getOWLAnnotationAssertionAxiom(zpTerm.getIRI(), labelAnno); manager.addAxiom(zp,labelAnnoAxiom); /* * Writing the annotation file */ try { annotationOut.write(entry.geneZfinID+"\t"+zpID+"\t"+label+"\n"); } catch (IOException e) { e.printStackTrace(); } return true; } }); manager.saveOntology(zp, new FileOutputStream(of)); log.info("Wrote \"" + of.toString() + "\""); annotationOut.close(); } catch (FileNotFoundException e) { System.err.println(String.format("Specified input file \"%s\" doesn't exist!",zfinFilePath)); } catch (IOException e) { e.printStackTrace(); } catch (OWLOntologyStorageException e) { e.printStackTrace(); } } public static String getOption(Option opt, final CommandLine commandLine) { if (commandLine.hasOption(opt.getOpt())) { return commandLine.getOptionValue(opt.getOpt()); } if (commandLine.hasOption(opt.getLongOpt())) { return commandLine.getOptionValue(opt.getLongOpt()); } return null; } }
import java.util.Objects; public class MovementRoutine { public MovementRoutine (String command, int numberOfCommands) { _command = command; _numberOfCommands = numberOfCommands; } public boolean containsRoutine (MovementRoutine compare) { System.out.println("contains "+compare.getCommand().contains(_command)); return (_command.indexOf(compare.getCommand()) != -1); } public void removeRoutine (MovementRoutine compare) { System.out.println("Removing "+compare.getCommand()+" from "+_command); _command = _command.replace(compare.getCommand(), ""); _numberOfCommands -= compare.numberOfCommands(); } public String getCommand () { return _command; } public int getLength () { return ((_command == null) ? 0 : _command.length()); } public int numberOfCommands () { return _numberOfCommands; } @Override public String toString () { return "MovementRoutine: "+_command+" and size: "+getLength(); } @Override public int hashCode () { return Objects.hash(_command, _numberOfCommands); } @Override public boolean equals (Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() == obj.getClass()) { MovementRoutine temp = (MovementRoutine) obj; return (_command.equals(temp._command)); } return false; } private String _command; private int _numberOfCommands; }
package com.googlecode.urho3d; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.egl.*; import android.app.*; import android.content.*; import android.view.*; import android.os.*; import android.util.Log; import android.graphics.*; import android.text.method.*; import android.text.*; import android.media.*; import android.hardware.*; import android.content.*; import android.content.res.*; import java.lang.*; /** SDL Activity */ public class SDLActivity extends Activity { // Main components private static SDLActivity mSingleton; private static SDLSurface mSurface; // This is what SDL runs in. It invokes SDL_main(), eventually private static Thread mSDLThread; // Audio private static Thread mAudioThread; private static AudioTrack mAudioTrack; // EGL private objects private EGLContext mEGLContext; private EGLSurface mEGLSurface; private EGLDisplay mEGLDisplay; private EGLConfig mEGLConfig; private int mGLMajor, mGLMinor; private boolean mFinished = false; // Load the .so static { System.loadLibrary("Urho3D"); } // Setup protected void onCreate(Bundle savedInstanceState) { Log.v("SDL", "onCreate()"); super.onCreate(savedInstanceState); // So we can call stuff from static callbacks mSingleton = this; // Set up the surface mSurface = new SDLSurface(getApplication()); setContentView(mSurface); SurfaceHolder holder = mSurface.getHolder(); } // Events protected void onPause() { Log.v("SDL", "onPause()"); super.onPause(); SDLActivity.nativePause(); } protected void onResume() { Log.v("SDL", "onResume()"); super.onResume(); SDLActivity.nativeResume(); } protected void onDestroy() { Log.v("SDL", "onDestroy()"); super.onDestroy(); mFinished = true; // Send a quit message to the application SDLActivity.nativeQuit(); // Now wait for the SDL thread to quit if (mSDLThread != null) { try { mSDLThread.join(); } catch(Exception e) { Log.v("SDL", "Problem stopping thread: " + e); } mSDLThread = null; //Log.v("SDL", "Finished waiting for SDL thread"); } mSingleton = null; } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } public static SDLActivity getSingleton() { return mSingleton; } // Messages from the SDLMain thread static int COMMAND_CHANGE_TITLE = 1; static int COMMAND_FINISH = 2; // Handler for the messages Handler commandHandler = new Handler() { public void handleMessage(Message msg) { if (msg.arg1 == COMMAND_CHANGE_TITLE) { setTitle((String)msg.obj); } if (msg.arg1 == COMMAND_FINISH) { if (mFinished == false) { mFinished = true; finish(); } } } }; // Send a message from the SDLMain thread void sendCommand(int command, Object data) { Message msg = commandHandler.obtainMessage(); msg.arg1 = command; msg.obj = data; commandHandler.sendMessage(msg); } // C functions we call public static native void nativeInit(String filesDir); public static native void nativeQuit(); public static native void nativePause(); public static native void nativeResume(); public static native void onNativeResize(int x, int y, int format); public static native void onNativeKeyDown(int keycode); public static native void onNativeKeyUp(int keycode); public static native void onNativeTouch(int touchDevId, int pointerFingerId, int action, float x, float y, float p); public static native void onNativeAccel(float x, float y, float z); public static native void onNativeSurfaceDestroyed(); public static native void onNativeSurfaceCreated(); public static native void nativeRunAudioThread(); // Java functions called from C public static boolean createGLContext(int majorVersion, int minorVersion) { return SDLActivity.mSingleton.initEGL(majorVersion, minorVersion); } public static void flipBuffers() { flipEGL(); } public static void setActivityTitle(String title) { // Called from SDLMain() thread and can't directly affect the view mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title); } public static void finishActivity() { mSingleton.sendCommand(COMMAND_FINISH, null); } public static Context getContext() { return mSingleton; } public static void startApp() { // Start up the C app thread if (mSDLThread == null) { mSDLThread = new Thread(new SDLMain(), "SDLThread"); mSDLThread.start(); } else { SDLActivity.nativeResume(); // startApp() is called whenever the window is ready to be rendered to. If the SDL main thread is already running, // notify it that any OpenGL resources can be recreated SDLActivity.onNativeSurfaceCreated(); } } // EGL functions public boolean initEGL(int majorVersion, int minorVersion) { EGL10 egl = (EGL10)EGLContext.getEGL(); try { if (mEGLDisplay == null) { EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(dpy, version); int EGL_OPENGL_ES_BIT = 1; int EGL_OPENGL_ES2_BIT = 4; int renderableType = 0; if (majorVersion == 2) { renderableType = EGL_OPENGL_ES2_BIT; } else if (majorVersion == 1) { renderableType = EGL_OPENGL_ES_BIT; } EGLConfig config = null; EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; int depth = 24; while (depth >= 16) { int[] configSpec = { EGL10.EGL_DEPTH_SIZE, depth, EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; if (egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) && num_config[0] > 0) { config = configs[0]; break; } depth -= 8; } if (config == null) { Log.e("SDL", "No EGL config available"); return false; } mEGLDisplay = dpy; mEGLConfig = config; mGLMajor = majorVersion; mGLMinor = minorVersion; } else { egl.eglMakeCurrent(mEGLDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); if (mEGLSurface != null) { egl.eglDestroySurface(mEGLDisplay, mEGLSurface); mEGLSurface = null; } if (mEGLContext != null) { egl.eglDestroyContext(mEGLDisplay, mEGLContext); mEGLContext = null; } } int EGL_CONTEXT_CLIENT_VERSION=0x3098; int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, mGLMajor, EGL10.EGL_NONE }; EGLContext context = egl.eglCreateContext(mEGLDisplay, mEGLConfig, EGL10.EGL_NO_CONTEXT, contextAttrs); if (context == EGL10.EGL_NO_CONTEXT) { Log.e("SDL", "Couldn't create context"); return false; } mEGLContext = context; Log.v("SDL", "Creating new EGL Surface"); EGLSurface surface = egl.eglCreateWindowSurface(mEGLDisplay, mEGLConfig, mSurface, null); if (surface == EGL10.EGL_NO_SURFACE) { Log.e("SDL", "Couldn't create surface"); return false; } mEGLSurface = surface; if (!egl.eglMakeCurrent(mEGLDisplay, surface, surface, mEGLContext)) { Log.e("SDL", "Failed making EGL Context current"); return false; } return true; } catch(Exception e) { Log.v("SDL", e + ""); for (StackTraceElement s : e.getStackTrace()) { Log.v("SDL", s.toString()); } return false; } } // EGL buffer flip public static void flipEGL() { try { EGL10 egl = (EGL10)EGLContext.getEGL(); egl.eglSwapBuffers(SDLActivity.mSingleton.mEGLDisplay, SDLActivity.mSingleton.mEGLSurface); } catch(Exception e) { Log.v("SDL", "flipEGL(): " + e); for (StackTraceElement s : e.getStackTrace()) { Log.v("SDL", s.toString()); } } } // Audio private static Object buf; public static Object audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) { int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO; int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT; int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1); Log.v("SDL", "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + ((float)sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer"); // Let the user pick a larger buffer if they really want -- but ye // gods they probably shouldn't, the minimums are horrifyingly high // latency already desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize); mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM); audioStartThread(); Log.v("SDL", "SDL audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + ((float)mAudioTrack.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer"); if (is16Bit) { buf = new short[desiredFrames * (isStereo ? 2 : 1)]; } else { buf = new byte[desiredFrames * (isStereo ? 2 : 1)]; } return buf; } public static void audioStartThread() { mAudioThread = new Thread(new Runnable() { public void run() { mAudioTrack.play(); nativeRunAudioThread(); } }); // I'd take REALTIME if I could get it! mAudioThread.setPriority(Thread.MAX_PRIORITY); mAudioThread.start(); } public static void audioWriteShortBuffer(short[] buffer) { for (int i = 0; i < buffer.length; ) { int result = mAudioTrack.write(buffer, i, buffer.length - i); if (result > 0) { i += result; } else if (result == 0) { try { Thread.sleep(1); } catch(InterruptedException e) { // Nom nom } } else { Log.w("SDL", "SDL audio: error return from write(short)"); return; } } } public static void audioWriteByteBuffer(byte[] buffer) { for (int i = 0; i < buffer.length; ) { int result = mAudioTrack.write(buffer, i, buffer.length - i); if (result > 0) { i += result; } else if (result == 0) { try { Thread.sleep(1); } catch(InterruptedException e) { // Nom nom } } else { Log.w("SDL", "SDL audio: error return from write(short)"); return; } } } public static void audioQuit() { if (mAudioThread != null) { try { mAudioThread.join(); } catch(Exception e) { Log.v("SDL", "Problem stopping audio thread: " + e); } mAudioThread = null; //Log.v("SDL", "Finished waiting for audio thread"); } if (mAudioTrack != null) { mAudioTrack.stop(); mAudioTrack = null; } } } /** Simple nativeInit() runnable */ class SDLMain implements Runnable { public void run() { // Runs SDL_main() SDLActivity.nativeInit(SDLActivity.getSingleton().getFilesDir().getAbsolutePath()); //Log.v("SDL", "SDL thread terminated"); SDLActivity.finishActivity(); } } /** SDLSurface. This is what we draw on, so we need to know when it's created in order to do anything useful. Because of this, that's where we set up the SDL thread */ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnKeyListener, View.OnTouchListener, SensorEventListener { // Sensors private static SensorManager mSensorManager; // Startup public SDLSurface(Context context) { super(context); getHolder().addCallback(this); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); setOnKeyListener(this); setOnTouchListener(this); mSensorManager = (SensorManager)context.getSystemService("sensor"); } // Called when we have a valid drawing surface public void surfaceCreated(SurfaceHolder holder) { Log.v("SDL", "surfaceCreated()"); holder.setType(SurfaceHolder.SURFACE_TYPE_GPU); enableSensor(Sensor.TYPE_ACCELEROMETER, true); } // Called when we lose the surface public void surfaceDestroyed(SurfaceHolder holder) { Log.v("SDL", "surfaceDestroyed()"); SDLActivity.nativePause(); enableSensor(Sensor.TYPE_ACCELEROMETER, false); SDLActivity.onNativeSurfaceDestroyed(); } // Called when the surface is resized public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.v("SDL", "surfaceChanged()"); int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default switch (format) { case PixelFormat.A_8: Log.v("SDL", "pixel format A_8"); break; case PixelFormat.LA_88: Log.v("SDL", "pixel format LA_88"); break; case PixelFormat.L_8: Log.v("SDL", "pixel format L_8"); break; case PixelFormat.RGBA_4444: Log.v("SDL", "pixel format RGBA_4444"); sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444 break; case PixelFormat.RGBA_5551: Log.v("SDL", "pixel format RGBA_5551"); sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551 break; case PixelFormat.RGBA_8888: Log.v("SDL", "pixel format RGBA_8888"); sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888 break; case PixelFormat.RGBX_8888: Log.v("SDL", "pixel format RGBX_8888"); sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888 break; case PixelFormat.RGB_332: Log.v("SDL", "pixel format RGB_332"); sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332 break; case PixelFormat.RGB_565: Log.v("SDL", "pixel format RGB_565"); sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 break; case PixelFormat.RGB_888: Log.v("SDL", "pixel format RGB_888"); // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead? sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888 break; default: Log.v("SDL", "pixel format unknown " + format); break; } SDLActivity.onNativeResize(width, height, sdlFormat); Log.v("SDL", "Window size:" + width + "x"+height); SDLActivity.startApp(); } // unused public void onDraw(Canvas canvas) {} // Key events public boolean onKey(View v, int keyCode, KeyEvent event) { // Let the home & volume keys be handled by the system if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_HOME) return false; if (event.getAction() == KeyEvent.ACTION_DOWN) { //Log.v("SDL", "key down: " + keyCode); SDLActivity.onNativeKeyDown(keyCode); return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { //Log.v("SDL", "key up: " + keyCode); SDLActivity.onNativeKeyUp(keyCode); return true; } return false; } // Touch events public boolean onTouch(View v, MotionEvent event) { { final int touchDevId = event.getDeviceId(); final int pointerCount = event.getPointerCount(); // touchId, pointerId, action, x, y, pressure int actionPointerIndex = event.getActionIndex(); int pointerFingerId = event.getPointerId(actionPointerIndex); int action = event.getActionMasked(); float x = event.getX(actionPointerIndex); float y = event.getY(actionPointerIndex); float p = event.getPressure(actionPointerIndex); if (action == MotionEvent.ACTION_MOVE && pointerCount > 1) { // TODO send motion to every pointer if its position has // changed since prev event. for (int i = 0; i < pointerCount; i++) { pointerFingerId = event.getPointerId(i); x = event.getX(i); y = event.getY(i); p = event.getPressure(i); SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p); } } else { SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p); } } return true; } // Sensor events public void enableSensor(int sensortype, boolean enabled) { // TODO: This uses getDefaultSensor - what if we have >1 accels? if (enabled) { mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(sensortype), SensorManager.SENSOR_DELAY_GAME, null); } else { mSensorManager.unregisterListener(this, mSensorManager.getDefaultSensor(sensortype)); } } public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO } public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { SDLActivity.onNativeAccel(event.values[0] / SensorManager.GRAVITY_EARTH, event.values[1] / SensorManager.GRAVITY_EARTH, event.values[2] / SensorManager.GRAVITY_EARTH); } } }
package org.jboss.remoting.spi; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import java.net.URLDecoder; import java.net.URLEncoder; import java.io.UnsupportedEncodingException; /** * A qualified name for service registration. A qualified name is a path-like structure comprised of a series of * zero or more name segments. The string representation of a qualified name is a sequence of a forward slash * ({@code /}) followed by a non-empty URL-encoded name segment. */ public final class QualifiedName implements Comparable<QualifiedName>, Iterable<String> { /** * The root name. */ public static final QualifiedName ROOT_NAME = new QualifiedName(new String[0]); private final String[] segments; public QualifiedName(final String[] nameSegments) throws NullPointerException, IllegalArgumentException { if (nameSegments == null) { throw new NullPointerException("segments is null"); } String[] segments = nameSegments.clone(); for (String s : segments) { if (s == null) { throw new NullPointerException("Null segment"); } if (s.length() == 0) { throw new IllegalArgumentException("Empty segment"); } } this.segments = segments; } /** * Compare this qualified name to another for equality. Returns {@code true} if both names have the same number of segments * with the same content. * * @param o the object to compare to * @return {@code true} if the given object is a qualified name which is equal to this name */ public boolean equals(final Object o) { if (this == o) return true; if (! (o instanceof QualifiedName)) return false; final QualifiedName name = (QualifiedName) o; if (!Arrays.equals(segments, name.segments)) return false; return true; } /** * Get the hash code of this qualified name. Equal to the return value of {@link Arrays#hashCode(Object[]) Arrays.hashCode(segments)} * where {@code segments} is the array of decoded segment strings. * * @return the hash code */ public int hashCode() { return Arrays.hashCode(segments); } /** * Compare this qualified name to another. Each segment is compared in turn; if they are equal then the comparison * carries on to the next segment. If all leading segments are equal but one qualified name has more segments, * then the longer name is said to come after the shorter name. * * @param o the other name * @return {@code 0} if the elements are equal, {@code -1} if this name comes before the given name, or {@code 1} if * this name comes after the given name */ public int compareTo(final QualifiedName o) { if (this == o) return 0; String[] a = segments; String[] b = o.segments; final int alen = a.length; final int blen = b.length; for (int i = 0; i < alen && i < blen; i ++) { final int cmp = a[i].compareTo(b[i]); if (cmp != 0) { return cmp; } } if (alen < blen) { return -1; } else if (alen > blen) { return 1; } else { return 0; } } /** * Get the string representation of this qualified name. The root name is "{@code /}"; all other names are comprised * of one or more consecutive character sequences of a forward slash followed by one or more URL-encoded characters. * * @return the string representation of this name */ public String toString() { StringBuilder builder = new StringBuilder(); if (segments.length == 0) { return "/"; } else for (String segment : segments) { try { builder.append('/'); builder.append(URLEncoder.encode(segment, "utf-8")); } catch (UnsupportedEncodingException e) { // cannot happen throw new IllegalStateException(e); } } return builder.toString(); } /** * Parse a qualified name. A qualified name must consist of either a single forward slash ("{@code /}") or else * a series of path components, each comprised of a single forward slash followed by a URL-encoded series of non-forward-slash * characters. * * @param path the path * @return the qualified name */ public static QualifiedName parse(String path) { List<String> decoded = new ArrayList<String>(); final int len = path.length(); if (len < 1) { throw new IllegalArgumentException("Empty path"); } if (path.charAt(0) != '/') { throw new IllegalArgumentException("Relative paths are not allowed"); } if (len == 1) { return ROOT_NAME; } int segStart = 0; int segEnd; do { segEnd = path.indexOf('/', segStart + 1); String segment = segEnd == -1 ? path.substring(segStart + 1) : path.substring(segStart + 1, segEnd); if (segment.length() == 0) { throw new IllegalArgumentException(segEnd == -1 ? "Invalid trailing slash" : "Empty segment in path"); } try { decoded.add(URLDecoder.decode(segment, "utf-8")); } catch (UnsupportedEncodingException e) { // cannot happen throw new IllegalStateException(e); } segStart = segEnd; } while (segEnd != -1); return new QualifiedName(decoded.toArray(new String[decoded.size()])); } /** * Get an iterator over the sequence of strings. * * @return an iterator */ public Iterator<String> iterator() { return new Iterator<String>() { int i; public boolean hasNext() { return i < segments.length; } public String next() { try { return segments[i++]; } catch (ArrayIndexOutOfBoundsException e) { throw new NoSuchElementException("next() past end"); } } public void remove() { throw new UnsupportedOperationException("remove()"); } }; } /** * Get the number of segments in this name. * * @return the number of segments */ public int length() { return segments.length; } }
import java.util.*; import java.awt.*; import java.io.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class nwchem_RMS extends JFrame implements ActionListener, ChangeListener, WindowListener, MouseListener { Font defaultFont; int setnumber=0; JFileChooser chooser; ExtensionFilter rmsFilter; JFrame dialogFrame; BufferedReader br; String card; Graph rmsPlot = new Graph(); Graph rmsaPlot = new Graph(); Graph rmsrPlot = new Graph(); Graph bfacaPlot = new Graph(); Graph bfacrPlot = new Graph(); JLabel systemLabel = new JLabel(); JButton doneButton = new JButton("done"); double time,rms1,rms2; public nwchem_RMS(){ super("RMS Viewer 2"); defaultFont = new Font("Dialog", Font.BOLD,12); super.getContentPane().setLayout(new GridBagLayout()); super.getContentPane().setForeground(Color.black); super.getContentPane().setBackground(Color.lightGray); super.getContentPane().setFont(defaultFont); super.addWindowListener(this); chooser = new JFileChooser("./"); rmsFilter = new ExtensionFilter(".rms"); chooser.setFileFilter(rmsFilter); dialogFrame = new JFrame(); dialogFrame.setSize(300,400); chooser.showOpenDialog(dialogFrame); JPanel header = new JPanel(); header.setLayout(new GridBagLayout()); header.setForeground(Color.black); header.setBackground(Color.lightGray); addComponent(super.getContentPane(),header,0,0,2,1,1,1, GridBagConstraints.NONE,GridBagConstraints.WEST); JLabel systemLabel = new JLabel(chooser.getSelectedFile().toString()); addComponent(header,systemLabel,2,0,10,1,1,1, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); systemLabel.setForeground(Color.black); addComponent(header,doneButton,0,0,1,1,1,1, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); doneButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ setVisible(false); }}); rmsPlot.init(); rmsaPlot.init(); rmsrPlot.init(); bfacaPlot.init(); bfacrPlot.init(); rmsPlot.setTitle("RMS Deviation vs Time"); rmsaPlot.setTitle("Atomic RMS Deviation"); rmsrPlot.setTitle("Segment RMS Deviation"); bfacaPlot.setTitle("Atomic B factor"); bfacrPlot.setTitle("Segment B Factor"); rmsrPlot.setBars(1.0,0.0); rmsPlot.setSize(500,300); rmsaPlot.setSize(350,300); rmsrPlot.setSize(350,300); bfacaPlot.setSize(350,300); bfacrPlot.setSize(350,300); addComponent(header,rmsPlot,0,1,20,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); addComponent(header,rmsaPlot,0,11,10,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); addComponent(header,rmsrPlot,11,11,10,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); addComponent(header,bfacaPlot,0,21,10,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); addComponent(header,bfacrPlot,11,21,10,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); try{ BufferedReader br = new BufferedReader(new FileReader(chooser.getSelectedFile().toString())); String card; card=br.readLine(); int numt=0; boolean first=true; while(!card.startsWith("analysis")){ time=Double.valueOf(card.substring(1,12)).doubleValue(); rms1=Double.valueOf(card.substring(13,24)).doubleValue(); rms2=Double.valueOf(card.substring(25,36)).doubleValue(); rmsPlot.addData(0,time,rms1,!first,false); rmsPlot.addData(1,time,rms2,!first,false); first=false; card=br.readLine(); }; rmsPlot.fillPlot(); card=br.readLine(); int numa=0; first=true; while(!card.startsWith("analysis")){ rms1=Double.valueOf(card.substring(32,43)).doubleValue(); rms2=Double.valueOf(card.substring(44,55)).doubleValue(); numa++; rmsaPlot.addData(1,numa,rms1,!first,false); bfacaPlot.addData(1,numa,rms2,!first,false); first=false; card=br.readLine(); }; numa=0; int n; first=true; while((card=br.readLine()) != null){ rms1=Double.valueOf(card.substring(12,23)).doubleValue(); rms2=Double.valueOf(card.substring(24,35)).doubleValue(); System.out.println(rms1+" "+rms2); rmsrPlot.addData(0,numa,rms1,!first,false); bfacrPlot.addData(0,numa,rms2,!first,false); numa++; }; rmsaPlot.fillPlot(); rmsrPlot.fillPlot(); bfacaPlot.fillPlot(); bfacrPlot.fillPlot(); br.close(); } catch(Exception ee) {ee.printStackTrace();}; setLocation(25,225); setSize(900,700); setVisible(true); } void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy){ gbc.gridx = gx; gbc.gridy = gy; gbc.gridwidth = gw; gbc.gridheight = gh; gbc.weightx = wx; gbc.weighty = wy; } static void addComponent(Container container, Component component, int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int fill, int anchor) { LayoutManager lm = container.getLayout(); if(!(lm instanceof GridBagLayout)){ System.out.println("Illegal layout"); System.exit(1); } else { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx=gridx; gbc.gridy=gridy; gbc.gridwidth=gridwidth; gbc.gridheight=gridheight; gbc.weightx=weightx; gbc.weighty=weighty; gbc.fill=fill; gbc.anchor=anchor; container.add(component,gbc); } } public void actionPerformed(ActionEvent e) { } public void stateChanged(ChangeEvent e) {} public void windowClosing(WindowEvent event) {} public void windowClosed(WindowEvent event) { } public void windowDeiconified(WindowEvent event) {} public void windowIconified(WindowEvent event) {} public void windowActivated(WindowEvent event) {} public void windowDeactivated(WindowEvent e) {} public void windowOpened(WindowEvent event) {} public void mouseClicked(MouseEvent mouse) {} public void mousePressed(MouseEvent mouse){} public void mouseReleased(MouseEvent mouse){ } public void mouseEntered(MouseEvent mouse){ } public void mouseExited(MouseEvent mouse){ } }
/* Write a program that prompts the user to enter two strings and tests whether the second string is a substring of the first string. Suppose the neighboring characters in the string are distinct. (Don't use the indexOf method in the String class.) Your algorithm needs to be at least O(n) time. */ import java.util.Scanner; public class E22_03 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a string s1: "); String s1 = input.nextLine(); System.out.print("Enter a string s2: "); String s2 = input.nextLine(); int index = 0; int matchIndex = -1; for (int i = 0; i < s1.length(); i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(index); if (c1 == c2) { index++; if (index == s2.length()) { matchIndex = i - (index - 1); break; } } else { index = 0; } } if (matchIndex == -1) { System.out.println("no match"); } else { System.out.println("match at index " + matchIndex); } } }
package smartsockets.virtual; import ibis.util.ThreadPool; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.BindException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import smartsockets.Properties; import smartsockets.direct.DirectSocketAddress; import smartsockets.discovery.Discovery; import smartsockets.hub.servicelink.ServiceLink; import smartsockets.util.TypedProperties; import smartsockets.virtual.modules.ConnectModule; /** * This class implements a 'virtual' socket factory. * * @author Jason Maassen * @version 1.0 Jan 30, 2006 * @since 1.0 * */ public class VirtualSocketFactory { private static class StatisticsPrinter implements Runnable { private final int timeout; StatisticsPrinter(int timeout) { if (timeout < 1000) { timeout *= 1000; } this.timeout = timeout; } public void run() { while (true) { try { Thread.sleep(timeout); } catch (Exception e){ // ignore } try { for (String s : VirtualSocketFactory.factories.keySet()) { VirtualSocketFactory.factories.get(s).printStatistics(s); } } catch (Exception e) { // TODO: IGNORE ? } } } } private static final Map<String, VirtualSocketFactory> factories = Collections.synchronizedMap(new HashMap<String, VirtualSocketFactory>()); private static StatisticsPrinter printer = null; private static int printerInterval = -1; protected static Logger logger = ibis.util.GetLogger.getLogger("smartsockets.virtual.misc"); protected static Logger conlogger = ibis.util.GetLogger.getLogger("smartsockets.virtual.connect"); private static final Logger statslogger = ibis.util.GetLogger.getLogger("smartsockets.statistics"); private final ArrayList<ConnectModule> modules = new ArrayList<ConnectModule>(); private final TypedProperties properties; private final int DEFAULT_BACKLOG; private final int DEFAULT_TIMEOUT; // private final int DISCOVERY_PORT; private final HashMap<Integer, VirtualServerSocket> serverSockets = new HashMap<Integer, VirtualServerSocket>(); private int nextPort = 3000; private DirectSocketAddress myAddresses; private DirectSocketAddress hubAddress; private VirtualSocketAddress localVirtualAddress; private String localVirtualAddressAsString; private ServiceLink serviceLink; private VirtualClusters clusters; private VirtualSocketFactory(TypedProperties p) throws Exception { if (logger.isInfoEnabled()) { logger.info("Creating VirtualSocketFactory"); } properties = p; DEFAULT_BACKLOG = p.getIntProperty(Properties.BACKLOG); DEFAULT_TIMEOUT = p.getIntProperty(Properties.TIMEOUT); // DISCOVERY_PORT = // NOTE: order is VERY important here! loadModules(); String localCluster = p.getProperty(Properties.CLUSTER_MEMBER, null); createServiceLink(localCluster); startModules(); loadClusterDefinitions(); if (modules.size() == 0) { logger.warn("Failed to load any modules!"); throw new Exception("Failed to load any modules!"); } localVirtualAddress = new VirtualSocketAddress(myAddresses, 0, hubAddress, clusters.localCluster()); localVirtualAddressAsString = localVirtualAddress.toString(); } private void loadClusterDefinitions() { clusters = new VirtualClusters(this, properties, getModules()); } private void createServiceLink(String localCluster) { DirectSocketAddress address = null; // Check if the proxy address was passed as a property. String tmp = properties.getProperty(Properties.HUB_ADDRESS); if (tmp != null) { try { address = DirectSocketAddress.getByAddress(tmp); } catch (Exception e) { logger.warn("Failed to understand proxy address: " + tmp, e); } } boolean useDiscovery = properties.booleanProperty(Properties.DISCOVERY_ALLOWED, false); boolean discoveryPreferred = properties.booleanProperty(Properties.DISCOVERY_PREFERRED, false); // Check if we can discover the proxy address using UDP multicast. if (useDiscovery && (discoveryPreferred || address == null)) { if (logger.isInfoEnabled()) { logger.info("Attempting to discover proxy using UDP multicast..."); } int port = properties.getIntProperty(Properties.DISCOVERY_PORT); int time = properties.getIntProperty(Properties.DISCOVERY_TIMEOUT); Discovery d = new Discovery(port, 0, time); String message = "Any Proxies? "; message += localCluster; String result = d.broadcastWithReply(message); if (result != null) { try { address = DirectSocketAddress.getByAddress(result); if (logger.isInfoEnabled()) { logger.info("Hub found at: " + address.toString()); } } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Got unknown reply to hub discovery!"); } } } else { if (logger.isInfoEnabled()) { logger.info("No hubs found."); } } } // Still no address ? Give up... if (address == null) { // properties not set, so no central hub is available // if (logger.isInfoEnabled()) { System.out.println("ServiceLink not created: no hub address available!"); logger.warn("ServiceLink not created: no hub address available!"); return; } try { serviceLink = ServiceLink.getServiceLink(properties, address, myAddresses); hubAddress = serviceLink.getAddress(); if (true) { serviceLink.waitConnected(10000); } } catch (Exception e) { logger.warn("Failed to connect service link to hub!", e); return; } // Check if the users want us to register any properties with the hub. String [] props = properties.getStringList( "smartsockets.register.property", ",", null); if (props != null && props.length > 0) { try { if (props.length == 1) { serviceLink.registerProperty(props[0], ""); } else { serviceLink.registerProperty(props[0], props[1]); } } catch (Exception e) { if (props.length == 1) { logger.warn("Failed to register user property: " + props[0]); } else { logger.warn("Failed to register user property: " + props[0] + "=" + props[1]); } } } } private ConnectModule loadModule(String name) { if (logger.isInfoEnabled()) { logger.info("Loading module: " + name); } String classname = properties.getProperty( Properties.MODULES_PREFIX + name, null); if (classname == null) { // The class implementing the module is not explicitly defined, so // instead we use an 'educated guess' of the form: // smartsockets.virtual.modules.<name>.<Name> StringBuffer tmp = new StringBuffer(); tmp.append("smartsockets.virtual.modules."); tmp.append(name.toLowerCase()); tmp.append("."); tmp.append(Character.toUpperCase(name.charAt(0))); tmp.append(name.substring(1)); classname = tmp.toString(); } if (logger.isInfoEnabled()) { logger.info(" class name: " + classname); } try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class c = cl.loadClass(classname); // Check if the class we loaded is indeed a flavor of ConnectModule if (!ConnectModule.class.isAssignableFrom(c)) { logger.warn("Cannot load module " + classname + " since it is " + " not a subclass of ConnectModule!"); return null; } return (ConnectModule) c.newInstance(); } catch (Exception e) { logger.warn("Failed to load module " + classname, e); } return null; } private void loadModules() throws Exception { // Get the list of modules that we should load... String [] mods = properties.getStringList(Properties.MODULES_DEFINE, ",", null); int count = mods.length; if (mods == null || mods.length == 0) { logger.error("No smartsockets modules defined!"); return; } String [] skip = properties.getStringList(Properties.MODULES_SKIP, ",", null); // Remove all modules that should be skipped. if (skip != null) { for (int s=0;s<skip.length;s++) { for (int m=0;m<mods.length;m++) { if (skip[s].equals(mods[m])) { if (logger.isInfoEnabled()) { logger.info("Skipping module " + mods[m]); } mods[m] = null; count } } } } String t = ""; for (int i=0;i<mods.length;i++) { if (mods[i] != null) { t += mods[i] + " "; } } if (logger.isInfoEnabled()) { logger.info("Loading " + count + " modules: " + t); } for (int i=0;i<mods.length;i++) { if (mods[i] != null) { try { ConnectModule m = loadModule(mods[i]); m.init(this, mods[i], properties, logger); DirectSocketAddress tmp = m.getAddresses(); if (tmp != null) { if (myAddresses == null) { myAddresses = tmp; } else { myAddresses = DirectSocketAddress.merge(myAddresses, tmp); } } modules.add(m); } catch (Exception e) { logger.warn("Failed to load module: " + mods[i], e); mods[i] = null; count } } } if (logger.isInfoEnabled()) { logger.info(count + " modules loaded."); } } protected ConnectModule [] getModules() { return modules.toArray(new ConnectModule[modules.size()]); } protected ConnectModule [] getModules(String [] names) { ArrayList<ConnectModule> tmp = new ArrayList<ConnectModule>(); for (int i=0;i<names.length;i++) { boolean found = false; if (names[i] != null && !names[i].equals("none")) { for (int j=0;j<modules.size();j++) { ConnectModule m = modules.get(j); if (m.getName().equals(names[i])) { tmp.add(m); found = true; break; } } if (!found) { logger.warn("Module " + names[i] + " not found!"); } } } return tmp.toArray(new ConnectModule[tmp.size()]); } private void startModules() { ArrayList<ConnectModule> failed = new ArrayList<ConnectModule>(); if (serviceLink == null) { // No servicelink, so remove all modules that depend on it.... for (ConnectModule c : modules) { if (c.requiresServiceLink) { failed.add(c); } } for (ConnectModule c : failed) { logger.warn("Module " + c.module + " removed (no serviceLink)!"); modules.remove(c); } failed.clear(); } for (ConnectModule c : modules) { try { c.startModule(serviceLink); } catch (Exception e) { // Remove all modules that fail to start... logger.warn("Module " + c.module + " did not accept serviceLink!", e); failed.add(c); } } for (ConnectModule c : failed) { logger.warn("Module " + c.module + " removed (exception during setup)!"); modules.remove(c); } failed.clear(); } public VirtualServerSocket getServerSocket(int port) { synchronized (serverSockets) { return serverSockets.get(port); } } public ConnectModule findModule(String name) { for (ConnectModule m : modules) { if (m.module.equals(name)) { return m; } } return null; } public static void close(VirtualSocket s, OutputStream out, InputStream in) { try { if (out != null) { out.close(); } } catch (Exception e) { // ignore } try { if (in != null) { in.close(); } } catch (Exception e) { // ignore } try { if (s != null){ s.close(); } } catch (Exception e) { // ignore } } private VirtualSocket createClientSocket(ConnectModule m, VirtualSocketAddress target, int timeout, Map<String, Object> properties) throws IOException { if (m.matchRuntimeRequirements(properties)) { if (conlogger.isDebugEnabled()) { conlogger.debug("Using module " + m.module + " to set up " + "connection to " + target + " timeout = " + timeout); } long start = System.currentTimeMillis(); try { VirtualSocket vs = m.connect(target, timeout, properties); long end = System.currentTimeMillis(); // TODO: move to ibis ? if (vs != null) { vs.setTcpNoDelay(true); if (conlogger.isInfoEnabled()) { conlogger.info(getVirtualAddressAsString() + ": Sucess " + m.module + " connected to " + target + " (time = " + (end-start) + " ms.)"); } m.success(end-start); return vs; } m.failed(end-start); } catch (ModuleNotSuitableException e) { long end = System.currentTimeMillis(); // Just print and try the next module... if (conlogger.isInfoEnabled()) { conlogger.info(getVirtualAddressAsString() + ": Failed " + m.module + " not suitable (time = " + (end-start) + " ms.)"); } m.failed(end-start); } // NOTE: other exceptions are forwarded to the user! } else { if (conlogger.isInfoEnabled()) { conlogger.warn("Failed: module " + m.module + " may not be used to set " + "up connection to " + target); } m.notAllowed(); } return null; } public VirtualSocket createClientSocket(VirtualSocketAddress target, int timeout, Map<String, Object> prop) throws IOException { // Note: it's up to the user to ensure that this thing is large enough! // i.e., it should be of size 1+modules.length long [] timing = null; if (prop != null) { timing = (long []) prop.get("virtual.detailed.timing"); if (timing != null) { timing[0] = System.nanoTime(); } } try { int notSuitableCount = 0; if (timeout < 0) { timeout = DEFAULT_TIMEOUT; } ConnectModule [] order = clusters.getOrder(target); int timeLeft = timeout; int partialTimeout; if (timeout > 0 && order.length > 1) { partialTimeout = (timeout / order.length); } else if (order.length > 0) { partialTimeout = DEFAULT_TIMEOUT; } else { partialTimeout = 0; } // Now try the remaining modules (or all of them if we weren't // using the cache in the first place...) for (int i = 0; i<order.length;i++) { ConnectModule m = order[i]; long start = System.currentTimeMillis(); if (timing != null) { timing[1+i] = System.nanoTime(); if (i > 0) { prop.put("direct.detailed.timing.ignore", null); } } VirtualSocket vs = createClientSocket(m, target, partialTimeout, prop); if (timing != null) { timing[1+i] = System.nanoTime() - timing[1+i]; } if (vs != null) { if (notSuitableCount > 0) { // We managed to connect, but not with the first module, so // we remember this to speed up later connections. clusters.succes(target, m); } return vs; } if (timeout > 0 && i < order.length-1) { timeLeft -= System.currentTimeMillis() - start; if (timeLeft <= 0) { // TODO can this happen ? partialTimeout = 1000; } else { partialTimeout = (timeLeft / (order.length - (i+1))); } } notSuitableCount++; } if (notSuitableCount == order.length) { if (logger.isInfoEnabled()) { logger.info("No suitable module found to connect to " + target); } // No suitable modules found... throw new ConnectException("No suitable module found to connect to " + target); } else { // Apparently, some modules where suitable but failed to connect. // This is treated as a timeout if (logger.isInfoEnabled()) { logger.info("None of the modules could to connect to " + target); } // TODO: is this right ? throw new SocketTimeoutException("Timeout during connect to " + target); } } finally { if (timing != null) { timing[0] = System.nanoTime() - timing[0]; prop.remove("direct.detailed.timing.ignore"); } } } private int getPort() { // TODO: should this be random ? synchronized (serverSockets) { while (true) { if (!serverSockets.containsKey(nextPort)) { return nextPort++; } else { nextPort++; } } } } public VirtualServerSocket createServerSocket(int port, int backlog, boolean retry, Map properties) { VirtualServerSocket result = null; while (result == null) { try { result = createServerSocket(port, backlog, null); } catch (Exception e) { // retry if (logger.isDebugEnabled()) { logger.debug("Failed to open serversocket on port " + port + " (will retry): ", e); } } } return result; } public VirtualServerSocket createServerSocket(int port, int backlog, Map<String, Object> properties) throws IOException { if (backlog <= 0) { backlog = DEFAULT_BACKLOG; } if (port <= 0) { port = getPort(); } if (logger.isInfoEnabled()) { logger.info("Creating VirtualServerSocket(" + port + ", " + backlog + ", " + properties + ")"); } synchronized (serverSockets) { if (serverSockets.containsKey(port)) { throw new BindException("Port " + port + " already in use!"); } VirtualSocketAddress a = new VirtualSocketAddress(myAddresses, port, hubAddress, clusters.localCluster()); VirtualServerSocket vss = new VirtualServerSocket(this, a, port, backlog, properties); serverSockets.put(port, vss); return vss; } } // TODO: hide this thing ? public ServiceLink getServiceLink() { return serviceLink; } public DirectSocketAddress getLocalHost() { return myAddresses; } public String getLocalCluster() { return clusters.localCluster(); } public DirectSocketAddress getLocalProxy() { return hubAddress; } protected void closed(int port) { synchronized (serverSockets) { serverSockets.remove(new Integer(port)); } } public static VirtualSocketFactory getSocketFactory(String name) { return factories.get(name); } public static void registerSocketFactory(String name, VirtualSocketFactory factory) { factories.put(name, factory); } public static VirtualSocketFactory createSocketFactory() { VirtualSocketFactory f = getSocketFactory("default"); if (f == null) { TypedProperties p = Properties.getDefaultProperties(); p.put("smartsockets.factory.name", "default"); f = createSocketFactory(p, false); } return f; } public static VirtualSocketFactory createSocketFactory(HashMap p, boolean addDefaults) { return createSocketFactory(new TypedProperties(p), addDefaults); } public static VirtualSocketFactory createSocketFactory(TypedProperties p, boolean addDefaults) { //logger.warn("Creating VirtualSocketFactory(Prop, bool)!", new Exception()); // System.err.println("Creating VirtualSocketFactory(Prop, bool)!"); //new Exception().printStackTrace(System.err); if (printerInterval == -1 && printer == null) { printerInterval = p.getIntProperty(Properties.STATISTICS_INTERVAL, 0); if (printerInterval > 0) { printer = new StatisticsPrinter(printerInterval); ThreadPool.createNew(printer, "SmartSockets Statistics Printer"); } } if (p == null) { p = Properties.getDefaultProperties(); } else if (addDefaults) { p.putAll(Properties.getDefaultProperties()); } VirtualSocketFactory factory = null; String name = p.getProperty("smartsockets.factory.name"); if (name != null) { factory = factories.get(name); } if (factory == null) { try { factory = new VirtualSocketFactory(p); if (name != null) { factories.put(name, factory); } } catch (Exception e) { logger.warn("Failed to create VirtualSocketFactory!", e); } } return factory; } public VirtualSocket createBrokeredSocket(InputStream brokered_in, OutputStream brokered_out, boolean b, Map p) { throw new RuntimeException("createBrokeredSocket not implemented"); } public VirtualSocketAddress getLocalVirtual() { return localVirtualAddress; } public String getVirtualAddressAsString() { return localVirtualAddressAsString; } public void printStatistics(String prefix) { if (statslogger.isInfoEnabled()) { statslogger.info(prefix + " === VirtualSocketFactory (" + modules.size() + " / " + (serviceLink == null ? "No SL" : "SL") + ") ==="); for (ConnectModule c : modules) { c.printStatistics(prefix); } if (serviceLink != null) { serviceLink.printStatistics(prefix); } } } }
package com.dmdirc.ui.messages; import com.dmdirc.config.IdentityManager; import java.awt.Color; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class ColourManagerTest { @BeforeClass public static void setUp() throws Exception { IdentityManager.load(); } @Test public void testGetColourInt() { int spec = 4; Color expResult = Color.RED; Color result = ColourManager.getColour(spec); assertEquals(expResult, result); } @Test public void testGetColourOOB() { Color result = ColourManager.getColour(20); assertEquals(Color.WHITE, result); } @Test public void testGetColourHexInvalid() { String spec = "FFZZFF"; Color result = ColourManager.getColour(spec); assertEquals(Color.WHITE, result); } @Test public void testGetColourHex() { String spec = "FFFFFF"; Color expResult = Color.decode("#FFFFFF"); Color result = ColourManager.getColour(spec); assertEquals(expResult, result); } @Test public void testParseColourNull() { Color fallback = Color.RED; Color result = ColourManager.parseColour(null, fallback); assertEquals(fallback, result); } @Test public void testParseColourInvalidNumber() { Color fallback = Color.RED; Color result = ColourManager.parseColour("zz", fallback); assertEquals(fallback, result); } @Test public void testParseColourOOBNumber() { Color fallback = Color.RED; Color result = ColourManager.parseColour("20", fallback); assertEquals(fallback, result); } @Test public void testParseColourShortNumber() { Color fallback = Color.RED; Color result = ColourManager.parseColour("1234", fallback); assertEquals(fallback, result); } @Test public void testColourCache() { Color result1 = ColourManager.parseColour("ff0f0f"); Color result2 = ColourManager.parseColour("ff0f0f"); Color result3 = ColourManager.getColour("ff0f0f"); assertSame(result1, result2); assertSame(result2, result3); } @Test public void testColourToHex() { Color c1 = ColourManager.parseColour("ab3400"); assertEquals("ab3400", ColourManager.getHex(c1).toLowerCase()); } @Test public void testCustomColours() { IdentityManager.getConfigIdentity().setOption("colour", "4", "00ff00"); assertEquals("00ff00", ColourManager.getHex(ColourManager.getColour(4)).toLowerCase()); IdentityManager.getConfigIdentity().unsetOption("colour", "4"); } public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(ColourManagerTest.class); } }
package soot.jimple.infoflow.heros; import heros.EdgeFunction; import heros.FlowFunction; import heros.InterproceduralCFG; import heros.edgefunc.EdgeIdentity; import heros.solver.CountingThreadPoolExecutor; import heros.solver.IFDSSolver; import heros.solver.PathEdge; import heros.solver.PathTrackingIFDSSolver; import java.util.HashSet; import java.util.Set; import soot.SootMethod; import soot.Unit; import soot.jimple.infoflow.data.Abstraction; import soot.jimple.infoflow.problems.AbstractInfoflowProblem; /** * We are subclassing the JimpleIFDSSolver because we need the same executor for both the forward and the backward analysis * Also we need to be able to insert edges containing new taint information * */ public class InfoflowSolver extends PathTrackingIFDSSolver<Unit, Abstraction, SootMethod, InterproceduralCFG<Unit, SootMethod>> { public InfoflowSolver(AbstractInfoflowProblem problem, CountingThreadPoolExecutor executor) { super(problem); this.executor = executor; problem.setSolver(this); } @Override protected CountingThreadPoolExecutor getExecutor() { return executor; } public boolean processEdge(PathEdge<Unit, Abstraction> edge){ // We are generating a fact out of thin air here. If we have an // edge <d1,n,d2>, there need not necessarily be a jump function // to <n,d2>. if (!jumpFn.forwardLookup(edge.factAtSource(), edge.getTarget()).containsKey(edge.factAtTarget())) { propagate(edge.factAtSource(), edge.getTarget(), edge.factAtTarget(), EdgeIdentity.<IFDSSolver.BinaryDomain>v(), null, false); return true; } return false; } public void injectContext(InfoflowSolver otherSolver, SootMethod callee, Abstraction d3, Unit callSite, Abstraction d2) { synchronized (incoming) { for (Unit sP : icfg.getStartPointsOf(callee)) addIncoming(sP, d3, callSite, d2); } // First, get a list of the other solver's jump functions. // Then release the lock on otherSolver.jumpFn before doing // anything that locks our own jumpFn. final Set<Abstraction> otherAbstractions; synchronized (otherSolver.jumpFn) { otherAbstractions = new HashSet<Abstraction> (otherSolver.jumpFn.reverseLookup(callSite, d2).keySet()); } for (Abstraction d1: otherAbstractions) if (!d1.getAccessPath().isEmpty() && !d1.getAccessPath().isStaticFieldRef()) processEdge(new PathEdge<Unit, Abstraction>(d1, callSite, d2)); } @Override protected Set<Abstraction> computeReturnFlowFunction (FlowFunction<Abstraction> retFunction, Abstraction d2, Unit callSite, Set<Abstraction> callerSideDs) { if (retFunction instanceof SolverReturnFlowFunction) { // Get the d1s at the start points of the caller Set<Abstraction> d1s = new HashSet<Abstraction>(callerSideDs.size() * 5); for (Abstraction d4 : callerSideDs) if (d4 == zeroValue) d1s.add(d4); else synchronized (jumpFn) { d1s.addAll(jumpFn.reverseLookup(callSite, d4).keySet()); } return ((SolverReturnFlowFunction) retFunction).computeTargets(d2, d1s); } else return retFunction.computeTargets(d2); } @Override protected Set<Abstraction> computeNormalFlowFunction (FlowFunction<Abstraction> flowFunction, Abstraction d1, Abstraction d2) { if (flowFunction instanceof SolverNormalFlowFunction) return ((SolverNormalFlowFunction) flowFunction).computeTargets(d1, d2); else return flowFunction.computeTargets(d2); } @Override protected Set<Abstraction> computeCallToReturnFlowFunction (FlowFunction<Abstraction> flowFunction, Abstraction d1, Abstraction d2) { if (flowFunction instanceof SolverCallToReturnFlowFunction) return ((SolverCallToReturnFlowFunction) flowFunction).computeTargets(d1, d2); else return flowFunction.computeTargets(d2); } @Override protected void propagate(Abstraction sourceVal, Unit target, Abstraction targetVal, EdgeFunction<BinaryDomain> f, /* deliberately exposed to clients */ Unit relatedCallSite, /* deliberately exposed to clients */ boolean isUnbalancedReturn) { // Check whether we already have an abstraction that entails the new one. // In such a case, we can simply ignore the new abstraction. boolean noProp = false; /* for (Abstraction abs : new HashSet<Abstraction>(jumpFn.forwardLookup(sourceVal, target).keySet())) if (abs != targetVal) { if (abs.entails(targetVal)) { noProp = true; break; } if (targetVal.entails(abs)) { jumpFn.removeFunction(sourceVal, target, abs); } } */ if (!noProp) super.propagate(sourceVal, target, targetVal, f, relatedCallSite, isUnbalancedReturn); } }
package edu.jhu.thrax.util.io; import org.testng.annotations.Test; import org.testng.Assert; import edu.jhu.thrax.util.exceptions.*; public class InputUtilitiesTest { @Test public void parseYield_EmptyString_ReturnsZeroLengthArray() throws MalformedInputException { Assert.assertEquals(InputUtilities.parseYield("").length, 0); } @Test public void parseYield_Whitespace_ReturnsZeroLengthArray() throws MalformedInputException { Assert.assertEquals(InputUtilities.parseYield(" ").length, 0); } @Test public void parseYield_EmptyParse_ReturnsZeroLengthArray() throws MalformedInputException { Assert.assertEquals(InputUtilities.parseYield("()").length, 0); } @Test(expectedExceptions = { MalformedInputException.class }) public void parseYield_UnbalancedLeft_ThrowsException() throws MalformedInputException { InputUtilities.parseYield("(S (DT the) (NP dog)"); } @Test(expectedExceptions = { MalformedInputException.class }) public void parseYield_UnbalancedRight_ThrowsException() throws MalformedInputException { InputUtilities.parseYield("(S (DT the) (NP dog)))"); } @Test public void getWords_EmptyString_ReturnsZeroLengthArray() throws MalformedInputException { Assert.assertEquals(InputUtilities.getWords("", false).length, 0); Assert.assertEquals(InputUtilities.getWords("", true).length, 0); } @Test public void getWords_Whitespace_ReturnsZeroLengthArray() throws MalformedInputException { Assert.assertEquals(InputUtilities.getWords(" ", false).length, 0); Assert.assertEquals(InputUtilities.getWords(" ", true).length, 0); } @Test public void getWords_PlainWords_ReturnsStringArray() throws MalformedInputException { String [] tokens = { "hello", ",", "world" }; Assert.assertEquals(InputUtilities.getWords("hello , world", false), tokens); } }
package test.com.mac.tarchan.nanika; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.ComponentEvent; import java.io.File; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.mac.tarchan.desktop.DesktopSupport; import com.mac.tarchan.desktop.InputBox; import com.mac.tarchan.desktop.SexyControl; import com.mac.tarchan.desktop.event.EventQuery; import com.mac.tarchan.nanika.shell.NanikaCanvas; import com.mac.tarchan.nanika.shell.NanikaShell; import com.mac.tarchan.nanika.util.NarFile; import com.mac.tarchan.nanika.util.NarFile.Type; /** * NanikaPreview * * @author tarchan */ public class NanikaPreview { private static final Log log = LogFactory.getLog(NanikaPreview.class); JFrame window; JPanel grid; JFileChooser fd = new JFileChooser(); NanikaShell shell; /** * @param args */ public static void main(String[] args) { SexyControl.setAppleMenuAboutName("NanikaPreview"); SexyControl.useScreenMenuBar(); DesktopSupport.useSystemLookAndFeel(); // PropertyConfigurator.configure("log4j.properties"); try { // String zip = "/Users/tarchan/Documents/nanika/nar/akane_v135.nar"; // String zip = "/Users/tarchan/Documents/nanika/nar/333-2.60.nar"; // String zip = "/Users/tarchan/Documents/nanika/nar/mayura_v340.zip"; // String zip = "/Users/tarchan/Documents/nanika/nar/cmd.nar"; // if (args.length > 0) zip = args[0]; String zip = args[0]; NanikaPreview preview = new NanikaPreview(); // app.createWindow().setVisible(true); DesktopSupport.show(preview.createWindow()); preview.setNar(zip); } catch (Exception x) { x.printStackTrace(); } } // public NanikaPreview(String zip) throws IOException // setNar(zip); /** * * * @return */ JFrame createWindow() { JFrame window = new JFrame("NanikaPreview"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setName("window"); window.setSize(900, 500); // TODO // window.setBackground(new java.awt.Color(0, true)); // window.setUndecorated(true); // window.add(this, BorderLayout.CENTER); // window.add(createFooterComponent(), BorderLayout.SOUTH); window.setJMenuBar(createJMenuBar()); window.add(createComponent()); SexyControl.setWindowShadow(window, false); EventQuery.from(window).find("preferencesTable").change(this, "selectRow", "").end() .find("menubar").button().click(this).end() .find("footer").button().click(this).end() .find("window").resize(this, "resizeView", ""); // SexyControl.setWindowShadow(window, false); // SexyControl.setWindowAlpha(window, 0.5); // window.setBackground(new Color(0, true)); // window.setUndecorated(true); // window.setAlwaysOnTop(true); this.window = window; return window; } Component createComponent() { JPanel grid = new JPanel(); this.grid = grid; // Box box = Box.createHorizontalBox(); // box.add(grid); // box.add(Box.createHorizontalGlue()); // box.setOpaque(false); JScrollPane scroll = new JScrollPane(grid); scroll.setName("scroll"); // main.setPreferredSize(new Dimension(800, 0)); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scroll.getVerticalScrollBar().setUnitIncrement(8); scroll.getVerticalScrollBar().setBlockIncrement(320); // scroll.setBackground(new Color(0, true)); // scroll.setOpaque(false); // scroll.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); // window.add(scroll); return scroll; } /** * * * @return */ JMenuBar createJMenuBar() { JMenuItem openNar = new JMenuItem("Open Nar..."); openNar.setName("openNar"); JMenu fileMenu = new JMenu("File"); fileMenu.add(openNar); JMenuBar menubar = new JMenuBar(); menubar.setName("menubar"); menubar.add(fileMenu); return menubar; } /** * * * @param evt */ public void resizeView(ComponentEvent evt) { log.debug("evt=" + evt); } /** * NAR */ public void openNar() { try { if (fd.showOpenDialog(window) != JFileChooser.APPROVE_OPTION) return; File file = fd.getSelectedFile(); setNar(file.getPath()); } catch (Throwable x) { InputBox.alert("NAR " + x.getLocalizedMessage()); } } /** * * * @param zip NAR * @throws IOException */ public void setNar(String zip) throws IOException { NarFile nar = NarFile.load(zip); fd.setSelectedFile(new File(zip)); log.info("nar=" + nar); nar.list(); if (nar.getType() == Type.ghost) { NarFile shell_master = nar.subdir("shell/master"); shell = new NanikaShell(shell_master); // NanikaSurface surface = shell.getSurface(NanikaShell.SAKURA_ID); // log.info("shell=" + shell); // log.info("surface=" + surface); // JPanel main = new JPanel(); // main.add(surface); // window.add(main); int rows = (shell.getSurfaceCount() + 4) / 5; log.debug("rows=" + rows + ", " + shell.getSurfaceKeys()); grid.removeAll(); grid.setLayout(new GridLayout(rows, 5)); // JPanel grid = new JPanel(new GridLayout(rows, 5)); // JPanel main = new JPanel(new FlowLayout()); for (String id : shell.getSurfaceKeys()) { NanikaCanvas canvas = new NanikaCanvas(); canvas.setShell(shell); canvas.setSurface(id); JLabel label = new JLabel(id, JLabel.CENTER); JPanel koma = new JPanel(new BorderLayout()); koma.add(canvas, BorderLayout.CENTER); koma.add(label, BorderLayout.SOUTH); grid.add(koma); // grid.add(scope); } //// Box box = Box.createHorizontalBox(); //// box.add(grid); //// box.add(Box.createHorizontalGlue()); //// box.setOpaque(false); // JScrollPane scroll = new JScrollPane(grid); // scroll.setName("scroll"); //// main.setPreferredSize(new Dimension(800, 0)); // scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); // scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // scroll.getVerticalScrollBar().setUnitIncrement(8); // scroll.getVerticalScrollBar().setBlockIncrement(320); //// scroll.setBackground(new Color(0, true)); // scroll.setOpaque(false); //// scroll.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); // window.add(scroll); //// window.add(main); window.validate(); // box.setBackground(new Color(0, true)); // window.setBackground(new Color(0, true)); // window.setUndecorated(true); // window.setAlwaysOnTop(true); // NarFile ghost = nar.subdir("ghost/master"); // log.info("ghost=" + ghost); } else { } } // /** // * {@inheritDoc} // */ // public void paint2(Graphics g) //// log.debug("g=" + g); // if (shell == null) return; // Rectangle clip = g.getClipBounds(); // Graphics2D g2 = (Graphics2D)g; // NanikaSurface sakura = shell.getSurface(NanikaShell.SAKURA_ID); // sakura.x = clip.width - sakura.getWidth(); // sakura.y = clip.height - sakura.getHeight(); // sakura.draw(g2); // NanikaSurface kero = shell.getSurface(NanikaShell.KERO_ID); // kero.y = clip.height - kero.getHeight(); // kero.draw(g2); }
package com.zandero.rest; import com.zandero.rest.test.TestAsyncRest; import io.vertx.ext.web.Router; import io.vertx.ext.web.codec.BodyCodec; import io.vertx.junit5.*; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(VertxExtension.class) class RouteAsyncTest extends VertxTest { @BeforeAll static void start() { before(); Router router = RestRouter.register(vertx, TestAsyncRest.class); vertx.createHttpServer() .requestHandler(router) .listen(PORT); } /* @Test void testAsyncCallFutureInsideRest(VertxTestContext context) { client.get(PORT, HOST, "/async/call_future") .as(BodyCodec.string()) .send(context.succeeding(response -> context.verify(() -> { assertEquals(200, response.statusCode()); assertEquals("{\"name\": \"async\", \"value\": \"called\"}", response.body()); context.completeNow(); }))); }*/ @Test void testAsyncCallPromiseInsideRest(VertxTestContext context) { client.get(PORT, HOST, "/async/call_promise") .as(BodyCodec.string()) .send(context.succeeding(response -> context.verify(() -> { assertEquals(200, response.statusCode()); assertEquals("{\"name\": \"async\", \"value\": \"called\"}", response.body()); context.completeNow(); }))); } @Test void testAsyncCompletableRest(VertxTestContext context) { client.get(PORT, HOST, "/async/completable") .as(BodyCodec.string()) .send(context.succeeding(response -> context.verify(() -> { assertEquals(200, response.statusCode()); assertEquals("{\"name\": \"hello\", \"value\": \"world\"}", response.body()); context.completeNow(); }))); } /* @Test void testAsyncCallWithExecutorFutureRest(VertxTestContext context) { client.get(PORT, HOST, "/async/executor_future") .as(BodyCodec.string()) .send(context.succeeding(response -> context.verify(() -> { assertEquals(200, response.statusCode()); assertEquals("{\"name\": \"async\", \"value\": \"called\"}", response.body()); context.completeNow(); }))); }*/ @Test void testAsyncCallWithExecutorPromiseRest(VertxTestContext context) { client.get(PORT, HOST, "/async/executor_promise") .as(BodyCodec.string()) .send(context.succeeding(response -> context.verify(() -> { assertEquals(200, response.statusCode()); assertEquals("{\"name\": \"async\", \"value\": \"called\"}", response.body()); context.completeNow(); }))); } @Test void testAsyncCallInsideRestNullFutureResult(VertxTestContext context) { client.get(PORT, HOST, "/async/empty") .as(BodyCodec.string()) .send(context.succeeding(response -> context.verify(() -> { assertEquals(204, response.statusCode()); context.completeNow(); }))); } @Test void testAsyncCallInsideRestNullNoWriterFutureResult(VertxTestContext context) { client.get(PORT, HOST, "/async/null") .as(BodyCodec.string()) .send(context.succeeding(response -> context.verify(() -> { assertEquals(200, response.statusCode()); context.completeNow(); }))); } @Test void testAsyncHanlder(VertxTestContext context) throws InterruptedException { client.get(PORT, HOST, "/async/handler") .as(BodyCodec.string()) .send(context.succeeding(response -> context.verify(() -> { assertEquals(200, response.statusCode()); assertEquals("\"invoked\"", response.body()); context.completeNow(); }))); Thread.sleep(2000); // wait until handler finished } }
package dcll.iParser.iParser; import junit.framework.TestCase; public class ParserTest extends TestCase{ private Question questionSimple; private Question questionMultiple; protected void setUp() throws Exception{ super.setUp(); Parser parser = new Parser(); String questionSimpleTexte = "{Qui est le président des États Unis?\n"+ "|type=\"()\"}\n"+ "+ Obama.\n"+ "- François Hollande.\n"+ "- Xi Jinping.\n"; questionSimple = parser.doIt(questionSimpleTexte); String questionMultipleTexte = "{Quels sont les coleur de feu rouge?\n"+ "|type=\"[]\"}\n"+ "+ rouge.\n"+ "- bleu.\n"+ "+ vert.\n"+ "- noir.\n"; questionMultiple = parser.doIt(questionMultipleTexte); } //Question Simple public void testQuestionTexteSimple(){ assertEquals("Question = Qui est le président des États Unis? ","Qui est le président des États Unis?", questionSimple.getQuestionText()); } public void test1emeReponseTexteSimple(){ assertEquals("première réponse = \"Obama.\"","Obama.", questionSimple.getIemeReponse(0).getReponseText()); } public void testNature1emeReponseSimple(){ assertEquals("Nature de première réponse = true",true, questionSimple.getIemeReponse(0).getReponseValue()); } public void test2emeReponseSimple(){ assertEquals("deuxième réponse = \"François Hollande.\"","François Hollande.", questionSimple.getIemeReponse(1).getReponseText()); } public void testNature2emeReponseSimple(){ assertEquals("Nature de deuxième réponse = false",false, questionSimple.getIemeReponse(1).getReponseValue()); } public void test3emeReponseSimple(){ assertEquals("troisième réponse = \"Xi Jinping.\"","Xi Jinping.", questionSimple.getIemeReponse(2).getReponseText()); } public void testNature3emeReponseSimple(){ assertEquals("Nature de troisième réponse = false",false, questionSimple.getIemeReponse(2).getReponseValue()); } public void testIsQuestionSimple(){ assertEquals("Question a une seul réponse",1,questionSimple.nbReponseCorrecte()); } //Question Multiple public void testQuestionTexteMultiple(){ assertEquals("Question = Quels sont les coleur de feu rouge?","Quels sont les coleur de feu rouge?", questionMultiple.getQuestionText()); } public void test1emeReponseTexteMultiple(){ assertEquals("première réponse = \"rouge.\"","rouge.", questionMultiple.getIemeReponse(0).getReponseText()); } public void testNature1emeReponseMultiple(){ assertEquals("Nature de première réponse = true",true, questionMultiple.getIemeReponse(0).getReponseValue()); } public void test2emeReponseMultiple(){ assertEquals("deuxième réponse = \"bleu.\"","bleu.", questionMultiple.getIemeReponse(1).getReponseText()); } public void testNature2emeReponseMultiple(){ assertEquals("Nature de deuxième réponse = false",false, questionMultiple.getIemeReponse(1).getReponseValue()); } public void test3emeReponseMultiple(){ assertEquals("troisième réponse = \"vert.\"","vert.", questionMultiple.getIemeReponse(2).getReponseText()); } public void testNature3emeReponseMultiple(){ assertEquals("Nature de troisième réponse = true",true, questionMultiple.getIemeReponse(2).getReponseValue()); } public void test4emeReponseMultiple(){ assertEquals("troisième réponse = \"noir.\"","noir.", questionMultiple.getIemeReponse(3).getReponseText()); } public void testNature4emeReponseMultiple(){ assertEquals("Nature de troisième réponse = false",false, questionMultiple.getIemeReponse(3).getReponseValue()); } public void testIsQuestionMultiple(){ assertEquals("Question a 2 réponses correctes",2,questionMultiple.nbReponseCorrecte()); } }
package de.dhbw.humbuch.tests; import static org.junit.Assert.assertEquals; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Test; import de.dhbw.humbuch.model.GradeHandler; import de.dhbw.humbuch.model.MapperAmountAndBorrowedMaterial; import de.dhbw.humbuch.model.ProfileTypeHandler; import de.dhbw.humbuch.model.StudentHandler; import de.dhbw.humbuch.model.TeachingMaterialHandler; import de.dhbw.humbuch.model.entity.BorrowedMaterial; import de.dhbw.humbuch.model.entity.Grade; import de.dhbw.humbuch.model.entity.ProfileType; import de.dhbw.humbuch.model.entity.Student; import de.dhbw.humbuch.model.entity.TeachingMaterial; import de.dhbw.humbuch.pdfExport.MyPDFClassList; public class GradeTest { @Test public void testGetAllRentedBooksOfGrade(){ Grade grade = prepareGradeTest(); List<MapperAmountAndBorrowedMaterial> maabm = GradeHandler.getAllRentedBooksOfGrade(grade); assertEquals(2, maabm.get(0).getAmount()); assertEquals("Bio1 - Bugs", maabm.get(0).getBorrowedMaterial().getTeachingMaterial().getName()); assertEquals(1, maabm.get(1).getAmount()); assertEquals("German1 - Faust", maabm.get(1).getBorrowedMaterial().getTeachingMaterial().getName()); assertEquals(2, maabm.get(2).getAmount()); assertEquals("Java rocks", maabm.get(2).getBorrowedMaterial().getTeachingMaterial().getName()); assertEquals(1, maabm.get(3).getAmount()); assertEquals("Geometrie for Dummies", maabm.get(3).getBorrowedMaterial().getTeachingMaterial().getName()); } public static Grade prepareGradeTest(){ Grade grade = new Grade.Builder("7b").teacher("Herr Bob").build(); List<Student> studentsList = new ArrayList<Student>(); Set<ProfileType> profileTypeSet = ProfileTypeHandler.createProfile(new String[]{"L", "E", ""}, "ev"); Date date = null; try { date = new SimpleDateFormat("dd.mm.yyyy", Locale.GERMAN).parse("12.04.1970"); } catch (ParseException e) { System.err.println("Could not format date " + e.getStackTrace()); } Student student = new Student.Builder(2, "Karl", "August", date, grade).gender("m").profileTypes(profileTypeSet).build(); List<BorrowedMaterial> borrowedMaterialList = new ArrayList<BorrowedMaterial>(); TeachingMaterial teachingMaterial = TeachingMaterialHandler.createTeachingMaterial(6, "Bio1 - Bugs", 79.75); BorrowedMaterial borrowedMaterial = new BorrowedMaterial(); borrowedMaterial.setTeachingMaterial(teachingMaterial); borrowedMaterialList.add(borrowedMaterial); teachingMaterial = TeachingMaterialHandler.createTeachingMaterial(11, "German1 - Faust", 22.49); borrowedMaterial = new BorrowedMaterial(); borrowedMaterial.setTeachingMaterial(teachingMaterial); borrowedMaterialList.add(borrowedMaterial); teachingMaterial = TeachingMaterialHandler.createTeachingMaterial(11, "Java rocks", 22.49); borrowedMaterial = new BorrowedMaterial(); borrowedMaterial.setTeachingMaterial(teachingMaterial); borrowedMaterialList.add(borrowedMaterial); student.setBorrowedList(borrowedMaterialList); studentsList.add(student); profileTypeSet = ProfileTypeHandler.createProfile(new String[]{"E", "", "F"}, "rk"); try { date = new SimpleDateFormat("dd.mm.yyyy", Locale.GERMAN).parse("12.04.1981"); } catch (ParseException e) { System.err.println("Could not format date " + e.getStackTrace()); } student = new Student.Builder(5, "Karla", "Kolumna", date, grade).gender("w").profileTypes(profileTypeSet).build(); borrowedMaterialList = new ArrayList<BorrowedMaterial>(); //subject = SubjectHandler.createSubject("Biology"); teachingMaterial = TeachingMaterialHandler.createTeachingMaterial(6, "Bio1 - Bugs", 79.75); borrowedMaterial = new BorrowedMaterial(); borrowedMaterial.setTeachingMaterial(teachingMaterial); borrowedMaterialList.add(borrowedMaterial); //subject = SubjectHandler.createSubject("IT"); teachingMaterial = TeachingMaterialHandler.createTeachingMaterial(11, "Java rocks", 22.49); borrowedMaterial = new BorrowedMaterial(); borrowedMaterial.setTeachingMaterial(teachingMaterial); borrowedMaterialList.add(borrowedMaterial); //subject = SubjectHandler.createSubject("Mathe"); teachingMaterial = TeachingMaterialHandler.createTeachingMaterial(11, "Geometrie for Dummies", 22.49); borrowedMaterial = new BorrowedMaterial(); borrowedMaterial.setTeachingMaterial(teachingMaterial); borrowedMaterialList.add(borrowedMaterial); student.setBorrowedList(borrowedMaterialList); studentsList.add(student); grade.setStudents(studentsList); return grade; } }
package dk.kleistsvendsen; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class GameTimerTest { private GameTimer gameTimer; @Mock private ITicSource ticSource; @Before public void setup() { MockitoAnnotations.initMocks(this); TestGuiceModule module = new TestGuiceModule(); module.addBinding(ITicSource.class, ticSource); TestGuiceModule.setUp(this, module); gameTimer = new GameTimer(); } @After public void teardown() { TestGuiceModule.tearDown(); } @Test public void testCallsTickOnStartTimer() { when(ticSource.tic()).thenReturn(0L); gameTimer.startTimer(); } @Test public void testStartThenTimeLeft() { when(ticSource.tic()).thenReturn(0L); gameTimer.startTimer(); when(ticSource.tic()).thenReturn(1000L); assertThat(gameTimer.timeLeft(), equalTo(1000L)); } }
package loci.common.utests; import static org.testng.AssertJUnit.assertEquals; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; import java.util.Arrays; import java.util.List; import loci.common.Location; import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Unit tests for the loci.common.Location class. * * @see loci.common.Location */ public class LocationTest { private static final boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows"); // -- Fields -- private enum LocalRemoteType { LOCAL, HTTP, S3, }; private Location[] files; private Location[] rootFiles; private boolean[] exists; private boolean[] isDirectory; private boolean[] isHidden; private String[] mode; private LocalRemoteType[] isRemote; private boolean isOnline; private boolean canAccessS3; // -- Setup methods -- @BeforeClass public void setup() throws IOException { File tmpDirectory = new File(System.getProperty("java.io.tmpdir"), System.currentTimeMillis() + "-location-test"); boolean success = tmpDirectory.mkdirs(); tmpDirectory.deleteOnExit(); File hiddenFile = File.createTempFile(".hiddenTest", null, tmpDirectory); hiddenFile.deleteOnExit(); File invalidFile = File.createTempFile("invalidTest", null, tmpDirectory); String invalidPath = invalidFile.getAbsolutePath(); invalidFile.delete(); File validFile = File.createTempFile("validTest", null, tmpDirectory); validFile.deleteOnExit(); files = new Location[] { new Location(validFile.getAbsolutePath()), new Location(invalidPath), new Location(tmpDirectory), new Location("http: new Location("https: new Location("https: new Location("https: new Location(hiddenFile), new Location("s3://minio.openmicroscopy.org/bucket-dne"), new Location("s3://minio.openmicroscopy.org/bioformats.test.public"), new Location("s3://minio.openmicroscopy.org/bioformats.test.public/z-series.ome.tif"), }; rootFiles = new Location[] { new Location("/"), new Location("https: new Location("s3://minio.openmicroscopy.org"), }; exists = new boolean[] { true, false, true, true, true, false, false, true, false, true, true, }; isDirectory = new boolean[] { false, false, true, false, false, false, false, false, false, true, false, }; isHidden = new boolean[] { false, false, false, false, false, false, false, true, false, false, false, }; mode = new String[] { "rw", "", "rw", "r", "r", "", "", "rw", "", "r", "r", }; isRemote = new LocalRemoteType[] { LocalRemoteType.LOCAL, LocalRemoteType.LOCAL, LocalRemoteType.LOCAL, LocalRemoteType.HTTP, LocalRemoteType.HTTP, LocalRemoteType.HTTP, LocalRemoteType.HTTP, LocalRemoteType.LOCAL, LocalRemoteType.S3, LocalRemoteType.S3, LocalRemoteType.S3, }; } @BeforeClass public void checkIfOnline() throws IOException { try { new Socket("www.openmicroscopy.org", 80).close(); isOnline = true; } catch (IOException e) { isOnline = false; } try { new Socket("minio.openmicroscopy.org", 443).close(); canAccessS3 = true; } catch (IOException e) { canAccessS3 = false; } if (!isOnline) { System.err.println("WARNING: online tests are disabled!"); } if (!canAccessS3) { System.err.println("WARNING: S3 tests are disabled!"); } } private void skipIfOffline(int i) throws SkipException { if (isRemote[i] == LocalRemoteType.HTTP && !isOnline) { throw new SkipException("must be online to test " + files[i].getName()); } } private void skipIfS3Offline(int i) throws SkipException { if (isRemote[i] == LocalRemoteType.S3 && !canAccessS3) { throw new SkipException("must have access to s3 to test " + files[i].getName()); } } // -- Tests -- @Test public void testReadWriteMode() { for (int i=0; i<files.length; i++) { skipIfOffline(i); skipIfS3Offline(i); String msg = files[i].getName(); assertEquals(msg, files[i].canRead(), mode[i].contains("r")); assertEquals(msg, files[i].canWrite(), mode[i].contains("w")); } } @Test public void testAbsolute() { for (Location file : files) { assertEquals(file.getName(), file.getAbsolutePath(), file.getAbsoluteFile().getAbsolutePath()); } } @Test public void testExists() { for (int i=0; i<files.length; i++) { skipIfOffline(i); skipIfS3Offline(i); assertEquals(files[i].getName(), files[i].exists(), exists[i]); } } @Test public void testCanonical() throws IOException { for (Location file : files) { assertEquals(file.getName(), file.getCanonicalPath(), file.getCanonicalFile().getAbsolutePath()); } } @Test public void testParent() { for (Location file : files) { assertEquals(file.getName(), file.getParent(), file.getParentFile().getAbsolutePath()); } } @Test public void testParentRoot() { for (Location file : rootFiles) { assertEquals(file.getName(), file.getParent(), null); } } @Test public void testIsDirectory() { for (int i=0; i<files.length; i++) { skipIfS3Offline(i); assertEquals(files[i].getName(), files[i].isDirectory(), isDirectory[i]); } } @Test public void testIsFile() { for (int i=0; i<files.length; i++) { skipIfOffline(i); skipIfS3Offline(i); assertEquals(files[i].getName(), files[i].isFile(), !isDirectory[i] && exists[i]); } } @Test public void testIsHidden() { for (int i=0; i<files.length; i++) { assertEquals(files[i].getName(), files[i].isHidden() || IS_WINDOWS, isHidden[i] || IS_WINDOWS); } } @Test public void testListFiles() { for (int i=0; i<files.length; i++) { String[] completeList = files[i].list(); String[] unhiddenList = files[i].list(true); Location[] fileList = files[i].listFiles(); if (!files[i].isDirectory()) { assertEquals(files[i].getName(), completeList, null); assertEquals(files[i].getName(), unhiddenList, null); assertEquals(files[i].getName(), fileList, null); continue; } assertEquals(files[i].getName(), completeList.length, fileList.length); List<String> complete = Arrays.asList(completeList); for (String child : unhiddenList) { assertEquals(files[i].getName(), complete.contains(child), true); assertEquals(files[i].getName(), new Location(files[i], child).isHidden(), false); } for (int f=0; f<fileList.length; f++) { assertEquals(files[i].getName(), fileList[f].getName(), completeList[f]); } } } @Test public void testToURL() throws IOException { for (Location file : files) { String path = file.getAbsolutePath(); if (!path.contains(": if (IS_WINDOWS) { path = "file:/" + path; } else { path = "file://" + path; } } if (file.isDirectory() && !path.endsWith(File.separator)) { path += File.separator; } try { assertEquals(file.getName(), file.toURL(), new URL(path)); } catch (MalformedURLException e) { assertEquals(path, true, path.contains("s3: } } } @Test public void testToString() { for (Location file : files) { assertEquals(file.getName(), file.toString(), file.getAbsolutePath()); } } }
package org.amc.game.chess; import static org.junit.Assert.*; import static org.amc.game.chess.ChessBoard.Coordinate.*; import static org.amc.game.chess.StartingSquare.WHITE_KING; import static org.amc.game.chess.StartingSquare.WHITE_ROOK_LEFT; import static org.amc.game.chess.StartingSquare.WHITE_ROOK_RIGHT; import org.junit.After; import org.junit.Before; import org.junit.Test; public class CastlingTest { private ChessBoard board; private KingPiece whiteKing; private RookPiece whiteLeftRook; private RookPiece whiteRightRook; private Location whiteKingStartPosition; private final Location castlingKingRightLocation=new Location(G,1); private final Location castlingKingLeftLocation=new Location(C,1); private Location whiteLeftRookStartPosition; private Location whiteRightRookStartPosition; private ChessGame chessGame; private CastlingRule gameRule; private Player whitePlayer; private Player blackPlayer; @Before public void setUp() throws Exception { board=new ChessBoard(); whitePlayer=new HumanPlayer("White Player",Colour.WHITE); blackPlayer=new HumanPlayer("Black Player", Colour.BLACK); chessGame=new ChessGame(board,whitePlayer,blackPlayer); gameRule=new CastlingRule(); whiteKing=new KingPiece(Colour.WHITE); whiteLeftRook=new RookPiece(Colour.WHITE); whiteRightRook=new RookPiece(Colour.WHITE); whiteKingStartPosition=WHITE_KING.getLocation(); whiteLeftRookStartPosition=WHITE_ROOK_LEFT.getLocation(); whiteRightRookStartPosition=WHITE_ROOK_RIGHT.getLocation(); board.putPieceOnBoardAt(whiteKing, whiteKingStartPosition); board.putPieceOnBoardAt(whiteRightRook, whiteRightRookStartPosition); board.putPieceOnBoardAt(whiteLeftRook, whiteLeftRookStartPosition); } @After public void tearDown() throws Exception { } @Test public void testLeftSideCastling(){ assertTrue(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingLeftLocation))); } @Test public void testRightSideCastling(){ assertTrue(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingRightLocation))); } @Test public void testKingMovedCastlingNotAllowed(){ whiteKing.moved(); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingRightLocation))); } @Test public void testRightRookMovedCastlingNotAllowed(){ whiteRightRook.moved(); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingRightLocation))); } @Test public void testLeftRookMovedCastlingNotAllowed(){ whiteLeftRook.moved(); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingLeftLocation))); } @Test public void testKingHasMoveOneSquare(){ Location castlingKingLocation=new Location(F,1); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingLocation))); } @Test public void testKingHasTwoSquareUpAndAcrossTheBoard(){ Location castlingKingLocation=new Location(G,3); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingLocation))); } @Test public void testNotLeftRook(){ board.putPieceOnBoardAt(new BishopPiece(Colour.WHITE), whiteLeftRookStartPosition); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingLeftLocation))); } @Test public void testNotRightRook(){ board.putPieceOnBoardAt(new BishopPiece(Colour.WHITE), whiteRightRookStartPosition); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingRightLocation))); } @Test public void testSquareBetweenKingAndRightRookNotEmpty(){ board.putPieceOnBoardAt(new BishopPiece(Colour.WHITE), new Location(F,1)); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingRightLocation))); board.putPieceOnBoardAt(new BishopPiece(Colour.WHITE), castlingKingRightLocation); board.removePieceOnBoardAt(new Location(F,1)); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingRightLocation))); } @Test public void testSquareBetweenKingAndLeftRookNotEmpty(){ board.putPieceOnBoardAt(new BishopPiece(Colour.WHITE), new Location(B,1)); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingLeftLocation))); board.putPieceOnBoardAt(new BishopPiece(Colour.WHITE), castlingKingLeftLocation); board.removePieceOnBoardAt(new Location(B,1)); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingLeftLocation))); board.removePieceOnBoardAt(castlingKingLeftLocation); board.putPieceOnBoardAt(new BishopPiece(Colour.WHITE), new Location(D,1)); assertFalse(gameRule.isRuleApplicable(board,new Move(whiteKingStartPosition,castlingKingLeftLocation))); } @Test public void testRightRookMovesToCastlePosition() throws InvalidMoveException{ Move whiteKingCastleMove=new Move(whiteKingStartPosition, castlingKingRightLocation); chessGame.move(whitePlayer, whiteKingCastleMove); ChessPiece piece=board.getPieceFromBoardAt(new Location(F,1)); assertEquals(piece, whiteRightRook); } @Test public void testLeftRookMovesToCastlePosition() throws InvalidMoveException{ Move whiteKingCastleMove=new Move(whiteKingStartPosition, castlingKingLeftLocation); chessGame.move(whitePlayer, whiteKingCastleMove); ChessPiece piece=board.getPieceFromBoardAt(new Location(D,1)); assertEquals(piece, whiteLeftRook); } @Test public void testKingMovesLefttoCastlePosition() throws InvalidMoveException{ Move whiteKingCastleMove=new Move(whiteKingStartPosition, castlingKingRightLocation); chessGame.move(whitePlayer, whiteKingCastleMove); ChessPiece piece=board.getPieceFromBoardAt(castlingKingRightLocation); assertEquals(piece, whiteKing); } @Test public void testKingMovesRighttoCastlePosition() throws InvalidMoveException{ Move whiteKingCastleMove=new Move(whiteKingStartPosition, castlingKingLeftLocation); chessGame.move(whitePlayer, whiteKingCastleMove); ChessPiece piece=board.getPieceFromBoardAt(castlingKingLeftLocation); assertEquals(piece, whiteKing); } }
package org.dlw.ai.blackboard; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.dlw.ai.blackboard.knowledge.KnowledgeSourcesImpl; import org.dlw.ai.blackboard.util.UniversalContext; import org.junit.Before; import org.junit.Test; public class BrainTest { private Brain brain; @Before public void setUp() throws Exception { brain = (Brain) UniversalContext.getApplicationContext().getBean( "brain"); } @Test public void engageTest() throws AssertionError { brain.engage(); // load KnowledgeSources assertNotNull(brain.getKnowledgeSources()); KnowledgeSourcesImpl kss = (KnowledgeSourcesImpl) brain .getKnowledgeSources(); int count = kss.size(); assertTrue(count == 13); } }
package org.scijava; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Arrays; import org.junit.Test; import org.scijava.plugin.Parameter; import org.scijava.plugin.PluginIndex; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.SciJavaPlugin; import org.scijava.service.AbstractService; import org.scijava.service.Service; import org.scijava.thread.ThreadService; /** * Tests {@link Context} creation with {@link Service} dependencies. * * @author Curtis Rueden */ public class ContextCreationTest { /** Tests that a new empty {@link Context} indeed has no {@link Service}s. */ @Test public void testEmpty() { final Context context = new Context(true); assertTrue(context.getServiceIndex().isEmpty()); } /** * Tests that a new fully populated {@link Context} has all available core * {@link Service}s, in the expected priority order. */ @Test public void testFull() { final Class<?>[] expected = { org.scijava.event.DefaultEventService.class, org.scijava.script.DefaultScriptService.class, org.scijava.app.DefaultAppService.class, org.scijava.app.DefaultStatusService.class, org.scijava.command.DefaultCommandService.class, org.scijava.console.DefaultConsoleService.class, org.scijava.display.DefaultDisplayService.class, org.scijava.event.DefaultEventHistory.class, org.scijava.io.DefaultIOService.class, org.scijava.io.DefaultRecentFileService.class, org.scijava.menu.DefaultMenuService.class, org.scijava.module.DefaultModuleService.class, org.scijava.object.DefaultObjectService.class, org.scijava.options.DefaultOptionsService.class, org.scijava.platform.DefaultPlatformService.class, org.scijava.plugin.DefaultPluginService.class, org.scijava.text.DefaultTextService.class, org.scijava.thread.DefaultThreadService.class, org.scijava.tool.DefaultToolService.class, org.scijava.widget.DefaultWidgetService.class, org.scijava.log.StderrLogService.class, org.scijava.platform.DefaultAppEventService.class }; final Context context = new Context(); verifyServiceOrder(expected, context); } /** * Tests that dependent {@link Service}s are automatically created and * populated in downstream {@link Service} classes. */ @Test public void testDependencies() { final Context context = new Context(FooService.class); // verify that the Foo service is there final FooService fooService = context.getService(FooService.class); assertNotNull(fooService); assertSame(context, fooService.getContext()); // verify that the Bar service is there final BarService barService = context.getService(BarService.class); assertNotNull(barService); assertSame(context, barService.getContext()); assertSame(barService, fooService.barService); // verify that the *only* two services are Foo and Bar assertEquals(2, context.getServiceIndex().size()); } @Test public void testMissingDirect() { try { new Context(MissingService.class); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException exc) { final String expectedMessage = "No compatible service: " + MissingService.class.getName(); assertEquals(expectedMessage, exc.getMessage()); } } @Test public void testMissingTransitive() { try { new Context(ServiceRequiringMissingService.class); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException exc) { final String expectedMessage = "Invalid service: " + ServiceRequiringMissingService.class.getName(); assertEquals(expectedMessage, exc.getMessage()); final String expectedCause = "No compatible service: " + MissingService.class.getName(); assertEquals(expectedCause, exc.getCause().getMessage()); } } @Test public void testOptionalMissingTransitive() { try { new Context(ServiceRequiringOptionalMissingService.class); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException exc) { final String expectedMessage = "Invalid service: " + ServiceRequiringOptionalMissingService.class.getName(); assertEquals(expectedMessage, exc.getMessage()); final String expectedCause = "No compatible service: " + OptionalMissingService.class.getName(); assertEquals(expectedCause, exc.getCause().getMessage()); } } /** * Verifies that the order plugins appear in the PluginIndex and Service list * does not affect which services are loaded. */ @SuppressWarnings("unchecked") @Test public void testClassOrder() { final int expectedSize = 2; // Same order, Base first Context c = createContext(pluginIndex(BaseImpl.class, ExtensionImpl.class), services( BaseService.class, ExtensionService.class)); assertEquals(expectedSize, c.getServiceIndex().size()); // Same order, Extension first c = createContext(pluginIndex(ExtensionImpl.class, BaseImpl.class), services( ExtensionService.class, BaseService.class)); assertEquals(expectedSize, c.getServiceIndex().size()); // Different order, Extension first c = createContext(pluginIndex(ExtensionImpl.class, BaseImpl.class), services( BaseService.class, ExtensionService.class)); assertEquals(expectedSize, c.getServiceIndex().size()); // Different order, Base first c = createContext(pluginIndex(BaseImpl.class, ExtensionImpl.class), services( ExtensionService.class, BaseService.class)); assertEquals(expectedSize, c.getServiceIndex().size()); } /** * Verifies that the Service index created when using Abstract classes is the * same as for interfaces. */ @SuppressWarnings("unchecked") @Test public void testAbstractClasslist() { final Context cAbstract = createContext(pluginIndex(BaseImpl.class, ExtensionImpl.class), services( AbstractBase.class, AbstractExtension.class)); final Context cService = createContext(pluginIndex(BaseImpl.class, ExtensionImpl.class), services( BaseService.class, ExtensionService.class)); assertEquals(cService.getServiceIndex().size(), cAbstract.getServiceIndex() .size()); } /** * Verify that if no services are explicitly passed, all subclasses of * Service.class are discovered automatically. */ @Test public void testNoServicesCtor() { // create a 2-service context final PluginIndex index = pluginIndex(BaseImpl.class, ExtensionImpl.class); // Add another service, that is not indexed under Service.class index.add(new PluginInfo<SciJavaPlugin>(ThreadService.class.getName(), SciJavaPlugin.class)); final Context c = new Context(pluginIndex(BaseImpl.class, ExtensionImpl.class)); assertEquals(2, c.getServiceIndex().size()); } /** * Tests that missing-but-optional {@link Service}s are handled properly; * specifically, that the {@link Context} is still created successfully when * attempting to include a missing-but-optional service directly. * <p> * A service marked {@link Optional} is assumed to be optional for the context * when requested for inclusion directly. (This behavior is, after all, one * main reason for the {@link Optional} interface.) * </p> */ @Test public void testOptionalMissingDirect() { final Context context = new Context(OptionalMissingService.class); final OptionalMissingService optionalMissingService = context.getService(OptionalMissingService.class); assertNull(optionalMissingService); // verify that there are *no* services in the context assertEquals(0, context.getServiceIndex().size()); } /** * Tests that missing {@link Service}s marked with {@code required = false} * are handled properly; specifically, that the {@link Context} is still * created successfully when attempting to request (but not require) a missing * service transitively. */ @Test public void testNonRequiredMissingService() { final Context context = new Context(ServiceWantingMissingService.class); assertEquals(1, context.getServiceIndex().size()); final ServiceWantingMissingService serviceWantingMissingService = context.getService(ServiceWantingMissingService.class); assertNotNull(serviceWantingMissingService); assertNull(serviceWantingMissingService.missingService); final MissingService missingService = context.getService(MissingService.class); assertNull(missingService); // verify that the *only* service is ServiceWantingMissing assertEquals(1, context.getServiceIndex().size()); } // -- Helper methods -- /** * Checks the expected order vs. the order in the provided Context's * ServiceIndex */ private void verifyServiceOrder(final Class<?>[] expected, final Context context) { assertEquals(expected.length, context.getServiceIndex().size()); int index = 0; for (final Service service : context.getServiceIndex()) { assertSame(expected[index++], service.getClass()); } } /** * Initializes and returns a Context given the provided PluginIndex and array * of services. */ private Context createContext(final PluginIndex index, final Class<? extends Service>[] services) { return new Context(Arrays.<Class<? extends Service>> asList(services), index); } /** * Convenience method since you can't instantiate a Class<? extends Service> * array. */ private Class<? extends Service>[] services( final Class<? extends Service>... serviceClasses) { return serviceClasses; } /** * Creates a PluginIndex and adds all the provided classes as plugins, indexed * under Service.class */ private PluginIndex pluginIndex(final Class<?>... plugins) { final PluginIndex index = new PluginIndex(null); for (final Class<?> c : plugins) { index.add(new PluginInfo<Service>(c.getName(), Service.class)); } return index; } // -- Helper classes -- /** A service which requires a {@link BarService}. */ public static class FooService extends AbstractService { @Parameter private BarService barService; } /** A service that is extended by {@link ExtensionService}. */ public static interface BaseService extends Service { // NB: No implementation needed. } /** A service extending {@link BaseService}. */ public static interface ExtensionService extends BaseService { // NB: No implementation needed. } /** A simple service with no dependencies. */ public static class BarService extends AbstractService { // NB: No implementation needed. } /** A required service interface with no available implementation. */ public static interface MissingService extends Service { // NB: Marker interface. } /** A optional service interface with no available implementation. */ public static interface OptionalMissingService extends Service, Optional { // NB: Marker interface. } /** Abstract implementation of {@link BaseService}. */ public static abstract class AbstractBase extends AbstractService implements BaseService { // NB: No implementation needed. } /** Abstract implementation of {@link ExtensionService}. */ public static abstract class AbstractExtension extends AbstractService implements ExtensionService { // NB: No implementation needed. } /** Empty {@link BaseService} implementation. */ public static class BaseImpl extends AbstractBase { // NB: No implementation needed. } /** Empty {@link ExtensionService} implementation. */ public static class ExtensionImpl extends AbstractExtension { // NB: No implementation needed. } /** A service that is doomed to fail, for depending on a missing service. */ public static class ServiceRequiringMissingService extends AbstractService { @Parameter private MissingService missingService; } /** * Another service that is doomed to fail. It depends on a missing service * which, although optional, is marked with {@code required = true} * (implicitly), and so cannot be filled. */ public static class ServiceRequiringOptionalMissingService extends AbstractService { @Parameter private OptionalMissingService optionalMissingService; } /** * A service with a missing dependency marked {@code required = false}. This * service should be able to be filled, since its missing service dependency * is optional. */ public static class ServiceWantingMissingService extends AbstractService { @Parameter(required = false) private MissingService missingService; } }
package org.scijava; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.scijava.plugin.Parameter; import org.scijava.plugin.PluginIndex; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.SciJavaPlugin; import org.scijava.service.AbstractService; import org.scijava.service.Service; import org.scijava.thread.ThreadService; /** * Tests {@link Context} creation with {@link Service} dependencies. * * @author Curtis Rueden */ public class ContextCreationTest { /** Tests that a new empty {@link Context} indeed has no {@link Service}s. */ @Test public void testEmpty() { final Context context = new Context(true); assertTrue(context.getServiceIndex().isEmpty()); } /** * Tests that a new fully populated {@link Context} has all available core * {@link Service}s, in the expected priority order. */ @Test public void testFull() { final Class<?>[] expected = { org.scijava.event.DefaultEventService.class, org.scijava.script.DefaultScriptService.class, org.scijava.app.DefaultAppService.class, org.scijava.app.DefaultStatusService.class, org.scijava.command.DefaultCommandService.class, org.scijava.console.DefaultConsoleService.class, org.scijava.display.DefaultDisplayService.class, org.scijava.event.DefaultEventHistory.class, org.scijava.input.DefaultInputService.class, org.scijava.io.DefaultIOService.class, org.scijava.io.DefaultRecentFileService.class, org.scijava.menu.DefaultMenuService.class, org.scijava.module.DefaultModuleService.class, org.scijava.object.DefaultObjectService.class, org.scijava.options.DefaultOptionsService.class, org.scijava.platform.DefaultPlatformService.class, org.scijava.plugin.DefaultPluginService.class, org.scijava.text.DefaultTextService.class, org.scijava.thread.DefaultThreadService.class, org.scijava.tool.DefaultToolService.class, org.scijava.ui.DefaultUIService.class, org.scijava.ui.dnd.DefaultDragAndDropService.class, org.scijava.welcome.DefaultWelcomeService.class, org.scijava.widget.DefaultWidgetService.class, org.scijava.log.StderrLogService.class, org.scijava.platform.DefaultAppEventService.class }; final Context context = new Context(); verifyServiceOrder(expected, context); } /** * Tests that dependent {@link Service}s are automatically created and * populated in downstream {@link Service} classes. */ @Test public void testDependencies() { final Context context = new Context(FooService.class); // verify that the Foo service is there final FooService fooService = context.getService(FooService.class); assertNotNull(fooService); assertSame(context, fooService.getContext()); // verify that the Bar service is there final BarService barService = context.getService(BarService.class); assertNotNull(barService); assertSame(context, barService.getContext()); assertSame(barService, fooService.barService); // verify that the *only* two services are Foo and Bar assertEquals(2, context.getServiceIndex().size()); } @Test public void testMissingDirect() { try { new Context(MissingService.class); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException exc) { final String expectedMessage = "No compatible service: " + MissingService.class.getName(); assertEquals(expectedMessage, exc.getMessage()); } } @Test public void testMissingTransitive() { try { new Context(ServiceRequiringMissingService.class); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException exc) { final String expectedMessage = "Invalid service: " + ServiceRequiringMissingService.class.getName(); assertEquals(expectedMessage, exc.getMessage()); final String expectedCause = "No compatible service: " + MissingService.class.getName(); assertEquals(expectedCause, exc.getCause().getMessage()); } } @Test public void testOptionalMissingTransitive() { try { new Context(ServiceRequiringOptionalMissingService.class); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException exc) { final String expectedMessage = "Invalid service: " + ServiceRequiringOptionalMissingService.class.getName(); assertEquals(expectedMessage, exc.getMessage()); final String expectedCause = "No compatible service: " + OptionalMissingService.class.getName(); assertEquals(expectedCause, exc.getCause().getMessage()); } } @Test public void testNonStrictMissingDirect() { final List<Class<? extends Service>> serviceClasses = Context.serviceClassList(MissingService.class); final Context context = new Context(serviceClasses, false); assertEquals(0, context.getServiceIndex().size()); } @Test public void testNonStrictMissingTransitive() { final List<Class<? extends Service>> serviceClasses = Context.serviceClassList(MissingService.class); final Context context = new Context(serviceClasses, false); assertEquals(0, context.getServiceIndex().size()); } @Test public void testNonStrictOptionalMissingTransitive() { final List<Class<? extends Service>> serviceClasses = Context.serviceClassList(ServiceRequiringOptionalMissingService.class); final Context context = new Context(serviceClasses, false); final List<Service> services = context.getServiceIndex().getAll(); assertEquals(1, services.size()); assertSame(ServiceRequiringOptionalMissingService.class, services.get(0) .getClass()); } /** * Verifies that the order plugins appear in the PluginIndex and Service list * does not affect which services are loaded. */ @SuppressWarnings("unchecked") @Test public void testClassOrder() { final int expectedSize = 2; // Same order, Base first Context c = createContext(pluginIndex(BaseImpl.class, ExtensionImpl.class), services( BaseService.class, ExtensionService.class)); assertEquals(expectedSize, c.getServiceIndex().size()); // Same order, Extension first c = createContext(pluginIndex(ExtensionImpl.class, BaseImpl.class), services( ExtensionService.class, BaseService.class)); assertEquals(expectedSize, c.getServiceIndex().size()); // Different order, Extension first c = createContext(pluginIndex(ExtensionImpl.class, BaseImpl.class), services( BaseService.class, ExtensionService.class)); assertEquals(expectedSize, c.getServiceIndex().size()); // Different order, Base first c = createContext(pluginIndex(BaseImpl.class, ExtensionImpl.class), services( ExtensionService.class, BaseService.class)); assertEquals(expectedSize, c.getServiceIndex().size()); } /** * Verifies that the Service index created when using Abstract classes is the * same as for interfaces. */ @SuppressWarnings("unchecked") @Test public void testAbstractClasslist() { final Context cAbstract = createContext(pluginIndex(BaseImpl.class, ExtensionImpl.class), services( AbstractBase.class, AbstractExtension.class)); final Context cService = createContext(pluginIndex(BaseImpl.class, ExtensionImpl.class), services( BaseService.class, ExtensionService.class)); assertEquals(cService.getServiceIndex().size(), cAbstract.getServiceIndex() .size()); } /** * Verify that if no services are explicitly passed, all subclasses of * Service.class are discovered automatically. */ @Test public void testNoServicesCtor() { // create a 2-service context final PluginIndex index = pluginIndex(BaseImpl.class, ExtensionImpl.class); // Add another service, that is not indexed under Service.class index.add(new PluginInfo<SciJavaPlugin>(ThreadService.class.getName(), SciJavaPlugin.class)); final Context c = new Context(pluginIndex(BaseImpl.class, ExtensionImpl.class)); assertEquals(2, c.getServiceIndex().size()); } /** * Tests that missing-but-optional {@link Service}s are handled properly; * specifically, that the {@link Context} is still created successfully when * attempting to include a missing-but-optional service directly. * <p> * A service marked {@link Optional} is assumed to be optional for the context * when requested for inclusion directly. (This behavior is, after all, one * main reason for the {@link Optional} interface.) * </p> */ @Test public void testOptionalMissingDirect() { final Context context = new Context(OptionalMissingService.class); final OptionalMissingService optionalMissingService = context.getService(OptionalMissingService.class); assertNull(optionalMissingService); // verify that there are *no* services in the context assertEquals(0, context.getServiceIndex().size()); } /** * Tests that missing {@link Service}s marked with {@code required = false} * are handled properly; specifically, that the {@link Context} is still * created successfully when attempting to request (but not require) a missing * service transitively. */ @Test public void testNonRequiredMissingService() { final Context context = new Context(ServiceWantingMissingService.class); assertEquals(1, context.getServiceIndex().size()); final ServiceWantingMissingService serviceWantingMissingService = context.getService(ServiceWantingMissingService.class); assertNotNull(serviceWantingMissingService); assertNull(serviceWantingMissingService.missingService); final MissingService missingService = context.getService(MissingService.class); assertNull(missingService); // verify that the *only* service is ServiceWantingMissing assertEquals(1, context.getServiceIndex().size()); } // -- Helper methods -- /** * Checks the expected order vs. the order in the provided Context's * ServiceIndex */ private void verifyServiceOrder(final Class<?>[] expected, final Context context) { assertEquals(expected.length, context.getServiceIndex().size()); int index = 0; for (final Service service : context.getServiceIndex()) { assertSame(expected[index++], service.getClass()); } } /** * Initializes and returns a Context given the provided PluginIndex and array * of services. */ private Context createContext(final PluginIndex index, final Class<? extends Service>[] services) { return new Context(Arrays.<Class<? extends Service>> asList(services), index); } /** * Convenience method since you can't instantiate a Class<? extends Service> * array. */ private Class<? extends Service>[] services( final Class<? extends Service>... serviceClasses) { return serviceClasses; } /** * Creates a PluginIndex and adds all the provided classes as plugins, indexed * under Service.class */ private PluginIndex pluginIndex(final Class<?>... plugins) { final PluginIndex index = new PluginIndex(null); for (final Class<?> c : plugins) { index.add(new PluginInfo<Service>(c.getName(), Service.class)); } return index; } // -- Helper classes -- /** A service which requires a {@link BarService}. */ public static class FooService extends AbstractService { @Parameter private BarService barService; } /** A service that is extended by {@link ExtensionService}. */ public static interface BaseService extends Service { // NB: No implementation needed. } /** A service extending {@link BaseService}. */ public static interface ExtensionService extends BaseService { // NB: No implementation needed. } /** A simple service with no dependencies. */ public static class BarService extends AbstractService { // NB: No implementation needed. } /** A required service interface with no available implementation. */ public static interface MissingService extends Service { // NB: Marker interface. } /** A optional service interface with no available implementation. */ public static interface OptionalMissingService extends Service, Optional { // NB: Marker interface. } /** Abstract implementation of {@link BaseService}. */ public static abstract class AbstractBase extends AbstractService implements BaseService { // NB: No implementation needed. } /** Abstract implementation of {@link ExtensionService}. */ public static abstract class AbstractExtension extends AbstractService implements ExtensionService { // NB: No implementation needed. } /** Empty {@link BaseService} implementation. */ public static class BaseImpl extends AbstractBase { // NB: No implementation needed. } /** Empty {@link ExtensionService} implementation. */ public static class ExtensionImpl extends AbstractExtension { // NB: No implementation needed. } /** A service that is doomed to fail, for depending on a missing service. */ public static class ServiceRequiringMissingService extends AbstractService { @Parameter private MissingService missingService; } /** * Another service that is doomed to fail. It depends on a missing service * which, although optional, is marked with {@code required = true} * (implicitly), and so cannot be filled. */ public static class ServiceRequiringOptionalMissingService extends AbstractService { @Parameter private OptionalMissingService optionalMissingService; } /** * A service with a missing dependency marked {@code required = false}. This * service should be able to be filled, since its missing service dependency * is optional. */ public static class ServiceWantingMissingService extends AbstractService { @Parameter(required = false) private MissingService missingService; } }
package org.searsia.engine; import org.json.JSONObject; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.xpath.XPathExpressionException; import org.searsia.SearchResult; import org.searsia.engine.Resource; public class ResourceTest { private static final String SECRET_API_KEY = "a7235cdsf43d3a2dfgeda"; private Resource htmlSearch() throws XPathExpressionException { Resource hiemstra = new Resource("http://wwwhome.cs.utwente.nl/~hiemstra/?s={q}&api={apikey}&p={p?}","hiemstra"); hiemstra.setUrlUserTemplate(hiemstra.getAPITemplate()); hiemstra.addPrivateParameter("apikey", SECRET_API_KEY); hiemstra.addHeader("User-Agent", "Test/1.0"); hiemstra.setPrior(0.3f); hiemstra.setRate(133); hiemstra.setMimeType("text/html"); hiemstra.setFavicon("http://wwwhome.cs.utwente.nl/~hiemstra/images/ut.ico"); hiemstra.setItemXpath("//div[@class='post']"); hiemstra.addExtractor( new TextExtractor("title", "./h3"), new TextExtractor("description", "./h3/following-sibling::text()"), new TextExtractor("url", "./h3/a/@href") ); return hiemstra; } private Resource postSearch() throws XPathExpressionException { Resource hiemstra = new Resource("http://wwwhome.cs.utwente.nl/~hiemstra/","hiemstrapost"); hiemstra.setPostString("os={q}"); hiemstra.setPostQueryEncode("application/x-www-form-urlencoded"); hiemstra.setMimeType("application/xml"); hiemstra.setItemXpath("//item"); hiemstra.addExtractor( new TextExtractor("title", "./title"), new TextExtractor("description", "./description"), new TextExtractor("url", "./link") ); return hiemstra; } private Resource searsiaSearch() throws XPathExpressionException { return new Resource("http://searsia.org/searsia/wiki-{q?}-{r?}.json"); } private Resource xmlSearch() throws XPathExpressionException, SearchException { Resource wiki = new Resource("http://searsia.org/searsia/wiki-{q?}-{r?}.json"); Resource wikifull = wiki.searchResource("wikifull"); return wikifull; } private Resource jsonSearch() throws XPathExpressionException { Resource wiki = new Resource("http://searsia.org/searsia/wiki-{q?}-wikifull.json"); wiki.setMimeType("application/json"); wiki.setItemXpath("//hits"); wiki.addExtractor( new TextExtractor("title", "./title"), new TextExtractor("description", "./description"), new TextExtractor("url", "./url"), new TextExtractor("content", "./content") ); return wiki; } private Resource javascriptSearch() throws XPathExpressionException { Resource wikifull = new Resource("http://searsia.org/searsia/wiki-{q}-wikifull.js"); wikifull.setMimeType("application/x-javascript"); wikifull.setItemXpath("//hits"); wikifull.addExtractor( new TextExtractor("title", "./title"), new TextExtractor("description", "./description"), new TextExtractor("url", "./url") ); return wikifull; } @BeforeClass public static void setUp() { Logger.getLogger("").setLevel(Level.WARNING); } @Test public void testSearchSearsia() throws XPathExpressionException, SearchException { Resource se = searsiaSearch(); String query = "informat"; SearchResult result = se.search(query); Assert.assertEquals(query, result.getQuery()); Assert.assertTrue(result.getHits().size() > 0); } @Test public void testSearchHtml() throws XPathExpressionException, SearchException { Resource se = htmlSearch(); SearchResult result = se.search("dolf trieschnigg", true); Assert.assertEquals("text/html", se.getMimeType()); Assert.assertEquals(10, result.getHits().size()); // TODO text nodes are glued together. } @Test public void testSearchPost() throws XPathExpressionException, SearchException { Resource se = postSearch(); SearchResult result = se.search("dolf trieschnigg"); Assert.assertEquals("application/xml", se.getMimeType()); Assert.assertEquals(10, result.getHits().size()); } @Test public void testSearchXml() throws XPathExpressionException, SearchException { Resource se = xmlSearch(); SearchResult result = se.search("informat"); Assert.assertEquals("application/xml", se.getMimeType()); Assert.assertEquals(10, result.getHits().size()); } @Test public void testSearchXml2() throws XPathExpressionException, SearchException { Resource se = htmlSearch(); se.setMimeType("application/xml"); se.setRerank(null); long startTime = System.currentTimeMillis(); SearchResult result = se.search("test"); Assert.assertEquals(10, result.getHits().size()); Assert.assertFalse("Parser timed out", System.currentTimeMillis() - startTime > 10000); } @Test public void testSearchJson() throws XPathExpressionException, SearchException { Resource se = jsonSearch(); Boolean debug = true; SearchResult result = se.search("informat", debug); Assert.assertNotNull(result.getXmlOut()); Assert.assertEquals("application/json", se.getMimeType()); Assert.assertEquals(10, result.getHits().size()); } @Test public void testSearchJson2() throws XPathExpressionException, SearchException { Resource se = jsonSearch(); SearchResult result = se.search("json"); Assert.assertEquals(1, result.getHits().size()); Assert.assertEquals("extra content", result.getHits().get(0).getString("content")); } @Test public void testSearchJavascript() throws XPathExpressionException, SearchException { Resource se = javascriptSearch(); Boolean debug = true; SearchResult result = se.search("informat", debug); Assert.assertEquals("application/x-javascript", se.getMimeType()); Assert.assertEquals(10, result.getHits().size()); } @Test public void testSearchSearsiaEmpty() throws XPathExpressionException, SearchException { Resource se = searsiaSearch(); SearchResult result = se.search(); Assert.assertTrue(result.getHits().size() > 0); } @Test public void testSearchResource() throws XPathExpressionException, SearchException { Resource se = searsiaSearch(); Resource engine = se.searchResource("wikifull"); Assert.assertTrue(engine != null); } @Test public void testSearchError() throws XPathExpressionException { Resource se = htmlSearch(); se.setUrlAPITemplate("http://wwwhome.cs.utwente.nl/~hiemstra/WRONG/?s={q}&api={apikey}&p={p?}"); String message = null; try { se.search("test"); } catch (SearchException e) { message = e.getMessage(); } Assert.assertNotNull(message); Assert.assertFalse("error message reveals secret", message.contains(SECRET_API_KEY)); } @Test public void testJsonRoundtrip() throws XPathExpressionException { Resource se1 = htmlSearch(); se1.setPostString("POST"); se1.setPostQueryEncode("application/x-www-form-urlencoded"); se1.setRerank("lm"); se1.setBanner("me.png"); se1.setUrlSuggestTemplate("http://whatever"); JSONObject json = se1.toJson(); Resource se2 = new Resource(json); Assert.assertEquals("id", se1.getId(), se2.getId()); Assert.assertEquals("name", se1.getName(), se2.getName()); Assert.assertEquals("mimetype", se1.getMimeType(), se2.getMimeType()); Assert.assertEquals("urltemplate", se1.getUserTemplate(), se2.getUserTemplate()); Assert.assertEquals("apitemplate", se1.getAPITemplate(), se2.getAPITemplate()); Assert.assertEquals("suggesttemplate", se1.getSuggestTemplate(), se2.getSuggestTemplate()); Assert.assertEquals("favicon", se1.getFavicon(), se2.getFavicon()); Assert.assertEquals("rerank", se1.getRerank(), se2.getRerank()); Assert.assertEquals("banner", se1.getBanner(), se2.getBanner()); Assert.assertEquals("itempath", se1.getItemXpath(), se2.getItemXpath()); Assert.assertEquals("testquery", se1.getTestQuery(), se2.getTestQuery()); Assert.assertEquals("prior", se1.getPrior(), se2.getPrior(), 0.0001d); Assert.assertEquals("maxqueriesperday", se1.getRate(), se2.getRate()); Assert.assertEquals("extractors", se1.getExtractors().size(), se2.getExtractors().size()); Assert.assertEquals("headers", se1.getHeaders().size(), se2.getHeaders().size()); Assert.assertEquals("post", se1.getPostString(), se2.getPostString()); Assert.assertEquals("postencode", se1.getPostQueryEncode(), se2.getPostQueryEncode()); Assert.assertFalse("secret revealed", json.toString().contains(SECRET_API_KEY)); } @Test public void equalEngines1() throws XPathExpressionException { Resource se1 = htmlSearch(); JSONObject json = se1.toJson(); Resource se2 = new Resource(json); Assert.assertTrue("Equals big engine", se1.equals(se2)); } @Test public void equalEngines2() throws XPathExpressionException { Resource se1 = searsiaSearch(); JSONObject json = se1.toJson(); Resource se2 = new Resource(json); Assert.assertTrue("Truely Equals small engine", se1.equals(se2)); Assert.assertEquals("Equals small equals", se1, se2); } }
package sizebay.catalog.client; import static sizebay.catalog.client.CatalogAPI.DEFAULT_BASE_URL; import java.io.*; import java.net.*; import java.util.List; import java.util.function.BiConsumer; import org.junit.*; import sizebay.catalog.client.model.*; //import sizebay.emmett.tasks.Threads;
package web.component.impl.aws.model; import java.util.HashSet; import java.util.Set; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import web.component.api.model.VPC; /** * * @author ksc */ public class VPCImplTest { static final String expectedCidrBlock = "10.1.0.0/16"; static final String expectedTenancy = ""; static final String expectedState = ""; static final String expectedDhcpOptionsId = ""; static VPCImpl testInstance; static String expectedStringExpression; static Set<VPC> testInstances = new HashSet<>(); public VPCImplTest() { } @BeforeClass public static void setUpClass() { testInstance = (VPCImpl) new VPCImpl.Builder().cidr(expectedCidrBlock).tenancy(expectedTenancy).create(); testInstances.add(testInstance); while(!testInstance.getState().equals("available")){ System.out.println("wait for test vpc to be ready ..."); try { Thread.sleep(10000); } catch (InterruptedException ex) { } } expectedStringExpression = "{VpcId: " + testInstance.getId() + ",CidrBlock: " + expectedCidrBlock + ",DhcpOptionsId: " + expectedDhcpOptionsId + ",Tags: [],InstanceTenancy: " + expectedTenancy + ",}"; System.out.println("Vpc for test is now available."); } @AfterClass public static void tearDownClass() { for(VPC toDelete : testInstances){ System.out.println("Delete test vpc [" + toDelete.toString() + "]"); toDelete.delete(); } } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getCidrBlock method, of class VPCImpl. */ @Test public void testGetCidrBlock() { System.out.println("getCidrBlock"); assertEquals(expectedCidrBlock, testInstance.getCidrBlock()); } /** * Test of getDhcpOptionsId method, of class VPCImpl. */ @Test public void testGetDhcpOptionsId() { System.out.println("getDhcpOptionsId"); assertEquals(expectedDhcpOptionsId, testInstance.getDhcpOptionsId()); } /** * Test of getInstanceTenancy method, of class VPCImpl. */ @Test public void testGetInstanceTenancy() { System.out.println("getInstanceTenancy"); assertEquals(expectedTenancy, testInstance.getInstanceTenancy()); } /** * Test of getIsDefault method, of class VPCImpl. */ @Test public void testGetIsDefault() { System.out.println("getIsDefault"); assertEquals(true, testInstance.getIsDefault()); } /** * Test of getState method, of class VPCImpl. */ @Test public void testGetState() { System.out.println("getState"); assertEquals(expectedState, testInstance.getState()); } /** * Test of getId method, of class VPCImpl. */ @Test public void testGetId() { System.out.println("getId"); VPC existVpc = new VPCImpl.Builder().id(testInstance.getId()).get(); assertEquals(testInstance.getId(), existVpc.getId()); } /** * Test of delete method, of class VPCImpl. */ @Test public void testDelete() { System.out.println("delete"); VPC toBeDeleted = new VPCImpl.Builder().cidr(expectedCidrBlock).tenancy(expectedTenancy).create(); while(!toBeDeleted.getState().equals("available")){ try { Thread.sleep(10000); } catch (InterruptedException ex) { } } testInstances.add(toBeDeleted); String deletedId = toBeDeleted.getId(); toBeDeleted.delete(); //wait for deletion to be completed. try { Thread.sleep(3000); } catch (InterruptedException ex) { } VPC shouldHaveBeenDeleted = new VPCImpl.Builder().id(deletedId).get(); assertEquals("Unknown state", shouldHaveBeenDeleted.getState()); } /** * Test of equals method, of class VPCImpl. */ @Test public void testEquals() { System.out.println("equals"); VPC equalInstance = new VPCImpl.Builder().id(testInstance.getId()).get(); VPC anotherInstance = new VPCImpl.Builder().cidr(expectedCidrBlock).tenancy(expectedTenancy).create(); testInstances.add(anotherInstance); while(!anotherInstance.getState().equals("available")){ try { Thread.sleep(10000); } catch (InterruptedException ex) { } } assertTrue(testInstance.equals(equalInstance)); assertFalse(testInstance.equals(anotherInstance)); } /** * Test of hashCode method, of class VPCImpl. */ @Test public void testHashCode() { System.out.println("hashCode"); VPC equalInstance = new VPCImpl.Builder().id(testInstance.getId()).get(); VPC anotherInstance = new VPCImpl.Builder().cidr(expectedCidrBlock).tenancy(expectedTenancy).create(); testInstances.add(anotherInstance); while(!anotherInstance.getState().equals("available")){ try { Thread.sleep(10000); } catch (InterruptedException ex) { } } assertTrue(testInstance.hashCode() == equalInstance.hashCode()); assertTrue(testInstance.hashCode() != anotherInstance.hashCode()); } /** * Test of toString method, of class VPCImpl. */ @Test public void testToString() { System.out.println("toString"); assertEquals(expectedStringExpression, testInstance.toString()); } }
package autonomouscarfinalprogram2; import com.looi.looi.LooiObject; import com.looi.looi.gui_essentials.AstheticButton; import com.looi.looi.gui_essentials.Background; import com.looi.looi.gui_essentials.Button; import com.looi.looi.gui_essentials.ScrollBox; import com.looi.looi.gui_essentials.Slider; import group1.IPixel; import group1.Pixel; import com.looi.looi.gui_essentials.TextBox; import com.looi.looi.gui_essentials.Window; import com.looi.looi.gui_essentials.ScrollBox.ScrollBoxObject; import com.looi.looi.gui_essentials.Window.ExitButton; import global.Constant; import group1.FileImage; import group2.Blob; import group2.BlobDetection; import group3.MovingBlob; import group3.MovingBlobDetection; import group4.BlobFilter; import group5.IImageBoxDrawer; import java.awt.image.BufferedImage; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.awt.Color; import java.awt.Font; /** * * @author peter_000 */ public class Control extends LooiObject { private BlobDetection blobDetection; private MovingBlobDetection movingBlobDetection; private BlobFilter blobFilter; private IImageBoxDrawer boxDrawer; private FileImage currentImage; private Button toggleGraphics; private ScrollBox scrollBox; private Window sliderWindow; private BufferedImage testBI = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB); { for(int r = 0; r < testBI.getHeight(); r++) { for(int c = 0; c < testBI.getWidth(); c++) { int p = (255/*alpha*/ << 24) | (255 << 16) | (255 << 8) | 255; testBI.setRGB(c,r,p); } } } private int previousFrame; private int currentFrame; public static boolean keepGoing; private ArrayDeque<IPixel[][]> frames; private ArrayList<IPixel[][]> frameList; private int yCoordinate; public Control(int frameDelay) { blobDetection = new BlobDetection(); movingBlobDetection = new MovingBlobDetection(); blobFilter = new BlobFilter(); currentImage = new FileImage(); boxDrawer = new IImageBoxDrawer(); boxDrawer.setUsingBasicColors(true); previousFrame = 0; setCurrentFrame(1); keepGoing = true; currentImage.readCam(); IPixel[][] firstFrame = currentImage.getImage(); frames = new ArrayDeque<IPixel[][]>(5); frames.addFirst(firstFrame); /* yCoordinate = 10; sliderWindow = new DraggingWindow(100,100,500,500,new Background(Color.WHITE)); sliderWindow.add(sliderWindow.new ExitButton()); sliderWindow.add(scrollBox = new ScrollBox(25,100,450,375,new Background(new Color(250,250,255)))); String text[] = {"Max Time Off Screen", "Distance Limit X", "Distance Limit Y", "Max Change Width", "Max Change Height", "X Edge Distance Limit", "Y Edge Distance Limit", "X Overlap Percent", "Y Overlap Percent", "Unify Velocity Limit X", "Unify Velocity Limit Y", "Velocity Limit Increase X", "Velocity Limit Increase Y", "Age Min","Velocity X Max", "Velocity Y Max", "Max Velocity Change X", "Max Velocity Change Y", "Max Width Height Ratio", "Max Width", "Max Height", "Max Scaled Velocity X", "Max Scaled Velocity Y", }; int maximumValues[] = {0, 40, 40, 100, 100, 20, 20, 1, 1, 35, 35, 3, 3, 7, 100, 100, 100, 100, 2, 1000, 1000, 100, 100}; // displays text for(int i = 0; i < text.length; i++) { scrollBox.add(scrollBox.new ScrollBoxObject(new Text(150, i*100+20, 100, 30, new Background(Color.WHITE), text[i]))); } // displays sliders for(int j = 0; j < text.length; j++) { int i = j+1; scrollBox.add(scrollBox.new ScrollBoxObject( new VariableSlider(10,j*100+20,100,20, new Background(Color.WHITE),0,maximumValues[j],(a)->{ Constant.setVariable(i, a); }))); } scrollBox.add(scrollBox.new ScrollBoxObject(new SaveButton(10,100*text.length,150,100,"Save",new Color(150,200,40)))); toggleGraphics = new AstheticButton(10,100*text.length+100,135,100,"Toggle Graphics",Color.GRAY) { @Override protected void action() { boxDrawer.setUsingBasicColors(!boxDrawer.isUsingBasicColors()); } }; toggleGraphics.setLayer(-999); scrollBox.add(scrollBox.new ScrollBoxObject(toggleGraphics)); */ } /** * This method runs 60 timer per sec */ protected void looiStep() { if(keepGoing){ updateWhileUnpaused(); } else{ updateWhilePaused(); } } protected void updateWhileUnpaused(){ currentImage.readCam(); previousFrame++; if(currentImage.getFrameNo()==previousFrame){ previousFrame = 0; currentImage.finish(); currentImage = new FileImage(); blobDetection = new BlobDetection(); movingBlobDetection = new MovingBlobDetection(); blobFilter = new BlobFilter(); currentImage.readCam(); } List<Blob> knownBlobs = blobDetection.getBlobs(currentImage); List<MovingBlob> movingBlobs = movingBlobDetection.getMovingBlobs(knownBlobs); List<MovingBlob> fmovingBlobs = blobFilter.filterMovingBlobs(movingBlobs); List<MovingBlob> unifiedBlobs = movingBlobDetection.getUnifiedBlobs(fmovingBlobs); List<MovingBlob> funifiedBlobs = blobFilter.filterUnifiedBlobs(unifiedBlobs); //boxDrawer.draw2(currentImage,fmovingBlobs,funifiedBlobs); boxDrawer.draw(currentImage, unifiedBlobs); IPixel[][] image = currentImage.getImage(); IPixel[][] copy = new IPixel[image.length][image[0].length]; for(int i=0;i<image.length;i++){ for(int j=0;j<image[0].length;j++){ copy[i][j] = image[i][j]; } } frames.addFirst(copy); if(frames.size() >= 8){ frames.removeLast(); } } public void updateWhilePaused(){ currentImage.setImage(frameList.get(currentFrame)); List<Blob> knownBlobs = blobDetection.getBlobs(currentImage); List<MovingBlob> movingBlobs = movingBlobDetection.getMovingBlobs(knownBlobs); List<MovingBlob> fmovingBlobs = blobFilter.filterMovingBlobs(movingBlobs); List<MovingBlob> unifiedBlobs = movingBlobDetection.getUnifiedBlobs(fmovingBlobs); //boxDrawer.draw2(currentImage, movingBlobs, fmovingBlobs); boxDrawer.draw2(currentImage, unifiedBlobs, movingBlobs); } public void incrementCurrentFrame(int i){ setCurrentFrame(getCurrentFrame() + i); if(currentFrame == frames.size()){ currentFrame = frames.size()-1; } else if(currentFrame <= 0){ currentFrame = 0; } } public int getCurrentFrame() { return currentFrame; } public void setCurrentFrame(int frame){ currentFrame = frame; } public void pauseUnpause(){ keepGoing = !keepGoing; if(!keepGoing){ frameList = new ArrayList<>(frames); currentFrame = 0; } } public boolean getPaused(){ return !keepGoing; } protected void looiPaint() { drawString(Constant.AGE_MIN,300,300); drawImage(boxDrawer.getCurrentImage(),0,0,getInternalWidth(),getInternalHeight()); //drawImage(testBI,0,0,getInternalWidth(),getInternalHeight()); } }
package ca.eandb.jmist.framework.job; import java.io.IOException; import java.io.ObjectInput; import ca.eandb.jdcp.job.AbstractParallelizableJob; import ca.eandb.jdcp.job.TaskWorker; import ca.eandb.jmist.framework.Display; import ca.eandb.jmist.framework.PixelShader; import ca.eandb.jmist.framework.Raster; import ca.eandb.jmist.framework.color.Color; import ca.eandb.jmist.framework.color.ColorModel; import ca.eandb.jmist.math.Box2; import ca.eandb.util.io.Archive; import ca.eandb.util.progress.ProgressMonitor; /** * A <code>ParallelizableJob</code> that renders a <code>Raster</code> image. * @author Brad Kimmel */ public final class RasterJob extends AbstractParallelizableJob { /** * Creates a new <code>RasterJob</code>. This job will * divide the image into <code>rows * cols</code> tasks to render roughly * equally sized chunks of the image. * @param colorModel The <code>ColorModel</code> to use to render the * image. * @param pixelShader The <code>PixelShader</code> to use to compute the * values of individual <code>Pixel</code>s. * @param formatName The name of the format to save the image as. * @param width The width of the rendered image, in pixels. * @param height The height of the rendered image, in pixels. * @param cols The number of columns to divide the image into. * @param rows The number of rows to divide the image into. */ public RasterJob(ColorModel colorModel, PixelShader pixelShader, Display display, int width, int height, int cols, int rows) { this.pixelShader = pixelShader; this.colorModel = colorModel; this.width = width; this.height = height; this.cols = cols; this.rows = rows; this.display = display; } /* (non-Javadoc) * @see ca.eandb.jdcp.job.AbstractParallelizableJob#initialize() */ @Override public void initialize() throws IOException { display.initialize(width, height, colorModel); } /* (non-Javadoc) * @see ca.eandb.jdcp.job.AbstractParallelizableJob#restoreState(java.io.ObjectInput) */ @Override public void restoreState(ObjectInput input) throws Exception { super.restoreState(input); this.initialize(); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.ParallelizableJob#getNextTask() */ public Object getNextTask() { if (this.nextRow < this.rows) { /* Get the next cell. */ Cell cell = this.getCell(this.nextCol++, this.nextRow); /* If we're done this row, move on to the next row. */ if (this.nextCol >= this.cols) { this.nextCol = 0; this.nextRow++; } return cell; } else { /* this.nextRow >= this.rows */ /* no remaining tasks. */ return null; } } /** * Defines the region of the image that a task should perform. * @author Brad Kimmel */ private static final class Cell { /** The x-coordinate of the upper left corner of the cell. */ final int x; /** The y-coordinate of the upper left-corner of the cell. */ final int y; /** The width of the cell, in pixels. */ final int width; /** The height of the cell, in pixels. */ final int height; /** * Creates a new <code>Cell</code>. * @param x The x-coordinate of the upper left corner of the cell. * @param y The y-coordinate of the upper left-corner of the cell. * @param width The width of the cell, in pixels. * @param height The height of the cell, in pixels. */ Cell(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } }; /** * Gets the bounds of the cell at the specified row and column. * @param col The column index. * @param row The row index. * @return The cell bounds. */ private Cell getCell(int col, int row) { /* Figure out how big the cells should be: * - Make them as large as possible without exceeding the size * of the image. * - Allocate the remainder of the pixels (if any) to the first n * cells, where n is the remainder. */ /* Ensure that the cell is valid whose dimensions are being * requested. */ assert(0 <= col && col < this.cols); assert(0 <= row && row < this.rows); /* First figure out the base dimensions of the cells and the number * of remaining pixels in each dimension that need to be allocated. */ int wdivc = width / this.cols; int hdivr = height / this.rows; int wmodc = width % this.cols; int hmodr = height % this.rows; /* Calculate the upper-left corner of the cell, first assuming that * there are no "remainder" pixels.. we will then adjust for this. */ int xmin = col * wdivc; int ymin = row * hdivr; /* Adjust to account for the cells above and to the left that * received extra pixels. */ xmin += Math.min(col, wmodc); ymin += Math.min(row, hmodr); /* Now compute the lower right pixel, again first assuming that this * cell is not to receive extra pixels. */ int xmax = xmin + wdivc - 1; int ymax = ymin + hdivr - 1; /* Add the extra pixels, if required. */ if (col < wmodc) xmax++; if (row < hmodr) ymax++; /* Make sure the computed cell extents fall within the image. */ assert(0 <= xmin && xmin <= xmax && xmax < width); assert(0 <= ymin && ymin <= ymax && ymax < height); return new Cell(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.ParallelizableJob#submitTaskResults(java.lang.Object, java.lang.Object, ca.eandb.util.progress.ProgressMonitor) */ public void submitTaskResults(Object task, Object results, ProgressMonitor monitor) { Cell cell = (Cell) task; Raster pixels = (Raster) results; /* Write the submitted results to the raster. */ display.setPixels(cell.x, cell.y, pixels); /* Update the progress monitor. */ monitor.notifyProgress(++this.tasksComplete, this.rows * this.cols); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.ParallelizableJob#isComplete() */ public boolean isComplete() { return this.tasksComplete >= (this.rows * this.cols); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.ParallelizableJob#finish() */ public void finish() throws IOException { display.finish(); } /* (non-Javadoc) * @see ca.eandb.jdcp.job.AbstractParallelizableJob#archiveState(ca.eandb.util.io.Archive) */ @Override protected void archiveState(Archive ar) throws IOException { nextCol = ar.archiveInt(nextCol); nextRow = ar.archiveInt(nextRow); tasksComplete = ar.archiveInt(tasksComplete); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.ParallelizableJob#worker() */ public TaskWorker worker() { return new RasterTaskWorker(colorModel, pixelShader, width, height); } /** * A <code>TaskWorker</code> that renders a rectangular subset of a * <code>Raster</code> image. * @author Brad Kimmel */ private static final class RasterTaskWorker implements TaskWorker { /** The <code>ColorModel</code> to use to render this image. */ private final ColorModel colorModel; /** * The <code>PixelShader</code> to use to compute the values of * individual <code>Pixel</code>s. */ private final PixelShader pixelShader; /** The width of the image to render, in pixels. */ private final int width; /** The height of the image to render, in pixels. */ private final int height; /** * Creates a new <code>RasterTaskWorker</code>. * @param colorModel The <code>ColorModel</code> to use to render this * image. * @param pixelShader The <code>PixelShader</code> to use to compute * the values of individual <code>Pixel</code>s. * @param width The width of the image to render, in pixels. * @param height The height of the image to render, in pixels. */ public RasterTaskWorker(ColorModel colorModel, PixelShader pixelShader, int width, int height) { this.colorModel = colorModel; this.pixelShader = pixelShader; this.width = width; this.height = height; } /* (non-Javadoc) * @see ca.eandb.jmist.framework.TaskWorker#performTask(java.lang.Object, ca.eandb.util.progress.ProgressMonitor) */ public Object performTask(Object task, ProgressMonitor monitor) { Cell cell = (Cell) task; int numPixels = cell.width * cell.height; Color pixel; Box2 bounds; double x0, y0, x1, y1; double w = width; double h = height; Raster raster = colorModel.createRaster(cell.width, cell.height); for (int n = 0, y = cell.y; y < cell.y + cell.height; y++) { if (!monitor.notifyProgress(n, numPixels)) return null; y0 = (double) y / h; y1 = (double) (y + 1) / h; for (int x = cell.x; x < cell.x + cell.width; x++, n++) { x0 = (double) x / w; x1 = (double) (x + 1) / w; bounds = new Box2(x0, y0, x1, y1); pixel = pixelShader.shadePixel(bounds); raster.addPixel(x - cell.x, y - cell.y, pixel); } } monitor.notifyProgress(numPixels, numPixels); monitor.notifyComplete(); return raster; } /** * Serialization version ID. */ private static final long serialVersionUID = 8318742231359439076L; } /** The <code>Display</code> to render the image to. */ private final Display display; /** The <code>ColorModel</code> to use to render this image. */ private final ColorModel colorModel; /** * The <code>PixelShader</code> to use to compute the values of * individual <code>Pixel</code>s. */ private final PixelShader pixelShader; /** The width of the image to render, in pixels. */ private final int width; /** The height of the image to render, in pixels. */ private final int height; /** The number of columns to divide the <code>Raster</code> image into. */ private final int cols; /** The number of rows to divide the <code>Raster</code> image into. */ private final int rows; /** The column index of the next task to return. */ private transient int nextCol = 0; /** The row index of the next task to return. */ private transient int nextRow = 0; /** The number of tasks that have been completed. */ private transient int tasksComplete = 0; /** * Serialization version ID. */ private static final long serialVersionUID = 9173731839475893020L; }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app.windows; import cc.arduino.os.windows.Win32KnownFolders; import processing.app.PreferencesData; import processing.app.legacy.PApplet; import processing.app.legacy.PConstants; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import com.sun.jna.Native; import com.sun.jna.win32.StdCallLibrary; import com.sun.jna.win32.W32APIOptions; public class Platform extends processing.app.Platform { private File settingsFolder; private File defaultSketchbookFolder; @Override public void init() throws Exception { super.init(); checkPath(); recoverSettingsFolderPath(); recoverDefaultSketchbookFolder(); } private void recoverSettingsFolderPath() throws Exception { if (PreferencesData.getBoolean("runtime.is-windows-store-app")) { // LocalAppData is restricted for Windows Store Apps. // We are forced to use a document folder to store tools. Path path = Win32KnownFolders.getDocumentsFolder().toPath(); settingsFolder = path.resolve("ArduinoData").toFile(); } else { Path path = Win32KnownFolders.getLocalAppDataFolder().toPath(); settingsFolder = path.resolve("Arduino15").toFile(); } } private Path recoverOldSettingsFolderPath() throws Exception { Path path = Win32KnownFolders.getRoamingAppDataFolder().toPath(); return path.resolve("Arduino15"); } private void recoverDefaultSketchbookFolder() throws Exception { Path path = Win32KnownFolders.getDocumentsFolder().toPath(); defaultSketchbookFolder = path.resolve("Arduino").toFile(); } /** * Remove extra quotes, slashes, and garbage from the Windows PATH. */ protected void checkPath() { String path = System.getProperty("java.library.path"); String[] pieces = PApplet.split(path, File.pathSeparatorChar); String[] legit = new String[pieces.length]; int legitCount = 0; for (String item : pieces) { if (item.startsWith("\"")) { item = item.substring(1); } if (item.endsWith("\"")) { item = item.substring(0, item.length() - 1); } if (item.endsWith(File.separator)) { item = item.substring(0, item.length() - File.separator.length()); } File directory = new File(item); if (!directory.exists()) { continue; } if (item.trim().length() == 0) { continue; } legit[legitCount++] = item; } legit = PApplet.subset(legit, 0, legitCount); String newPath = PApplet.join(legit, File.pathSeparator); if (!newPath.equals(path)) { System.setProperty("java.library.path", newPath); } } @Override public File getSettingsFolder() { return settingsFolder; } @Override public File getDefaultSketchbookFolder() throws Exception { return defaultSketchbookFolder; } @Override public void openURL(String url) throws Exception { if (!url.startsWith("http") && !url.startsWith("file:")) { // Check if we are trying to open a local file File file = new File(url); if (file.exists()) { // in this case convert the path to a "file:" url url = file.toURI().toString(); // this allows to open the file on Windows 10 that } } // this is not guaranteed to work, because who knows if the // path will always be c:\progra~1 et al. also if the user has // a different browser set as their default (which would // include me) it'd be annoying to be dropped into ie. //Runtime.getRuntime().exec("c:\\progra~1\\intern~1\\iexplore " // + currentDir // the following uses a shell execute to launch the .html file // note that under cygwin, the .html files have to be chmodded +x // after they're unpacked from the zip file. i don't know why, // and don't understand what this does in terms of windows // "Access is denied" in both cygwin and the "dos" prompt. //Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" + // referenceFile + ".html"); if (url.startsWith("http") || url.startsWith("file:")) { // open dos prompt, give it 'start' command, which will // open the url properly. start by itself won't work since // it appears to need cmd Runtime.getRuntime().exec("cmd /c start \"\" \"" + url + "\""); } else { // just launching the .html file via the shell works // but make sure to chmod +x the .html files first // also place quotes around it in case there's a space // in the user.dir part of the url Runtime.getRuntime().exec("cmd /c \"" + url + "\""); } } @Override public boolean openFolderAvailable() { return true; } @Override public void openFolder(File file) throws Exception { String folder = file.getAbsolutePath(); // doesn't work //Runtime.getRuntime().exec("cmd /c \"" + folder + "\""); // works fine on winxp, prolly win2k as well Runtime.getRuntime().exec("explorer \"" + folder + "\""); // not tested //Runtime.getRuntime().exec("start explorer \"" + folder + "\""); } @Override public String getName() { return PConstants.platformNames[PConstants.WINDOWS]; } @Override public void fixPrefsFilePermissions(File prefsFile) throws IOException { //noop } @Override public List<File> postInstallScripts(File folder) { List<File> scripts = new LinkedList<>(); scripts.add(new File(folder, "post_install.bat")); return scripts; } @Override public List<File> preUninstallScripts(File folder) { List<File> scripts = new LinkedList<>(); scripts.add(new File(folder, "pre_uninstall.bat")); return scripts; } public void symlink(File something, File somewhere) throws IOException, InterruptedException { } @Override public void link(File something, File somewhere) throws IOException, InterruptedException { } @Override public void chmod(File file, int mode) throws IOException, InterruptedException { } @Override public void fixSettingsLocation() throws Exception { if (PreferencesData.getBoolean("runtime.is-windows-store-app")) return; Path oldSettingsFolder = recoverOldSettingsFolderPath(); if (!Files.exists(oldSettingsFolder)) { return; } if (!Files.exists(oldSettingsFolder.resolve(Paths.get("preferences.txt")))) { return; } if (settingsFolder.exists()) { return; } Files.move(oldSettingsFolder, settingsFolder.toPath()); } // Need to extend com.sun.jna.platform.win32.User32 to access // Win32 function GetDpiForSystem() interface ExtUser32 extends StdCallLibrary, com.sun.jna.platform.win32.User32 { ExtUser32 INSTANCE = (ExtUser32) Native.loadLibrary("user32", ExtUser32.class, W32APIOptions.DEFAULT_OPTIONS); public int GetDpiForSystem(); } @Override public int getSystemDPI() { try { return ExtUser32.INSTANCE.GetDpiForSystem(); } catch (Throwable e) { // DPI detection failed, fall back with default return super.getSystemDPI(); } } }
//package client; //import org.junit.Test; //import org.okraAx.rebot.FakeClient; //import org.okraAx.v3.GpcCall; //import org.okraAx.v3.GpcVoid; //import org.okraAx.v3.login.beans.CreateRoleBean; ///** // * @author TinyZ. // * @version 2017.05.10 // */ //public class FakeClientTest { // @Test // public void testLogin() { // FakeClient client = new FakeClient(); // client.addLastAction(()->{ // client.writeAndFlush(GpcCall.newBuilder() // .setMethod("onCreateRole") // .setParams(CreateRoleBean.newBuilder() // .setOpenId("xx-openId") // .setName("xx-name") // .setFigure(1) // .build().toByteString()) // .build()); // client.waitForCallback("callbackSyncTime"); // client.addLastAction(()->{ // client.writeAndFlush(GpcCall.newBuilder() // .setMethod("onSyncTime") // .setParams(GpcVoid.getDefaultInstance().toByteString()) // .build()); // client.waitForCallback("callbackSyncTime"); // client.connect("127.0.0.1", 9005); // while (true) { // client.doAction(); // try { // Thread.sleep(1000L); // } catch (InterruptedException e) { // e.printStackTrace();
package com.btmura.android.reddit; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentManager.OnBackStackChangedListener; import android.app.FragmentTransaction; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.btmura.android.reddit.ThingListFragment.OnThingSelectedListener; import com.btmura.android.reddit.TopicListFragment.OnTopicSelectedListener; public class MainActivity extends Activity implements OnBackStackChangedListener, OnTopicSelectedListener, OnThingSelectedListener, TopicHolder, ThingHolder, LayoutInfo { @SuppressWarnings("unused") private static final String TAG = "MainActivity"; private static final String CONTROL_TAG = "control"; private static final String TOPIC_LIST_TAG = "topicList"; private static final String THING_LIST_TAG = "thingList"; private static final String THING_TAG = "thing"; private static final String THING_FRAG_TYPE = "type"; private static final int THING_FRAG_LINK = 0; private static final int THING_FRAG_COMMENTS = 1; private FragmentManager manager; private ActionBar bar; private View singleContainer; private View topicListContainer; private View thingListContainer; private View thingContainer; private int topicListContainerId; private int thingListContainerId; private int thingContainerId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); manager = getFragmentManager(); manager.addOnBackStackChangedListener(this); singleContainer = findViewById(R.id.single_container); topicListContainer = findViewById(R.id.topic_list_container); thingListContainer = findViewById(R.id.thing_list_container); thingContainer = findViewById(R.id.thing_container); if (thingContainer != null) { thingContainer.setVisibility(View.GONE); } bar = getActionBar(); bar.setDisplayShowHomeEnabled(true); topicListContainerId = topicListContainer != null ? R.id.topic_list_container : R.id.single_container; thingListContainerId = thingListContainer != null ? R.id.thing_list_container : R.id.single_container; thingContainerId = thingContainer != null ? R.id.thing_container : R.id.single_container; if (savedInstanceState == null) { setupFragments(); } } private void setupFragments() { if (singleContainer != null) { ControlFragment controlFrag = ControlFragment.newInstance(null, -1, null, -1); TopicListFragment topicFrag = TopicListFragment.newInstance(-1); FragmentTransaction trans = manager.beginTransaction(); trans.add(controlFrag, CONTROL_TAG); trans.replace(topicListContainerId, topicFrag); trans.commit(); } Topic topic = Topic.newTopic("all"); if (topicListContainer != null) { ControlFragment controlFrag = ControlFragment.newInstance(topic, 0, null, -1); TopicListFragment topicFrag = TopicListFragment.newInstance(0); FragmentTransaction trans = manager.beginTransaction(); trans.add(controlFrag, CONTROL_TAG); trans.replace(topicListContainerId, topicFrag, TOPIC_LIST_TAG); trans.commit(); } if (thingListContainer != null) { replaceThingList(topic, 0, false); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState != null) { onBackStackChanged(); } } public void onTopicSelected(Topic topic, int position) { replaceThingList(topic, position, true); } private void replaceThingList(Topic topic, int position, boolean addToBackStack) { manager.popBackStack(THING_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE); manager.popBackStack(THING_LIST_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE); FragmentTransaction trans = manager.beginTransaction(); ControlFragment controlFrag = ControlFragment.newInstance(topic, position, null, -1); trans.add(controlFrag, CONTROL_TAG); ThingListFragment thingListFrag = ThingListFragment.newInstance(); trans.replace(thingListContainerId, thingListFrag, THING_LIST_TAG); if (addToBackStack) { trans.addToBackStack(THING_LIST_TAG); } trans.commit(); } public void onThingSelected(Entity thing, int position) { replaceThing(thing, position, thing.isSelf ? THING_FRAG_COMMENTS : THING_FRAG_LINK); } private void replaceThing(Entity thing, int position, int thingFragType) { manager.popBackStack(THING_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE); ControlFragment controlFrag = ControlFragment.newInstance(getTopic(), getTopicPosition(), thing, position); Fragment frag = thingFragType == THING_FRAG_COMMENTS ? CommentListFragment.newInstance() : LinkFragment.newInstance(); Bundle args = new Bundle(); args.putInt(THING_FRAG_TYPE, thingFragType); frag.setArguments(args); FragmentTransaction trans = manager.beginTransaction(); trans.add(controlFrag, CONTROL_TAG); trans.replace(thingContainerId, frag, THING_TAG); trans.addToBackStack(THING_TAG); trans.commit(); } public Topic getTopic() { return getControlFragment().getTopic(); } public Entity getThing() { return getControlFragment().getThing(); } public boolean hasTopicListContainer() { return topicListContainer != null; } public boolean hasThingListContainer() { return thingListContainer != null; } public boolean hasThingContainer() { return thingContainer != null; } private int getTopicPosition() { return getControlFragment().getTopicPosition(); } private int getThingPosition() { return getControlFragment().getThingPosition(); } private ControlFragment getControlFragment() { return (ControlFragment) manager.findFragmentByTag(CONTROL_TAG); } private TopicListFragment getTopicListFragment() { return (TopicListFragment) manager.findFragmentByTag(TOPIC_LIST_TAG); } private ThingListFragment getThingListFragment() { return (ThingListFragment) manager.findFragmentByTag(THING_LIST_TAG); } private Fragment getThingFragment() { return manager.findFragmentByTag(THING_TAG); } public void onBackStackChanged() { refreshHome(); refreshTitle(); refreshCheckedItems(); refreshThingContainer(); invalidateOptionsMenu(); } private void refreshHome() { bar.setDisplayHomeAsUpEnabled(singleContainer != null && getTopic() != null || getThing() != null); } private void refreshTitle() { Topic topic = getTopic(); Entity thing = getThing(); if (thing != null) { bar.setTitle(thing.title); } else if (topic != null) { bar.setTitle(topic.title); } else { bar.setTitle(R.string.app_name); } } private void refreshCheckedItems() { TopicListFragment topicFrag = getTopicListFragment(); if (topicFrag != null && topicFrag.isAdded()) { topicFrag.setItemChecked(getTopicPosition()); } ThingListFragment thingListFrag = getThingListFragment(); if (thingListFrag != null && thingListFrag.isAdded()) { thingListFrag.setItemChecked(getThingPosition()); } } private void refreshThingContainer() { if (thingContainer != null) { thingContainer.setVisibility(getThing() != null ? View.VISIBLE : View.GONE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean hasThing = getThing() != null; boolean isSelf = hasThing && getThing().isSelf; menu.findItem(R.id.menu_link).setVisible(hasThing && !isSelf && isThingFragmentType(THING_FRAG_COMMENTS)); menu.findItem(R.id.menu_comments).setVisible(hasThing && !isSelf && isThingFragmentType(THING_FRAG_LINK)); menu.findItem(R.id.menu_copy_link).setVisible(hasThing && !isSelf); menu.findItem(R.id.menu_copy_reddit_link).setVisible(hasThing); menu.findItem(R.id.menu_view).setVisible(hasThing && !isSelf); return true; } private boolean isThingFragmentType(int type) { Fragment thingFrag = getThingFragment(); return thingFrag != null && thingFrag.getArguments().getInt(THING_FRAG_TYPE) == type; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: handleHome(); return true; case R.id.menu_link: handleLink(); return true; case R.id.menu_comments: handleComments(); return true; case R.id.menu_copy_link: handleCopyLink(); return true; case R.id.menu_copy_reddit_link: handleCopyRedditLink(); return true; case R.id.menu_view: handleView(); return true; } return false; } private void handleHome() { int count = manager.getBackStackEntryCount(); if (count > 0) { String name = manager.getBackStackEntryAt(count - 1).getName(); if (THING_TAG.equals(name)) { manager.popBackStack(THING_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE); } else if (THING_LIST_TAG.equals(name)) { manager.popBackStack(THING_LIST_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE); } } } private void handleLink() { replaceThing(getThing(), getThingPosition(), THING_FRAG_LINK); } private void handleComments() { replaceThing(getThing(), getThingPosition(), THING_FRAG_COMMENTS); } private void handleCopyLink() { clipText(getThing().url); } private void handleCopyRedditLink() { clipText("http: } private void clipText(String text) { ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clip.setText(text); Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } private void handleView() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(getThing().url)); startActivity(Intent.createChooser(intent, getString(R.string.menu_view))); } }
package com.cctintl.c3dfx.skins; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.WeakInvalidationListener; import javafx.beans.binding.Bindings; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.value.WritableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.WeakListChangeListener; import javafx.css.CssMetaData; import javafx.css.PseudoClass; import javafx.css.Styleable; import javafx.css.StyleableObjectProperty; import javafx.css.StyleableProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.Side; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.SkinBase; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TabPane.TabClosingPolicy; import javafx.scene.control.Tooltip; import javafx.scene.effect.DropShadow; import javafx.scene.image.ImageView; import javafx.scene.input.ContextMenuEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.input.SwipeEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BorderPane; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.transform.Rotate; import javafx.util.Duration; import com.cctintl.c3dfx.controls.C3DRippler; import com.cctintl.c3dfx.controls.C3DRippler.RipplerMask; import com.cctintl.c3dfx.controls.C3DRippler.RipplerPos; import com.cctintl.c3dfx.controls.DepthManager; import com.sun.javafx.css.converters.EnumConverter; import com.sun.javafx.scene.control.MultiplePropertyChangeListenerHandler; import com.sun.javafx.scene.control.behavior.TabPaneBehavior; import com.sun.javafx.scene.control.skin.BehaviorSkinBase; import de.jensd.fx.fontawesome.Icon; public class C3DTabPaneSkin extends BehaviorSkinBase<TabPane, TabPaneBehavior> { private Color defaultColor = Color.valueOf("#00BCD4"), ripplerColor = Color.valueOf("FFFF8D"), selectedTabText = Color.WHITE, unSelectedTabText = Color.LIGHTGREY; private static enum TabAnimation { NONE, GROW // In future we could add FADE, ... } private ObjectProperty<TabAnimation> openTabAnimation = new StyleableObjectProperty<TabAnimation>(TabAnimation.GROW) { @Override public CssMetaData<TabPane, TabAnimation> getCssMetaData() { return StyleableProperties.OPEN_TAB_ANIMATION; } @Override public Object getBean() { return C3DTabPaneSkin.this; } @Override public String getName() { return "openTabAnimation"; } }; private ObjectProperty<TabAnimation> closeTabAnimation = new StyleableObjectProperty<TabAnimation>(TabAnimation.GROW) { @Override public CssMetaData<TabPane, TabAnimation> getCssMetaData() { return StyleableProperties.CLOSE_TAB_ANIMATION; } @Override public Object getBean() { return C3DTabPaneSkin.this; } @Override public String getName() { return "closeTabAnimation"; } }; private static int getRotation(Side pos) { switch (pos) { case TOP: return 0; case BOTTOM: return 180; case LEFT: return -90; case RIGHT: return 90; default: return 0; } } /** * VERY HACKY - this lets us 'duplicate' Label and ImageView nodes to be used in a * Tab and the tabs menu at the same time. */ private static Node clone(Node n) { if (n == null) { return null; } if (n instanceof ImageView) { ImageView iv = (ImageView) n; ImageView imageview = new ImageView(); imageview.setImage(iv.getImage()); return imageview; } if (n instanceof Label) { Label l = (Label) n; Label label = new Label(l.getText(), l.getGraphic()); return label; } return null; } private static final double ANIMATION_SPEED = 150; private static final int SPACER = 10; private TabHeaderArea tabHeaderArea; private ObservableList<TabContentRegion> tabContentRegions; private Rectangle clipRect; private Rectangle tabHeaderAreaClipRect; private Tab selectedTab; private boolean isSelectingTab, isDragged; private double dragStart, offsetStart; public C3DTabPaneSkin(TabPane tabPane) { super(tabPane, new TabPaneBehavior(tabPane)); clipRect = new Rectangle(tabPane.getWidth(), tabPane.getHeight()); //getSkinnable().setClip(clipRect); DepthManager.setDepth(getSkinnable(), 2); tabContentRegions = FXCollections.<TabContentRegion> observableArrayList(); for (Tab tab : getSkinnable().getTabs()) { addTabContent(tab); } tabHeaderAreaClipRect = new Rectangle(); tabHeaderArea = new TabHeaderArea(); tabHeaderArea.setClip(tabHeaderAreaClipRect); getChildren().add(tabHeaderArea); tabsContainer = new AnchorPane(); tabsContainer.setStyle("-fx-border-color:RED;"); tabsContainerHolder = new AnchorPane(); tabsContainerHolder.getChildren().add(tabsContainer); getChildren().add(tabsContainerHolder); if (getSkinnable().getTabs().size() == 0) { tabHeaderArea.setVisible(false); } initializeTabListener(); registerChangeListener(tabPane.getSelectionModel().selectedItemProperty(), "SELECTED_TAB"); registerChangeListener(tabPane.sideProperty(), "SIDE"); registerChangeListener(tabPane.widthProperty(), "WIDTH"); registerChangeListener(tabPane.heightProperty(), "HEIGHT"); selectedTab = getSkinnable().getSelectionModel().getSelectedItem(); // Could not find the selected tab try and get the selected tab using the selected index if (selectedTab == null && getSkinnable().getSelectionModel().getSelectedIndex() != -1) { getSkinnable().getSelectionModel().select(getSkinnable().getSelectionModel().getSelectedIndex()); selectedTab = getSkinnable().getSelectionModel().getSelectedItem(); } if (selectedTab == null) { // getSelectedItem and getSelectedIndex failed select the first. getSkinnable().getSelectionModel().selectFirst(); } selectedTab = getSkinnable().getSelectionModel().getSelectedItem(); isSelectingTab = false; initializeSwipeHandlers(); tabHeaderArea.headersRegion.setOnMouseDragged(me -> { isDragged = true; tabHeaderArea.setScrollOffset(offsetStart + me.getSceneX() - dragStart); }); getSkinnable().setOnMousePressed(me -> { dragStart = me.getSceneX(); offsetStart = tabHeaderArea.getScrollOffset(); }); getSkinnable().setOnMouseReleased(me -> { //isDragged = false; }); } public StackPane getSelectedTabContentRegion() { for (TabContentRegion contentRegion : tabContentRegions) { if (contentRegion.getTab().equals(selectedTab)) { return contentRegion; } } return null; } @Override protected void handleControlPropertyChanged(String property) { super.handleControlPropertyChanged(property); if ("SELECTED_TAB".equals(property)) { isSelectingTab = true; selectedTab = getSkinnable().getSelectionModel().getSelectedItem(); getSkinnable().requestLayout(); } else if ("SIDE".equals(property)) { updateTabPosition(); } else if ("WIDTH".equals(property)) { clipRect.setWidth(getSkinnable().getWidth()); } else if ("HEIGHT".equals(property)) { clipRect.setHeight(getSkinnable().getHeight()); } } private void removeTabs(List<? extends Tab> removedList) { for (final Tab tab : removedList) { // Animate the tab removal final TabHeaderSkin tabRegion = tabHeaderArea.getTabHeaderSkin(tab); if (tabRegion != null) { tabRegion.isClosing = true; if (closeTabAnimation.get() == TabAnimation.GROW) { Timeline closedTabTimeline = createTimeline(tabRegion, Duration.millis(ANIMATION_SPEED), 0.0F, event -> { handleClosedTab(tab); }); closedTabTimeline.play(); } else { handleClosedTab(tab); } } } } private void handleClosedTab(Tab tab) { removeTab(tab); if (getSkinnable().getTabs().isEmpty()) { tabHeaderArea.setVisible(false); } } private void addTabs(List<? extends Tab> addedList, int from) { int i = 0; for (final Tab tab : addedList) { // A new tab was added - animate it out if (!tabHeaderArea.isVisible()) { tabHeaderArea.setVisible(true); } int index = from + i++; tabHeaderArea.addTab(tab, index, false); addTabContent(tab); final TabHeaderSkin tabRegion = tabHeaderArea.getTabHeaderSkin(tab); if (tabRegion != null) { if (openTabAnimation.get() == TabAnimation.GROW) { tabRegion.animationTransition.setValue(0.0); tabRegion.setVisible(true); createTimeline(tabRegion, Duration.millis(ANIMATION_SPEED), 1.0, event -> { tabRegion.inner.requestLayout(); }).play(); } else { tabRegion.setVisible(true); tabRegion.inner.requestLayout(); } } } } private void initializeTabListener() { getSkinnable().getTabs().addListener((ListChangeListener<Tab>) c -> { List<Tab> tabsToRemove = new ArrayList<>(); List<Tab> tabsToAdd = new ArrayList<>(); int insertPos = -1; while (c.next()) { if (c.wasPermutated()) { TabPane tabPane = getSkinnable(); List<Tab> tabs = tabPane.getTabs(); // tabs sorted : create list of permutated tabs. // clear selection, set tab animation to NONE // remove permutated tabs, add them back in correct order. // restore old selection, and old tab animation states. int size = c.getTo() - c.getFrom(); Tab selTab = tabPane.getSelectionModel().getSelectedItem(); List<Tab> permutatedTabs = new ArrayList<Tab>(size); getSkinnable().getSelectionModel().clearSelection(); // save and set tab animation to none - as it is not a good idea // to animate on the same data for open and close. TabAnimation prevOpenAnimation = openTabAnimation.get(); TabAnimation prevCloseAnimation = closeTabAnimation.get(); openTabAnimation.set(TabAnimation.NONE); closeTabAnimation.set(TabAnimation.NONE); for (int i = c.getFrom(); i < c.getTo(); i++) { permutatedTabs.add(tabs.get(i)); } removeTabs(permutatedTabs); addTabs(permutatedTabs, c.getFrom()); openTabAnimation.set(prevOpenAnimation); closeTabAnimation.set(prevCloseAnimation); getSkinnable().getSelectionModel().select(selTab); } if (c.wasRemoved()) { tabsToRemove.addAll(c.getRemoved()); } if (c.wasAdded()) { tabsToAdd.addAll(c.getAddedSubList()); insertPos = c.getFrom(); } } // now only remove the tabs that are not in the tabsToAdd list tabsToRemove.removeAll(tabsToAdd); removeTabs(tabsToRemove); // and add in any new tabs (that we don't already have showing) if (!tabsToAdd.isEmpty()) { for (TabContentRegion tabContentRegion : tabContentRegions) { Tab tab = tabContentRegion.getTab(); TabHeaderSkin tabHeader = tabHeaderArea.getTabHeaderSkin(tab); if (!tabHeader.isClosing && tabsToAdd.contains(tabContentRegion.getTab())) { tabsToAdd.remove(tabContentRegion.getTab()); } } addTabs(tabsToAdd, insertPos == -1 ? tabContentRegions.size() : insertPos); } // Fix for RT-34692 getSkinnable().requestLayout(); } ); } private void addTabContent(Tab tab) { TabContentRegion tabContentRegion = new TabContentRegion(tab); tabContentRegion.setClip(new Rectangle()); tabContentRegions.add(tabContentRegion); // We want the tab content to always sit below the tab headers getChildren().add(0, tabContentRegion); } private void removeTabContent(Tab tab) { for (TabContentRegion contentRegion : tabContentRegions) { if (contentRegion.getTab().equals(tab)) { contentRegion.removeListeners(tab); getChildren().remove(contentRegion); tabContentRegions.remove(contentRegion); break; } } } private void removeTab(Tab tab) { final TabHeaderSkin tabRegion = tabHeaderArea.getTabHeaderSkin(tab); if (tabRegion != null) { tabRegion.removeListeners(tab); } tabHeaderArea.removeTab(tab); removeTabContent(tab); tabHeaderArea.requestLayout(); } private void updateTabPosition() { tabHeaderArea.setScrollOffset(0.0F); getSkinnable().applyCss(); getSkinnable().requestLayout(); } private Timeline createTimeline(final TabHeaderSkin tabRegion, final Duration duration, final double endValue, final EventHandler<ActionEvent> func) { Timeline timeline = new Timeline(); timeline.setCycleCount(1); KeyValue keyValue = new KeyValue(tabRegion.animationTransition, endValue, Interpolator.LINEAR); timeline.getKeyFrames().clear(); timeline.getKeyFrames().add(new KeyFrame(duration, func, keyValue)); return timeline; } private boolean isHorizontal() { Side tabPosition = getSkinnable().getSide(); return Side.TOP.equals(tabPosition) || Side.BOTTOM.equals(tabPosition); } private void initializeSwipeHandlers() { if (IS_TOUCH_SUPPORTED) { getSkinnable().addEventHandler(SwipeEvent.SWIPE_LEFT, t -> { getBehavior().selectNextTab(); }); getSkinnable().addEventHandler(SwipeEvent.SWIPE_RIGHT, t -> { getBehavior().selectPreviousTab(); }); } } //TODO need to cache this. private boolean isFloatingStyleClass() { return getSkinnable().getStyleClass().contains(TabPane.STYLE_CLASS_FLOATING); } private double maxw = 0.0d; @Override protected double computePrefWidth(double height, double topInset, double rightInset, double bottomInset, double leftInset) { // The TabPane can only be as wide as it widest content width. for (TabContentRegion contentRegion : tabContentRegions) { maxw = Math.max(maxw, snapSize(contentRegion.prefWidth(-1))); } final boolean isHorizontal = isHorizontal(); final double tabHeaderAreaSize = snapSize(isHorizontal ? tabHeaderArea.prefWidth(-1) : tabHeaderArea.prefHeight(-1)); double prefWidth = isHorizontal ? Math.max(maxw, tabHeaderAreaSize) : maxw + tabHeaderAreaSize; return snapSize(prefWidth) + rightInset + leftInset; } private double maxh = 0.0d; @Override protected double computePrefHeight(double width, double topInset, double rightInset, double bottomInset, double leftInset) { // The TabPane can only be as high as it highest content height. for (TabContentRegion contentRegion : tabContentRegions) { maxh = Math.max(maxh, snapSize(contentRegion.prefHeight(-1))); } final boolean isHorizontal = isHorizontal(); final double tabHeaderAreaSize = snapSize(isHorizontal ? tabHeaderArea.prefHeight(-1) : tabHeaderArea.prefWidth(-1)); double prefHeight = isHorizontal ? maxh + snapSize(tabHeaderAreaSize) : Math.max(maxh, tabHeaderAreaSize); return snapSize(prefHeight) + topInset + bottomInset; } @Override public double computeBaselineOffset(double topInset, double rightInset, double bottomInset, double leftInset) { Side tabPosition = getSkinnable().getSide(); if (tabPosition == Side.TOP) { return tabHeaderArea.getBaselineOffset() + topInset; } return 0; } @Override protected void layoutChildren(final double x, final double y, final double w, final double h) { TabPane tabPane = getSkinnable(); Side tabPosition = tabPane.getSide(); double headerHeight = snapSize(tabHeaderArea.prefHeight(-1)); double tabsStartX = tabPosition.equals(Side.RIGHT) ? x + w - headerHeight : x; double tabsStartY = tabPosition.equals(Side.BOTTOM) ? y + h - headerHeight : y; if (tabPosition == Side.TOP) { tabHeaderArea.resize(w, headerHeight); tabHeaderArea.relocate(tabsStartX, tabsStartY); tabHeaderArea.getTransforms().clear(); tabHeaderArea.getTransforms().add(new Rotate(getRotation(Side.TOP))); } else if (tabPosition == Side.BOTTOM) { tabHeaderArea.resize(w, headerHeight); tabHeaderArea.relocate(w, tabsStartY - headerHeight); tabHeaderArea.getTransforms().clear(); tabHeaderArea.getTransforms().add(new Rotate(getRotation(Side.BOTTOM), 0, headerHeight)); } else if (tabPosition == Side.LEFT) { tabHeaderArea.resize(h, headerHeight); tabHeaderArea.relocate(tabsStartX + headerHeight, h - headerHeight); tabHeaderArea.getTransforms().clear(); tabHeaderArea.getTransforms().add(new Rotate(getRotation(Side.LEFT), 0, headerHeight)); } else if (tabPosition == Side.RIGHT) { tabHeaderArea.resize(h, headerHeight); tabHeaderArea.relocate(tabsStartX, y - headerHeight); tabHeaderArea.getTransforms().clear(); tabHeaderArea.getTransforms().add(new Rotate(getRotation(Side.RIGHT), 0, headerHeight)); } tabHeaderAreaClipRect.setX(0); tabHeaderAreaClipRect.setY(0); if (isHorizontal()) { tabHeaderAreaClipRect.setWidth(w); } else { tabHeaderAreaClipRect.setWidth(h); } tabHeaderAreaClipRect.setHeight(headerHeight); // position the tab content for the selected tab only // if the tabs are on the left, the content needs to be indented double contentStartX = 0; double contentStartY = 0; if (tabPosition == Side.TOP) { contentStartX = x; contentStartY = y + headerHeight; if (isFloatingStyleClass()) { // This is to hide the top border content contentStartY -= 1; } } else if (tabPosition == Side.BOTTOM) { contentStartX = x; contentStartY = y; if (isFloatingStyleClass()) { // This is to hide the bottom border content contentStartY = 1; } } else if (tabPosition == Side.LEFT) { contentStartX = x + headerHeight; contentStartY = y; if (isFloatingStyleClass()) { // This is to hide the left border content contentStartX -= 1; } } else if (tabPosition == Side.RIGHT) { contentStartX = x; contentStartY = y; if (isFloatingStyleClass()) { // This is to hide the right border content contentStartX = 1; } } double contentWidth = w - (isHorizontal() ? 0 : headerHeight); double contentHeight = h - (isHorizontal() ? headerHeight : 0); Rectangle clip = new Rectangle(contentWidth,contentHeight); tabsContainerHolder.setClip(clip); tabsContainerHolder.resize(contentWidth, contentHeight); tabsContainerHolder.relocate(contentStartX, contentStartY); tabsContainer.getChildren().clear(); tabsContainer.setStyle("-fx-border-color:RED;"); tabsContainer.resize(contentWidth * tabContentRegions.size(), contentHeight); for (int i = 0, max = tabContentRegions.size(); i < max; i++) { TabContentRegion tabContent = tabContentRegions.get(i); tabContent.setVisible(true); tabsContainer.getChildren().add(tabContent); tabContent.setTranslateX(contentWidth*i); if (tabContent.getClip() != null) { ((Rectangle) tabContent.getClip()).setWidth(contentWidth); ((Rectangle) tabContent.getClip()).setHeight(contentHeight); } if(tabContent.getTab() == selectedTab){ Timeline animateTimeline = new Timeline(new KeyFrame(Duration.millis(320), new KeyValue(tabsContainer.translateXProperty(), -contentWidth*i, Interpolator.EASE_BOTH))); animateTimeline.play(); } tabContent.setStyle("-fx-border-color:BLUE;"); // we need to size all tabs, even if they aren't visible. For example, // see RT-29167 tabContent.resize(contentWidth, contentHeight); // tabContent.relocate(contentStartX, contentStartY); } } /** * Super-lazy instantiation pattern from Bill Pugh. * @treatAsPrivate implementation detail */ private static class StyleableProperties { private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; private final static CssMetaData<TabPane, TabAnimation> OPEN_TAB_ANIMATION = new CssMetaData<TabPane, C3DTabPaneSkin.TabAnimation>("-fx-open-tab-animation", new EnumConverter<TabAnimation>( TabAnimation.class), TabAnimation.GROW) { @Override public boolean isSettable(TabPane node) { return true; } @Override public StyleableProperty<TabAnimation> getStyleableProperty(TabPane node) { C3DTabPaneSkin skin = (C3DTabPaneSkin) node.getSkin(); return (StyleableProperty<TabAnimation>) (WritableValue<TabAnimation>) skin.openTabAnimation; } }; private final static CssMetaData<TabPane, TabAnimation> CLOSE_TAB_ANIMATION = new CssMetaData<TabPane, C3DTabPaneSkin.TabAnimation>("-fx-close-tab-animation", new EnumConverter<TabAnimation>( TabAnimation.class), TabAnimation.GROW) { @Override public boolean isSettable(TabPane node) { return true; } @Override public StyleableProperty<TabAnimation> getStyleableProperty(TabPane node) { C3DTabPaneSkin skin = (C3DTabPaneSkin) node.getSkin(); return (StyleableProperty<TabAnimation>) (WritableValue<TabAnimation>) skin.closeTabAnimation; } }; static { final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<CssMetaData<? extends Styleable, ?>>(SkinBase.getClassCssMetaData()); styleables.add(OPEN_TAB_ANIMATION); styleables.add(CLOSE_TAB_ANIMATION); STYLEABLES = Collections.unmodifiableList(styleables); } } /** * @return The CssMetaData associated with this class, which may include the * CssMetaData of its super classes. */ public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return StyleableProperties.STYLEABLES; } /** * {@inheritDoc} */ @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return getClassCssMetaData(); } class TabHeaderArea extends StackPane { private Rectangle headerClip; private StackPane headersRegion; private StackPane headerBackground; private TabControlButtons rightControlButtons; private TabControlButtons leftControlButtons; private Line selectedTabLine; private boolean initialized; private boolean measureClosingTabs = false; private double scrollOffset, selectedTabLineOffset; public TabHeaderArea() { getStyleClass().setAll("tab-header-area"); setManaged(false); final TabPane tabPane = getSkinnable(); headerClip = new Rectangle(); headersRegion = new StackPane() { @Override protected double computePrefWidth(double height) { double width = 0.0F; for (Node child : getChildren()) { if(child instanceof TabHeaderSkin){ TabHeaderSkin tabHeaderSkin = (TabHeaderSkin) child; if (tabHeaderSkin.isVisible() && (measureClosingTabs || !tabHeaderSkin.isClosing)) { width += tabHeaderSkin.prefWidth(height); } } } return snapSize(width) + snappedLeftInset() + snappedRightInset(); } @Override protected double computePrefHeight(double width) { double height = 0.0F; for (Node child : getChildren()) { if(child instanceof TabHeaderSkin){ TabHeaderSkin tabHeaderSkin = (TabHeaderSkin) child; height = Math.max(height, tabHeaderSkin.prefHeight(width)); } } return snapSize(height) + snappedTopInset() + snappedBottomInset(); } @Override protected void layoutChildren() { if (tabsFit()) { setScrollOffset(0.0); } else { if (!removeTab.isEmpty()) { double offset = 0; double w = tabHeaderArea.getWidth() - snapSize(rightControlButtons.prefWidth(-1)) - snapSize(leftControlButtons.prefWidth(-1)) - firstTabIndent() - SPACER; Iterator<Node> i = getChildren().iterator(); while (i.hasNext()) { Node temp = i.next(); if(temp instanceof TabHeaderSkin){ TabHeaderSkin tabHeader = (TabHeaderSkin) temp; double tabHeaderPrefWidth = snapSize(tabHeader.prefWidth(-1)); if (removeTab.contains(tabHeader)) { if (offset < w) { isSelectingTab = true; } i.remove(); removeTab.remove(tabHeader); if (removeTab.isEmpty()) { break; } } offset += tabHeaderPrefWidth; } } } } if (isSelectingTab) { ensureSelectedTabIsVisible(); isSelectingTab = false; } else { validateScrollOffset(); } Side tabPosition = getSkinnable().getSide(); double tabBackgroundHeight = snapSize(prefHeight(-1)); double tabX = (tabPosition.equals(Side.LEFT) || tabPosition.equals(Side.BOTTOM)) ? snapSize(getWidth()) - getScrollOffset() : getScrollOffset(); updateHeaderClip(); for (Node node : getChildren()) { if(node instanceof TabHeaderSkin){ TabHeaderSkin tabHeader = (TabHeaderSkin) node; // size and position the header relative to the other headers double tabHeaderPrefWidth = snapSize(tabHeader.prefWidth(-1) * tabHeader.animationTransition.get()); double tabHeaderPrefHeight = snapSize(tabHeader.prefHeight(-1)); tabHeader.resize(tabHeaderPrefWidth, tabHeaderPrefHeight); // This ensures that the tabs are located in the correct position // when there are tabs of differing heights. double startY = tabPosition.equals(Side.BOTTOM) ? 0 : tabBackgroundHeight - tabHeaderPrefHeight - snappedBottomInset(); if (tabPosition.equals(Side.LEFT) || tabPosition.equals(Side.BOTTOM)) { // build from the right tabX -= tabHeaderPrefWidth; tabHeader.relocate(tabX, startY); } else { // build from the left tabHeader.relocate(tabX, startY); tabX += tabHeaderPrefWidth; } } } } }; headersRegion.getStyleClass().setAll("headers-region"); headersRegion.setClip(headerClip); headerBackground = new StackPane(); headerBackground.setBackground(new Background(new BackgroundFill(defaultColor, CornerRadii.EMPTY, Insets.EMPTY))); headerBackground.getStyleClass().setAll("tab-header-background"); selectedTabLine = new Line(); selectedTabLine.setStrokeWidth(2); selectedTabLine.setStroke(ripplerColor); headersRegion.getChildren().add(selectedTabLine); selectedTabLine.translateYProperty().bind(Bindings.createDoubleBinding(()-> headersRegion.getHeight() - selectedTabLine.getStrokeWidth() + 1, headersRegion.heightProperty(), selectedTabLine.strokeWidthProperty())); int i = 0; for (Tab tab : tabPane.getTabs()) { addTab(tab, i++, true); } rightControlButtons = new TabControlButtons(ArrowPosition.RIGHT); leftControlButtons = new TabControlButtons(ArrowPosition.LEFT); //controlButtons.setVisible(false); if (rightControlButtons.isVisible()) { rightControlButtons.setVisible(true); } rightControlButtons.inner.prefHeightProperty().bind(headersRegion.heightProperty()); leftControlButtons.inner.prefHeightProperty().bind(headersRegion.heightProperty()); getChildren().addAll(headerBackground, headersRegion, leftControlButtons, rightControlButtons); // support for mouse scroll of header area (for when the tabs exceed // the available space) addEventHandler(ScrollEvent.SCROLL, (ScrollEvent e) -> { Side side = getSkinnable().getSide(); side = side == null ? Side.TOP : side; switch (side) { default: case TOP: case BOTTOM: setScrollOffset(scrollOffset - e.getDeltaY()); break; case LEFT: case RIGHT: setScrollOffset(scrollOffset + e.getDeltaY()); break; } }); } private void updateHeaderClip() { Side tabPosition = getSkinnable().getSide(); double x = 0; double y = 0; double clipWidth = 0; double clipHeight = 0; double maxWidth = 0; double shadowRadius = 0; double clipOffset = firstTabIndent(); double controlButtonPrefWidth = 2 * snapSize(rightControlButtons.prefWidth(-1)); measureClosingTabs = true; double headersPrefWidth = snapSize(headersRegion.prefWidth(-1)); measureClosingTabs = false; double headersPrefHeight = snapSize(headersRegion.prefHeight(-1)); // Add the spacer if isShowTabsMenu is true. if (controlButtonPrefWidth > 0) { controlButtonPrefWidth = controlButtonPrefWidth + SPACER; } if (headersRegion.getEffect() instanceof DropShadow) { DropShadow shadow = (DropShadow) headersRegion.getEffect(); shadowRadius = shadow.getRadius(); } maxWidth = snapSize(getWidth()) - controlButtonPrefWidth - clipOffset; if (tabPosition.equals(Side.LEFT) || tabPosition.equals(Side.BOTTOM)) { if (headersPrefWidth < maxWidth) { clipWidth = headersPrefWidth + shadowRadius; } else { x = headersPrefWidth - maxWidth; clipWidth = maxWidth + shadowRadius; } clipHeight = headersPrefHeight; } else { // If x = 0 the header region's drop shadow is clipped. x = -shadowRadius; clipWidth = (headersPrefWidth < maxWidth ? headersPrefWidth : maxWidth) + shadowRadius; clipHeight = headersPrefHeight; } headerClip.setX(x); headerClip.setY(y); headerClip.setWidth(clipWidth + 10); headerClip.setHeight(clipHeight); } private void addTab(Tab tab, int addToIndex, boolean visible) { TabHeaderSkin tabHeaderSkin = new TabHeaderSkin(tab); tabHeaderSkin.setVisible(visible); headersRegion.getChildren().add(addToIndex, tabHeaderSkin); } private List<TabHeaderSkin> removeTab = new ArrayList<>(); private void removeTab(Tab tab) { TabHeaderSkin tabHeaderSkin = getTabHeaderSkin(tab); if (tabHeaderSkin != null) { if (tabsFit()) { headersRegion.getChildren().remove(tabHeaderSkin); } else { // The tab will be removed during layout because // we need its width to compute the scroll offset. removeTab.add(tabHeaderSkin); tabHeaderSkin.removeListeners(tab); } } } private TabHeaderSkin getTabHeaderSkin(Tab tab) { for (Node child : headersRegion.getChildren()) { if(child instanceof TabHeaderSkin){ TabHeaderSkin tabHeaderSkin = (TabHeaderSkin) child; if (tabHeaderSkin.getTab().equals(tab)) { return tabHeaderSkin; } } } return null; } private boolean tabsFit() { double headerPrefWidth = snapSize(headersRegion.prefWidth(-1)); double controlTabWidth = 2 * snapSize(rightControlButtons.prefWidth(-1)); double visibleWidth = headerPrefWidth + controlTabWidth + firstTabIndent() + SPACER; return visibleWidth < getWidth(); } private void ensureSelectedTabIsVisible() { double offset = 0.0; double selectedTabOffset = 0.0; double selectedTabWidth = 0.0; for (Node node : headersRegion.getChildren()) { if(node instanceof TabHeaderSkin){ TabHeaderSkin tabHeader = (TabHeaderSkin) node; double tabHeaderPrefWidth = snapSize(tabHeader.prefWidth(-1)); if (selectedTab != null && selectedTab.equals(tabHeader.getTab())) { selectedTabOffset = offset; selectedTabWidth = tabHeaderPrefWidth; } offset += tabHeaderPrefWidth; } } runTimeline(selectedTabOffset + 1, selectedTabWidth - 2); } private void runTimeline(double newTransX, double newWidth) { double oldWidth = selectedTabLine.getEndX(); double oldTransX = selectedTabLineOffset; selectedTabLineOffset = newTransX; double transDiff = newTransX - oldTransX; Timeline timeline; if(transDiff > 0) { timeline = new Timeline( new KeyFrame( Duration.ZERO, new KeyValue(selectedTabLine.endXProperty(), oldWidth, Interpolator.EASE_BOTH), new KeyValue(selectedTabLine.translateXProperty(), oldTransX + offsetStart, Interpolator.EASE_BOTH)), new KeyFrame( Duration.seconds(0.15), new KeyValue(selectedTabLine.endXProperty(), transDiff, Interpolator.EASE_BOTH), new KeyValue(selectedTabLine.translateXProperty(), oldTransX + offsetStart, Interpolator.EASE_BOTH)), new KeyFrame( Duration.seconds(0.33), new KeyValue(selectedTabLine.endXProperty(), newWidth, Interpolator.EASE_BOTH), new KeyValue(selectedTabLine.translateXProperty(), newTransX + offsetStart, Interpolator.EASE_BOTH)) ); } else { timeline = new Timeline( new KeyFrame( Duration.ZERO, new KeyValue(selectedTabLine.endXProperty(), oldWidth, Interpolator.EASE_BOTH), new KeyValue(selectedTabLine.translateXProperty(), oldTransX + offsetStart, Interpolator.EASE_BOTH)), new KeyFrame( Duration.seconds(0.15), new KeyValue(selectedTabLine.endXProperty(), -transDiff, Interpolator.EASE_BOTH), new KeyValue(selectedTabLine.translateXProperty(), newTransX + offsetStart, Interpolator.EASE_BOTH)), new KeyFrame( Duration.seconds(0.33), new KeyValue(selectedTabLine.endXProperty(), newWidth, Interpolator.EASE_BOTH), new KeyValue(selectedTabLine.translateXProperty(), newTransX + offsetStart, Interpolator.EASE_BOTH)) ); } timeline.play(); } public double getScrollOffset() { return scrollOffset; } private void validateScrollOffset() { setScrollOffset(getScrollOffset()); } public void setScrollOffset(double newScrollOffset) { // work out the visible width of the tab header double tabPaneWidth = snapSize(getSkinnable().getWidth()); double controlTabWidth = 2 * snapSize(rightControlButtons.getWidth()); double visibleWidth = tabPaneWidth - controlTabWidth - firstTabIndent() - SPACER; // measure the width of all tabs double offset = 0.0; for (Node node : headersRegion.getChildren()) { if(node instanceof TabHeaderSkin){ TabHeaderSkin tabHeader = (TabHeaderSkin) node; double tabHeaderPrefWidth = snapSize(tabHeader.prefWidth(-1)); offset += tabHeaderPrefWidth; } } double actualNewScrollOffset; if ((visibleWidth - newScrollOffset) > offset && newScrollOffset < 0) { // need to make sure the right-most tab is attached to the // right-hand side of the tab header (e.g. if the tab header area width // is expanded), and if it isn't modify the scroll offset to bring // it into line. See RT-35194 for a test case. actualNewScrollOffset = visibleWidth - offset; } else if (newScrollOffset > 0) { // need to prevent the left-most tab from becoming detached // from the left-hand side of the tab header. actualNewScrollOffset = 0; } else { actualNewScrollOffset = newScrollOffset; } if (actualNewScrollOffset != scrollOffset) { scrollOffset = actualNewScrollOffset; headersRegion.requestLayout(); selectedTabLine.setTranslateX(selectedTabLineOffset + scrollOffset); } } private double firstTabIndent() { switch (getSkinnable().getSide()) { case TOP: case BOTTOM: return snappedLeftInset(); case RIGHT: case LEFT: return snappedTopInset(); default: return 0; } } @Override protected double computePrefWidth(double height) { double padding = isHorizontal() ? snappedLeftInset() + snappedRightInset() : snappedTopInset() + snappedBottomInset(); return snapSize(headersRegion.prefWidth(height)) + 2 * rightControlButtons.prefWidth(height) + firstTabIndent() + SPACER + padding; } @Override protected double computePrefHeight(double width) { double padding = isHorizontal() ? snappedTopInset() + snappedBottomInset() : snappedLeftInset() + snappedRightInset(); return snapSize(headersRegion.prefHeight(-1)) + padding; } @Override public double getBaselineOffset() { if (getSkinnable().getSide() == Side.TOP) { return headersRegion.getBaselineOffset() + snappedTopInset(); } return 0; } @Override protected void layoutChildren() { final double leftInset = snappedLeftInset(); final double rightInset = snappedRightInset(); final double topInset = snappedTopInset(); final double bottomInset = snappedBottomInset(); double w = snapSize(getWidth()) - (isHorizontal() ? leftInset + rightInset : topInset + bottomInset); double h = snapSize(getHeight()) - (isHorizontal() ? topInset + bottomInset : leftInset + rightInset); double tabBackgroundHeight = snapSize(prefHeight(-1)); double headersPrefWidth = snapSize(headersRegion.prefWidth(-1)); double headersPrefHeight = snapSize(headersRegion.prefHeight(-1)); rightControlButtons.showTabsMenu(!tabsFit()); leftControlButtons.showTabsMenu(!tabsFit()); updateHeaderClip(); headersRegion.requestLayout(); // RESIZE CONTROL BUTTONS double btnWidth = snapSize(rightControlButtons.prefWidth(-1)); final double btnHeight = rightControlButtons.prefHeight(btnWidth); rightControlButtons.resize(btnWidth, btnHeight); leftControlButtons.resize(btnWidth, btnHeight); // POSITION TABS headersRegion.resize(headersPrefWidth, headersPrefHeight); if (isFloatingStyleClass()) { headerBackground.setVisible(false); } else { headerBackground.resize(snapSize(getWidth()), snapSize(getHeight())); headerBackground.setVisible(true); } double startX = 0; double startY = 0; double controlStartX = 0; double controlStartY = 0; Side tabPosition = getSkinnable().getSide(); if (tabPosition.equals(Side.TOP)) { startX = leftInset; startY = tabBackgroundHeight - headersPrefHeight - bottomInset; controlStartX = w - btnWidth + leftInset; controlStartY = snapSize(getHeight()) - btnHeight - bottomInset; } else if (tabPosition.equals(Side.RIGHT)) { startX = topInset; startY = tabBackgroundHeight - headersPrefHeight - leftInset; controlStartX = w - btnWidth + topInset; controlStartY = snapSize(getHeight()) - btnHeight - leftInset; } else if (tabPosition.equals(Side.BOTTOM)) { startX = snapSize(getWidth()) - headersPrefWidth - leftInset; startY = tabBackgroundHeight - headersPrefHeight - topInset; controlStartX = rightInset; controlStartY = snapSize(getHeight()) - btnHeight - topInset; } else if (tabPosition.equals(Side.LEFT)) { startX = snapSize(getWidth()) - headersPrefWidth - topInset; startY = tabBackgroundHeight - headersPrefHeight - rightInset; controlStartX = leftInset; controlStartY = snapSize(getHeight()) - btnHeight - rightInset; } if (headerBackground.isVisible()) { positionInArea(headerBackground, 0, 0, snapSize(getWidth()), snapSize(getHeight()), 0, HPos.CENTER, VPos.CENTER); } positionInArea(headersRegion, startX + btnWidth, startY, w, h, 0, HPos.LEFT, VPos.CENTER); positionInArea(rightControlButtons, controlStartX, controlStartY, btnWidth, btnHeight, 0, HPos.CENTER, VPos.CENTER); positionInArea(leftControlButtons, 0, controlStartY, btnWidth, btnHeight, 0, HPos.CENTER, VPos.CENTER); if (!initialized) { double offset = 0.0; double selectedTabOffset = 0.0; double selectedTabWidth = 0.0; for (Node node : headersRegion.getChildren()) { if(node instanceof TabHeaderSkin){ TabHeaderSkin tabHeader = (TabHeaderSkin) node; double tabHeaderPrefWidth = snapSize(tabHeader.prefWidth(-1)); if (selectedTab != null && selectedTab.equals(tabHeader.getTab())) { selectedTabOffset = offset; selectedTabWidth = tabHeaderPrefWidth; } offset += tabHeaderPrefWidth; } } final double selectedTabStartX = selectedTabOffset; runTimeline(selectedTabStartX + 1, selectedTabWidth-2); initialized = true; } } } /* End TabHeaderArea */ private static int CLOSE_LBL_SIZE = 12; class TabHeaderSkin extends StackPane { private final Tab tab; public Tab getTab() { return tab; } private Label tabText; // private Label closeLabel; private BorderPane inner; private Tooltip oldTooltip; private Tooltip tooltip; private C3DRippler rippler; private boolean isClosing = false; private MultiplePropertyChangeListenerHandler listener = new MultiplePropertyChangeListenerHandler(param -> { handlePropertyChanged(param); return null; }); private final ListChangeListener<String> styleClassListener = new ListChangeListener<String>() { @Override public void onChanged(Change<? extends String> c) { getStyleClass().setAll(tab.getStyleClass()); } }; private final WeakListChangeListener<String> weakStyleClassListener = new WeakListChangeListener<>(styleClassListener); public TabHeaderSkin(final Tab tab) { getStyleClass().setAll(tab.getStyleClass()); setId(tab.getId()); setStyle(tab.getStyle()); this.tab = tab; tabText = new Label(tab.getText(), tab.getGraphic()); tabText.setFont(new Font(16)); tabText.setStyle("-fx-font-weight: BOLD"); tabText.setPadding(new Insets(5, 10, 5, 10)); tabText.getStyleClass().setAll("tab-label"); // TODO: close label animation // closeLabel = new Label(); // closeLabel.setPrefSize(CLOSE_LBL_SIZE, CLOSE_LBL_SIZE); // closeLabel.setText("X"); // closeLabel.setTextFill(Color.WHITE); // closeLabel.getStyleClass().setAll("tab-close-button"); // closeLabel.setOnMousePressed(new EventHandler<MouseEvent>() { // @Override // public void handle(MouseEvent me) { // Tab tab = getTab(); // TabPaneBehavior behavior = getBehavior(); // if (behavior.canCloseTab(tab)) { // behavior.closeTab(tab); // setOnMousePressed(null); updateGraphicRotation(); inner = new BorderPane(); inner.setCenter(tabText); inner.getStyleClass().add("tab-container"); inner.setRotate(getSkinnable().getSide().equals(Side.BOTTOM) ? 180.0F : 0.0F); rippler = new C3DRippler(inner, RipplerPos.FRONT); rippler.setRipplerFill(ripplerColor); // rippler.getChildren().add(closeLabel); // StackPane.setAlignment(closeLabel, Pos.TOP_RIGHT); getChildren().addAll(rippler); tooltip = tab.getTooltip(); if (tooltip != null) { Tooltip.install(this, tooltip); oldTooltip = tooltip; } if (tab.isSelected()) { tabText.setTextFill(selectedTabText); } else { tabText.setTextFill(unSelectedTabText); } // closeLabel.setVisible(tab.isSelected()); tab.selectedProperty().addListener((o, oldVal, newVal) -> { if (newVal) { tabText.setTextFill(selectedTabText); } else { tabText.setTextFill(unSelectedTabText); } // closeLabel.setVisible(newVal); }); listener.registerChangeListener(tab.closableProperty(), "CLOSABLE"); listener.registerChangeListener(tab.selectedProperty(), "SELECTED"); listener.registerChangeListener(tab.textProperty(), "TEXT"); listener.registerChangeListener(tab.graphicProperty(), "GRAPHIC"); listener.registerChangeListener(tab.contextMenuProperty(), "CONTEXT_MENU"); listener.registerChangeListener(tab.tooltipProperty(), "TOOLTIP"); listener.registerChangeListener(tab.disableProperty(), "DISABLE"); listener.registerChangeListener(tab.styleProperty(), "STYLE"); tab.getStyleClass().addListener(weakStyleClassListener); listener.registerChangeListener(getSkinnable().tabClosingPolicyProperty(), "TAB_CLOSING_POLICY"); listener.registerChangeListener(getSkinnable().sideProperty(), "SIDE"); listener.registerChangeListener(getSkinnable().rotateGraphicProperty(), "ROTATE_GRAPHIC"); listener.registerChangeListener(getSkinnable().tabMinWidthProperty(), "TAB_MIN_WIDTH"); listener.registerChangeListener(getSkinnable().tabMaxWidthProperty(), "TAB_MAX_WIDTH"); listener.registerChangeListener(getSkinnable().tabMinHeightProperty(), "TAB_MIN_HEIGHT"); listener.registerChangeListener(getSkinnable().tabMaxHeightProperty(), "TAB_MAX_HEIGHT"); getProperties().put(Tab.class, tab); getProperties().put(ContextMenu.class, tab.getContextMenu()); setOnContextMenuRequested((ContextMenuEvent me) -> { if (getTab().getContextMenu() != null) { getTab().getContextMenu().show(inner, me.getScreenX(), me.getScreenY()); me.consume(); } }); setOnMouseReleased(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent me) { if (isDragged) { isDragged = false; return; } if (getTab().isDisable()) { return; } if (me.getButton().equals(MouseButton.MIDDLE)) { if (showCloseButton()) { Tab tab = getTab(); TabPaneBehavior behavior = getBehavior(); if (behavior.canCloseTab(tab)) { removeListeners(tab); behavior.closeTab(tab); } } } else if (me.getButton().equals(MouseButton.PRIMARY)) { setOpacity(1); getBehavior().selectTab(getTab()); } } }); setOnMouseEntered((o) -> { // closeLabel.setVisible(true); if (!tab.isSelected()) { setOpacity(0.7); } }); setOnMouseExited((o) -> { // if (!tab.isSelected()) { // closeLabel.setVisible(false); setOpacity(1); }); // initialize pseudo-class state pseudoClassStateChanged(SELECTED_PSEUDOCLASS_STATE, tab.isSelected()); pseudoClassStateChanged(DISABLED_PSEUDOCLASS_STATE, tab.isDisable()); final Side side = getSkinnable().getSide(); pseudoClassStateChanged(TOP_PSEUDOCLASS_STATE, (side == Side.TOP)); pseudoClassStateChanged(RIGHT_PSEUDOCLASS_STATE, (side == Side.RIGHT)); pseudoClassStateChanged(BOTTOM_PSEUDOCLASS_STATE, (side == Side.BOTTOM)); pseudoClassStateChanged(LEFT_PSEUDOCLASS_STATE, (side == Side.LEFT)); } private void handlePropertyChanged(final String p) { if ("CLOSABLE".equals(p)) { inner.requestLayout(); requestLayout(); } else if ("SELECTED".equals(p)) { pseudoClassStateChanged(SELECTED_PSEUDOCLASS_STATE, tab.isSelected()); // Need to request a layout pass for inner because if the width // and height didn't not change the label or close button may have // changed. inner.requestLayout(); requestLayout(); } else if ("TEXT".equals(p)) { tabText.setText(getTab().getText()); } else if ("GRAPHIC".equals(p)) { tabText.setGraphic(getTab().getGraphic()); } else if ("CONTEXT_MENU".equals(p)) { // todo } else if ("TOOLTIP".equals(p)) { // uninstall the old tooltip if (oldTooltip != null) { Tooltip.uninstall(this, oldTooltip); } tooltip = tab.getTooltip(); if (tooltip != null) { // install new tooltip and save as old tooltip. Tooltip.install(this, tooltip); oldTooltip = tooltip; } } else if ("DISABLE".equals(p)) { pseudoClassStateChanged(DISABLED_PSEUDOCLASS_STATE, tab.isDisable()); inner.requestLayout(); requestLayout(); } else if ("STYLE".equals(p)) { setStyle(tab.getStyle()); } else if ("TAB_CLOSING_POLICY".equals(p)) { inner.requestLayout(); requestLayout(); } else if ("SIDE".equals(p)) { final Side side = getSkinnable().getSide(); pseudoClassStateChanged(TOP_PSEUDOCLASS_STATE, (side == Side.TOP)); pseudoClassStateChanged(RIGHT_PSEUDOCLASS_STATE, (side == Side.RIGHT)); pseudoClassStateChanged(BOTTOM_PSEUDOCLASS_STATE, (side == Side.BOTTOM)); pseudoClassStateChanged(LEFT_PSEUDOCLASS_STATE, (side == Side.LEFT)); inner.setRotate(side == Side.BOTTOM ? 180.0F : 0.0F); if (getSkinnable().isRotateGraphic()) { updateGraphicRotation(); } } else if ("ROTATE_GRAPHIC".equals(p)) { updateGraphicRotation(); } else if ("TAB_MIN_WIDTH".equals(p)) { requestLayout(); getSkinnable().requestLayout(); } else if ("TAB_MAX_WIDTH".equals(p)) { requestLayout(); getSkinnable().requestLayout(); } else if ("TAB_MIN_HEIGHT".equals(p)) { requestLayout(); getSkinnable().requestLayout(); } else if ("TAB_MAX_HEIGHT".equals(p)) { requestLayout(); getSkinnable().requestLayout(); } } private void updateGraphicRotation() { if (tabText.getGraphic() != null) { tabText.getGraphic().setRotate(getSkinnable().isRotateGraphic() ? 0.0F : (getSkinnable().getSide().equals(Side.RIGHT) ? -90.0F : (getSkinnable().getSide().equals(Side.LEFT) ? 90.0F : 0.0F))); } } private boolean showCloseButton() { return tab.isClosable() && (getSkinnable().getTabClosingPolicy().equals(TabClosingPolicy.ALL_TABS) || getSkinnable().getTabClosingPolicy().equals(TabClosingPolicy.SELECTED_TAB)); } private final DoubleProperty animationTransition = new SimpleDoubleProperty(this, "animationTransition", 1.0) { @Override protected void invalidated() { requestLayout(); } }; private void removeListeners(Tab tab) { listener.dispose(); ContextMenu menu = tab.getContextMenu(); if (menu != null) { menu.getItems().clear(); } inner.getChildren().clear(); getChildren().clear(); } @Override protected double computePrefWidth(double height) { double minWidth = snapSize(getSkinnable().getTabMinWidth()); double maxWidth = snapSize(getSkinnable().getTabMaxWidth()); double paddingRight = snappedRightInset(); double paddingLeft = snappedLeftInset(); double tmpPrefWidth = snapSize(tabText.prefWidth(-1)); // only include the close button width if it is relevant // if (showCloseButton()) { // tmpPrefWidth += snapSize(closeLabel.prefWidth(-1)); if (tmpPrefWidth > maxWidth) { tmpPrefWidth = maxWidth; } else if (tmpPrefWidth < minWidth) { tmpPrefWidth = minWidth; } tmpPrefWidth += paddingRight + paddingLeft; return tmpPrefWidth; } @Override protected double computePrefHeight(double width) { double minHeight = snapSize(getSkinnable().getTabMinHeight()); double maxHeight = snapSize(getSkinnable().getTabMaxHeight()); double paddingTop = snappedTopInset(); double paddingBottom = snappedBottomInset(); double tmpPrefHeight = snapSize(tabText.prefHeight(width)); if (tmpPrefHeight > maxHeight) { tmpPrefHeight = maxHeight; } else if (tmpPrefHeight < minHeight) { tmpPrefHeight = minHeight; } tmpPrefHeight += paddingTop + paddingBottom; return tmpPrefHeight; } @Override protected void layoutChildren() { double w = (snapSize(getWidth()) - snappedRightInset() - snappedLeftInset()) * animationTransition.getValue(); rippler.resize(w, snapSize(getHeight()) - snappedTopInset() - snappedBottomInset()); rippler.relocate(snappedLeftInset(), snappedTopInset()); } @Override protected void setWidth(double value) { super.setWidth(value); } @Override protected void setHeight(double value) { super.setHeight(value); } } /* End TabHeaderSkin */ private static final PseudoClass SELECTED_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("selected"); private static final PseudoClass TOP_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("top"); private static final PseudoClass BOTTOM_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("bottom"); private static final PseudoClass LEFT_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("left"); private static final PseudoClass RIGHT_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("right"); private static final PseudoClass DISABLED_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("disabled"); private AnchorPane tabsContainer; private AnchorPane tabsContainerHolder; class TabContentRegion extends StackPane { private Tab tab; private InvalidationListener tabContentListener = valueModel -> { updateContent(); }; private InvalidationListener tabSelectedListener = new InvalidationListener() { @Override public void invalidated(Observable valueModel) { setVisible(tab.isSelected()); } }; private WeakInvalidationListener weakTabContentListener = new WeakInvalidationListener(tabContentListener); private WeakInvalidationListener weakTabSelectedListener = new WeakInvalidationListener(tabSelectedListener); public Tab getTab() { return tab; } public TabContentRegion(Tab tab) { getStyleClass().setAll("tab-content-area"); setManaged(false); this.tab = tab; updateContent(); setVisible(tab.isSelected()); tab.selectedProperty().addListener(weakTabSelectedListener); tab.contentProperty().addListener(weakTabContentListener); } private void updateContent() { Node newContent = getTab().getContent(); if (newContent == null) { getChildren().clear(); } else { getChildren().setAll(newContent); } } private void removeListeners(Tab tab) { tab.selectedProperty().removeListener(weakTabSelectedListener); tab.contentProperty().removeListener(weakTabContentListener); } } /* End TabContentRegion */ private enum ArrowPosition { RIGHT, LEFT; } class TabControlButtons extends StackPane { private StackPane inner; private Icon downArrowBtn; private boolean showControlButtons, isLeftArrow; public TabControlButtons(ArrowPosition pos) { getStyleClass().setAll("control-buttons-tab"); isLeftArrow = pos == ArrowPosition.LEFT; downArrowBtn = new Icon(isLeftArrow ? "CHEVRON_LEFT" : "CHEVRON_RIGHT","1.5em"); downArrowBtn.setPadding(new Insets(7)); downArrowBtn.getStyleClass().setAll("tab-down-button"); downArrowBtn.setVisible(isShowTabsMenu()); downArrowBtn.setOnMouseClicked(me -> { }); C3DRippler arrowRippler = new C3DRippler(downArrowBtn,RipplerMask.CIRCLE,RipplerPos.BACK); arrowRippler.ripplerFillProperty().bind(downArrowBtn.textFillProperty()); StackPane.setMargin(downArrowBtn, new Insets(0,0,0,isLeftArrow?-4:4)); inner = new StackPane() { @Override protected double computePrefWidth(double height) { double pw; double maxArrowWidth = !isShowTabsMenu() ? 0 : snapSize(arrowRippler.prefWidth(getHeight())); pw = 0.0F; if (isShowTabsMenu()) { pw += maxArrowWidth; } if (pw > 0) { pw += snappedLeftInset() + snappedRightInset(); } return pw; } @Override protected double computePrefHeight(double width) { double height = 0.0F; if (isShowTabsMenu()) { height = Math.max(height, snapSize(arrowRippler.prefHeight(width))); } if (height > 0) { height += snappedTopInset() + snappedBottomInset(); } return height; } @Override protected void layoutChildren() { if (isShowTabsMenu()) { double x = 0; double y = snappedTopInset(); double w = snapSize(getWidth()) - x + snappedLeftInset(); double h = snapSize(getHeight()) - y + snappedBottomInset(); positionArrow(arrowRippler, x, y, w, h); } } private void positionArrow(C3DRippler btn, double x, double y, double width, double height) { btn.resize(width, height); positionInArea(btn, x, y, width, height, 0, HPos.CENTER, VPos.CENTER); } }; inner.getStyleClass().add("container"); inner.getChildren().add(arrowRippler); StackPane.setMargin(arrowRippler, new Insets(0,5,0,5)); getChildren().add(inner); showControlButtons = false; if (isShowTabsMenu()) { showControlButtons = true; requestLayout(); } } private boolean showTabsMenu = false; private void showTabsMenu(boolean value) { final boolean wasTabsMenuShowing = isShowTabsMenu(); this.showTabsMenu = value; if (showTabsMenu && !wasTabsMenuShowing) { downArrowBtn.setVisible(true); showControlButtons = true; inner.requestLayout(); tabHeaderArea.requestLayout(); } else if (!showTabsMenu && wasTabsMenuShowing) { hideControlButtons(); } } private boolean isShowTabsMenu() { return showTabsMenu; } @Override protected double computePrefWidth(double height) { double pw = snapSize(inner.prefWidth(height)); if (pw > 0) { pw += snappedLeftInset() + snappedRightInset(); } return pw; } @Override protected double computePrefHeight(double width) { return Math.max(getSkinnable().getTabMinHeight(), snapSize(inner.prefHeight(width))) + snappedTopInset() + snappedBottomInset(); } @Override protected void layoutChildren() { double x = snappedLeftInset(); double y = snappedTopInset(); double w = snapSize(getWidth()) - x + snappedRightInset(); double h = snapSize(getHeight()) - y + snappedBottomInset(); if (showControlButtons) { showControlButtons(); showControlButtons = false; } inner.resize(w, h); positionInArea(inner, x, y, w, h, 0, HPos.CENTER, VPos.BOTTOM); } private void showControlButtons() { setVisible(true); } private void hideControlButtons() { // If the scroll arrows or tab menu is still visible we don't want // to hide it animate it back it. if (isShowTabsMenu()) { showControlButtons = true; } else { setVisible(false); } // This needs to be called when we are in the left tabPosition // to allow for the clip offset to move properly (otherwise // it jumps too early - before the animation is done). requestLayout(); } } /* End TabControlButtons*/ class TabMenuItem extends RadioMenuItem { Tab tab; private InvalidationListener disableListener = new InvalidationListener() { @Override public void invalidated(Observable o) { setDisable(tab.isDisable()); } }; private WeakInvalidationListener weakDisableListener = new WeakInvalidationListener(disableListener); public TabMenuItem(final Tab tab) { super(tab.getText(), C3DTabPaneSkin.clone(tab.getGraphic())); this.tab = tab; setDisable(tab.isDisable()); tab.disableProperty().addListener(weakDisableListener); } public Tab getTab() { return tab; } public void dispose() { tab.disableProperty().removeListener(weakDisableListener); } } }
package com.chap.memo.memoNodes; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import com.eaio.uuid.UUID; import com.google.appengine.api.datastore.Blob; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; public class MemoShardStore { // These can be tweaked to modify performance and memory usage of the // application: protected static final int SHARDSIZE = 40000; // How many entries does a // shard have protected static final int NOFSHARDS = 20; // How many shards do we keep in // cache protected static final int NOFINDEXES = 25; // How many entries does a // MemoGroupIndex hold protected static UUID INSTANCEID = new UUID(); static DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); static MemoShard currentShard = new MemoShard(); static MemoGroupIndex rootIndex = new MemoGroupIndex(); static Map<Key, MemoShard> shards = Collections .synchronizedMap(new MyMap<Key, MemoShard>(NOFSHARDS, new Float( 0.5), true)); static protected void storeShard(MemoShard shard) { // What if stored before? Get old key from index! Should actually never // happen, due to immutable nature of nodes Entity shardEntity; if (shard.index.shardKey != null) { shardEntity = new Entity(shard.index.shardKey); } else { shardEntity = new Entity("MemoShardData"); } byte[] data = shard.data.serialize(); // TODO: What to do if size is too big? Split in multiple Properties? // System.out.println("Storing: "+data.length + " bytes in shard."); shardEntity.setProperty("shard", new Blob(data)); shardEntity.setProperty("size", data.length); datastore.put(shardEntity); Key shardKey = shardEntity.getKey(); Entity shardIndex; if (shard.index.myKey != null) { shardIndex = new Entity(shard.index.myKey); } else { shardIndex = new Entity("MemoShardIndex", shardKey); } shard.index.shardKey = shardKey; shardIndex.setProperty("index", new Blob(shard.index.serialize())); datastore.put(shardIndex); shard.index.myKey = shardIndex.getKey(); rootIndex = rootIndex.addIndex(shard.index); storeRootIndex();//Required, or else we miss on newest shards //System.out.println("Stored: "+shardKey+" -> "+shardIndex.getKey()); } static protected void storeIndex(MemoIndex index) { Entity shardIndex; if (index.myKey != null) { shardIndex = new Entity(index.myKey); } else { shardIndex = new Entity("MemoIndex"); } shardIndex.setProperty("index", new Blob(index.serialize())); datastore.put(shardIndex); index.myKey = shardIndex.getKey(); //System.out.println("Stored index:"+index.myKey); } static protected MemoIndex loadIndex(Key key) { try { Blob blob = (Blob) datastore.get(key).getProperty("index"); byte[] data = blob.getBytes(); MemoIndex res = MemoIndex.unserialize(data); res.myKey = key; //System.out.println("loaded index:"+res.type+":"+res.myKey); return res; } catch (EntityNotFoundException e) { e.printStackTrace(); return null; } } static protected void storeRootIndex() { Entity shardIndex; if (rootIndex.myKey != null) { shardIndex = new Entity(rootIndex.myKey); } else { shardIndex = new Entity("rootIndex"); } shardIndex.setProperty("index", new Blob(rootIndex.serialize())); shardIndex.setProperty("InstanceId", INSTANCEID.toString()); datastore.put(shardIndex); rootIndex.myKey = shardIndex.getKey(); //System.out.println("Stored rootindex:"+rootIndex.myKey + " with "+rootIndex.subindexes.size() + " elements"); } static protected ArrayList<MemoIndex> loadRootIndexes() { Query q = new Query("rootIndex"); PreparedQuery pq = datastore.prepare(q); ArrayList<MemoIndex> result = new ArrayList<MemoIndex>(pq.countEntities()); Iterator<Entity> iter = pq.asIterator(); while (iter.hasNext()) { Entity ent = iter.next(); byte[] data = ((Blob) ent.getProperty("index")).getBytes(); MemoIndex idx = MemoIndex.unserialize(data); idx.myKey = ent.getKey(); result.add(idx); } Collections.sort(result); /* for (MemoIndex idx: result){ System.out.println("loaded rootIndex:"+idx.type+":"+idx.myKey); } */ return result; } static protected MemoShardData loadShardData(Key key) { if (key == null) { System.out.println("Error: Shard with Null key requested!"); return null; } try { Entity shardData=datastore.get(key); Long size = (Long) shardData.getProperty("size"); byte[] data = new byte[size.intValue()]; data = ((Blob) shardData.getProperty("shard")) .getBytes(); // System.out.println("Loading: "+data.length + // " bytes from shard."); MemoShardData res = MemoShardData.unserialize(data); //System.out.println("loaded loadShardData:"+res.toString()+":"+res.nodes.size()); return res; } catch (EntityNotFoundException e) { e.printStackTrace(); return null; } } static protected Node findNewest(ArrayList<IndexKey> list, UUID nodeId, Date timestamp, Date before) { Iterator<IndexKey> iter = list.iterator(); //System.out.println("Searching through "+list.size()+" items"); //int count=0; while (iter.hasNext()) { //count++; IndexKey idxKey = iter.next(); if (idxKey.timestamp.before(timestamp)) { //System.out.println("time:"+count+"/"+list.size()); return null; } MemoIndex inner = MemoShardStore.loadIndex(idxKey.key); if (before != null && inner.lastTime.after(before)) { //System.out.println("tooNew:"+count+"/"+list.size()); return null; } if (inner.type.equals("MemoGroupIndex")) { MemoGroupIndex index = (MemoGroupIndex) inner; //System.out.println("recurse:"+count+"/"+list.size()); Node res = findNewest(index.subindexes, nodeId, timestamp, before); if (res != null) { return res; } } if (inner.type.equals("ShardIndex")) { MemoShardIndex index = (MemoShardIndex) inner; if (index.nodeids.contains(nodeId)) { MemoShardData data = MemoShardStore .loadShardData(index.shardKey); Node result = data.find(nodeId); Date nodeTime = result.getTimestamp(); if (nodeTime.after(timestamp)) { if (before == null || nodeTime.before(before) || nodeTime.equals(before)) { MemoShard shard = new MemoShard(); shard.index = index; shard.data = data; shards.put(idxKey.key, shard); //System.out.println("load:"+count+"/"+list.size()); return result; } } } else { //System.out.println("Not in "+inner.myKey); } } } //System.out.println("notFound:"+count+"/"+list.size()); return null; } static protected Node loadNode(UUID nodeId, Date before) { MemoShard shard = currentShard; // First check currentShard if (shard.index.nodeids.contains(nodeId)) { Node result = shard.data.find(nodeId); if (before == null || result.getTimestamp().before(before)) { //System.out.print("(current)"); return result; } } // Search in-memory cached shards synchronized (shards) { for (MemoShard next : shards.values()) { shard = next; if (shard.index.nodeids.contains(nodeId)) { Node result = shard.data.find(nodeId); if (before == null || result.getTimestamp().before(before) || result.getTimestamp().equals(before)) { //System.out.print("(shards)"); return result; } } } } ArrayList<MemoIndex> rootIndexes = MemoShardStore.loadRootIndexes(); Node result = null; Date timestamp = new Date(0); for (MemoIndex idx : rootIndexes) { // time ordered list; if (idx.firstTime.after(timestamp) && (before == null || idx.lastTime.before(before))) { MemoGroupIndex index = (MemoGroupIndex) idx; result = findNewest(index.subindexes, nodeId, timestamp, before); if (result != null) timestamp = result.getTimestamp(); } else { break; } } if (result != null) { //System.out.print("(loaded)"); return result; } System.out.println("Couldn't find node:"+nodeId); return null; } /* Published API */ static public void addNode(Node node) { currentShard.addNode(node); } static public Node findNode(UUID nodeId) { Node result = loadNode(nodeId, null); return result; } static public Node findBefore(UUID nodeId, Date timestamp) { Node result = loadNode(nodeId, timestamp); return result; } static public ArrayList<Node> findAll(UUID nodeId) { System.out.println("NOT IMPLEMENTED YET! FindAll called " + nodeId); // TODO: still needs to be implemented return new ArrayList<Node>(); } static public void emptyDB() { // create one big cleanup query String[] types = { "rootIndex", "MemoShardIndex", "MemoShardData", "MemoGroupIndex", "MemoIndex" }; for (String type : types) { Query q = new Query(type).setKeysOnly(); PreparedQuery pq = datastore.prepare(q); // int count = pq.countEntities(); // System.out.println("Deleting :"+count+" entries of type:"+type); for (Entity res : pq.asIterable()) { datastore.delete(res.getKey()); } } // Clean out memory, can only cleanup the ones I have reference to. INSTANCEID = new UUID(); rootIndex = new MemoGroupIndex(); shards.clear(); currentShard = new MemoShard(); System.out.println("Database cleared!"); } } @SuppressWarnings("rawtypes") class MyMap<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = 1L; MyMap(int capacity, float loadFactor, boolean order) { super(capacity, loadFactor, order); } protected boolean removeEldestEntry(Map.Entry eldest) { synchronized (this) { if (size() > MemoShardStore.NOFSHARDS) { this.remove(eldest.getKey()); } } return false; } } class MemoShard { MemoShardData data = new MemoShardData(); MemoShardIndex index = new MemoShardIndex(); public synchronized void addNode(Node node) { this.data.store(node); this.index.addNode(node); if (this.data.knownNodes.size() >= MemoShardStore.SHARDSIZE) { //System.out.println("New currentshard"); MemoShardStore.storeShard(this); //MemoShardStore.shards.put(this.index.myKey, this); MemoShardStore.shards.put(this.index.myKey, this); //System.out.println("node "+node.getValue()+" stored in shard:"+this.index.myKey); MemoShardStore.currentShard = new MemoShard(); } } } class MemoStorable implements Serializable { private static final long serialVersionUID = -5770613002073776843L; public byte[] serialize() { byte[] result = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); try { //zos.setLevel(4); zos.putNextEntry(new ZipEntry("Object")); ObjectOutputStream oos = new ObjectOutputStream(zos); //ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.flush(); oos.reset(); zos.closeEntry(); zos.flush(); result = bos.toByteArray(); bos.reset(); bos.close(); zos.close(); oos.close(); } catch (IOException e) { e.printStackTrace(); } return result; } public static MemoStorable _unserialize(byte[] data) { MemoStorable result = null; ByteArrayInputStream bis = new ByteArrayInputStream(data); ZipInputStream zis = new ZipInputStream(bis); try { zis.getNextEntry(); ObjectInputStream ios = new ObjectInputStream(zis); //ObjectInputStream ios = new ObjectInputStream(bis); result = (MemoStorable) ios.readObject(); zis.closeEntry(); bis.reset(); bis.close(); zis.close(); ios.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return result; } } class MemoShardData extends MemoStorable { private static final long serialVersionUID = -5770613002073776843L; HashMap<UUID, ArrayList<Node>> knownNodes = new HashMap<UUID, ArrayList<Node>>(MemoShardStore.SHARDSIZE); public static MemoShardData unserialize(byte[] data) { return (MemoShardData) _unserialize(data); } public Node find(UUID id) { ArrayList<Node> res = knownNodes.get(id); if (res != null && !res.isEmpty()) { Node result = null; Iterator<Node> iter = res.iterator(); while (iter.hasNext()) { Node next = iter.next(); if (result == null || next.getTimestamp().after(result.getTimestamp())) { result = next; } } return result; } return null; } public Node findBefore(UUID id, Date timestamp) { ArrayList<Node> res = knownNodes.get(id); if (res != null && !res.isEmpty()) { Node result = null; Iterator<Node> iter = res.iterator(); while (iter.hasNext()) { Node next = iter.next(); if (next.getTimestamp().before(timestamp)) { if (result == null || next.getTimestamp().after(result.getTimestamp())) { result = next; } } } return result; } return null; } public void store(Node node) { ArrayList<Node> cur = knownNodes.get(node.getId()); if (cur != null) { int size = cur.size(); boolean found = false; for (int i = 0; i < size; i++) { Date comp = cur.get(i).getTimestamp(); if (node.getTimestamp().equals(comp) || comp.before(node.getTimestamp())) { cur.add(i, node); found = true; break; } } if (!found) { cur.add(node); } } else { cur = new ArrayList<Node>(3); cur.add(node); } knownNodes.put(node.getId(), cur); } public ArrayList<Node> findAll(UUID id) { return knownNodes.get(id); } } class MemoIndex extends MemoStorable implements Comparable<MemoIndex> { private static final long serialVersionUID = 8232550041630847696L; Key myKey = null; Date firstTime = null; Date lastTime = null; String type = "generic"; public static MemoIndex unserialize(byte[] data) { MemoIndex index = (MemoIndex) _unserialize(data); if (index.type.equals("ShardIndex")) return (MemoShardIndex) index; if (index.type.equals("ShardGroupIndex")) return (MemoGroupIndex) index; return index; } @Override public int compareTo(MemoIndex o) { return -1 * (this.firstTime.compareTo(o.firstTime)); } } class MemoGroupIndex extends MemoIndex { private static final long serialVersionUID = 2550902839122518068L; ArrayList<IndexKey> subindexes = new ArrayList<IndexKey>( MemoShardStore.NOFINDEXES); public MemoGroupIndex() { this.type = "MemoGroupIndex"; } public MemoGroupIndex addIndex(MemoIndex index) { if (firstTime == null || firstTime.after(index.firstTime)) { firstTime = index.firstTime; } if (lastTime == null || lastTime.before(index.lastTime)) { lastTime = index.lastTime; } boolean found = false; for (int i = 0; i < this.subindexes.size(); i++) { if (this.subindexes.get(i).timestamp.after(index.firstTime)) { this.subindexes.add(i, new IndexKey(index.myKey, index.firstTime)); found = true; break; } } if (!found) this.subindexes.add(new IndexKey(index.myKey, index.firstTime)); if (this.subindexes.size() >= MemoShardStore.NOFINDEXES) { MemoGroupIndex newIdx = new MemoGroupIndex(); newIdx.myKey = this.myKey; this.myKey = null; MemoShardStore.storeIndex(this); //System.out.println("Stored groupIdx with "+this.subindexes.size() + " elements"); newIdx.addIndex(this); return newIdx; } //System.out.println("added index to groupIdx:"+this.subindexes.size()); return this; } public static MemoGroupIndex unserialize(byte[] data) { return (MemoGroupIndex) _unserialize(data); } } class MemoShardIndex extends MemoIndex { private static final long serialVersionUID = -5770613002073776843L; HashSet<UUID> nodeids = new HashSet<UUID>(MemoShardStore.SHARDSIZE); Key shardKey = null; public MemoShardIndex() { this.type = "ShardIndex"; } public void addNode(Node node) { this.nodeids.add(node.getId()); Date nodeTime = node.getTimestamp(); if (firstTime == null || firstTime.before(nodeTime)) { firstTime = nodeTime; } if (lastTime == null || lastTime.after(nodeTime)) { lastTime = nodeTime; } } public static MemoShardIndex unserialize(byte[] data) { return (MemoShardIndex) _unserialize(data); } } class IndexKey implements Serializable { private static final long serialVersionUID = -4804333997966989141L; Key key = null; Date timestamp = null; public IndexKey(Key key, Date timestamp) { this.key = key; this.timestamp = timestamp; } }
package it.unipi.di.acube.smaph; import it.unipi.di.acube.batframework.data.Tag; import java.util.HashMap; import java.util.List; public class QueryInformation { public HashMap<Tag, String[]> entityToBoldS2S3; public HashMap<String, Tag> boldToEntityS1; public HashMap<Tag, List<HashMap<String, Double>>> entityToFtrVects; public HashMap<Tag, List<String>> tagToBoldsS6; public Double webtotal; public List<String> allBoldsNS; }
package java.util.concurrent.locks; import java.util.concurrent.TimeUnit; import java.util.Collection; /** * , * :,A,B.A,B,A,C,A * : * A reentrant mutual exclusion {@link Lock} with the same basic * behavior and semantics as the implicit monitor lock accessed using * {@code synchronized} methods and statements, but with extended * capabilities. * * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last * successfully locking, but not yet unlocking it. A thread invoking * {@code lock} will return, successfully acquiring the lock, when * the lock is not owned by another thread. The method will return * immediately if the current thread already owns the lock. This can * be checked using methods {@link #isHeldByCurrentThread}, and {@link * #getHoldCount}. * * <p>The constructor for this class accepts an optional * <em>fairness</em> parameter. When set {@code true}, under * contention, locks favor granting access to the longest-waiting * thread. Otherwise this lock does not guarantee any particular * access order. Programs using fair locks accessed by many threads * may display lower overall throughput (i.e., are slower; often much * slower) than those using the default setting, but have smaller * variances in times to obtain locks and guarantee lack of * starvation. Note however, that fairness of locks does not guarantee * fairness of thread scheduling. Thus, one of many threads using a * fair lock may obtain it multiple times in succession while other * active threads are not progressing and not currently holding the * lock. * Also note that the untimed {@link #tryLock()} method does not * honor the fairness setting. It will succeed if the lock * is available even if other threads are waiting. * * <p>It is recommended practice to <em>always</em> immediately * follow a call to {@code lock} with a {@code try} block, most * typically in a before/after construction such as: * * <pre> {@code * class X { * private final ReentrantLock lock = new ReentrantLock(); * // ... * * public void m() { * lock.lock(); // block until condition holds * try { * // ... method body * } finally { * lock.unlock() * } * } * }}</pre> * * <p>In addition to implementing the {@link Lock} interface, this * class defines a number of {@code public} and {@code protected} * methods for inspecting the state of the lock. Some of these * methods are only useful for instrumentation and monitoring. * * <p>Serialization of this class behaves in the same way as built-in * locks: a deserialized lock is in the unlocked state, regardless of * its state when serialized. * * <p>This lock supports a maximum of 2147483647 recursive locks by * the same thread. Attempts to exceed this limit result in * {@link Error} throws from locking methods. * * @since 1.5 * @author Doug Lea */ public class ReentrantLock implements Lock, java.io.Serializable { private static final long serialVersionUID = 7373984872572414699L; /** final */ private final Sync sync; /** * ,AQS, * 1, * Base of synchronization control for this lock. Subclassed * into fair and nonfair versions below. Uses AQS state to * represent the number of holds on the lock. */ abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = -5179523762034025860L; /** * * Performs {@link Lock#lock}. The main reason for subclassing * is to allow fast path for nonfair version. */ abstract void lock(); /** * tryAcquire, * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState();//AQSstate if (c == 0) { //0/,cas if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { //0,,,state. int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } /** * * @param releases * @return */ protected final boolean tryRelease(int releases) { //,AQSstatereleases, int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) throw new IllegalMonitorStateException(); boolean free = false; if (c == 0) { //0,,null free = true; setExclusiveOwnerThread(null); } //state setState(c); return free; } protected final boolean isHeldExclusively() { // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); } final ConditionObject newCondition() { return new ConditionObject(); } // Methods relayed from outer class //,,null final Thread getOwner() { return getState() == 0 ? null : getExclusiveOwnerThread(); } final int getHoldCount() { return isHeldExclusively() ? getState() : 0; } final boolean isLocked() { return getState() != 0; } /** * Reconstitutes the instance from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } } static final class NonfairSync extends Sync { private static final long serialVersionUID = 7316153563782823691L; /** * cas * Performs lock. Try immediate barge, backing up to normal * acquire on failure. */ final void lock() { if (compareAndSetState(0, 1)) //cas, setExclusiveOwnerThread(Thread.currentThread()); else //,AQSacquire,,, acquire(1); } /** * AQStryAcquire,syncnonfairTryAcquire * @param acquires * @return */ protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } } static final class FairSync extends Sync { private static final long serialVersionUID = -3000897897090466540L; final void lock() { acquire(1); } /** * hasQueuedPredecessors,, * Fair version of tryAcquire. Don't grant access unless * recursive call or no waiters or is first. */ protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } } /** * ReentrantLock, * Creates an instance of {@code ReentrantLock}. * This is equivalent to using {@code ReentrantLock(false)}. */ public ReentrantLock() { sync = new NonfairSync(); } /** * ReentrantLock, * Creates an instance of {@code ReentrantLock} with the * given fairness policy. * * @param fair {@code true} if this lock should use a fair ordering policy */ public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); } /** * * sync,()lock * Acquires the lock. * * <p>Acquires the lock if it is not held by another thread and returns * immediately, setting the lock hold count to one. * * <p>If the current thread already holds the lock then the hold * count is incremented by one and the method returns immediately. * * <p>If the lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until the lock has been acquired, * at which time the lock hold count is set to one. */ public void lock() { sync.lock(); } /** * AQS * Acquires the lock unless the current thread is * {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the lock if it is not held by another thread and returns * immediately, setting the lock hold count to one. * * <p>If the current thread already holds this lock then the hold count * is incremented by one and the method returns immediately. * * <p>If the lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until one of two things happens: * * <ul> * * <li>The lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread. * * </ul> * * <p>If the lock is acquired by the current thread then the lock hold * count is set to one. * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; or * * <li>is {@linkplain Thread#interrupt interrupted} while acquiring * the lock, * * </ul> * * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to the * interrupt over normal or reentrant acquisition of the lock. * * @throws InterruptedException if the current thread is interrupted */ public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } /** * Acquires the lock only if it is not held by another thread at the time * of invocation. * * <p>Acquires the lock if it is not held by another thread and * returns immediately with the value {@code true}, setting the * lock hold count to one. Even when this lock has been set to use a * fair ordering policy, a call to {@code tryLock()} <em>will</em> * immediately acquire the lock if it is available, whether or not * other threads are currently waiting for the lock. * This &quot;barging&quot; behavior can be useful in certain * circumstances, even though it breaks fairness. If you want to honor * the fairness setting for this lock, then use * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } * which is almost equivalent (it also detects interruption). * * <p>If the current thread already holds this lock then the hold * count is incremented by one and the method returns {@code true}. * * <p>If the lock is held by another thread then this method will return * immediately with the value {@code false}. * * @return {@code true} if the lock was free and was acquired by the * current thread, or the lock was already held by the current * thread; and {@code false} otherwise */ public boolean tryLock() { return sync.nonfairTryAcquire(1); } /** * Acquires the lock if it is not held by another thread within the given * waiting time and the current thread has not been * {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the lock if it is not held by another thread and returns * immediately with the value {@code true}, setting the lock hold count * to one. If this lock has been set to use a fair ordering policy then * an available lock <em>will not</em> be acquired if any other threads * are waiting for the lock. This is in contrast to the {@link #tryLock()} * method. If you want a timed {@code tryLock} that does permit barging on * a fair lock then combine the timed and un-timed forms together: * * <pre> {@code * if (lock.tryLock() || * lock.tryLock(timeout, unit)) { * ... * }}</pre> * * <p>If the current thread * already holds this lock then the hold count is incremented by one and * the method returns {@code true}. * * <p>If the lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * * <ul> * * <li>The lock is acquired by the current thread; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified waiting time elapses * * </ul> * * <p>If the lock is acquired then the value {@code true} is returned and * the lock hold count is set to one. * * <p>If the current thread: * * <ul> * * <li>has its interrupted status set on entry to this method; or * * <li>is {@linkplain Thread#interrupt interrupted} while * acquiring the lock, * * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. * * <p>In this implementation, as this method is an explicit * interruption point, preference is given to responding to the * interrupt over normal or reentrant acquisition of the lock, and * over reporting the elapse of the waiting time. * * @param timeout the time to wait for the lock * @param unit the time unit of the timeout argument * @return {@code true} if the lock was free and was acquired by the * current thread, or the lock was already held by the current * thread; and {@code false} if the waiting time elapsed before * the lock could be acquired * @throws InterruptedException if the current thread is interrupted * @throws NullPointerException if the time unit is null */ public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } public void unlock() { sync.release(1); } public Condition newCondition() { return sync.newCondition(); } /** * Queries the number of holds on this lock by the current thread. * * <p>A thread has a hold on a lock for each lock action that is not * matched by an unlock action. * * <p>The hold count information is typically only used for testing and * debugging purposes. For example, if a certain section of code should * not be entered with the lock already held then we can assert that * fact: * * <pre> {@code * class X { * ReentrantLock lock = new ReentrantLock(); * // ... * public void m() { * assert lock.getHoldCount() == 0; * lock.lock(); * try { * // ... method body * } finally { * lock.unlock(); * } * } * }}</pre> * * @return the number of holds on this lock by the current thread, * or zero if this lock is not held by the current thread */ public int getHoldCount() { return sync.getHoldCount(); } /** * Queries if this lock is held by the current thread. * * <p>Analogous to the {@link Thread#holdsLock(Object)} method for * built-in monitor locks, this method is typically used for * debugging and testing. For example, a method that should only be * called while a lock is held can assert that this is the case: * * <pre> {@code * class X { * ReentrantLock lock = new ReentrantLock(); * // ... * * public void m() { * assert lock.isHeldByCurrentThread(); * // ... method body * } * }}</pre> * * <p>It can also be used to ensure that a reentrant lock is used * in a non-reentrant manner, for example: * * <pre> {@code * class X { * ReentrantLock lock = new ReentrantLock(); * // ... * * public void m() { * assert !lock.isHeldByCurrentThread(); * lock.lock(); * try { * // ... method body * } finally { * lock.unlock(); * } * } * }}</pre> * * @return {@code true} if current thread holds this lock and * {@code false} otherwise */ public boolean isHeldByCurrentThread() { return sync.isHeldExclusively(); } /** * Queries if this lock is held by any thread. This method is * designed for use in monitoring of the system state, * not for synchronization control. * * @return {@code true} if any thread holds this lock and * {@code false} otherwise */ public boolean isLocked() { return sync.isLocked(); } /** * Returns {@code true} if this lock has fairness set true. * * @return {@code true} if this lock has fairness set true */ public final boolean isFair() { return sync instanceof FairSync; } /** * Returns the thread that currently owns this lock, or * {@code null} if not owned. When this method is called by a * thread that is not the owner, the return value reflects a * best-effort approximation of current lock status. For example, * the owner may be momentarily {@code null} even if there are * threads trying to acquire the lock but have not yet done so. * This method is designed to facilitate construction of * subclasses that provide more extensive lock monitoring * facilities. * * @return the owner, or {@code null} if not owned */ protected Thread getOwner() { return sync.getOwner(); } /** * Queries whether any threads are waiting to acquire this lock. Note that * because cancellations may occur at any time, a {@code true} * return does not guarantee that any other thread will ever * acquire this lock. This method is designed primarily for use in * monitoring of the system state. * * @return {@code true} if there may be other threads waiting to * acquire the lock */ public final boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } /** * Queries whether the given thread is waiting to acquire this * lock. Note that because cancellations may occur at any time, a * {@code true} return does not guarantee that this thread * will ever acquire this lock. This method is designed primarily for use * in monitoring of the system state. * * @param thread the thread * @return {@code true} if the given thread is queued waiting for this lock * @throws NullPointerException if the thread is null */ public final boolean hasQueuedThread(Thread thread) { return sync.isQueued(thread); } /** * Returns an estimate of the number of threads waiting to * acquire this lock. The value is only an estimate because the number of * threads may change dynamically while this method traverses * internal data structures. This method is designed for use in * monitoring of the system state, not for synchronization * control. * * @return the estimated number of threads waiting for this lock */ public final int getQueueLength() { return sync.getQueueLength(); } /** * Returns a collection containing threads that may be waiting to * acquire this lock. Because the actual set of threads may change * dynamically while constructing this result, the returned * collection is only a best-effort estimate. The elements of the * returned collection are in no particular order. This method is * designed to facilitate construction of subclasses that provide * more extensive monitoring facilities. * * @return the collection of threads */ protected Collection<Thread> getQueuedThreads() { return sync.getQueuedThreads(); } public boolean hasWaiters(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); } public int getWaitQueueLength(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); } protected Collection<Thread> getWaitingThreads(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); } /** * Returns a string identifying this lock, as well as its lock state. * The state, in brackets, includes either the String {@code "Unlocked"} * or the String {@code "Locked by"} followed by the * {@linkplain Thread#getName name} of the owning thread. * * @return a string identifying this lock, as well as its lock state */ public String toString() { Thread o = sync.getOwner(); return super.toString() + ((o == null) ? "[Unlocked]" : "[Locked by thread " + o.getName() + "]"); } }
package org.biojava.bio.structure; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.biojava.bio.structure.io.PDBFileParser; import org.biojava.bio.structure.jama.Matrix; /** * * @author Andreas Prlic * @since 1.5 */ public class StructureTest extends TestCase { Structure structure; protected void setUp() { InputStream inStream = this.getClass().getResourceAsStream("/files/5pti_old.pdb"); assertNotNull(inStream); PDBFileParser pdbpars = new PDBFileParser(); try { structure = pdbpars.parsePDBFile(inStream) ; } catch (IOException e) { e.printStackTrace(); } assertNotNull(structure); assertEquals("structure does not contain one chain ", 2 ,structure.size()); } public void testSeqResParsing() { // System.out.println(structure); List<Chain> chains = structure.getChains(0); assertEquals(" nr of found chains not correct!",2,chains.size()); Chain c = chains.get(0); List<Group> seqResGroups = c.getSeqResGroups(); assertEquals("nr of SEQRES groups not correct!",58,seqResGroups.size()); List<Group> atomGroups = c.getAtomGroups(); Group g3 = seqResGroups.get(2); int indexAtom = atomGroups.indexOf(g3); //System.out.println(" index in atomlist: " + indexAtom); assertEquals("the SEQRES group can not be found in the ATOM list",2,indexAtom); Group g5 = atomGroups.get(5); assertEquals("The ATOM group can not be fond in the SEQRES list", 5,seqResGroups.indexOf(g5)); Chain c2 = chains.get(1); List<Group>atomGroups2 = c2.getAtomGroups(); Group g58 = atomGroups2.get(0); assertEquals("The group is not PO4","PO4", g58.getPDBName()); assertEquals("The group P04 should not be in the SEQRES list", -1 , seqResGroups.indexOf(g58)); } /** test if a PDB file can be parsed * @throws Exception */ public void testReadPDBFile() throws Exception { assertEquals("pdb code not set!","5PTI",structure.getPDBCode()); Chain c = structure.getChain(0); assertEquals("did not find the expected 58 amino acids!",58,c.getAtomGroups("amino").size()); assertTrue(c.getAtomGroups("hetatm").size() == 0); Chain c2 = structure.getChain(1); assertTrue(c2.getAtomGroups("hetatm").size() == 65); assertTrue(c2.getAtomGroups("nucleotide").size() == 0 ); List<Compound> compounds= structure.getCompounds(); assertTrue(compounds.size() == 1); Compound mol = compounds.get(0); assertTrue(mol.getMolName().startsWith("TRYPSIN INHIBITOR")); } public void testSSBondParsing() throws Exception { assertNotNull(structure); List<SSBond> ssbonds = structure.getSSBonds(); assertEquals("did not find the correct nr of SSBonds ",3,ssbonds.size()); String pdb1 = "SSBOND 1 CYS A 5 CYS A 55"; String pdb2 = "SSBOND 2 CYS A 14 CYS A 38"; SSBond bond1 = ssbonds.get(0); String b1 = bond1.toPDB(); assertTrue("PDB representation incorrect",pdb1.equals(b1.trim())); assertTrue("not right resnum1 " , bond1.getResnum1().equals("5")); assertTrue("not right resnum2 " , bond1.getResnum2().equals("55")); SSBond bond2 = ssbonds.get(1); String b2 = bond2.toPDB(); assertTrue("not right resnum1 " , bond2.getResnum1().equals("14")); assertTrue("not right resnum2 " , bond2.getResnum2().equals("38")); assertTrue("PDB representation incorrect",pdb2.equals(b2.trim())); } /** Tests that standard amino acids are working properly * @throws Exception */ public void testStandardAmino() throws Exception { AminoAcid arg = StandardAminoAcid.getAminoAcid("ARG"); assertTrue(arg.size() == 11 ); AminoAcid gly = StandardAminoAcid.getAminoAcid("G"); assertTrue(gly.size() == 4); } public void testHeader() { Map<String, Object> m = structure.getHeader(); assertNotNull(m); String classification = (String)m.get("classification"); assertTrue(classification.equals("PROTEINASE INHIBITOR (TRYPSIN)")); String idCode = (String)m.get("idCode"); assertEquals("the idCode in the Header is " + idCode + " and not 5PTI, as expected","5PTI",idCode); Float resolution = (Float) m.get("resolution"); assertEquals("the resolution in the Header is " + resolution + " and not 1.0, as expected",new Float(1.0),resolution); String technique = (String) m.get("technique"); String techShould = "X-RAY DIFFRACTION "; assertEquals("the technique in the Header is " + technique, techShould,technique); List <Compound> compounds = structure.getCompounds(); assertEquals("did not find the right number of compounds! ", 1, compounds.size()); Compound comp = compounds.get(0); assertEquals("did not get the right compounds info",true,comp.getMolName().startsWith("TRYPSIN INHIBITOR")); List<String> chainIds = comp.getChainId(); List<Chain> chains = comp.getChains(); assertEquals("the number of chain ids and chains did not match!",chainIds.size(),chains.size()); assertEquals("the chain ID did not match", chainIds.get(0),chains.get(0).getName()); } public void testPDBHeader(){ Map<String, Object> m = structure.getHeader(); PDBHeader header = structure.getPDBHeader(); String classification = (String)m.get("classification"); assertTrue(classification.equals(header.getClassification())); String idCode = (String)m.get("idCode"); assertTrue(idCode.equals(header.getIdCode())); Float resolution = (Float) m.get("resolution"); assertTrue(resolution.floatValue() == header.getResolution()); String technique = (String) m.get("technique"); assertTrue(technique.equals(header.getTechnique())); } public void testCreateVirtualCBAtom(){ Group g1 = structure.getChain(0).getAtomGroup(11); if ( g1.getPDBName().equals("GLY")){ if ( g1 instanceof AminoAcid){ try { Atom cb = Calc.createVirtualCBAtom((AminoAcid)g1); g1.addAtom(cb); } catch (StructureException e){ fail ("createVirtualCBAtom failed with " + e.getMessage()); } } } else { fail("the group at position 11 is not a GLY!"); } } public void testMutation() throws Exception { Group g1 = (Group)structure.getChain(0).getAtomGroup(21).clone(); assertTrue(g1 != null); Group g2 = (Group)structure.getChain(0).getAtomGroup(53).clone(); assertTrue(g2 != null); assertEquals("The group at position 22 is not a PHE","PHE", g1.getPDBName()); assertEquals("The group position is not number 22","22", g1.getPDBCode()); assertEquals("The group at position 54 is not a THR","THR", g2.getPDBName()); assertEquals("The group position is not number 54","54", g2.getPDBCode()); Atom[] atoms1 = new Atom[3]; Atom[] atoms2 = new Atom[3]; atoms1[0] = g1.getAtom("N"); atoms1[1] = g1.getAtom("CA"); atoms1[2] = g1.getAtom("CB"); atoms2[0] = g2.getAtom("N"); atoms2[1] = g2.getAtom("CA"); atoms2[2] = g2.getAtom("CB"); SVDSuperimposer svds = new SVDSuperimposer(atoms1,atoms2); Matrix rotMatrix = svds.getRotation(); Atom tran = svds.getTranslation(); Group newGroup = (Group)g2.clone(); Calc.rotate(newGroup,rotMatrix); Calc.shift(newGroup,tran); Atom ca1 = g1.getAtom("CA"); Atom oldca2 = g2.getAtom("CA"); Atom newca2 = newGroup.getAtom("CA"); // this also tests the cloning ... double olddistance = Calc.getDistance(ca1,oldca2); assertTrue( olddistance > 10 ); // final test check that the distance between the CA atoms is small ; double newdistance = Calc.getDistance(ca1,newca2); assertTrue( newdistance < 0.1); } }
package com.ecyrd.jspwiki.plugin; import org.apache.oro.text.*; import org.apache.oro.text.regex.*; import org.apache.log4j.Category; import java.io.StreamTokenizer; import java.io.StringReader; import java.io.StringWriter; import java.io.IOException; import java.util.NoSuchElementException; import java.util.Map; import java.util.Vector; import java.util.Iterator; import java.util.Properties; import java.util.StringTokenizer; import java.util.HashMap; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.FileUtil; import com.ecyrd.jspwiki.InternalWikiException; /** * Manages plugin classes. There exists a single instance of PluginManager * per each instance of WikiEngine, that is, each JSPWiki instance. * <P> * A plugin is defined to have three parts: * <OL> * <li>The plugin class * <li>The plugin parameters * <li>The plugin body * </ol> * * For example, in the following line of code: * <pre> * [{INSERT com.ecyrd.jspwiki.plugin.FunnyPlugin foo='bar' * blob='goo' * * abcdefghijklmnopqrstuvw * 01234567890}] * </pre> * * The plugin class is "com.ecyrd.jspwiki.plugin.FunnyPlugin", the * parameters are "foo" and "blob" (having values "bar" and "goo", * respectively), and the plugin body is then * "abcdefghijklmnopqrstuvw\n01234567890". * <P> * The class name can be shortened, and marked without the package. * For example, "FunnyPlugin" would be expanded to * "com.ecyrd.jspwiki.plugin.FunnyPlugin" automatically. It is also * possible to defined other packages, by setting the * "jspwiki.plugin.searchPath" property. See the included * jspwiki.properties file for examples. * <P> * Even though the nominal way of writing the plugin is * <pre> * [{INSERT pluginclass WHERE param1=value1...}], * </pre> * it is possible to shorten this quite a lot, by skipping the * INSERT, and WHERE words, and dropping the package name. For * example: * * <pre> * [{INSERT com.ecyrd.jspwiki.plugin.Counter WHERE name='foo'}] * </pre> * * is the same as * <pre> * [{Counter name='foo'}] * </pre> * * @author Janne Jalkanen * @since 1.6.1 */ public class PluginManager { private static Category log = Category.getInstance( PluginManager.class ); /** * This is the default package to try in case the instantiation * fails. */ public static final String DEFAULT_PACKAGE = "com.ecyrd.jspwiki.plugin"; /** * The property name defining which packages will be searched for properties. */ public static final String PROP_SEARCHPATH = "jspwiki.plugin.searchPath"; /** * The name of the body content. Current value is "_body". */ public static final String PARAM_BODY = "_body"; Vector m_searchPath = new Vector(); Pattern m_pluginPattern; private boolean m_pluginsEnabled = true; /** * Create a new PluginManager. * * @param props Contents of a "jspwiki.properties" file. */ public PluginManager( Properties props ) { String packageNames = props.getProperty( PROP_SEARCHPATH ); if( packageNames != null ) { StringTokenizer tok = new StringTokenizer( packageNames, "," ); while( tok.hasMoreTokens() ) { m_searchPath.add( tok.nextToken() ); } } // The default package is always added. m_searchPath.add( DEFAULT_PACKAGE ); PatternCompiler compiler = new Perl5Compiler(); try { m_pluginPattern = compiler.compile( "\\{?(INSERT)?\\s*([\\w\\._]+)[ \\t]*(WHERE)?([^\\}]*)\\}?$" ); } catch( MalformedPatternException e ) { log.fatal("Internal error: someone messed with pluginmanager patterns.", e ); throw new InternalWikiException( "PluginManager patterns are broken" ); } } /** * Enables or disables plugin execution. */ public void enablePlugins( boolean enabled ) { m_pluginsEnabled = enabled; } /** * Returns plugin execution status. If false, plugins are not * executed when they are encountered on a WikiPage, and an * empty string is returned in their place. */ public boolean pluginsEnabled() { return( m_pluginsEnabled ); } /** * Returns true if the link is really command to insert * a plugin. * <P> * Currently we just check if the link starts with "{INSERT", * or just plain "{" but not "{$". * * @param link Link text, i.e. the contents of text between []. * @return True, if this link seems to be a command to insert a plugin here. */ public static boolean isPluginLink( String link ) { return link.startsWith("{INSERT") || (link.startsWith("{") && !link.startsWith("{$")); } /** * Attempts to locate a plugin class from the class path * set in the property file. * * @param classname Either a fully fledged class name, or just * the name of the file (that is, * "com.ecyrd.jspwiki.plugin.Counter" or just plain "Counter"). * * @return A found class. * * @throws ClassNotFoundException if no such class exists. */ private Class findPluginClass( String classname ) throws ClassNotFoundException { ClassLoader loader = getClass().getClassLoader(); try { return loader.loadClass( classname ); } catch( ClassNotFoundException e ) { for( Iterator i = m_searchPath.iterator(); i.hasNext(); ) { String packageName = (String)i.next(); try { return loader.loadClass( packageName + "." + classname ); } catch( ClassNotFoundException ex ) { // This is okay, we go to the next package. } } // Nope, it wasn't on the normal plugin path. Let's try tags. // We'll only accept tags that implement the WikiPluginTag /* FIXME: Not functioning, need to create a PageContext try { Class c = loader.loadClass( "com.ecyrd.jspwiki.tags."+classname ); if( c instanceof WikiPluginTag ) { return new TagPlugin( c ); } } catch( ClassNotFoundException exx ) { // Just fall through, and let the execution end with stuff. } */ } throw new ClassNotFoundException("Plugin not in "+PROP_SEARCHPATH); } /** * Executes a plugin class in the given context. * <P>Used to be private, but is public since 1.9.21. * * @param context The current WikiContext. * @param classname The name of the class. Can also be a * shortened version without the package name, since the class name is searched from the * package search path. * * @param params A parsed map of key-value pairs. * * @return Whatever the plugin returns. * * @throws PluginException If the plugin execution failed for * some reason. * * @since 2.0 */ public String execute( WikiContext context, String classname, Map params ) throws PluginException { if( !m_pluginsEnabled ) return( "" ); try { Class pluginClass; WikiPlugin plugin; pluginClass = findPluginClass( classname ); // Create... try { plugin = (WikiPlugin) pluginClass.newInstance(); } catch( InstantiationException e ) { throw new PluginException( "Cannot instantiate plugin "+classname, e ); } catch( IllegalAccessException e ) { throw new PluginException( "Not allowed to access plugin "+classname, e ); } catch( Exception e ) { throw new PluginException( "Instantiation of plugin "+classname+" failed.", e ); } // ...and launch. try { return plugin.execute( context, params ); } catch( PluginException e ) { // Just pass this exception onward. throw (PluginException) e.fillInStackTrace(); } catch( Exception e ) { // But all others get captured here. log.warn( "Plugin failed while executing:", e ); throw new PluginException( "Plugin failed", e ); } } catch( ClassNotFoundException e ) { throw new PluginException( "Could not find plugin "+classname, e ); } catch( ClassCastException e ) { throw new PluginException( "Class "+classname+" is not a Wiki plugin.", e ); } } /** * Parses plugin arguments. Handles quotes and all other kewl * stuff. * * @param argstring The argument string to the plugin. This is * typically a list of key-value pairs, using "'" to escape * spaces in strings, followed by an empty line and then the * plugin body. * * @return A parsed list of parameters. The plugin body is put * into a special parameter defined by PluginManager.PARAM_BODY. * * @throws IOException If the parsing fails. */ public Map parseArgs( String argstring ) throws IOException { HashMap arglist = new HashMap(); StringReader in = new StringReader(argstring); StreamTokenizer tok = new StreamTokenizer(in); int type; String param = null, value = null; tok.eolIsSignificant( true ); boolean potentialEmptyLine = false; boolean quit = false; while( !quit ) { String s; type = tok.nextToken(); switch( type ) { case StreamTokenizer.TT_EOF: quit = true; s = null; break; case StreamTokenizer.TT_WORD: s = tok.sval; potentialEmptyLine = false; break; case StreamTokenizer.TT_EOL: quit = potentialEmptyLine; potentialEmptyLine = true; s = null; break; case StreamTokenizer.TT_NUMBER: s = Integer.toString( new Double(tok.nval).intValue() ); potentialEmptyLine = false; break; case '\'': s = tok.sval; break; default: s = null; } // Assume that alternate words on the line are // parameter and value, respectively. if( s != null ) { if( param == null ) { param = s; } else { value = s; arglist.put( param, value ); // log.debug("ARG: "+param+"="+value); param = null; } } } // Now, we'll check the body. if( potentialEmptyLine ) { StringWriter out = new StringWriter(); FileUtil.copyContents( in, out ); String bodyContent = out.toString(); if( bodyContent != null ) { arglist.put( PARAM_BODY, bodyContent ); } } return arglist; } /** * Parses a plugin. Plugin commands are of the form: * [{INSERT myplugin WHERE param1=value1, param2=value2}] * myplugin may either be a class name or a plugin alias. * <P> * This is the main entry point that is used. * * @param context The current WikiContext. * @param commandline The full command line, including plugin * name, parameters and body. * * @return HTML as returned by the plugin, or possibly an error * message. */ public String execute( WikiContext context, String commandline ) throws PluginException { if( !m_pluginsEnabled ) return( "" ); PatternMatcher matcher = new Perl5Matcher(); try { if( matcher.contains( commandline, m_pluginPattern ) ) { MatchResult res = matcher.getMatch(); String plugin = res.group(2); String args = commandline.substring(res.begin(4), commandline.length() - (commandline.charAt(commandline.length()-1) == '}' ? 1 : 0 ) ); Map arglist = parseArgs( args ); return execute( context, plugin, arglist ); } } catch( NoSuchElementException e ) { String msg = "Missing parameter in plugin definition: "+commandline; log.warn( msg, e ); throw new PluginException( msg ); } catch( IOException e ) { String msg = "Zyrf. Problems with parsing arguments: "+commandline; log.warn( msg, e ); throw new PluginException( msg ); } // FIXME: We could either return an empty string "", or // the original line. If we want unsuccessful requests // to be invisible, then we should return an empty string. return commandline; } /* // FIXME: Not functioning, needs to create or fetch PageContext from somewhere. public class TagPlugin implements WikiPlugin { private Class m_tagClass; public TagPlugin( Class tagClass ) { m_tagClass = tagClass; } public String execute( WikiContext context, Map params ) throws PluginException { WikiPluginTag plugin = m_tagClass.newInstance(); } } */ }
package jp.gecko655.bot.tomorinao; import java.text.DateFormat; import java.time.Duration; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; import java.util.TimeZone; import java.util.logging.Level; import java.util.regex.Pattern; import java.util.stream.Collectors; import jp.gecko655.bot.AbstractCron; import jp.gecko655.bot.DBConnection; import twitter4j.Paging; import twitter4j.Relationship; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterException; public class TomoriNaoReply extends AbstractCron { static final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); private static final Pattern whoPattern = Pattern.compile("( $| $|[^]|[^]|[^]?|[^]?| | )"); public TomoriNaoReply() { format.setTimeZone(TimeZone.getDefault()); } @Override protected void twitterCron() { try { Status lastStatus = DBConnection.getLastStatus(); List<Status> replies = twitter.getMentionsTimeline((new Paging()).count(20)); if(replies.isEmpty()){ logger.log(Level.INFO, "Not yet replied. Stop."); return; } DBConnection.setLastStatus(replies.get(0)); if(lastStatus == null){ logger.log(Level.INFO,"memcache saved. Stop. "+replies.get(0).getUser().getName()+"'s tweet at "+format.format(replies.get(0).getCreatedAt())); return; } List<Status> validReplies = replies.stream().filter(reply -> isValid(reply, lastStatus)).collect(Collectors.toList()); if(validReplies.isEmpty()){ logger.log(Level.FINE, "No valid replies. Stop."); return; } for(Status reply : validReplies){ Relationship relation = twitter.friendsFollowers().showFriendship(twitter.getId(), reply.getUser().getId()); if(!relation.isSourceFollowingTarget()){ twitter.createFriendship(reply.getUser().getId()); } if(whoPattern.matcher(reply.getText()).find()//The reply has format &&reply.getInReplyToStatusId()>0//The reply replies to a specific tweet. &&twitter.showStatus(reply.getInReplyToStatusId()).getMediaEntities().length>0){ // put latest image URL to black-list who(reply); }else{ //auto reply (when bot follows the replier) StatusUpdate update= new StatusUpdate("@"+reply.getUser().getScreenName()+" "); update.setInReplyToStatusId(reply.getId()); String query = query(); updateStatusWithMedia(update, query, 100); } } } catch (TwitterException e) { logger.log(Level.WARNING,e.toString()); e.printStackTrace(); } catch (Exception e) { logger.log(Level.WARNING,e.toString()); e.printStackTrace(); } } private String query(){ int rand = (int) (Math.random()*10); if(rand<6){ return " "; }else if(rand<8){ return " "; }else{ return " "; } } private boolean isValid(Status reply, Status lastStatus) { if(lastStatus==null) return false; if(Duration.between(reply.getCreatedAt().toInstant(), LocalDateTime.now().toInstant(ZoneOffset.UTC)).toHours()>12) { logger.log(Level.FINE, reply.getUser().getName()+"'s tweet \""+reply.getText()+"\" is Too old, skip."); return false; } return reply.getCreatedAt().after(lastStatus.getCreatedAt()); } private void who(Status reply) { //Store the url to the black list. DBConnection.storeImageUrlToBlackList(reply.getInReplyToStatusId(),reply.getUser().getScreenName()); try{ //Delete the reported tweet. twitter.destroyStatus(reply.getInReplyToStatusId()); //Apologize to the report user. StatusUpdate update= new StatusUpdate("@"+reply.getUser().getScreenName()+" "); update.setInReplyToStatusId(reply.getId()); twitter.updateStatus(update); }catch(TwitterException e){ e.printStackTrace(); } } }
package cgeo.geocaching.utils; import cgeo.geocaching.connector.gc.GCConstants; import cgeo.geocaching.connector.gc.GCConstantsTest; import cgeo.geocaching.test.mock.MockedCache; import android.test.AndroidTestCase; import java.util.regex.Pattern; public class BaseUtilsTest extends AndroidTestCase { public static void testRegEx() { final String page = MockedCache.readCachePage("GC2CJPF"); assertEquals(GCConstantsTest.MOCK_LOGIN_NAME, BaseUtils.getMatch(page, GCConstants.PATTERN_LOGIN_NAME, true, "???")); assertTrue(page.contains("id=\"ctl00_hlRenew\"") || GCConstants.MEMBER_STATUS_PM.equals(BaseUtils.getMatch(page, GCConstants.PATTERN_MEMBER_STATUS, true, "???"))); } public static void testReplaceWhitespaces() { assertEquals("foo bar baz ", BaseUtils.replaceWhitespace(" foo\n\tbar \r baz ")); } public static void testControlCharactersCleanup() { final Pattern patternAll = Pattern.compile("(.*)", Pattern.DOTALL); assertEquals("some control characters removed", BaseUtils.getMatch("some" + "\u001C" + "control" + (char) 0x1D + "characters removed", patternAll, "")); assertEquals("newline also removed", BaseUtils.getMatch("newline\nalso\nremoved", patternAll, "")); } }
package com.esotericsoftware.kryo; import static com.esotericsoftware.minlog.Log.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; /** * Serializes objects to and from byte arrays and streams.<br> * <br> * This class uses a buffer internally and is not thread safe. * @author Nathan Sweet <misc@n4te.com> */ public class ObjectBuffer { private final Kryo kryo; private final int maxCapacity; private ByteBuffer buffer; private byte[] bytes; /** * Creates an ObjectStream with an initial buffer size of 2KB and a maximum size of 16KB. */ public ObjectBuffer (Kryo kryo) { this(kryo, 2 * 1024, 16 * 1024); } /** * @param maxCapacity The initial and maximum size in bytes of an object that can be read or written. * @see #ObjectBuffer(Kryo, int, int) */ public ObjectBuffer (Kryo kryo, int maxCapacity) { this(kryo, maxCapacity, maxCapacity); } /** * @param initialCapacity The initial maximum size in bytes of an object that can be read or written. * @param maxCapacity The maximum size in bytes of an object that can be read or written. The capacity is doubled until the * maxCapacity is exceeded, then BufferOverflowException is thrown by the read and write methods. */ public ObjectBuffer (Kryo kryo, int initialCapacity, int maxCapacity) { this.kryo = kryo; buffer = ByteBuffer.allocate(initialCapacity); bytes = buffer.array(); this.maxCapacity = maxCapacity; } /** * Reads the specified number of bytes from the stream into the buffer. * @param contentLength The number of bytes to read, or -1 to read to the end of the stream. */ private void readToBuffer (InputStream input, int contentLength) { if (contentLength == -1) contentLength = Integer.MAX_VALUE; try { int position = 0; while (position < contentLength) { int count = input.read(bytes, position, bytes.length - position); if (count == -1) break; position += count; if (position == bytes.length && !resizeBuffer(true)) throw new BufferOverflowException(); } buffer.position(0); buffer.limit(position); } catch (IOException ex) { throw new SerializationException("Error reading object bytes.", ex); } } /** * Reads to the end of the stream and returns the deserialized object. * @see Kryo#readClassAndObject(ByteBuffer) */ public Object readClassAndObject (InputStream input) { readToBuffer(input, -1); return kryo.readClassAndObject(buffer); } /** * Reads the specified number of bytes and returns the deserialized object. * @see Kryo#readClassAndObject(ByteBuffer) */ public Object readClassAndObject (InputStream input, int contentLength) { readToBuffer(input, contentLength); return kryo.readClassAndObject(buffer); } /** * Reads to the end of the stream and returns the deserialized object. * @see Kryo#readObject(ByteBuffer, Class) */ public <T> T readObject (InputStream input, Class<T> type) { readToBuffer(input, -1); return kryo.readObject(buffer, type); } /** * Reads the specified number of bytes and returns the deserialized object. * @see Kryo#readObject(ByteBuffer, Class) */ public <T> T readObject (InputStream input, int contentLength, Class<T> type) { readToBuffer(input, contentLength); return kryo.readObject(buffer, type); } /** * Reads to the end of the stream and returns the deserialized object. * @see Kryo#readObjectData(ByteBuffer, Class) */ public <T> T readObjectData (InputStream input, Class<T> type) { readToBuffer(input, -1); return kryo.readObjectData(buffer, type); } /** * Reads the specified number of bytes and returns the deserialized object. * @see Kryo#readObjectData(ByteBuffer, Class) */ public <T> T readObjectData (InputStream input, int contentLength, Class<T> type) { readToBuffer(input, contentLength); return kryo.readObjectData(buffer, type); } /** * @see Kryo#writeClassAndObject(ByteBuffer, Object) */ public void writeClassAndObject (OutputStream output, Object object) { buffer.clear(); while (true) { try { kryo.writeClassAndObject(buffer, object); break; } catch (BufferOverflowException ex) { if (!resizeBuffer(false)) throw ex; } } writeToStream(output); } /** * @see Kryo#writeObject(ByteBuffer, Object) */ public void writeObject (OutputStream output, Object object) { buffer.clear(); while (true) { try { kryo.writeObject(buffer, object); break; } catch (BufferOverflowException ex) { if (!resizeBuffer(false)) throw ex; } } writeToStream(output); } /** * @see Kryo#writeObjectData(ByteBuffer, Object) */ public void writeObjectData (OutputStream output, Object object) { buffer.clear(); while (true) { try { kryo.writeObjectData(buffer, object); break; } catch (BufferOverflowException ex) { if (!resizeBuffer(false)) throw ex; } } writeToStream(output); } private void writeToStream (OutputStream output) { try { output.write(bytes, 0, buffer.position()); } catch (IOException ex) { throw new SerializationException("Error writing object bytes.", ex); } } /** * @see Kryo#readClassAndObject(ByteBuffer) */ public Object readClassAndObject (byte[] objectBytes) { return kryo.readClassAndObject(ByteBuffer.wrap(objectBytes)); } /** * @see Kryo#readObject(ByteBuffer, Class) */ public <T> T readObject (byte[] objectBytes, Class<T> type) { return kryo.readObject(ByteBuffer.wrap(objectBytes), type); } /** * @see Kryo#readObjectData(ByteBuffer, Class) */ public <T> T readObjectData (byte[] objectBytes, Class<T> type) { return kryo.readObjectData(ByteBuffer.wrap(objectBytes), type); } /** * @see Kryo#writeClassAndObject(ByteBuffer, Object) */ public byte[] writeClassAndObject (Object object) { buffer.clear(); while (true) { try { kryo.writeClassAndObject(buffer, object); break; } catch (BufferOverflowException ex) { if (!resizeBuffer(false)) throw ex; } } return writeToBytes(); } /** * @see Kryo#writeObject(ByteBuffer, Object) */ public byte[] writeObject (Object object) { buffer.clear(); while (true) { try { kryo.writeObject(buffer, object); break; } catch (BufferOverflowException ex) { if (!resizeBuffer(false)) throw ex; } } return writeToBytes(); } /** * @see Kryo#writeObjectData(ByteBuffer, Object) */ public byte[] writeObjectData (Object object) { buffer.clear(); while (true) { try { kryo.writeObjectData(buffer, object); break; } catch (BufferOverflowException ex) { if (!resizeBuffer(false)) throw ex; } } return writeToBytes(); } private byte[] writeToBytes () { byte[] objectBytes = new byte[buffer.position()]; System.arraycopy(bytes, 0, objectBytes, 0, objectBytes.length); return objectBytes; } private boolean resizeBuffer (boolean preserveContents) { int capacity = buffer.capacity(); if (capacity == maxCapacity) return false; int newCapacity = Math.min(maxCapacity, capacity * 2); ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity); byte[] newArray = newBuffer.array(); if (preserveContents) System.arraycopy(bytes, 0, newArray, 0, bytes.length); buffer = newBuffer; bytes = newArray; if (DEBUG) debug("kryo", "Resized ObjectBuffer to: " + newCapacity); return true; } }
package kr.co.vcnc.haeinsa; import java.util.List; import kr.co.vcnc.haeinsa.thrift.generated.TRowLock; import com.google.common.collect.Lists; /** * Contains Transaction information of single row. * This information is only saved in client memory until {@link HaeinsaTransaction#commit()} called. * @author Myungbo Kim * */ class HaeinsaRowTransaction { // current RowLock saved in HBase. null if there is no lock at all. private TRowLock current; private final List<HaeinsaMutation> mutations = Lists.newArrayList(); private final HaeinsaTableTransaction tableTransaction; HaeinsaRowTransaction(HaeinsaTableTransaction tableTransaction) { this.tableTransaction = tableTransaction; } public TRowLock getCurrent() { return current; } public void setCurrent(TRowLock current) { this.current = current; } public List<HaeinsaMutation> getMutations() { return mutations; } public int getIterationCount(){ if (mutations.size() > 0){ if (mutations.get(0) instanceof HaeinsaPut){ return mutations.size(); }else{ return mutations.size() + 1; } } return 1; } public void addMutation(HaeinsaMutation mutation) { if (mutations.size() <= 0){ mutations.add(mutation); } else { HaeinsaMutation lastMutation = mutations.get(mutations.size() - 1); if (lastMutation.getClass() != mutation.getClass()){ mutations.add(mutation); }else{ lastMutation.add(mutation); } } } public HaeinsaTableTransaction getTableTransaction() { return tableTransaction; } /** * Return list of {@link HaeinsaKeyValueScanner}s which wrap mutations - (Put & Delete) contained inside instance. * @return */ public List<HaeinsaKeyValueScanner> getScanners() { List<HaeinsaKeyValueScanner> result = Lists.newArrayList(); for (int i=0;i<mutations.size();i++){ HaeinsaMutation mutation = mutations.get(i); result.add(mutation.getScanner(mutations.size() - i)); } return result; } }
package logbook.internal.gui; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.control.cell.TreeItemPropertyValueFactory; import logbook.bean.BattleLog; import logbook.bean.BattleTypes.CombinedType; import logbook.bean.BattleTypes.IFormation; import logbook.bean.BattleTypes.IMidnightBattle; import logbook.bean.MapStartNext; import logbook.bean.Ship; import logbook.bean.SlotItem; import logbook.internal.BattleLogs; import logbook.internal.BattleLogs.SimpleBattleLog; import logbook.internal.BattleLogs.Unit; import logbook.internal.LoggerHolder; public class BattleLogController extends WindowController { @FXML private TreeTableView<BattleLogCollect> collect; @FXML private TreeTableColumn<BattleLogCollect, String> unit; @FXML private TreeTableColumn<BattleLogCollect, String> start; @FXML private TreeTableColumn<BattleLogCollect, String> win; @FXML private TreeTableColumn<BattleLogCollect, String> s; @FXML private TreeTableColumn<BattleLogCollect, String> a; @FXML private TreeTableColumn<BattleLogCollect, String> b; @FXML private TreeTableColumn<BattleLogCollect, String> c; @FXML private TreeTableColumn<BattleLogCollect, String> d; @FXML private TableView<BattleLogDetail> detail; @FXML private TableColumn<BattleLogDetail, String> date; @FXML private TableColumn<BattleLogDetail, String> area; @FXML private TableColumn<BattleLogDetail, String> cell; @FXML private TableColumn<BattleLogDetail, String> boss; @FXML private TableColumn<BattleLogDetail, String> rank; @FXML private TableColumn<BattleLogDetail, String> intercept; @FXML private TableColumn<BattleLogDetail, String> fformation; @FXML private TableColumn<BattleLogDetail, String> eformation; @FXML private TableColumn<BattleLogDetail, String> dispseiku; @FXML private TableColumn<BattleLogDetail, String> ftouch; @FXML private TableColumn<BattleLogDetail, String> etouch; @FXML private TableColumn<BattleLogDetail, String> efleet; @FXML private TableColumn<BattleLogDetail, String> dropType; @FXML private TableColumn<BattleLogDetail, String> dropShip; private Map<Unit, List<SimpleBattleLog>> logMap; private ObservableList<BattleLogDetail> details = FXCollections.observableArrayList(); @FXML void initialize() { try { TableTool.setVisible(this.detail, this.getClass().toString() + "#" + "detail"); this.collect.setShowRoot(false); this.unit.setCellValueFactory(new TreeItemPropertyValueFactory<>("unit")); this.start.setCellValueFactory(new TreeItemPropertyValueFactory<>("start")); this.win.setCellValueFactory(new TreeItemPropertyValueFactory<>("win")); this.s.setCellValueFactory(new TreeItemPropertyValueFactory<>("s")); this.a.setCellValueFactory(new TreeItemPropertyValueFactory<>("a")); this.b.setCellValueFactory(new TreeItemPropertyValueFactory<>("b")); this.c.setCellValueFactory(new TreeItemPropertyValueFactory<>("c")); this.d.setCellValueFactory(new TreeItemPropertyValueFactory<>("d")); this.collect.getSelectionModel() .selectedItemProperty() .addListener(this::detail); this.detail.setRowFactory(tv -> { TableRow<BattleLogDetail> r = new TableRow<>(); r.setOnMouseClicked(e -> { if (e.getClickCount() == 2 && (!r.isEmpty())) { BattleLogDetail d = r.getItem(); BattleLog log = BattleLogs.read(d.getDate()); if (log != null) { try { MapStartNext last = log.getNext().get(log.getNext().size() - 1); CombinedType combinedType = log.getCombinedType(); Map<Integer, List<Ship>> deckMap = log.getDeckMap(); Map<Integer, SlotItem> itemMap = log.getItemMap(); IFormation battle = log.getBattle(); IMidnightBattle midnight = log.getMidnight(); Set<Integer> escape = log.getEscape(); InternalFXMLLoader.showWindow("logbook/gui/battle_detail.fxml", this.getWindow(), "", c -> { ((BattleDetail) c).setData(last, combinedType, deckMap, escape, itemMap, battle, midnight); }, null); } catch (Exception ex) { LoggerHolder.get().error("", ex); } } } }); return r; }); this.detail.setItems(this.details); this.detail.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); this.detail.setOnKeyPressed(TableTool::defaultOnKeyPressedHandler); this.date.setCellValueFactory(new PropertyValueFactory<>("date")); this.area.setCellValueFactory(new PropertyValueFactory<>("area")); this.cell.setCellValueFactory(new PropertyValueFactory<>("cell")); this.boss.setCellValueFactory(new PropertyValueFactory<>("boss")); this.rank.setCellValueFactory(new PropertyValueFactory<>("rank")); this.intercept.setCellValueFactory(new PropertyValueFactory<>("intercept")); this.fformation.setCellValueFactory(new PropertyValueFactory<>("fformation")); this.eformation.setCellValueFactory(new PropertyValueFactory<>("eformation")); this.dispseiku.setCellValueFactory(new PropertyValueFactory<>("dispseiku")); this.ftouch.setCellValueFactory(new PropertyValueFactory<>("ftouch")); this.etouch.setCellValueFactory(new PropertyValueFactory<>("etouch")); this.efleet.setCellValueFactory(new PropertyValueFactory<>("efleet")); this.dropType.setCellValueFactory(new PropertyValueFactory<>("dropType")); this.dropShip.setCellValueFactory(new PropertyValueFactory<>("dropShip")); TreeItem<BattleLogCollect> root = new TreeItem<BattleLogCollect>(new BattleLogCollect()); this.collect.setRoot(root); this.setCollect(); } catch (Exception e) { LoggerHolder.get().error("FXML", e); } } private void setCollect() { this.logMap = BattleLogs.readSimpleLog(); for (Unit unit : Unit.values()) { List<SimpleBattleLog> list = this.logMap.get(unit); BattleLogCollect unitRootValue = BattleLogs.collect(list, null, false); unitRootValue.setUnit(unit.getName()); unitRootValue.setCollectUnit(unit); TreeItem<BattleLogCollect> unitRoot = new TreeItem<BattleLogCollect>(unitRootValue); unitRoot.setExpanded(true); BattleLogCollect bossValue = BattleLogs.collect(list, null, true); bossValue.setUnit(""); bossValue.setCollectUnit(unit); bossValue.setBoss(true); TreeItem<BattleLogCollect> boss = new TreeItem<BattleLogCollect>(bossValue); unitRoot.getChildren().add(boss); List<String> areaNames = list.stream() .map(SimpleBattleLog::getArea) .distinct() .sorted(Comparator.naturalOrder()) .collect(Collectors.toList()); for (String area : areaNames) { BattleLogCollect areaValue = BattleLogs.collect(list, area, false); areaValue.setUnit(area); areaValue.setCollectUnit(unit); areaValue.setArea(area); TreeItem<BattleLogCollect> areaRoot = new TreeItem<BattleLogCollect>(areaValue); BattleLogCollect areaBossValue = BattleLogs.collect(list, area, true); areaBossValue.setUnit(""); areaBossValue.setCollectUnit(unit); areaBossValue.setArea(area); areaBossValue.setBoss(true); TreeItem<BattleLogCollect> areaBoss = new TreeItem<BattleLogCollect>(areaBossValue); areaRoot.getChildren().add(areaBoss); unitRoot.getChildren().add(areaRoot); } this.collect.getRoot().getChildren().add(unitRoot); } } @FXML void reloadAction(ActionEvent event) { int selectedIndex = this.collect.getSelectionModel().getSelectedIndex(); this.collect.getRoot().getChildren().clear(); this.setCollect(); this.collect.getSelectionModel().focus(selectedIndex); this.collect.getSelectionModel().select(selectedIndex); } @FXML void copyDetail() { TableTool.selectionCopy(this.detail); } @FXML void selectAllDetail() { TableTool.selectAll(this.detail); } @FXML void columnVisibleDetail() { try { TableTool.showVisibleSetting(this.detail, this.getClass().toString() + "#" + "detail", this.getWindow()); } catch (Exception e) { LoggerHolder.get().error("FXML", e); } } /** * * * @param observable ObservableValue * @param oldValue * @param value */ private void detail(ObservableValue<? extends TreeItem<BattleLogCollect>> observable, TreeItem<BattleLogCollect> oldValue, TreeItem<BattleLogCollect> value) { this.details.clear(); if (value != null) { BattleLogCollect collect = value.getValue(); String area = collect.getArea(); boolean boss = collect.isBoss(); Predicate<BattleLogDetail> anyFilter = e -> true; Predicate<BattleLogDetail> areaFilter = area != null ? e -> area.equals(e.getArea()) : anyFilter; Predicate<BattleLogDetail> bossFilter = boss ? e -> e.getBoss().indexOf("") != -1 : anyFilter; this.details.addAll(this.logMap.get(collect.getCollectUnit()) .stream() .map(BattleLogDetail::toBattleLogDetail) .filter(areaFilter) .filter(bossFilter) .sorted(Comparator.comparing(BattleLogDetail::getDate).reversed()) .collect(Collectors.toList())); } } }
package me.coley.recaf.workspace; import me.coley.recaf.Recaf; import me.coley.recaf.command.impl.Export; import me.coley.recaf.util.ClassUtil; import me.coley.recaf.util.Log; import me.coley.recaf.util.TypeUtil; import org.clyze.jphantom.ClassMembers; import org.clyze.jphantom.JPhantom; import org.clyze.jphantom.Phantoms; import org.clyze.jphantom.access.ClassAccessStateMachine; import org.clyze.jphantom.adapters.ClassPhantomExtractor; import org.clyze.jphantom.hier.ClassHierarchy; import org.clyze.jphantom.hier.IncrementalClassHierarchy; import org.objectweb.asm.*; import org.objectweb.asm.tree.ClassNode; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Resource for holding phantom references. * * @author Matt */ public class PhantomResource extends JavaResource { private static final ResourceLocation LOCATION = LiteralResourceLocation.ofKind(ResourceKind.JAR, "Phantoms"); private static final Path PHANTOM_DIR = Recaf.getDirectory("classpath").resolve("generated"); // TODO: Update phantom refs when: // - using the recompilers // - assembling methods (just at startup?) // TODO: Add a visual indicator when this passes / fails /** * Constructs the phantom resource. */ public PhantomResource() { super(ResourceKind.JAR); } /** * Clear the Phantom class cache internally and in file cache. * * @throws IOException * When the files cannot be deleted. */ public void clear() throws IOException { // Clear internal getClasses().clear(); // Clear file cache Path input = PHANTOM_DIR.resolve("input.jar"); Path output = PHANTOM_DIR.resolve("output.jar"); if (!Files.isDirectory(PHANTOM_DIR)) Files.createDirectories(PHANTOM_DIR); Files.deleteIfExists(input); Files.deleteIfExists(output); } /** * Populates the current resource with phantom classes * and dumps the classes into {@code [RECAF]/classpath/generated/output.jar} * * @param classes * Collection of classes to generate phantoms for. * * @throws IOException * Thrown when JPhantom cannot read from the temporary file where these classes are written to. */ public void populatePhantoms(Collection<byte[]> classes) throws IOException { Log.debug("Begin generating phantom classes, given {} input classes", classes.size()); // Clear old classes clear(); Path input = PHANTOM_DIR.resolve("input.jar"); Path output = PHANTOM_DIR.resolve("output.jar"); // Write the parameter passed classes to a temp jar Map<String, byte[]> classMap = new HashMap<>(); Map<Type, ClassNode> nodes = new HashMap<>(); classes.forEach(c -> { ClassReader cr = new ClassReader(c); ClassNode node = ClassUtil.getNode(cr, ClassReader.EXPAND_FRAMES); classMap.put(node.name + ".class", c); nodes.put(Type.getObjectType(node.name), node); }); Export.writeArchive(input.toFile(), classMap); Log.debug("Wrote classes to temp file, starting phantom analysis...", classes.size()); // Read into JPhantom ClassHierarchy hierarchy = clsHierarchyFromArchive(new JarFile(input.toFile())); ClassMembers members = ClassMembers.fromJar(new JarFile(input.toFile()), hierarchy); classes.forEach(c -> { // TODO: Look more into JPhantom having issues with type clashes of picocli classes // - Correctly identifies inner pico classes as annotations, then tries to mark them as normal classes // which JPhantom sees and decides to throw a type clash error. ClassReader cr = new ClassReader(c); if (cr.getClassName().contains("$")) return; try { cr.accept(new ClassPhantomExtractor(hierarchy, members), 0); } catch (Throwable t) { Log.debug("Phantom extraction failed: {}", t); } }); // Remove duplicate constraints for faster analysis Set<String> existingConstraints = new HashSet<>(); ClassAccessStateMachine.v().getConstraints().removeIf(c -> { boolean isDuplicate = existingConstraints.contains(c.toString()); existingConstraints.add(c.toString()); return isDuplicate; }); // Execute and populate the current resource with generated classes JPhantom phantom = new JPhantom(nodes, hierarchy, members); phantom.run(); phantom.getGenerated().forEach((k, v) -> getClasses().put(k.getInternalName(), decorate(v))); classMap.clear(); getClasses().forEach((k, v) -> classMap.put(k + ".class", v)); Export.writeArchive(output.toFile(), classMap); Log.debug("Phantom analysis complete, cleaning temp file", classes.size()); // Cleanup try { Field tmap = Phantoms.class.getDeclaredField("transformers"); tmap.setAccessible(true); Map<?, ?> map = (Map<?, ?>) tmap.get(Phantoms.V()); map.clear(); } catch (Throwable t) { Log.error("Failed to cleanup phantom transformer cache"); } Phantoms.V().clear(); Files.deleteIfExists(input); } /** * This is copy pasted from JPhantom, modified to be more lenient towards obfuscated inputs. * * @param file * Some jar file. * * @return Class hierarchy. * * @throws IOException * When the archive cannot be read. */ private static ClassHierarchy clsHierarchyFromArchive(JarFile file) throws IOException { try { ClassHierarchy hierarchy = new IncrementalClassHierarchy(); for (Enumeration<JarEntry> e = file.entries(); e.hasMoreElements(); ) { JarEntry entry = e.nextElement(); if (entry.isDirectory()) continue; if (!entry.getName().endsWith(".class")) continue; try (InputStream stream = file.getInputStream(entry)) { ClassReader reader = new ClassReader(stream); String[] ifaceNames = reader.getInterfaces(); Type clazz = Type.getObjectType(reader.getClassName()); Type superclass = reader.getSuperName() == null ? TypeUtil.OBJECT_TYPE : Type.getObjectType(reader.getSuperName()); Type[] ifaces = new Type[ifaceNames.length]; for (int i = 0; i < ifaces.length; i++) ifaces[i] = Type.getObjectType(ifaceNames[i]); // Add type to hierarchy boolean isInterface = (reader.getAccess() & Opcodes.ACC_INTERFACE) != 0; try { if (isInterface) { hierarchy.addInterface(clazz, ifaces); } else { hierarchy.addClass(clazz, superclass, ifaces); } } catch (Exception ex) { Log.error(ex, "JPhantom: Hierarchy failure for: {}", clazz); } } catch (IOException ex) { Log.error(ex, "JPhantom: IO Error reading from archive: {}", file.getName()); } } return hierarchy; } finally { file.close(); } } /** * Adds a note to the given class that it has been auto-generated. * * @param generated * Input generated JPhantom class. * * @return modified class that clearly indicates it is generated. */ private byte[] decorate(byte[] generated) { ClassWriter cw = new ClassWriter(0); ClassVisitor cv = new ClassVisitor(Recaf.ASM_VERSION, cw) { @Override public void visitEnd() { visitAnnotation("LAutoGenerated;", true) .visit("msg", "Recaf/JPhantom automatically generated this class"); } }; new ClassReader(generated).accept(cv, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); return cw.toByteArray(); } @Override protected Map<String, byte[]> loadClasses() throws IOException { return Collections.emptyMap(); } @Override protected Map<String, byte[]> loadFiles() throws IOException { return Collections.emptyMap(); } @Override public ResourceLocation getShortName() { return LOCATION; } @Override public ResourceLocation getName() { return LOCATION; } }
package com.googlecode.jmxtrans; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.pool.KeyedObjectPool; import org.apache.commons.pool.impl.GenericKeyedObjectPool; import org.quartz.CronExpression; import org.quartz.CronTrigger; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerUtils; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.googlecode.jmxtrans.jmx.ManagedGenericKeyedObjectPool; import com.googlecode.jmxtrans.jmx.ManagedJmxTransformerProcess; import com.googlecode.jmxtrans.jobs.ServerJob; import com.googlecode.jmxtrans.model.JmxProcess; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Server; import com.googlecode.jmxtrans.util.JmxUtils; import com.googlecode.jmxtrans.util.LifecycleException; import com.googlecode.jmxtrans.util.OptionsException; import com.googlecode.jmxtrans.util.ValidationException; import com.googlecode.jmxtrans.util.WatchDir; import com.googlecode.jmxtrans.util.WatchedCallback; /** * Main() class that takes an argument which is the directory to look in for * files which contain json data that defines queries to run against JMX * servers. * * @author jon */ public class JmxTransformer implements WatchedCallback { private static final Logger log = LoggerFactory.getLogger(JmxTransformer.class); /** The Quartz server properties. */ private String quartPropertiesFile = null; /** The seconds between server job runs. */ private int runPeriod = 60; /** Json file or dir to watch. */ private File jsonDirOrFile; private boolean runEndlessly = false; private Scheduler serverScheduler; private WatchDir watcher; /** * Pools. TODO : Move to a PoolUtils or PoolRegistry so others can use it */ private Map<String, KeyedObjectPool> poolMap; private Map<String, ManagedGenericKeyedObjectPool> poolMBeans; private List<Server> masterServersList = new ArrayList<Server>(); /** The shutdown hook. */ private Thread shutdownHook = new ShutdownHook(); private volatile boolean isRunning = false; public static void main(String[] args) throws Exception { JmxTransformer transformer = new JmxTransformer(); // Start the process transformer.doMain(args); } /** * The real main method. */ private void doMain(String[] args) throws Exception { if (!this.parseOptions(args)) { return; } ManagedJmxTransformerProcess mbean = new ManagedJmxTransformerProcess(this); JmxUtils.registerJMX(mbean); // Start the process this.start(); while (true) { // look for some terminator // attempt to read off queue // process message // TODO : Make something here, maybe watch for files? try { Thread.sleep(5); } catch (Exception e) { break; } } JmxUtils.unregisterJMX(mbean); } /** * Start. * * @throws LifecycleException * the lifecycle exception */ public synchronized void start() throws LifecycleException { if (isRunning) { throw new LifecycleException("Process already started"); } else { log.info("Starting Jmxtrans on : " + this.jsonDirOrFile.toString()); try { this.startupScheduler(); this.startupWatchdir(); this.setupObjectPooling(); this.startupSystem(); } catch (Exception e) { log.error(e.getMessage(), e); throw new LifecycleException(e); } // Ensure resources are free Runtime.getRuntime().addShutdownHook(shutdownHook); isRunning = true; } } /** * Stop. * * @throws LifecycleException * the lifecycle exception */ public synchronized void stop() throws LifecycleException { if (!isRunning) { throw new LifecycleException("Process already stoped"); } else { try { log.info("Stopping Jmxtrans"); // Remove hook to not call twice if (shutdownHook != null) { Runtime.getRuntime().removeShutdownHook(shutdownHook); } this.stopServices(); isRunning = false; } catch (LifecycleException e) { log.error(e.getMessage(), e); throw new LifecycleException(e); } } } /** * Stop services. * * @throws LifecycleException * the lifecycle exception */ private synchronized void stopServices() throws LifecycleException { try { // Shutdown the scheduler if (this.serverScheduler != null) { this.serverScheduler.shutdown(true); log.debug("Shutdown server scheduler"); try { // Quartz issue, need to sleep Thread.sleep(1500); } catch (InterruptedException e) { log.error(e.getMessage(), e); } this.serverScheduler = null; } // Shutdown the file watch service if (this.watcher != null) { this.watcher.stopService(); this.watcher = null; log.debug("Shutdown watch service"); } for (String key : poolMap.keySet()) { JmxUtils.unregisterJMX(poolMBeans.get(key)); } this.poolMBeans = null; // Shutdown the pools for (Entry<String, KeyedObjectPool> entry : this.poolMap.entrySet()) { try { entry.getValue().close(); log.debug("Closed object pool factory: " + entry.getKey()); } catch (Exception ex) { log.error("Error closing object pool factory: " + entry.getKey()); } } this.poolMap = null; // Shutdown the outputwriters for (Server server : this.masterServersList) { for (Query query : server.getQueries()) { for (OutputWriter writer : query.getOutputWriters()) { try { writer.stop(); log.debug("Stopped writer: " + writer.getClass().getSimpleName() + " for query: " + query); } catch (LifecycleException ex) { log.error("Error stopping writer: " + writer.getClass().getSimpleName() + " for query: " + query); } } } } this.masterServersList.clear(); } catch (Exception e) { log.error(e.getMessage(), e); throw new LifecycleException(e); } } /** * Startup the watchdir service. */ private void startupWatchdir() throws Exception { File dirToWatch = null; if (this.getJsonDirOrFile().isFile()) { dirToWatch = new File(FilenameUtils.getFullPath(this.getJsonDirOrFile().getAbsolutePath())); } else { dirToWatch = this.getJsonDirOrFile(); } // start the watcher this.watcher = new WatchDir(dirToWatch, this); this.watcher.start(); } /** * start the server scheduler which loops over all the Server jobs */ private void startupScheduler() throws Exception { StdSchedulerFactory serverSchedFact = new StdSchedulerFactory(); InputStream stream = null; if (quartPropertiesFile == null) { stream = JmxTransformer.class.getResourceAsStream("/quartz.server.properties"); } else { stream = new FileInputStream(quartPropertiesFile); } serverSchedFact.initialize(stream); this.serverScheduler = serverSchedFact.getScheduler(); this.serverScheduler.start(); } /** * Handy method which runs the JmxProcess */ public void executeStandalone(JmxProcess process) throws Exception { this.masterServersList = process.getServers(); this.startupScheduler(); this.setupObjectPooling(); this.processServersIntoJobs(this.serverScheduler); // Sleep for 10 seconds to wait for jobs to complete. // There should be a better way, but it seems that way isn't working // right now. Thread.sleep(10 * 1000); } /** * Processes files into Server objects and then processesServers into jobs */ private void startupSystem() throws LifecycleException { // process all the json files into Server objects this.processFilesIntoServers(this.getJsonFiles()); // process the servers into jobs this.processServersIntoJobs(this.serverScheduler); } /** * Override this method if you'd like to add your own object pooling. * * @throws Exception */ protected void setupObjectPooling() throws Exception { if (this.poolMap == null) { this.poolMap = JmxUtils.getDefaultPoolMap(); this.poolMBeans = new HashMap<String, ManagedGenericKeyedObjectPool>(); for (String key : poolMap.keySet()) { ManagedGenericKeyedObjectPool mbean = new ManagedGenericKeyedObjectPool((GenericKeyedObjectPool) poolMap.get(key)); mbean.setPoolName(key); JmxUtils.registerJMX(mbean); poolMBeans.put(key, mbean); } } } private void validateSetup(List<Query> queries) throws ValidationException { for (Query q : queries) { this.validateSetup(q); } } private void validateSetup(Query query) throws ValidationException { List<OutputWriter> writers = query.getOutputWriters(); if (writers != null) { for (OutputWriter w : writers) { w.validateSetup(query); } } } /** * Processes all the json files and manages the dedup process */ private void processFilesIntoServers(List<File> jsonFiles) throws LifecycleException { for (File jsonFile : jsonFiles) { JmxProcess process; try { process = JmxUtils.getJmxProcess(jsonFile); if (log.isDebugEnabled()) { log.debug("Loaded file: " + jsonFile.getAbsolutePath()); } JmxUtils.mergeServerLists(this.masterServersList, process.getServers()); } catch (Exception ex) { throw new LifecycleException("Error parsing json: " + jsonFile, ex); } } } /** * Processes all the Servers into Job's * * Needs to be called after processFiles() */ private void processServersIntoJobs(Scheduler scheduler) throws LifecycleException { for (Server server : this.masterServersList) { try { // need to inject the poolMap for (Query query : server.getQueries()) { query.setServer(server); for (OutputWriter writer : query.getOutputWriters()) { writer.setObjectPoolMap(this.poolMap); writer.start(); } } // Now validate the setup of each of the OutputWriter's per // query. this.validateSetup(server.getQueries()); // Now schedule the jobs for execution. this.scheduleJob(scheduler, server); } catch (ParseException ex) { throw new LifecycleException("Error parsing cron expression: " + server.getCronExpression(), ex); } catch (SchedulerException ex) { throw new LifecycleException("Error scheduling job for server: " + server, ex); } catch (ValidationException ex) { throw new LifecycleException("Error validating json setup for query", ex); } } } /** * Schedules an individual job. */ private void scheduleJob(Scheduler scheduler, Server server) throws ParseException, SchedulerException { String name = server.getHost() + ":" + server.getPort() + "-" + System.currentTimeMillis() + "-" + RandomStringUtils.randomNumeric(10); JobDetail jd = new JobDetail(name, "ServerJob", ServerJob.class); JobDataMap map = new JobDataMap(); map.put(Server.class.getName(), server); map.put(Server.JMX_CONNECTION_FACTORY_POOL, this.poolMap.get(Server.JMX_CONNECTION_FACTORY_POOL)); jd.setJobDataMap(map); Trigger trigger = null; if ((server.getCronExpression() != null) && CronExpression.isValidExpression(server.getCronExpression())) { trigger = new CronTrigger(); ((CronTrigger) trigger).setCronExpression(server.getCronExpression()); ((CronTrigger) trigger).setName(server.getHost() + ":" + server.getPort() + "-" + Long.valueOf(System.currentTimeMillis()).toString()); ((CronTrigger) trigger).setStartTime(new Date()); } else { Trigger minuteTrigger = TriggerUtils.makeSecondlyTrigger(runPeriod); minuteTrigger.setName(server.getHost() + ":" + server.getPort() + "-" + Long.valueOf(System.currentTimeMillis()).toString()); minuteTrigger.setStartTime(new Date()); trigger = minuteTrigger; } scheduler.scheduleJob(jd, trigger); if (log.isDebugEnabled()) { log.debug("Scheduled job: " + jd.getName() + " for server: " + server); } } /** * Deletes all of the Jobs */ private void deleteAllJobs(Scheduler scheduler) throws Exception { List<JobDetail> allJobs = new ArrayList<JobDetail>(); String[] jobGroups = scheduler.getJobGroupNames(); for (String jobGroup : jobGroups) { String[] jobNames = scheduler.getJobNames(jobGroup); for (String jobName : jobNames) { allJobs.add(scheduler.getJobDetail(jobName, jobGroup)); } } for (JobDetail jd : allJobs) { scheduler.deleteJob(jd.getName(), jd.getGroup()); if (log.isDebugEnabled()) { log.debug("Deleted scheduled job: " + jd.getName() + " group: " + jd.getGroup()); } } } /** * If this is true, then this class will execute the main() loop and then * wait 60 seconds until running again. */ public void setRunEndlessly(boolean runEndlessly) { this.runEndlessly = runEndlessly; } public boolean isRunEndlessly() { return this.runEndlessly; } /** * Parse the options given on the command line. */ private boolean parseOptions(String[] args) throws OptionsException, org.apache.commons.cli.ParseException { CommandLineParser parser = new GnuParser(); CommandLine cl = parser.parse(this.getOptions(), args); Option[] options = cl.getOptions(); boolean result = true; for (Option option : options) { if (option.getOpt().equals("j")) { File tmp = new File(option.getValue()); if (!tmp.exists() && !tmp.isDirectory()) { throw new OptionsException("Path to json directory is invalid: " + tmp); } this.setJsonDirOrFile(tmp); } else if (option.getOpt().equals("f")) { File tmp = new File(option.getValue()); if (!tmp.exists() && !tmp.isFile()) { throw new OptionsException("Path to json file is invalid: " + tmp); } this.setJsonDirOrFile(tmp); } else if (option.getOpt().equals("e")) { this.setRunEndlessly(true); } else if (option.getOpt().equals("q")) { this.setQuartPropertiesFile(option.getValue()); File file = new File(option.getValue()); if (!file.exists()) { throw new OptionsException("Could not find path to the quartz properties file: " + file.getAbsolutePath()); } } else if (option.getOpt().equals("s")) { this.setRunPeriod(Integer.valueOf(option.getValue())); } else if (option.getOpt().equals("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar jmxtrans-all.jar", this.getOptions()); result = false; } } if ((result == true) && (this.getJsonDirOrFile() == null)) { throw new OptionsException("Please specify either the -f or -j option."); } return result; } public Options getOptions() { Options options = new Options(); options.addOption("j", true, "Directory where json configuration is stored. Default is ."); options.addOption("f", true, "A single json file to execute."); options.addOption("e", false, "Run endlessly. Default false."); options.addOption("q", true, "Path to quartz configuration file."); options.addOption("s", true, "Seconds between server job runs (not defined with cron). Default: 60"); options.addOption("h", false, "Help"); return options; } /** * Gets the quart properties file. * * @return the quart properties file */ public String getQuartPropertiesFile() { return quartPropertiesFile; } /** * Sets the quart properties file. * * @param quartPropertiesFile * the quart properties file */ public void setQuartPropertiesFile(String quartPropertiesFile) { this.quartPropertiesFile = quartPropertiesFile; } /** * Gets the run period. * * @return the run period */ public int getRunPeriod() { return runPeriod; } /** * Sets the run period. * * @param runPeriod * the run period */ public void setRunPeriod(int runPeriod) { this.runPeriod = runPeriod; } /** * Sets the json dir or file. * * @param jsonDirOrFile * the json dir or file */ public void setJsonDirOrFile(File jsonDirOrFile) { this.jsonDirOrFile = jsonDirOrFile; } /** * Gets the json dir or file. * * @return the json dir or file */ public File getJsonDirOrFile() { return this.jsonDirOrFile; } /** * If getJsonFile() is a file, then that is all we load. Otherwise, look in * the jsonDir for files. * * Files must end with .json as the suffix. */ private List<File> getJsonFiles() { File[] files = null; if ((this.getJsonDirOrFile() != null) && this.getJsonDirOrFile().isFile()) { files = new File[1]; files[0] = this.getJsonDirOrFile(); } else { files = this.getJsonDirOrFile().listFiles(); } List<File> result = new ArrayList<File>(); for (File file : files) { if (this.isJsonFile(file)) { result.add(file); } } return result; } /** * Are we a file and a json file? */ private boolean isJsonFile(File file) { if (this.getJsonDirOrFile().isFile()) { return file.equals(this.getJsonDirOrFile()); } return file.isFile() && file.getName().endsWith(".json"); } @Override public void fileModified(File file) throws Exception { if (this.isJsonFile(file)) { Thread.sleep(1000); if (log.isDebugEnabled()) { log.debug("File modified: " + file); } this.deleteAllJobs(this.serverScheduler); this.startupSystem(); } } @Override public void fileDeleted(File file) throws Exception { if (this.isJsonFile(file)) { Thread.sleep(1000); if (log.isDebugEnabled()) { log.debug("File deleted: " + file); } this.deleteAllJobs(this.serverScheduler); this.startupSystem(); } } @Override public void fileAdded(File file) throws Exception { if (this.isJsonFile(file)) { Thread.sleep(1000); if (log.isDebugEnabled()) { log.debug("File added: " + file); } this.startupSystem(); } } protected class ShutdownHook extends Thread { public void run() { try { JmxTransformer.this.stopServices(); } catch (LifecycleException e) { log.error("Error shutdown hook", e); } } } }
package me.rojo8399.placeholderapi; import me.rojo8399.placeholderapi.expansions.Expansion; public class RegistryEntry { private final Expansion exp; private final String key; private final String version; private final String author; public RegistryEntry(Expansion exp) { this.exp = exp; this.key = exp.getIdentifier(); this.version = exp.getVersion(); this.author = exp.getAuthor(); } /** * @return the exp */ public Expansion getExpansion() { return exp; } /** * @return the key */ public String getKey() { return key; } /** * @return the version */ public String getVersion() { return version; } /** * @return the author */ public String getAuthor() { return author; } }
package me.unrealization.jeeves.modules; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import me.unrealization.jeeves.bot.Jeeves; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.handle.obj.Permissions; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.RateLimitException; import me.unrealization.jeeves.interfaces.BotCommand; import me.unrealization.jeeves.interfaces.BotModule; public class Internal extends BotModule { public Internal() { this.version = Jeeves.version; this.commandList = new String[21]; this.commandList[0] = "Help"; this.commandList[1] = "Version"; this.commandList[2] = "Ping"; this.commandList[3] = "Shutdown"; this.commandList[4] = "GetDebugging"; this.commandList[5] = "SetDebugging"; this.commandList[6] = "GetCommandPrefix"; this.commandList[7] = "SetCommandPrefix"; this.commandList[8] = "GetRespondOnPrefix"; this.commandList[9] = "SetRespondOnPrefix"; this.commandList[10] = "GetRespondOnMention"; this.commandList[11] = "SetRespondOnMention"; this.commandList[12] = "GetIgnoredChannels"; this.commandList[13] = "AddIgnoredChannel"; this.commandList[14] = "RemoveIgnoredChannel"; this.commandList[15] = "GetIgnoredUsers"; this.commandList[16] = "AddIgnoredUser"; this.commandList[17] = "RemoveIgnoredUser"; this.commandList[18] = "GetModules"; this.commandList[19] = "EnableModule"; this.commandList[20] = "DisableModule"; this.defaultConfig.put("commandPrefix", "!"); this.defaultConfig.put("respondOnPrefix", "0"); this.defaultConfig.put("respondOnMention", "1"); this.defaultConfig.put("ignoredChannels", new String[0]); this.defaultConfig.put("ignoredUsers", new String[0]); this.defaultConfig.put("disabledModules", new String[0]); } @Override public boolean canDisable() { return false; } public static class Help extends BotCommand { @Override public String getHelp() { String output = "Get help."; return output; } @Override public String getParameters() { String output = "[module]"; return output; } @Override public void execute(IMessage message, String[] arguments) { String[] moduleList = Jeeves.getModuleList(); String output = ""; for (int moduleIndex = 0; moduleIndex < moduleList.length; moduleIndex++) { BotModule module = Jeeves.getModule(moduleList[moduleIndex]); if (Jeeves.isDisabled(message.getGuild().getID(), module) == true) { continue; } output += "**" + moduleList[moduleIndex] + " functions**\n\n"; output += module.getHelp() + "\n"; } IChannel channel; try { channel = message.getAuthor().getOrCreatePMChannel(); } catch (RateLimitException | DiscordException e) { Jeeves.debugException(e); channel = message.getChannel(); } Jeeves.sendMessage(channel, output); } } public static class Version extends BotCommand { @Override public String getHelp() { String output = "Show the bot's version number."; return output; } @Override public String getParameters() { return null; } @Override public void execute(IMessage message, String[] arguments) { Jeeves.sendMessage(message.getChannel(), "Jeeves " + Jeeves.version); } } public static class Ping extends BotCommand { @Override public String getHelp() { String output = "Check if the bot is alive."; return output; } @Override public String getParameters() { return null; } @Override public void execute(IMessage message, String[] arguments) { Jeeves.sendMessage(message.getChannel(), "Pong!"); } } public static class Shutdown extends BotCommand { @Override public String getHelp() { String output = "Shut down the bot."; return output; } @Override public String getParameters() { return null; } @Override public boolean owner() { return true; } @Override public void execute(IMessage message, String[] arguments) { Jeeves.sendMessage(message.getChannel(), "Good bye, cruel world."); try { message.getClient().logout(); } catch (DiscordException e) { Jeeves.debugException(e); } } } public static class GetDebugging extends BotCommand { @Override public String getHelp() { String output = "Check if debugging is enabled."; return output; } @Override public String getParameters() { return null; } @Override public boolean owner() { return true; } @Override public void execute(IMessage message, String[] arguments) { String debugging = (String)Jeeves.clientConfig.getValue("debugging"); if (debugging.equals("0") == true) { Jeeves.sendMessage(message.getChannel(), "Debugging is disabled."); } else { Jeeves.sendMessage(message.getChannel(), "Debugging is enabled."); } } } public static class SetDebugging extends BotCommand { @Override public String getHelp() { String output = "Enable/disable debugging."; return output; } @Override public String getParameters() { String output = "<1|0>"; return output; } @Override public boolean owner() { return true; } @Override public void execute(IMessage message, String[] arguments) { String debugging = String.join(" ", arguments).trim(); if ((debugging.equals("0") == false) && (debugging.equals("1") == false)) { Jeeves.sendMessage(message.getChannel(), "Invalid value"); } Jeeves.clientConfig.setValue("debugging", debugging); try { Jeeves.clientConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } if (debugging.equals("0") == true) { Jeeves.sendMessage(message.getChannel(), "Debugging has been disabled."); } else { Jeeves.sendMessage(message.getChannel(), "Debugging has been enabled."); } } } public static class GetCommandPrefix extends BotCommand { @Override public String getHelp() { String output = "Get the current command prefix."; return output; } @Override public String getParameters() { return null; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String commandPrefix = (String)Jeeves.serverConfig.getValue(message.getGuild().getID(), "commandPrefix"); Jeeves.sendMessage(message.getChannel(), "The command prefix is: " + commandPrefix); } } public static class SetCommandPrefix extends BotCommand { @Override public String getHelp() { String output = "Set the command prefix."; return output; } @Override public String getParameters() { String output = "<prefix>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String commandPrefix = String.join(" ", arguments).trim(); if (commandPrefix.isEmpty() == true) { Jeeves.sendMessage(message.getChannel(), "The command prefix cannot be empty."); return; } Jeeves.serverConfig.setValue(message.getGuild().getID(), "commandPrefix", commandPrefix); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } Jeeves.sendMessage(message.getChannel(), "The command prefix has been set to: " + commandPrefix); } } public static class GetRespondOnPrefix extends BotCommand { @Override public String getHelp() { String output = "Check if the bot will respond to messages starting with the command prefix."; return output; } @Override public String getParameters() { return null; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String respondOnPrefix = (String)Jeeves.serverConfig.getValue(message.getGuild().getID(), "respondOnPrefix"); if (respondOnPrefix.equals("0") == true) { Jeeves.sendMessage(message.getChannel(), "The bot will not respond to the command prefix."); } else { Jeeves.sendMessage(message.getChannel(), "The bot will respond to the command prefix."); } } } public static class SetRespondOnPrefix extends BotCommand { @Override public String getHelp() { String output = "Set whether or not the bot will respond to messages starting with the command prefix."; return output; } @Override public String getParameters() { String output = "<1|0>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String respondOnPrefix = String.join(" ", arguments).trim(); if ((respondOnPrefix.equals("0") == false) && (respondOnPrefix.equals("1") == false)) { Jeeves.sendMessage(message.getChannel(), "Invalid value"); return; } System.out.println(respondOnPrefix); Jeeves.serverConfig.setValue(message.getGuild().getID(), "respondOnPrefix", respondOnPrefix); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } if (respondOnPrefix.equals("0") == true) { Jeeves.sendMessage(message.getChannel(), "The bot will no longer respond to the command prefix."); } else { Jeeves.sendMessage(message.getChannel(), "The bot now responds to the command prefix."); } } } public static class GetRespondOnMention extends BotCommand { @Override public String getHelp() { String output = "Check if the bot will respond to mentions."; return output; } @Override public String getParameters() { return null; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String respondOnMention = (String)Jeeves.serverConfig.getValue(message.getGuild().getID(), "respondOnMention"); if (respondOnMention.equals("0") == true) { Jeeves.sendMessage(message.getChannel(), "The bot will not respond to mentions."); } else { Jeeves.sendMessage(message.getChannel(), "The bot will respond to mentions."); } } } public static class SetRespondOnMention extends BotCommand { @Override public String getHelp() { String output = "Set whether or not the bot will respond to mentions."; return output; } @Override public String getParameters() { String output = "<1|0>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String respondOnMention = String.join(" ", arguments).trim(); if ((respondOnMention.equals("0") == false) && (respondOnMention.equals("1") == false)) { Jeeves.sendMessage(message.getChannel(), "Invalid value"); return; } Jeeves.serverConfig.setValue(message.getGuild().getID(), "respondOnMention", respondOnMention); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } if (respondOnMention.equals("0") == true) { Jeeves.sendMessage(message.getChannel(), "The bot will no longer respond to mentions."); } else { Jeeves.sendMessage(message.getChannel(), "The bot now responds to mentions."); } } } public static class GetIgnoredChannels extends BotCommand { @Override public String getHelp() { String output = "Get the list of ignored channels."; return output; } @Override public String getParameters() { return null; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { Object ignoredChannels = Jeeves.serverConfig.getValue(message.getGuild().getID(), "ignoredChannels"); if (ignoredChannels.getClass() == String.class) { Jeeves.sendMessage(message.getChannel(), "No channels are being ignored."); return; } String[] ignoredChannelList = (String[])ignoredChannels; if (ignoredChannelList.length == 0) { Jeeves.sendMessage(message.getChannel(), "No channels are being ignored."); return; } String output = "The following channels are being ignored:\n\n"; for (int channelIndex = 0; channelIndex < ignoredChannelList.length; channelIndex++) { IChannel channel = message.getGuild().getChannelByID(ignoredChannelList[channelIndex]); output += channel.getName() + "\n"; } Jeeves.sendMessage(message.getChannel(), output); } } public static class AddIgnoredChannel extends BotCommand { @Override public String getHelp() { String output = "Add a channel to the ignore list."; return output; } @Override public String getParameters() { String output = "<channel>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String channelName = String.join(" ", arguments).trim(); if (channelName.isEmpty() == true) { Jeeves.sendMessage(message.getChannel(), "You need to provide a channel name."); return; } IChannel channel = Jeeves.findChannel(message.getGuild(), channelName); if (channel == null) { Jeeves.sendMessage(message.getChannel(), "Cannot find the channel " + channelName); return; } if (Jeeves.isIgnored(channel) == true) { Jeeves.sendMessage(message.getChannel(), "The channel " + channel.getName() + " is being ignored already."); return; } Object ignoredChannels = Jeeves.serverConfig.getValue(message.getGuild().getID(), "ignoredChannels"); String[] ignoredChannelList; if (ignoredChannels.getClass() == String.class) { ignoredChannelList = new String[0]; } else { ignoredChannelList = (String[])ignoredChannels; } String[] tmpIgnoredChannelList = new String[ignoredChannelList.length + 1]; for (int channelIndex = 0; channelIndex < ignoredChannelList.length; channelIndex++) { tmpIgnoredChannelList[channelIndex] = ignoredChannelList[channelIndex]; } tmpIgnoredChannelList[ignoredChannelList.length] = channel.getID(); ignoredChannelList = tmpIgnoredChannelList; Jeeves.serverConfig.setValue(message.getGuild().getID(), "ignoredChannels", ignoredChannelList); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } Jeeves.sendMessage(message.getChannel(), "The following channel is now being ignored: " + channel.getName()); } } public static class RemoveIgnoredChannel extends BotCommand { @Override public String getHelp() { String output = "Remove a channel from the ignore list."; return output; } @Override public String getParameters() { String output = "<channel>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String channelName = String.join(" ", arguments).trim(); if (channelName.isEmpty() == true) { Jeeves.sendMessage(message.getChannel(), "You need to provide a channel name."); return; } IChannel channel = Jeeves.findChannel(message.getGuild(), channelName); if (channel == null) { Jeeves.sendMessage(message.getChannel(), "Cannot find the channel " + channelName); return; } Object ignoredChannels = Jeeves.serverConfig.getValue(message.getGuild().getID(), "ignoredChannels"); if (ignoredChannels.getClass() == String.class) { Jeeves.sendMessage(message.getChannel(), "No channels are being ignored."); return; } String[] ignoredChannelList = (String[])ignoredChannels; String[] tmpIgnoredChannelList = new String[ignoredChannelList.length - 1]; int tmpIndex = 0; boolean removed = false; for (int channelIndex = 0; channelIndex < ignoredChannelList.length; channelIndex++) { if (channel.getID().equals(ignoredChannelList[channelIndex]) == true) { removed = true; continue; } if (tmpIndex == tmpIgnoredChannelList.length) { break; } tmpIgnoredChannelList[tmpIndex] = ignoredChannelList[channelIndex]; tmpIndex++; } if (removed == false) { Jeeves.sendMessage(message.getChannel(), "The channel " + channel.getName() + " is not being ignored."); return; } ignoredChannelList = tmpIgnoredChannelList; Jeeves.serverConfig.setValue(message.getGuild().getID(), "ignoredChannels", ignoredChannelList); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } Jeeves.sendMessage(message.getChannel(), "The following channel is no longer being ignored: " + channel.getName()); } } public static class GetIgnoredUsers extends BotCommand { @Override public String getHelp() { String output = "Get the list of ignored users."; return output; } @Override public String getParameters() { return null; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { Object ignoredUsers = Jeeves.serverConfig.getValue(message.getGuild().getID(), "ignoredUsers"); if (ignoredUsers.getClass() == String.class) { Jeeves.sendMessage(message.getChannel(), "No users are being ignored."); return; } String[] ignoredUserList = (String[])ignoredUsers; if (ignoredUserList.length == 0) { Jeeves.sendMessage(message.getChannel(), "No users are being ignored."); return; } String output = "The following users are being ignored:\n\n"; for (int userIndex = 0; userIndex < ignoredUserList.length; userIndex++) { IUser user = message.getGuild().getUserByID(ignoredUserList[userIndex]); output += user.getName() + "\n"; } Jeeves.sendMessage(message.getChannel(), output); } } public static class AddIgnoredUser extends BotCommand { @Override public String getHelp() { String output = "Add a user to the ignore list."; return output; } @Override public String getParameters() { String output = "<user>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String userName = String.join(" ", arguments).trim(); if (userName.isEmpty() == true) { Jeeves.sendMessage(message.getChannel(), "You need to provide a user name."); return; } IUser user = Jeeves.findUser(message.getGuild(), userName); if (user == null) { Jeeves.sendMessage(message.getChannel(), "Cannot find the user " + userName); return; } if (Jeeves.isIgnored(message.getGuild().getID(), user) == true) { Jeeves.sendMessage(message.getChannel(), "The user " + user.getName() + " is being ignored already."); return; } Object ignoredUsers = Jeeves.serverConfig.getValue(message.getGuild().getID(), "ignoredUsers"); String[] ignoredUserList; if (ignoredUsers.getClass() == String.class) { ignoredUserList = new String[0]; } else { ignoredUserList = (String[])ignoredUsers; } String[] tmpIgnoredUserList = new String[ignoredUserList.length + 1]; for (int userIndex = 0; userIndex < ignoredUserList.length; userIndex++) { tmpIgnoredUserList[userIndex] = ignoredUserList[userIndex]; } tmpIgnoredUserList[ignoredUserList.length] = user.getID(); ignoredUserList = tmpIgnoredUserList; Jeeves.serverConfig.setValue(message.getGuild().getID(), "ignoredUsers", ignoredUserList); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } Jeeves.sendMessage(message.getChannel(), "The following user is now being ignored: " + user.getName()); } } public static class RemoveIgnoredUser extends BotCommand { @Override public String getHelp() { String output = "Remove a user from the ignore list."; return output; } @Override public String getParameters() { String output = "<user>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String userName = String.join(" ", arguments).trim(); if (userName.isEmpty() == true) { Jeeves.sendMessage(message.getChannel(), "You need to provide a user name."); return; } IUser user = Jeeves.findUser(message.getGuild(), userName); if (user == null) { Jeeves.sendMessage(message.getChannel(), "Cannot find the user " + userName); return; } Object ignoredUsers = Jeeves.serverConfig.getValue(message.getGuild().getID(), "ignoredUsers"); if (ignoredUsers.getClass() == String.class) { Jeeves.sendMessage(message.getChannel(), "No users are being ignored."); return; } String[] ignoredUserList = (String[])ignoredUsers; String[] tmpIgnoredUserList = new String[ignoredUserList.length - 1]; int tmpIndex = 0; boolean removed = false; for (int userIndex = 0; userIndex < ignoredUserList.length; userIndex++) { if (user.getID().equals(ignoredUserList[userIndex]) == true) { removed = true; continue; } if (tmpIndex == tmpIgnoredUserList.length) { break; } tmpIgnoredUserList[tmpIndex] = ignoredUserList[userIndex]; tmpIndex++; } if (removed == false) { Jeeves.sendMessage(message.getChannel(), "The user " + user.getName() + " is not being ignored."); return; } ignoredUserList = tmpIgnoredUserList; Jeeves.serverConfig.setValue(message.getGuild().getID(), "ignoredUsers", ignoredUserList); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } Jeeves.sendMessage(message.getChannel(), "The following user is no longer being ignored: " + user.getName()); } } public static class GetModules extends BotCommand { @Override public String getHelp() { String output = "Get the list of available modules."; return output; } @Override public String getParameters() { return null; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String[] moduleList = Jeeves.getModuleList(); String output = "The following modules are available:\n\n"; for (int moduleIndex = 0; moduleIndex < moduleList.length; moduleIndex++) { BotModule module = Jeeves.getModule(moduleList[moduleIndex]); output += "\t" + moduleList[moduleIndex] + " " + module.getVersion(); if (Jeeves.isDisabled(message.getGuild().getID(), module) == true) { output += " (disabled)"; } output += "\n"; } Jeeves.sendMessage(message.getChannel(), output); } } public static class EnableModule extends BotCommand { @Override public String getHelp() { String output = "Enable a module."; return output; } @Override public String getParameters() { String output = "<module>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String moduleName = String.join(" ", arguments).trim(); if (moduleName.isEmpty() == true) { Jeeves.sendMessage(message.getChannel(), "You need to provide a module name."); return; } BotModule module = Jeeves.getModule(moduleName); if (module == null) { Jeeves.sendMessage(message.getChannel(), "Cannot find the module " + moduleName); return; } String discordId = module.getDiscordId(); if ((discordId != null) && (message.getGuild().getID().equals(discordId) == false)) { Jeeves.sendMessage(message.getChannel(), "The module " + moduleName + " is not available on this server."); return; } Object disabledModules = Jeeves.serverConfig.getValue(message.getGuild().getID(), "disabledModules"); if (disabledModules.getClass() == String.class) { Jeeves.sendMessage(message.getChannel(), "All available modules are enabled."); return; } String[] disabledModuleList = (String[])disabledModules; String[] tmpDisabledModuleList = new String[disabledModuleList.length - 1]; int tmpIndex = 0; boolean removed = true; for (int moduleIndex = 0; moduleIndex < disabledModuleList.length; moduleIndex++) { if (moduleName.equals(disabledModuleList[moduleIndex]) == true) { removed = true; continue; } if (tmpIndex == tmpDisabledModuleList.length) { break; } tmpDisabledModuleList[tmpIndex] = disabledModuleList[moduleIndex]; tmpIndex++; } if (removed == false) { Jeeves.sendMessage(message.getChannel(), "The module " + moduleName + " is not disabled."); return; } disabledModuleList = tmpDisabledModuleList; Jeeves.serverConfig.setValue(message.getGuild().getID(), "disabledModules", disabledModuleList); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } Jeeves.sendMessage(message.getChannel(), "The following module has been enabled: " + moduleName); } } public static class DisableModule extends BotCommand { @Override public String getHelp() { String output = "Disable a module."; return output; } @Override public String getParameters() { String output = "<module>"; return output; } @Override public Permissions[] permissions() { Permissions[] permissionList = new Permissions[1]; permissionList[0] = Permissions.MANAGE_SERVER; return permissionList; } @Override public void execute(IMessage message, String[] arguments) { String moduleName = String.join(" ", arguments).trim(); if (moduleName.isEmpty() == true) { Jeeves.sendMessage(message.getChannel(), "You need to provide a module name."); return; } BotModule module = Jeeves.getModule(moduleName); if (module == null) { Jeeves.sendMessage(message.getChannel(), "Cannot find the module " + moduleName); return; } if (module.canDisable() == false) { Jeeves.sendMessage(message.getChannel(), "The module " + moduleName + " cannot be disabled."); return; } if (Jeeves.isDisabled(message.getGuild().getID(), module) == true) { Jeeves.sendMessage(message.getChannel(), "The module " + moduleName + " is disabled already."); return; } Object disabledModules = Jeeves.serverConfig.getValue(message.getGuild().getID(), "disabledModules"); String[] disabledModuleList; if (disabledModules.getClass() == String.class) { disabledModuleList = new String[0]; } else { disabledModuleList = (String[])disabledModules; } String[] tmpDisabledModuleList = new String[disabledModuleList.length + 1]; for (int moduleIndex = 0; moduleIndex < disabledModuleList.length; moduleIndex++) { tmpDisabledModuleList[moduleIndex] = disabledModuleList[moduleIndex]; } tmpDisabledModuleList[disabledModuleList.length] = moduleName; disabledModuleList = tmpDisabledModuleList; Jeeves.serverConfig.setValue(message.getGuild().getID(), "disabledModules", disabledModuleList); try { Jeeves.serverConfig.saveConfig(); } catch (ParserConfigurationException | TransformerException e) { Jeeves.debugException(e); Jeeves.sendMessage(message.getChannel(), "Cannot store the setting."); return; } Jeeves.sendMessage(message.getChannel(), "The following module has been disabled: " + moduleName); } } }
package android.support.v4.app; import android.annotation.SuppressLint; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.Rect; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.support.v7.app.ActionBarActivity; import android.support.v7.internal.view.menu.ContextMenuCallbackGetter; import android.support.v7.internal.view.menu.ContextMenuDecorView.ContextMenuListenersProvider; import android.support.v7.internal.view.menu.ContextMenuListener; import android.test.mock.MockApplication; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import org.holoeverywhere.HoloEverywhere; import org.holoeverywhere.HoloEverywhere.PreferenceImpl; import org.holoeverywhere.LayoutInflater; import org.holoeverywhere.R; import org.holoeverywhere.SystemServiceManager; import org.holoeverywhere.SystemServiceManager.SuperSystemService; import org.holoeverywhere.ThemeManager; import org.holoeverywhere.ThemeManager.SuperStartActivity; import org.holoeverywhere.addon.IAddonActivity; import org.holoeverywhere.addon.IAddonAttacher; import org.holoeverywhere.app.Activity; import org.holoeverywhere.app.Application; import org.holoeverywhere.app.ContextThemeWrapperPlus; import org.holoeverywhere.preference.PreferenceManagerHelper; import org.holoeverywhere.preference.SharedPreferences; import org.holoeverywhere.util.SparseIntArray; import org.holoeverywhere.util.WeaklyMap; import org.holoeverywhere.widget.WindowDecorView; import java.util.Map; public abstract class _HoloActivity extends ActionBarActivity implements SuperStartActivity, SuperSystemService, ContextMenuListener, ContextMenuListenersProvider, IAddonAttacher<IAddonActivity> { private static final String CONFIG_KEY = "holo:config:activity"; private Context mActionBarContext; private Holo mConfig; private Map<View, ContextMenuListener> mContextMenuListeners; private WindowDecorView mDecorView; private boolean mInited = false; private int mLastThemeResourceId = 0; private Handler mUserHandler; public static FragmentActivity extract(Context context, boolean exceptionWhenNotFound) { FragmentActivity fa = null; while (context instanceof ContextWrapper) { if (context instanceof FragmentActivity) { fa = (FragmentActivity) context; break; } context = ((ContextWrapper) context).getBaseContext(); } if (fa == null && exceptionWhenNotFound) { throw new ActivityNotFoundException(); } return fa; } @Override public void addContentView(View view, LayoutParams params) { if (requestDecorView(view, params, -1)) { mDecorView.addView(view, params); } onSupportContentChanged(); } protected Holo createConfig(Bundle savedInstanceState) { if (mConfig == null) { mConfig = onCreateConfig(savedInstanceState); } if (mConfig == null) { mConfig = Holo.defaultConfig(); } return mConfig; } protected void forceInit(Bundle savedInstanceState) { if (mInited) { return; } if (mConfig == null && savedInstanceState != null && savedInstanceState.containsKey(CONFIG_KEY)) { mConfig = savedInstanceState.getParcelable(CONFIG_KEY); } onInit(mConfig, savedInstanceState); } public Holo getConfig() { return mConfig; } @Override public ContextMenuListener getContextMenuListener(View view) { if (mContextMenuListeners == null) { return null; } return mContextMenuListeners.get(view); } public SharedPreferences getDefaultSharedPreferences() { return PreferenceManagerHelper.getDefaultSharedPreferences(this); } public SharedPreferences getDefaultSharedPreferences(PreferenceImpl impl) { return PreferenceManagerHelper.getDefaultSharedPreferences(this, impl); } public int getLastThemeResourceId() { return mLastThemeResourceId; } @Override public LayoutInflater getLayoutInflater() { return LayoutInflater.from(this); } public SharedPreferences getSharedPreferences(PreferenceImpl impl, String name, int mode) { return PreferenceManagerHelper.wrap(this, impl, name, mode); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { return PreferenceManagerHelper.wrap(this, name, mode); } /** * @return Themed context for using in action bar */ public Context getSupportActionBarContext() { if (mActionBarContext == null) { int theme = ThemeManager.getThemeType(this); if (theme != ThemeManager.LIGHT) { theme = ThemeManager.DARK; } theme = ThemeManager.getThemeResource(theme, false); if (mLastThemeResourceId == theme) { mActionBarContext = this; } else { mActionBarContext = new ContextThemeWrapperPlus(this, theme); } } return mActionBarContext; } public Application getSupportApplication() { return Application.getLastInstance(); } @Override public Object getSystemService(String name) { return SystemServiceManager.getSystemService(this, name); } @Override public Theme getTheme() { if (mLastThemeResourceId == 0) { setTheme(ThemeManager.getDefaultTheme()); } return super.getTheme(); } @Override public void setTheme(int resid) { setTheme(resid, true); } public LayoutInflater getThemedLayoutInflater() { return getLayoutInflater(); } public Handler getUserHandler() { if (mUserHandler == null) { mUserHandler = new Handler(getMainLooper()); } return mUserHandler; } protected final WindowDecorView getWindowDecorView() { return mDecorView; } public boolean isDecorViewInited() { return mDecorView != null; } public boolean isInited() { return mInited; } @Override protected void onCreate(Bundle savedInstanceState) { forceInit(savedInstanceState); super.onCreate(savedInstanceState); if (this instanceof Activity && mConfig != null) { mConfig.requestWindowFeature((Activity) this); } } protected Holo onCreateConfig(Bundle savedInstanceState) { if (savedInstanceState != null && savedInstanceState.containsKey(CONFIG_KEY)) { final Holo config = savedInstanceState.getParcelable(CONFIG_KEY); if (config != null) { return config; } } return Holo.defaultConfig(); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); if (view instanceof ContextMenuCallbackGetter) { final OnCreateContextMenuListener l = ((ContextMenuCallbackGetter) view) .getOnCreateContextMenuListener(); if (l != null) { l.onCreateContextMenu(menu, view, menuInfo); } } } @Override protected void onDestroy() { super.onDestroy(); LayoutInflater.removeInstance(this); } /** * Do not override this method. Use {@link #onPreInit(Holo, Bundle)} and * {@link #onPostInit(Holo, Bundle)} */ protected void onInit(Holo config, Bundle savedInstanceState) { if (mInited) { throw new IllegalStateException("This instance was already inited"); } mInited = true; if (config == null) { config = createConfig(savedInstanceState); } if (config == null) { config = Holo.defaultConfig(); } onPreInit(config, savedInstanceState); if (!config.ignoreApplicationInstanceCheck && !(getApplication() instanceof Application)) { boolean throwError = true; if (config.allowMockApplicationInstance) { try { throwError = !(getApplication() instanceof MockApplication); if (!throwError) { Log.w("HoloEverywhere", "Application instance is MockApplication. Wow. Let's begin tests..."); } } catch (Exception e) { } } if (throwError) { String text = "Application instance isn't HoloEverywhere.\n"; if (getApplication().getClass() == android.app.Application.class) { text += "Put attr 'android:name=\"org.holoeverywhere.app.Application\"'" + " in <application> tag of AndroidManifest.xml"; } else { text += "Please sure that you extend " + getApplication().getClass() + " from a org.holoeverywhere.app.Application"; } throw new IllegalStateException(text); } } getLayoutInflater().setFragmentActivity(this); if (this instanceof Activity) { final Activity activity = (Activity) this; ThemeManager.applyTheme(activity, mLastThemeResourceId == 0); if (!config.ignoreThemeCheck && ThemeManager.getThemeType(this) == ThemeManager.INVALID) { throw new HoloThemeException(activity); } TypedArray a = obtainStyledAttributes(new int[]{android.R.attr.windowActionBarOverlay, R.attr.windowActionBarOverlay}); if (a.getBoolean(0, false) || a.getBoolean(1, false)) { supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); } a.recycle(); a = obtainStyledAttributes(new int[]{android.R.attr.windowActionModeOverlay, R.attr.windowActionBarOverlay}); if (a.getBoolean(0, false) || a.getBoolean(1, false)) { supportRequestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY); } a.recycle(); } onPostInit(config, savedInstanceState); lockAttaching(); } @Override protected void onPostCreate(Bundle savedInstanceState) { requestDecorView(null, null, -1); super.onPostCreate(savedInstanceState); } protected void onPostInit(Holo config, Bundle savedInstanceState) { } protected void onPreInit(Holo config, Bundle savedInstanceState) { } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mConfig != null) { outState.putParcelable(CONFIG_KEY, mConfig); } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (mDecorView != null) { rOnWindowFocusChanged(mDecorView, hasFocus); } } private void rOnWindowFocusChanged(View view, boolean hasFocus) { if (view instanceof OnWindowFocusChangeListener) { ((OnWindowFocusChangeListener) view).onWindowFocusChanged(hasFocus); } if (view instanceof ViewGroup) { final ViewGroup vg = (ViewGroup) view; final int childCount = vg.getChildCount(); for (int i = 0; i < childCount; i++) { rOnWindowFocusChanged(vg.getChildAt(i), hasFocus); } } } @Override public void registerForContextMenu(View view) { registerForContextMenu(view, this); } public void registerForContextMenu(View view, ContextMenuListener listener) { if (mContextMenuListeners == null) { mContextMenuListeners = new WeaklyMap<View, ContextMenuListener>(); } mContextMenuListeners.put(view, listener); view.setLongClickable(true); } protected final void requestDecorView() { if (mDecorView == null) { requestDecorView(null, null, -1); } } private boolean requestDecorView(View view, LayoutParams params, int layoutRes) { if (mDecorView != null) { return true; } mDecorView = new ActivityDecorView(); mDecorView.setId(android.R.id.content); mDecorView.setProvider(this); if (view != null) { mDecorView.addView(view, params); } else if (layoutRes > 0) { getThemedLayoutInflater().inflate(layoutRes, mDecorView, true); } final LayoutParams p = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); performAddonAction(new AddonCallback<IAddonActivity>() { @Override public boolean action(IAddonActivity addon) { return addon.installDecorView(mDecorView, p); } @Override public void justPost() { _HoloActivity.super.setContentView(mDecorView, p); } }); return false; } /** * @deprecated Use @{link supportRequestWindowFeature(int)} instead */ public void requestWindowFeature(long featureId) { supportRequestWindowFeature((int) featureId); } @Override public boolean supportRequestWindowFeature(int featureId) { createConfig(null).requestWindowFeature(featureId); return !isSupportImplReady() || super.supportRequestWindowFeature(featureId); } @Override public void setContentView(int layoutResID) { if (requestDecorView(null, null, layoutResID)) { mDecorView.removeAllViewsInLayout(); getThemedLayoutInflater().inflate(layoutResID, mDecorView, true); } onSupportContentChanged(); } public void onSupportContentChanged() { } @Override public void setContentView(View view) { setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } @Override public void setContentView(View view, LayoutParams params) { if (requestDecorView(view, params, -1)) { mDecorView.removeAllViewsInLayout(); if(view != null){ mDecorView.addView(view, params); } } onSupportContentChanged(); } public synchronized void setTheme(int resid, boolean modifyGlobal) { if (resid > ThemeManager._START_RESOURCES_ID) { if (mLastThemeResourceId != resid) { mActionBarContext = null; super.setTheme(mLastThemeResourceId = resid); } } else { if ((resid & ThemeManager.COLOR_SCHEME_MASK) == 0) { int theme = ThemeManager.getTheme(getIntent(), false); if (theme == 0) { final android.app.Activity activity = getParent(); if (activity != null) { theme = ThemeManager.getTheme(activity.getIntent(), false); } } theme &= ThemeManager.COLOR_SCHEME_MASK; if (theme != 0) { resid |= theme; } } setTheme(ThemeManager.getThemeResource(resid, modifyGlobal)); } } @SuppressLint("NewApi") @Override public void startActivities(Intent[] intents) { startActivities(intents, null); } @SuppressLint("NewApi") @Override public void startActivities(Intent[] intents, Bundle options) { for (Intent intent : intents) { startActivity(intent, options); } } @SuppressLint("NewApi") @Override public void startActivity(Intent intent) { startActivity(intent, null); } @SuppressLint("NewApi") @Override public void startActivity(Intent intent, Bundle options) { startActivityForResult(intent, -1, options); } @SuppressLint("NewApi") @Override public void startActivityForResult(Intent intent, int requestCode) { startActivityForResult(intent, requestCode, null); } @Override public void startActivityForResult(Intent intent, int requestCode, Bundle options) { if (HoloEverywhere.ALWAYS_USE_PARENT_THEME) { ThemeManager.startActivity(this, intent, requestCode, options); } else { superStartActivity(intent, requestCode, options); } } public android.content.SharedPreferences superGetSharedPreferences( String name, int mode) { return super.getSharedPreferences(name, mode); } @Override public Object superGetSystemService(String name) { return super.getSystemService(name); } @Override @SuppressLint("NewApi") public void superStartActivity(Intent intent, int requestCode, Bundle options) { if (VERSION.SDK_INT >= 16) { super.startActivityForResult(intent, requestCode, options); } else { super.startActivityForResult(intent, requestCode); } } @Override public void onContextMenuClosed(ContextMenu menu) { } @Override public void unregisterForContextMenu(View view) { if (mContextMenuListeners != null) { mContextMenuListeners.remove(view); } view.setLongClickable(false); } public static interface OnWindowFocusChangeListener { public void onWindowFocusChanged(boolean hasFocus); } public static final class Holo implements Parcelable { public static final Parcelable.Creator<Holo> CREATOR = new Creator<Holo>() { @Override public Holo createFromParcel(Parcel source) { return new Holo(source); } @Override public Holo[] newArray(int size) { return new Holo[size]; } }; public boolean ignoreApplicationInstanceCheck = false; public boolean ignoreThemeCheck = false; public boolean allowMockApplicationInstance = false; private SparseIntArray windowFeatures; private boolean mForbidRequestWindowFeature = false; public Holo() { } private Holo(Parcel source) { ignoreThemeCheck = source.readInt() == 1; ignoreApplicationInstanceCheck = source.readInt() == 1; allowMockApplicationInstance = source.readInt() == 1; windowFeatures = source.readParcelable(SparseIntArray.class.getClassLoader()); } public static Holo defaultConfig() { return new Holo(); } @Override public int describeContents() { return 0; } public void requestWindowFeature(int feature) { if (windowFeatures == null) { windowFeatures = new SparseIntArray(); } if (mForbidRequestWindowFeature && windowFeatures.get(feature, -1) == -1) { throw new RuntimeException("Request of window features forbid now. Something is broken."); } windowFeatures.put(feature, feature); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(ignoreThemeCheck ? 1 : 0); dest.writeInt(ignoreApplicationInstanceCheck ? 1 : 0); dest.writeInt(allowMockApplicationInstance ? 1 : 0); dest.writeParcelable(windowFeatures, flags); } private void requestWindowFeature(Activity holoActivity) { mForbidRequestWindowFeature = true; if (windowFeatures != null) { for (int i = 0; i < windowFeatures.size(); i++) { if (windowFeatures.valueAt(i) > 0) { holoActivity.supportRequestWindowFeature(windowFeatures.keyAt(i)); } } } mForbidRequestWindowFeature = false; } } private static final class HoloThemeException extends RuntimeException { private static final long serialVersionUID = -2346897999325868420L; public HoloThemeException(_HoloActivity activity) { super("You must apply Holo.Theme, Holo.Theme.Light or " + "Holo.Theme.Light.DarkActionBar theme on the activity (" + activity.getClass().getSimpleName() + ") for using HoloEverywhere"); } } private final class ActivityDecorView extends WindowDecorView { public ActivityDecorView() { super(_HoloActivity.this); } @Override protected boolean fitSystemWindows(Rect insets) { final SparseIntArray windowFeatures = createConfig(null).windowFeatures; if (windowFeatures != null && windowFeatures.get(Window.FEATURE_ACTION_BAR_OVERLAY, 0) != 0) { return false; } return super.fitSystemWindows(insets); } } }
package com.jme.widget.font; import java.io.DataInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.logging.Level; import com.jme.image.Image; import com.jme.image.Texture; import com.jme.math.Vector2f; import com.jme.renderer.ColorRGBA; import com.jme.util.LoggingSystem; /** * @author Gregg Patton * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public abstract class WidgetFontAbstract implements WidgetFont { private static String FONT_DIRECTORY = "data/Font/"; private static String FONT_EXT = "glf"; protected WidgetFontHeader header; protected Texture texture; private String name; public WidgetFontAbstract(String name) { this.name = name; String filename = FONT_DIRECTORY + name + "." + FONT_EXT; create(filename); } public void create(String filename) { try { URL url = new URL("file:"+filename); create(url); } catch (MalformedURLException e){ LoggingSystem.getLogger().log(Level.WARNING, "Could not load: "+filename); } } public void create(URL filename) { try { int numChars, numTexBytes, cnt; WidgetFontChar fontChar; header = new WidgetFontHeader(); texture = new Texture(); InputStream is = filename.openStream(); DataInputStream dis = new DataInputStream(is); byte[] data = new byte[dis.available()]; dis.readFully(data); ByteBuffer buf = ByteBuffer.allocateDirect(data.length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.rewind(); buf.put(data); buf.rewind(); header.setTex(buf.getInt()); header.setTexWidth(buf.getInt()); header.setTexHeight(buf.getInt()); header.setStartChar(buf.getInt()); header.setEndChar(buf.getInt()); //header.chars buf.getInt(); float newHeight = 0; float height = 0; numChars = header.getEndChar() - header.getStartChar() + 1; for (cnt = 0; cnt < numChars; cnt++) { fontChar = new WidgetFontChar(); fontChar.setDx(buf.getFloat()); fontChar.setDy(buf.getFloat()); fontChar.setTx1(buf.getFloat()); fontChar.setTy1(buf.getFloat()); fontChar.setTx2(buf.getFloat()); fontChar.setTy2(buf.getFloat()); header.addChar(fontChar); newHeight = fontChar.getDy() * header.getTexHeight(); if (newHeight > height) height = newHeight; } Image textureImage = new Image(); textureImage.setType(Image.RA88); textureImage.setWidth(header.getTexWidth()); textureImage.setHeight(header.getTexHeight()); textureImage.setData(buf); texture.setBlendColor(new ColorRGBA(1, 1, 1, 1)); texture.setFilter(Texture.MM_NEAREST); texture.setImage(textureImage); texture.setMipmapState(Texture.MM_NONE); texture.setWrap(Texture.WM_CLAMP_S_CLAMP_T); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //Calculate size of a string public Vector2f getStringSize(String text) { Vector2f ret = new Vector2f(); int i; char c; WidgetFontChar fontChar; float width = 0, height = 0; //, newHeight = 0; fontChar = header.getChar(header.getStartChar()); ret.y = fontChar.getDy() * header.getTexHeight(); //Calculate width of string width = 0; for (i = 0; i < text.length(); i++) { //Make sure character is in range c = text.charAt(i); if (c < header.getStartChar() || c > header.getEndChar()) continue; //Get pointer to glFont character fontChar = header.getChar(c - header.getStartChar()); //Get width and height width += fontChar.getDx() * header.getTexWidth(); } ret.x = width; return ret; } public Texture getTexture() { return texture; } public String getName() { return name; } public abstract void renderString( String text, float x, float y, float scalar, ColorRGBA topColor, ColorRGBA bottomColor); public String toString() { return "[" + name + "]"; } }
package com.rilixtech; import android.content.Context; import android.support.annotation.DrawableRes; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; class CountryUtils { private static final String TAG = CountryUtils.class.getSimpleName(); private static List<Country> countries; private static Map<String, List<String>> timeZoneAndCountryISOs; /** * Returns image res based on country name code * @param country selected country * @return drawable resource id of country flag. */ @DrawableRes static int getFlagDrawableResId(Country country) { switch (country.getIso()) { case "af": //afghanistan return R.drawable.flag_afghanistan; case "al": //albania return R.drawable.flag_albania; case "dz": //algeria return R.drawable.flag_algeria; case "ad": //andorra return R.drawable.flag_andorra; case "ao": //angola return R.drawable.flag_angola; case "aq": //antarctica // custom return R.drawable.flag_antarctica; case "ar": //argentina return R.drawable.flag_argentina; case "am": //armenia return R.drawable.flag_armenia; case "aw": //aruba return R.drawable.flag_aruba; case "au": //australia return R.drawable.flag_australia; case "at": //austria return R.drawable.flag_austria; case "az": //azerbaijan return R.drawable.flag_azerbaijan; case "bh": //bahrain return R.drawable.flag_bahrain; case "bd": //bangladesh return R.drawable.flag_bangladesh; case "by": //belarus return R.drawable.flag_belarus; case "be": //belgium return R.drawable.flag_belgium; case "bz": //belize return R.drawable.flag_belize; case "bj": //benin return R.drawable.flag_benin; case "bt": //bhutan return R.drawable.flag_bhutan; case "bo": //bolivia, plurinational state of return R.drawable.flag_bolivia; case "ba": //bosnia and herzegovina return R.drawable.flag_bosnia; case "bw": //botswana return R.drawable.flag_botswana; case "br": //brazil return R.drawable.flag_brazil; case "bn": //brunei darussalam // custom return R.drawable.flag_brunei; case "bg": //bulgaria return R.drawable.flag_bulgaria; case "bf": //burkina faso return R.drawable.flag_burkina_faso; case "mm": //myanmar return R.drawable.flag_myanmar; case "bi": //burundi return R.drawable.flag_burundi; case "kh": //cambodia return R.drawable.flag_cambodia; case "cm": //cameroon return R.drawable.flag_cameroon; case "ca": //canada return R.drawable.flag_canada; case "cv": //cape verde return R.drawable.flag_cape_verde; case "cf": //central african republic return R.drawable.flag_central_african_republic; case "td": //chad return R.drawable.flag_chad; case "cl": //chile return R.drawable.flag_chile; case "cn": //china return R.drawable.flag_china; case "cx": //christmas island return R.drawable.flag_christmas_island; case "cc": //cocos (keeling) islands return R.drawable.flag_cocos;// custom case "co": //colombia return R.drawable.flag_colombia; case "km": //comoros return R.drawable.flag_comoros; case "cg": //congo return R.drawable.flag_republic_of_the_congo; case "cd": //congo, the democratic republic of the return R.drawable.flag_democratic_republic_of_the_congo; case "ck": //cook islands return R.drawable.flag_cook_islands; case "cr": //costa rica return R.drawable.flag_costa_rica; case "hr": //croatia return R.drawable.flag_croatia; case "cu": //cuba return R.drawable.flag_cuba; case "cy": //cyprus return R.drawable.flag_cyprus; case "cz": //czech republic return R.drawable.flag_czech_republic; case "dk": //denmark return R.drawable.flag_denmark; case "dj": //djibouti return R.drawable.flag_djibouti; case "tl": //timor-leste return R.drawable.flag_timor_leste; case "ec": //ecuador return R.drawable.flag_ecuador; case "eg": //egypt return R.drawable.flag_egypt; case "sv": //el salvador return R.drawable.flag_el_salvador; case "gq": //equatorial guinea return R.drawable.flag_equatorial_guinea; case "er": //eritrea return R.drawable.flag_eritrea; case "ee": //estonia return R.drawable.flag_estonia; case "et": //ethiopia return R.drawable.flag_ethiopia; case "fk": //falkland islands (malvinas) return R.drawable.flag_falkland_islands; case "fo": //faroe islands return R.drawable.flag_faroe_islands; case "fj": //fiji return R.drawable.flag_fiji; case "fi": //finland return R.drawable.flag_finland; case "fr": //france return R.drawable.flag_france; case "pf": //french polynesia return R.drawable.flag_french_polynesia; case "ga": //gabon return R.drawable.flag_gabon; case "gm": //gambia return R.drawable.flag_gambia; case "ge": //georgia return R.drawable.flag_georgia; case "de": //germany return R.drawable.flag_germany; case "gh": //ghana return R.drawable.flag_ghana; case "gi": //gibraltar return R.drawable.flag_gibraltar; case "gr": //greece return R.drawable.flag_greece; case "gl": //greenland return R.drawable.flag_greenland; case "gt": //guatemala return R.drawable.flag_guatemala; case "gn": //guinea return R.drawable.flag_guinea; case "gw": //guinea-bissau return R.drawable.flag_guinea_bissau; case "gy": //guyana return R.drawable.flag_guyana; case "gf": //guyane return R.drawable.flag_guyane; case "ht": //haiti return R.drawable.flag_haiti; case "hn": //honduras return R.drawable.flag_honduras; case "hk": //hong kong return R.drawable.flag_hong_kong; case "hu": //hungary return R.drawable.flag_hungary; case "in": //india return R.drawable.flag_india; case "id": //indonesia return R.drawable.flag_indonesia; case "ir": //iran, islamic republic of return R.drawable.flag_iran; case "iq": //iraq return R.drawable.flag_iraq; case "ie": //ireland return R.drawable.flag_ireland; case "im": //isle of man return R.drawable.flag_isleof_man; // custom case "il": //israel return R.drawable.flag_israel; case "it": //italy return R.drawable.flag_italy; case "ci": return R.drawable.flag_cote_divoire; case "jp": //japan return R.drawable.flag_japan; case "jo": //jordan return R.drawable.flag_jordan; case "kz": //kazakhstan return R.drawable.flag_kazakhstan; case "ke": //kenya return R.drawable.flag_kenya; case "ki": //kiribati return R.drawable.flag_kiribati; case "kw": //kuwait return R.drawable.flag_kuwait; case "kg": //kyrgyzstan return R.drawable.flag_kyrgyzstan; case "ky": // Cayman Islands return R.drawable.flag_cayman_islands; case "la": //lao people\'s democratic republic return R.drawable.flag_laos; case "lv": //latvia return R.drawable.flag_latvia; case "lb": //lebanon return R.drawable.flag_lebanon; case "ls": //lesotho return R.drawable.flag_lesotho; case "lr": //liberia return R.drawable.flag_liberia; case "ly": //libya return R.drawable.flag_libya; case "li": //liechtenstein return R.drawable.flag_liechtenstein; case "lt": //lithuania return R.drawable.flag_lithuania; case "lu": //luxembourg return R.drawable.flag_luxembourg; case "mo": //macao return R.drawable.flag_macao; case "mk": //macedonia, the former yugoslav republic of return R.drawable.flag_macedonia; case "mg": //madagascar return R.drawable.flag_madagascar; case "mw": //malawi return R.drawable.flag_malawi; case "my": //malaysia return R.drawable.flag_malaysia; case "mv": //maldives return R.drawable.flag_maldives; case "ml": //mali return R.drawable.flag_mali; case "mt": //malta return R.drawable.flag_malta; case "mh": //marshall islands return R.drawable.flag_marshall_islands; case "mr": //mauritania return R.drawable.flag_mauritania; case "mu": //mauritius return R.drawable.flag_mauritius; case "yt": //mayotte return R.drawable.flag_martinique; // no exact flag found case "re": //la reunion return R.drawable.flag_martinique; // no exact flag found case "mq": //martinique return R.drawable.flag_martinique; case "mx": //mexico return R.drawable.flag_mexico; case "fm": //micronesia, federated states of return R.drawable.flag_micronesia; case "md": //moldova, republic of return R.drawable.flag_moldova; case "mc": //monaco return R.drawable.flag_monaco; case "mn": //mongolia return R.drawable.flag_mongolia; case "me": //montenegro return R.drawable.flag_of_montenegro;// custom case "ma": //morocco return R.drawable.flag_morocco; case "mz": //mozambique return R.drawable.flag_mozambique; case "na": //namibia return R.drawable.flag_namibia; case "nr": //nauru return R.drawable.flag_nauru; case "np": //nepal return R.drawable.flag_nepal; case "nl": //netherlands return R.drawable.flag_netherlands; case "nc": //new caledonia return R.drawable.flag_new_caledonia;// custom case "nz": //new zealand return R.drawable.flag_new_zealand; case "ni": //nicaragua return R.drawable.flag_nicaragua; case "ne": //niger return R.drawable.flag_niger; case "ng": //nigeria return R.drawable.flag_nigeria; case "nu": //niue return R.drawable.flag_niue; case "kp": //north korea return R.drawable.flag_north_korea; case "no": //norway return R.drawable.flag_norway; case "om": //oman return R.drawable.flag_oman; case "pk": //pakistan return R.drawable.flag_pakistan; case "pw": //palau return R.drawable.flag_palau; case "pa": //panama return R.drawable.flag_panama; case "pg": //papua new guinea return R.drawable.flag_papua_new_guinea; case "py": //paraguay return R.drawable.flag_paraguay; case "pe": //peru return R.drawable.flag_peru; case "ph": //philippines return R.drawable.flag_philippines; case "pn": //pitcairn return R.drawable.flag_pitcairn_islands; case "pl": //poland return R.drawable.flag_poland; case "pt": //portugal return R.drawable.flag_portugal; case "pr": //puerto rico return R.drawable.flag_puerto_rico; case "qa": //qatar return R.drawable.flag_qatar; case "ro": //romania return R.drawable.flag_romania; case "ru": //russian federation return R.drawable.flag_russian_federation; case "rw": //rwanda return R.drawable.flag_rwanda; case "bl": return R.drawable.flag_saint_barthelemy;// custom case "ws": //samoa return R.drawable.flag_samoa; case "sm": //san marino return R.drawable.flag_san_marino; case "st": //sao tome and principe return R.drawable.flag_sao_tome_and_principe; case "sa": //saudi arabia return R.drawable.flag_saudi_arabia; case "sn": //senegal return R.drawable.flag_senegal; case "rs": //serbia return R.drawable.flag_serbia; // custom case "sc": //seychelles return R.drawable.flag_seychelles; case "sl": //sierra leone return R.drawable.flag_sierra_leone; case "sg": //singapore return R.drawable.flag_singapore; case "sx": // Sint Maarten //TODO: Add Flag. return 0; case "sk": //slovakia return R.drawable.flag_slovakia; case "si": //slovenia return R.drawable.flag_slovenia; case "sb": //solomon islands return R.drawable.flag_soloman_islands; case "so": //somalia return R.drawable.flag_somalia; case "za": //south africa return R.drawable.flag_south_africa; case "kr": //south korea return R.drawable.flag_south_korea; case "es": //spain return R.drawable.flag_spain; case "lk": //sri lanka return R.drawable.flag_sri_lanka; case "sh": //saint helena, ascension and tristan da cunha return R.drawable.flag_saint_helena; // custom case "pm": //saint pierre and miquelon return R.drawable.flag_saint_pierre; case "sd": //sudan return R.drawable.flag_sudan; case "sr": //suriname return R.drawable.flag_suriname; case "sz": //swaziland return R.drawable.flag_swaziland; case "se": //sweden return R.drawable.flag_sweden; case "ch": //switzerland return R.drawable.flag_switzerland; case "sy": //syrian arab republic return R.drawable.flag_syria; case "tw": //taiwan, province of china return R.drawable.flag_taiwan; case "tj": //tajikistan return R.drawable.flag_tajikistan; case "tz": //tanzania, united republic of return R.drawable.flag_tanzania; case "th": //thailand return R.drawable.flag_thailand; case "tg": //togo return R.drawable.flag_togo; case "tk": //tokelau return R.drawable.flag_tokelau; // custom case "to": //tonga return R.drawable.flag_tonga; case "tn": //tunisia return R.drawable.flag_tunisia; case "tr": //turkey return R.drawable.flag_turkey; case "tm": //turkmenistan return R.drawable.flag_turkmenistan; case "tv": //tuvalu return R.drawable.flag_tuvalu; case "ae": //united arab emirates return R.drawable.flag_uae; case "ug": //uganda return R.drawable.flag_uganda; case "gb": //united kingdom return R.drawable.flag_united_kingdom; case "ua": //ukraine return R.drawable.flag_ukraine; case "uy": //uruguay return R.drawable.flag_uruguay; case "us": //united states return R.drawable.flag_united_states_of_america; case "uz": //uzbekistan return R.drawable.flag_uzbekistan; case "vu": //vanuatu return R.drawable.flag_vanuatu; case "va": //holy see (vatican city state) return R.drawable.flag_vatican_city; case "ve": //venezuela, bolivarian republic of return R.drawable.flag_venezuela; case "vn": //vietnam return R.drawable.flag_vietnam; case "wf": //wallis and futuna return R.drawable.flag_wallis_and_futuna; case "ye": //yemen return R.drawable.flag_yemen; case "zm": //zambia return R.drawable.flag_zambia; case "zw": //zimbabwe return R.drawable.flag_zimbabwe; // Caribbean Islands case "ai": //anguilla return R.drawable.flag_anguilla; case "ag": //antigua & barbuda return R.drawable.flag_antigua_and_barbuda; case "bs": //bahamas return R.drawable.flag_bahamas; case "bb": //barbados return R.drawable.flag_barbados; case "bm": //bermuda return R.drawable.flag_bermuda; case "vg": //british virgin islands return R.drawable.flag_british_virgin_islands; case "dm": //dominica return R.drawable.flag_dominica; case "do": //dominican republic return R.drawable.flag_dominican_republic; case "gd": //grenada return R.drawable.flag_grenada; case "jm": //jamaica return R.drawable.flag_jamaica; case "ms": //montserrat return R.drawable.flag_montserrat; case "kn": //st kitts & nevis return R.drawable.flag_saint_kitts_and_nevis; case "lc": //st lucia return R.drawable.flag_saint_lucia; case "vc": //st vincent & the grenadines return R.drawable.flag_saint_vicent_and_the_grenadines; case "tt": //trinidad & tobago return R.drawable.flag_trinidad_and_tobago; case "tc": //turks & caicos islands return R.drawable.flag_turks_and_caicos_islands; case "vi": //us virgin islands return R.drawable.flag_us_virgin_islands; case "ss": // south sudan return R.drawable.flag_south_sudan; case "xk": // kosovo return R.drawable.flag_kosovo; default: return R.drawable.flag_transparent; } } /** * Get all countries * @param context caller context * @return List of Country */ static List<Country> getAllCountries(Context context) { if(countries != null) { return countries; } countries = new ArrayList<>(); countries.add(new Country(context.getString(R.string.country_afghanistan_code), context.getString(R.string.country_afghanistan_number), context.getString(R.string.country_afghanistan_name))); countries.add(new Country(context.getString(R.string.country_albania_code), context.getString(R.string.country_albania_number), context.getString(R.string.country_albania_name))); countries.add(new Country(context.getString(R.string.country_algeria_code), context.getString(R.string.country_algeria_number), context.getString(R.string.country_algeria_name))); countries.add(new Country(context.getString(R.string.country_andorra_code), context.getString(R.string.country_andorra_number), context.getString(R.string.country_andorra_name))); countries.add(new Country(context.getString(R.string.country_angola_code), context.getString(R.string.country_angola_number), context.getString(R.string.country_angola_name))); countries.add(new Country(context.getString(R.string.country_anguilla_code), context.getString(R.string.country_anguilla_number), context.getString(R.string.country_anguilla_name))); countries.add(new Country(context.getString(R.string.country_antarctica_code), context.getString(R.string.country_antarctica_number), context.getString(R.string.country_antarctica_name))); countries.add(new Country(context.getString(R.string.country_antigua_and_barbuda_code), context.getString(R.string.country_antigua_and_barbuda_number), context.getString(R.string.country_antigua_and_barbuda_name))); countries.add(new Country(context.getString(R.string.country_argentina_code), context.getString(R.string.country_argentina_number), context.getString(R.string.country_argentina_name))); countries.add(new Country(context.getString(R.string.country_armenia_code), context.getString(R.string.country_armenia_number), context.getString(R.string.country_armenia_name))); countries.add(new Country(context.getString(R.string.country_aruba_code), context.getString(R.string.country_aruba_number), context.getString(R.string.country_aruba_name))); countries.add(new Country(context.getString(R.string.country_australia_code), context.getString(R.string.country_australia_number), context.getString(R.string.country_australia_name))); countries.add(new Country(context.getString(R.string.country_austria_code), context.getString(R.string.country_austria_number), context.getString(R.string.country_austria_name))); countries.add(new Country(context.getString(R.string.country_azerbaijan_code), context.getString(R.string.country_azerbaijan_number), context.getString(R.string.country_azerbaijan_name))); countries.add(new Country(context.getString(R.string.country_bahamas_code), context.getString(R.string.country_bahamas_number), context.getString(R.string.country_bahamas_name))); countries.add(new Country(context.getString(R.string.country_bahrain_code), context.getString(R.string.country_bahrain_number), context.getString(R.string.country_bahrain_name))); countries.add(new Country(context.getString(R.string.country_bangladesh_code), context.getString(R.string.country_bangladesh_number), context.getString(R.string.country_bangladesh_name))); countries.add(new Country(context.getString(R.string.country_barbados_code), context.getString(R.string.country_barbados_number), context.getString(R.string.country_barbados_name))); countries.add(new Country(context.getString(R.string.country_belarus_code), context.getString(R.string.country_belarus_number), context.getString(R.string.country_belarus_name))); countries.add(new Country(context.getString(R.string.country_belgium_code), context.getString(R.string.country_belgium_number), context.getString(R.string.country_belgium_name))); countries.add(new Country(context.getString(R.string.country_belize_code), context.getString(R.string.country_belize_number), context.getString(R.string.country_belize_name))); countries.add(new Country(context.getString(R.string.country_benin_code), context.getString(R.string.country_benin_number), context.getString(R.string.country_benin_name))); countries.add(new Country(context.getString(R.string.country_bermuda_code), context.getString(R.string.country_bermuda_number), context.getString(R.string.country_bermuda_name))); countries.add(new Country(context.getString(R.string.country_bhutan_code), context.getString(R.string.country_bhutan_number), context.getString(R.string.country_bhutan_name))); countries.add(new Country(context.getString(R.string.country_bolivia_code), context.getString(R.string.country_bolivia_number), context.getString(R.string.country_bolivia_name))); countries.add(new Country(context.getString(R.string.country_bosnia_and_herzegovina_code), context.getString(R.string.country_bosnia_and_herzegovina_number), context.getString(R.string.country_bosnia_and_herzegovina_name))); countries.add(new Country(context.getString(R.string.country_botswana_code), context.getString(R.string.country_botswana_number), context.getString(R.string.country_botswana_name))); countries.add(new Country(context.getString(R.string.country_brazil_code), context.getString(R.string.country_brazil_number), context.getString(R.string.country_brazil_name))); countries.add(new Country(context.getString(R.string.country_british_virgin_islands_code), context.getString(R.string.country_british_virgin_islands_number), context.getString(R.string.country_british_virgin_islands_name))); countries.add(new Country(context.getString(R.string.country_brunei_darussalam_code), context.getString(R.string.country_brunei_darussalam_number), context.getString(R.string.country_brunei_darussalam_name))); countries.add(new Country(context.getString(R.string.country_bulgaria_code), context.getString(R.string.country_bulgaria_number), context.getString(R.string.country_bulgaria_name))); countries.add(new Country(context.getString(R.string.country_burkina_faso_code), context.getString(R.string.country_burkina_faso_number), context.getString(R.string.country_burkina_faso_name))); countries.add(new Country(context.getString(R.string.country_burundi_code), context.getString(R.string.country_burundi_number), context.getString(R.string.country_burundi_name))); countries.add(new Country(context.getString(R.string.country_cambodia_code), context.getString(R.string.country_cambodia_number), context.getString(R.string.country_cambodia_name))); countries.add(new Country(context.getString(R.string.country_cameroon_code), context.getString(R.string.country_cameroon_number), context.getString(R.string.country_cameroon_name))); countries.add(new Country(context.getString(R.string.country_canada_code), context.getString(R.string.country_canada_number), context.getString(R.string.country_canada_name))); countries.add(new Country(context.getString(R.string.country_cape_verde_code), context.getString(R.string.country_cape_verde_number), context.getString(R.string.country_cape_verde_name))); countries.add(new Country(context.getString(R.string.country_cayman_islands_code), context.getString(R.string.country_cayman_islands_number), context.getString(R.string.country_cayman_islands_name))); countries.add(new Country(context.getString(R.string.country_central_african_republic_code), context.getString(R.string.country_central_african_republic_number), context.getString(R.string.country_central_african_republic_name))); countries.add(new Country(context.getString(R.string.country_chad_code), context.getString(R.string.country_chad_number), context.getString(R.string.country_chad_name))); countries.add(new Country(context.getString(R.string.country_chile_code), context.getString(R.string.country_chile_number), context.getString(R.string.country_chile_name))); countries.add(new Country(context.getString(R.string.country_china_code), context.getString(R.string.country_china_number), context.getString(R.string.country_china_name))); countries.add(new Country(context.getString(R.string.country_christmas_island_code), context.getString(R.string.country_christmas_island_number), context.getString(R.string.country_christmas_island_name))); countries.add(new Country(context.getString(R.string.country_cocos_keeling_islands_code), context.getString(R.string.country_cocos_keeling_islands_number), context.getString(R.string.country_cocos_keeling_islands_name))); countries.add(new Country(context.getString(R.string.country_colombia_code), context.getString(R.string.country_colombia_number), context.getString(R.string.country_colombia_name))); countries.add(new Country(context.getString(R.string.country_comoros_code), context.getString(R.string.country_comoros_number), context.getString(R.string.country_comoros_name))); countries.add(new Country(context.getString(R.string.country_congo_code), context.getString(R.string.country_congo_number), context.getString(R.string.country_congo_name))); countries.add(new Country(context.getString(R.string.country_the_democratic_republic_of_congo_code), context.getString(R.string.country_the_democratic_republic_of_congo_number), context.getString(R.string.country_the_democratic_republic_of_congo_name))); countries.add(new Country(context.getString(R.string.country_cook_islands_code), context.getString(R.string.country_cook_islands_number), context.getString(R.string.country_cook_islands_name))); countries.add(new Country(context.getString(R.string.country_costa_rica_code), context.getString(R.string.country_costa_rica_number), context.getString(R.string.country_costa_rica_name))); countries.add(new Country(context.getString(R.string.country_croatia_code), context.getString(R.string.country_croatia_number), context.getString(R.string.country_croatia_name))); countries.add(new Country(context.getString(R.string.country_cuba_code), context.getString(R.string.country_cuba_number), context.getString(R.string.country_cuba_name))); countries.add(new Country(context.getString(R.string.country_cyprus_code), context.getString(R.string.country_cyprus_number), context.getString(R.string.country_cyprus_name))); countries.add(new Country(context.getString(R.string.country_czech_republic_code), context.getString(R.string.country_czech_republic_number), context.getString(R.string.country_czech_republic_name))); countries.add(new Country(context.getString(R.string.country_denmark_code), context.getString(R.string.country_denmark_number), context.getString(R.string.country_denmark_name))); countries.add(new Country(context.getString(R.string.country_djibouti_code), context.getString(R.string.country_djibouti_number), context.getString(R.string.country_djibouti_name))); countries.add(new Country(context.getString(R.string.country_dominica_code), context.getString(R.string.country_dominica_number), context.getString(R.string.country_dominica_name))); countries.add(new Country(context.getString(R.string.country_dominican_republic_code), context.getString(R.string.country_dominican_republic_number), context.getString(R.string.country_dominican_republic_name))); countries.add(new Country(context.getString(R.string.country_timor_leste_code), context.getString(R.string.country_timor_leste_number), context.getString(R.string.country_timor_leste_name))); countries.add(new Country(context.getString(R.string.country_ecuador_code), context.getString(R.string.country_ecuador_number), context.getString(R.string.country_ecuador_name))); countries.add(new Country(context.getString(R.string.country_egypt_code), context.getString(R.string.country_egypt_number), context.getString(R.string.country_egypt_name))); countries.add(new Country(context.getString(R.string.country_el_salvador_code), context.getString(R.string.country_el_salvador_number), context.getString(R.string.country_el_salvador_name))); countries.add(new Country(context.getString(R.string.country_equatorial_guinea_code), context.getString(R.string.country_equatorial_guinea_number), context.getString(R.string.country_equatorial_guinea_name))); countries.add(new Country(context.getString(R.string.country_eritrea_code), context.getString(R.string.country_eritrea_number), context.getString(R.string.country_eritrea_name))); countries.add(new Country(context.getString(R.string.country_estonia_code), context.getString(R.string.country_estonia_number), context.getString(R.string.country_estonia_name))); countries.add(new Country(context.getString(R.string.country_ethiopia_code), context.getString(R.string.country_ethiopia_number), context.getString(R.string.country_ethiopia_name))); countries.add(new Country(context.getString(R.string.country_falkland_islands_malvinas_code), context.getString(R.string.country_falkland_islands_malvinas_number), context.getString(R.string.country_falkland_islands_malvinas_name))); countries.add(new Country(context.getString(R.string.country_faroe_islands_code), context.getString(R.string.country_faroe_islands_number), context.getString(R.string.country_faroe_islands_name))); countries.add(new Country(context.getString(R.string.country_fiji_code), context.getString(R.string.country_fiji_number), context.getString(R.string.country_fiji_name))); countries.add(new Country(context.getString(R.string.country_finland_code), context.getString(R.string.country_finland_number), context.getString(R.string.country_finland_name))); countries.add(new Country(context.getString(R.string.country_france_code), context.getString(R.string.country_france_number), context.getString(R.string.country_france_name))); countries.add(new Country(context.getString(R.string.country_french_guyana_code), context.getString(R.string.country_french_guyana_number), context.getString(R.string.country_french_guyana_name))); countries.add(new Country(context.getString(R.string.country_french_polynesia_code), context.getString(R.string.country_french_polynesia_number), context.getString(R.string.country_french_polynesia_name))); countries.add(new Country(context.getString(R.string.country_gabon_code), context.getString(R.string.country_gabon_number), context.getString(R.string.country_gabon_name))); countries.add(new Country(context.getString(R.string.country_gambia_code), context.getString(R.string.country_gambia_number), context.getString(R.string.country_gambia_name))); countries.add(new Country(context.getString(R.string.country_georgia_code), context.getString(R.string.country_georgia_number), context.getString(R.string.country_georgia_name))); countries.add(new Country(context.getString(R.string.country_germany_code), context.getString(R.string.country_germany_number), context.getString(R.string.country_germany_name))); countries.add(new Country(context.getString(R.string.country_ghana_code), context.getString(R.string.country_ghana_number), context.getString(R.string.country_ghana_name))); countries.add(new Country(context.getString(R.string.country_gibraltar_code), context.getString(R.string.country_gibraltar_number), context.getString(R.string.country_gibraltar_name))); countries.add(new Country(context.getString(R.string.country_greece_code), context.getString(R.string.country_greece_number), context.getString(R.string.country_greece_name))); countries.add(new Country(context.getString(R.string.country_greenland_code), context.getString(R.string.country_greenland_number), context.getString(R.string.country_greenland_name))); countries.add(new Country(context.getString(R.string.country_grenada_code), context.getString(R.string.country_grenada_number), context.getString(R.string.country_grenada_name))); countries.add(new Country(context.getString(R.string.country_guatemala_code), context.getString(R.string.country_guatemala_number), context.getString(R.string.country_guatemala_name))); countries.add(new Country(context.getString(R.string.country_guinea_code), context.getString(R.string.country_guinea_number), context.getString(R.string.country_guinea_name))); countries.add(new Country(context.getString(R.string.country_guinea_bissau_code), context.getString(R.string.country_guinea_bissau_number), context.getString(R.string.country_guinea_bissau_name))); countries.add(new Country(context.getString(R.string.country_guyana_code), context.getString(R.string.country_guyana_number), context.getString(R.string.country_guyana_name))); countries.add(new Country(context.getString(R.string.country_haiti_code), context.getString(R.string.country_haiti_number), context.getString(R.string.country_haiti_name))); countries.add(new Country(context.getString(R.string.country_honduras_code), context.getString(R.string.country_honduras_number), context.getString(R.string.country_honduras_name))); countries.add(new Country(context.getString(R.string.country_hong_kong_code), context.getString(R.string.country_hong_kong_number), context.getString(R.string.country_hong_kong_name))); countries.add(new Country(context.getString(R.string.country_hungary_code), context.getString(R.string.country_hungary_number), context.getString(R.string.country_hungary_name))); countries.add(new Country(context.getString(R.string.country_india_code), context.getString(R.string.country_india_number), context.getString(R.string.country_india_name))); countries.add(new Country(context.getString(R.string.country_indonesia_code), context.getString(R.string.country_indonesia_number), context.getString(R.string.country_indonesia_name))); countries.add(new Country(context.getString(R.string.country_iran_code), context.getString(R.string.country_iran_number), context.getString(R.string.country_iran_name))); countries.add(new Country(context.getString(R.string.country_iraq_code), context.getString(R.string.country_iraq_number), context.getString(R.string.country_iraq_name))); countries.add(new Country(context.getString(R.string.country_ireland_code), context.getString(R.string.country_ireland_number), context.getString(R.string.country_ireland_name))); countries.add(new Country(context.getString(R.string.country_isle_of_man_code), context.getString(R.string.country_isle_of_man_number), context.getString(R.string.country_isle_of_man_name))); countries.add(new Country(context.getString(R.string.country_israel_code), context.getString(R.string.country_israel_number), context.getString(R.string.country_israel_name))); countries.add(new Country(context.getString(R.string.country_italy_code), context.getString(R.string.country_italy_number), context.getString(R.string.country_italy_name))); countries.add(new Country(context.getString(R.string.country_cote_d_ivoire_code), context.getString(R.string.country_cote_d_ivoire_number), context.getString(R.string.country_cote_d_ivoire_name))); countries.add(new Country(context.getString(R.string.country_jamaica_code), context.getString(R.string.country_jamaica_number), context.getString(R.string.country_jamaica_name))); countries.add(new Country(context.getString(R.string.country_japan_code), context.getString(R.string.country_japan_number), context.getString(R.string.country_japan_name))); countries.add(new Country(context.getString(R.string.country_jordan_code), context.getString(R.string.country_jordan_number), context.getString(R.string.country_jordan_name))); countries.add(new Country(context.getString(R.string.country_kazakhstan_code), context.getString(R.string.country_kazakhstan_number), context.getString(R.string.country_kazakhstan_name))); countries.add(new Country(context.getString(R.string.country_kenya_code), context.getString(R.string.country_kenya_number), context.getString(R.string.country_kenya_name))); countries.add(new Country(context.getString(R.string.country_kiribati_code), context.getString(R.string.country_kiribati_number), context.getString(R.string.country_kiribati_name))); countries.add(new Country(context.getString(R.string.country_kosovo_code), context.getString(R.string.country_kosovo_number), context.getString(R.string.country_kosovo_name))); countries.add(new Country(context.getString(R.string.country_kuwait_code), context.getString(R.string.country_kuwait_number), context.getString(R.string.country_kuwait_name))); countries.add(new Country(context.getString(R.string.country_kyrgyzstan_code), context.getString(R.string.country_kyrgyzstan_number), context.getString(R.string.country_kyrgyzstan_name))); countries.add(new Country(context.getString(R.string.country_lao_peoples_democratic_republic_code), context.getString(R.string.country_lao_peoples_democratic_republic_number), context.getString(R.string.country_lao_peoples_democratic_republic_name))); countries.add(new Country(context.getString(R.string.country_latvia_code), context.getString(R.string.country_latvia_number), context.getString(R.string.country_latvia_name))); countries.add(new Country(context.getString(R.string.country_lebanon_code), context.getString(R.string.country_lebanon_number), context.getString(R.string.country_lebanon_name))); countries.add(new Country(context.getString(R.string.country_lesotho_code), context.getString(R.string.country_lesotho_number), context.getString(R.string.country_lesotho_name))); countries.add(new Country(context.getString(R.string.country_liberia_code), context.getString(R.string.country_liberia_number), context.getString(R.string.country_liberia_name))); countries.add(new Country(context.getString(R.string.country_libya_code), context.getString(R.string.country_libya_number), context.getString(R.string.country_libya_name))); countries.add(new Country(context.getString(R.string.country_liechtenstein_code), context.getString(R.string.country_liechtenstein_number), context.getString(R.string.country_liechtenstein_name))); countries.add(new Country(context.getString(R.string.country_lithuania_code), context.getString(R.string.country_lithuania_number), context.getString(R.string.country_lithuania_name))); countries.add(new Country(context.getString(R.string.country_luxembourg_code), context.getString(R.string.country_luxembourg_number), context.getString(R.string.country_luxembourg_name))); countries.add(new Country(context.getString(R.string.country_macao_code), context.getString(R.string.country_macao_number), context.getString(R.string.country_macao_name))); countries.add(new Country(context.getString(R.string.country_macedonia_code), context.getString(R.string.country_macedonia_number), context.getString(R.string.country_macedonia_name))); countries.add(new Country(context.getString(R.string.country_madagascar_code), context.getString(R.string.country_madagascar_number), context.getString(R.string.country_madagascar_name))); countries.add(new Country(context.getString(R.string.country_malawi_code), context.getString(R.string.country_malawi_number), context.getString(R.string.country_malawi_name))); countries.add(new Country(context.getString(R.string.country_malaysia_code), context.getString(R.string.country_malaysia_number), context.getString(R.string.country_malaysia_name))); countries.add(new Country(context.getString(R.string.country_maldives_code), context.getString(R.string.country_maldives_number), context.getString(R.string.country_maldives_name))); countries.add(new Country(context.getString(R.string.country_mali_code), context.getString(R.string.country_mali_number), context.getString(R.string.country_mali_name))); countries.add(new Country(context.getString(R.string.country_malta_code), context.getString(R.string.country_malta_number), context.getString(R.string.country_malta_name))); countries.add(new Country(context.getString(R.string.country_marshall_islands_code), context.getString(R.string.country_marshall_islands_number), context.getString(R.string.country_marshall_islands_name))); countries.add(new Country(context.getString(R.string.country_martinique_code), context.getString(R.string.country_martinique_number), context.getString(R.string.country_martinique_name))); countries.add(new Country(context.getString(R.string.country_mauritania_code), context.getString(R.string.country_mauritania_number), context.getString(R.string.country_mauritania_name))); countries.add(new Country(context.getString(R.string.country_mauritius_code), context.getString(R.string.country_mauritius_number), context.getString(R.string.country_mauritius_name))); countries.add(new Country(context.getString(R.string.country_mayotte_code), context.getString(R.string.country_mayotte_number), context.getString(R.string.country_mayotte_name))); countries.add(new Country(context.getString(R.string.country_mexico_code), context.getString(R.string.country_mexico_number), context.getString(R.string.country_mexico_name))); countries.add(new Country(context.getString(R.string.country_micronesia_code), context.getString(R.string.country_micronesia_number), context.getString(R.string.country_micronesia_name))); countries.add(new Country(context.getString(R.string.country_moldova_code), context.getString(R.string.country_moldova_number), context.getString(R.string.country_moldova_name))); countries.add(new Country(context.getString(R.string.country_monaco_code), context.getString(R.string.country_monaco_number), context.getString(R.string.country_monaco_name))); countries.add(new Country(context.getString(R.string.country_mongolia_code), context.getString(R.string.country_mongolia_number), context.getString(R.string.country_mongolia_name))); countries.add(new Country(context.getString(R.string.country_montserrat_code), context.getString(R.string.country_montserrat_number), context.getString(R.string.country_montserrat_name))); countries.add(new Country(context.getString(R.string.country_montenegro_code), context.getString(R.string.country_montenegro_number), context.getString(R.string.country_montenegro_name))); countries.add(new Country(context.getString(R.string.country_morocco_code), context.getString(R.string.country_morocco_number), context.getString(R.string.country_morocco_name))); countries.add(new Country(context.getString(R.string.country_myanmar_code), context.getString(R.string.country_myanmar_number), context.getString(R.string.country_myanmar_name))); countries.add(new Country(context.getString(R.string.country_mozambique_code), context.getString(R.string.country_mozambique_number), context.getString(R.string.country_mozambique_name))); countries.add(new Country(context.getString(R.string.country_namibia_code), context.getString(R.string.country_namibia_number), context.getString(R.string.country_namibia_name))); countries.add(new Country(context.getString(R.string.country_nauru_code), context.getString(R.string.country_nauru_number), context.getString(R.string.country_nauru_name))); countries.add(new Country(context.getString(R.string.country_nepal_code), context.getString(R.string.country_nepal_number), context.getString(R.string.country_nepal_name))); countries.add(new Country(context.getString(R.string.country_netherlands_code), context.getString(R.string.country_netherlands_number), context.getString(R.string.country_netherlands_name))); countries.add(new Country(context.getString(R.string.country_new_caledonia_code), context.getString(R.string.country_new_caledonia_number), context.getString(R.string.country_new_caledonia_name))); countries.add(new Country(context.getString(R.string.country_new_zealand_code), context.getString(R.string.country_new_zealand_number), context.getString(R.string.country_new_zealand_name))); countries.add(new Country(context.getString(R.string.country_nicaragua_code), context.getString(R.string.country_nicaragua_number), context.getString(R.string.country_nicaragua_name))); countries.add(new Country(context.getString(R.string.country_niger_code), context.getString(R.string.country_niger_number), context.getString(R.string.country_niger_name))); countries.add(new Country(context.getString(R.string.country_nigeria_code), context.getString(R.string.country_nigeria_number), context.getString(R.string.country_nigeria_name))); countries.add(new Country(context.getString(R.string.country_niue_code), context.getString(R.string.country_niue_number), context.getString(R.string.country_niue_name))); countries.add(new Country(context.getString(R.string.country_north_korea_code), context.getString(R.string.country_north_korea_number), context.getString(R.string.country_north_korea_name))); countries.add(new Country(context.getString(R.string.country_norway_code), context.getString(R.string.country_norway_number), context.getString(R.string.country_norway_name))); countries.add(new Country(context.getString(R.string.country_oman_code), context.getString(R.string.country_oman_number), context.getString(R.string.country_oman_name))); countries.add(new Country(context.getString(R.string.country_pakistan_code), context.getString(R.string.country_pakistan_number), context.getString(R.string.country_pakistan_name))); countries.add(new Country(context.getString(R.string.country_palau_code), context.getString(R.string.country_palau_number), context.getString(R.string.country_palau_name))); countries.add(new Country(context.getString(R.string.country_panama_code), context.getString(R.string.country_panama_number), context.getString(R.string.country_panama_name))); countries.add(new Country(context.getString(R.string.country_papua_new_guinea_code), context.getString(R.string.country_papua_new_guinea_number), context.getString(R.string.country_papua_new_guinea_name))); countries.add(new Country(context.getString(R.string.country_paraguay_code), context.getString(R.string.country_paraguay_number), context.getString(R.string.country_paraguay_name))); countries.add(new Country(context.getString(R.string.country_peru_code), context.getString(R.string.country_peru_number), context.getString(R.string.country_peru_name))); countries.add(new Country(context.getString(R.string.country_philippines_code), context.getString(R.string.country_philippines_number), context.getString(R.string.country_philippines_name))); countries.add(new Country(context.getString(R.string.country_pitcairn_code), context.getString(R.string.country_pitcairn_number), context.getString(R.string.country_pitcairn_name))); countries.add(new Country(context.getString(R.string.country_poland_code), context.getString(R.string.country_poland_number), context.getString(R.string.country_poland_name))); countries.add(new Country(context.getString(R.string.country_portugal_code), context.getString(R.string.country_portugal_number), context.getString(R.string.country_portugal_name))); countries.add(new Country(context.getString(R.string.country_puerto_rico_code), context.getString(R.string.country_puerto_rico_number), context.getString(R.string.country_puerto_rico_name))); countries.add(new Country(context.getString(R.string.country_qatar_code), context.getString(R.string.country_qatar_number), context.getString(R.string.country_qatar_name))); countries.add(new Country(context.getString(R.string.country_reunion_code), context.getString(R.string.country_reunion_number), context.getString(R.string.country_reunion_name))); countries.add(new Country(context.getString(R.string.country_romania_code), context.getString(R.string.country_romania_number), context.getString(R.string.country_romania_name))); countries.add(new Country(context.getString(R.string.country_russian_federation_code), context.getString(R.string.country_russian_federation_number), context.getString(R.string.country_russian_federation_name))); countries.add(new Country(context.getString(R.string.country_rwanda_code), context.getString(R.string.country_rwanda_number), context.getString(R.string.country_rwanda_name))); countries.add(new Country(context.getString(R.string.country_saint_barthelemy_code), context.getString(R.string.country_saint_barthelemy_number), context.getString(R.string.country_saint_barthelemy_name))); countries.add(new Country(context.getString(R.string.country_saint_kitts_and_nevis_code), context.getString(R.string.country_saint_kitts_and_nevis_number), context.getString(R.string.country_saint_kitts_and_nevis_name))); countries.add(new Country(context.getString(R.string.country_saint_lucia_code), context.getString(R.string.country_saint_lucia_number), context.getString(R.string.country_saint_lucia_name))); countries.add(new Country(context.getString(R.string.country_saint_vincent_the_grenadines_code), context.getString(R.string.country_saint_vincent_the_grenadines_number), context.getString(R.string.country_saint_vincent_the_grenadines_name))); countries.add(new Country(context.getString(R.string.country_samoa_code), context.getString(R.string.country_samoa_number), context.getString(R.string.country_samoa_name))); countries.add(new Country(context.getString(R.string.country_san_marino_code), context.getString(R.string.country_san_marino_number), context.getString(R.string.country_san_marino_name))); countries.add(new Country(context.getString(R.string.country_sao_tome_and_principe_code), context.getString(R.string.country_sao_tome_and_principe_number), context.getString(R.string.country_sao_tome_and_principe_name))); countries.add(new Country(context.getString(R.string.country_saudi_arabia_code), context.getString(R.string.country_saudi_arabia_number), context.getString(R.string.country_saudi_arabia_name))); countries.add(new Country(context.getString(R.string.country_senegal_code), context.getString(R.string.country_senegal_number), context.getString(R.string.country_senegal_name))); countries.add(new Country(context.getString(R.string.country_serbia_code), context.getString(R.string.country_serbia_number), context.getString(R.string.country_serbia_name))); countries.add(new Country(context.getString(R.string.country_seychelles_code), context.getString(R.string.country_seychelles_number), context.getString(R.string.country_seychelles_name))); countries.add(new Country(context.getString(R.string.country_sierra_leone_code), context.getString(R.string.country_sierra_leone_number), context.getString(R.string.country_sierra_leone_name))); countries.add(new Country(context.getString(R.string.country_singapore_code), context.getString(R.string.country_singapore_number), context.getString(R.string.country_singapore_name))); countries.add(new Country(context.getString(R.string.country_sint_maarten_code), context.getString(R.string.country_sint_maarten_number), context.getString(R.string.country_sint_maarten_name))); countries.add(new Country(context.getString(R.string.country_slovakia_code), context.getString(R.string.country_slovakia_number), context.getString(R.string.country_slovakia_name))); countries.add(new Country(context.getString(R.string.country_slovenia_code), context.getString(R.string.country_slovenia_number), context.getString(R.string.country_slovenia_name))); countries.add(new Country(context.getString(R.string.country_solomon_islands_code), context.getString(R.string.country_solomon_islands_number), context.getString(R.string.country_solomon_islands_name))); countries.add(new Country(context.getString(R.string.country_somalia_code), context.getString(R.string.country_somalia_number), context.getString(R.string.country_somalia_name))); countries.add(new Country(context.getString(R.string.country_south_africa_code), context.getString(R.string.country_south_africa_number), context.getString(R.string.country_south_africa_name))); countries.add(new Country(context.getString(R.string.country_south_korea_code), context.getString(R.string.country_south_korea_number), context.getString(R.string.country_south_korea_name))); countries.add(new Country(context.getString(R.string.country_spain_code), context.getString(R.string.country_spain_number), context.getString(R.string.country_spain_name))); countries.add(new Country(context.getString(R.string.country_sri_lanka_code), context.getString(R.string.country_sri_lanka_number), context.getString(R.string.country_sri_lanka_name))); countries.add(new Country(context.getString(R.string.country_saint_helena_code), context.getString(R.string.country_saint_helena_number), context.getString(R.string.country_saint_helena_name))); countries.add(new Country(context.getString(R.string.country_saint_pierre_and_miquelon_code), context.getString(R.string.country_saint_pierre_and_miquelon_number), context.getString(R.string.country_saint_pierre_and_miquelon_name))); countries.add(new Country(context.getString(R.string.country_south_sudan_code), context.getString(R.string.country_south_sudan_number), context.getString(R.string.country_south_sudan_name))); countries.add(new Country(context.getString(R.string.country_sudan_code), context.getString(R.string.country_sudan_number), context.getString(R.string.country_sudan_name))); countries.add(new Country(context.getString(R.string.country_suriname_code), context.getString(R.string.country_suriname_number), context.getString(R.string.country_suriname_name))); countries.add(new Country(context.getString(R.string.country_swaziland_code), context.getString(R.string.country_swaziland_number), context.getString(R.string.country_swaziland_name))); countries.add(new Country(context.getString(R.string.country_sweden_code), context.getString(R.string.country_sweden_number), context.getString(R.string.country_sweden_name))); countries.add(new Country(context.getString(R.string.country_switzerland_code), context.getString(R.string.country_switzerland_number), context.getString(R.string.country_switzerland_name))); countries.add(new Country(context.getString(R.string.country_syrian_arab_republic_code), context.getString(R.string.country_syrian_arab_republic_number), context.getString(R.string.country_syrian_arab_republic_name))); countries.add(new Country(context.getString(R.string.country_taiwan_code), context.getString(R.string.country_taiwan_number), context.getString(R.string.country_taiwan_name))); countries.add(new Country(context.getString(R.string.country_tajikistan_code), context.getString(R.string.country_tajikistan_number), context.getString(R.string.country_tajikistan_name))); countries.add(new Country(context.getString(R.string.country_tanzania_code), context.getString(R.string.country_tanzania_number), context.getString(R.string.country_tanzania_name))); countries.add(new Country(context.getString(R.string.country_thailand_code), context.getString(R.string.country_thailand_number), context.getString(R.string.country_thailand_name))); countries.add(new Country(context.getString(R.string.country_togo_code), context.getString(R.string.country_togo_number), context.getString(R.string.country_togo_name))); countries.add(new Country(context.getString(R.string.country_tokelau_code), context.getString(R.string.country_tokelau_number), context.getString(R.string.country_tokelau_name))); countries.add(new Country(context.getString(R.string.country_tonga_code), context.getString(R.string.country_tonga_number), context.getString(R.string.country_tonga_name))); countries.add(new Country(context.getString(R.string.country_trinidad_tobago_code), context.getString(R.string.country_trinidad_tobago_number), context.getString(R.string.country_trinidad_tobago_name))); countries.add(new Country(context.getString(R.string.country_tunisia_code), context.getString(R.string.country_tunisia_number), context.getString(R.string.country_tunisia_name))); countries.add(new Country(context.getString(R.string.country_turkey_code), context.getString(R.string.country_turkey_number), context.getString(R.string.country_turkey_name))); countries.add(new Country(context.getString(R.string.country_turkmenistan_code), context.getString(R.string.country_turkmenistan_number), context.getString(R.string.country_turkmenistan_name))); countries.add(new Country(context.getString(R.string.country_turks_and_caicos_islands_code), context.getString(R.string.country_turks_and_caicos_islands_number), context.getString(R.string.country_turks_and_caicos_islands_name))); countries.add(new Country(context.getString(R.string.country_tuvalu_code), context.getString(R.string.country_tuvalu_number), context.getString(R.string.country_tuvalu_name))); countries.add(new Country(context.getString(R.string.country_united_arab_emirates_code), context.getString(R.string.country_united_arab_emirates_number), context.getString(R.string.country_united_arab_emirates_name))); countries.add(new Country(context.getString(R.string.country_uganda_code), context.getString(R.string.country_uganda_number), context.getString(R.string.country_uganda_name))); countries.add(new Country(context.getString(R.string.country_united_kingdom_code), context.getString(R.string.country_united_kingdom_number), context.getString(R.string.country_united_kingdom_name))); countries.add(new Country(context.getString(R.string.country_ukraine_code), context.getString(R.string.country_ukraine_number), context.getString(R.string.country_ukraine_name))); countries.add(new Country(context.getString(R.string.country_uruguay_code), context.getString(R.string.country_uruguay_number), context.getString(R.string.country_uruguay_name))); countries.add(new Country(context.getString(R.string.country_united_states_code), context.getString(R.string.country_united_states_number), context.getString(R.string.country_united_states_name))); countries.add(new Country(context.getString(R.string.country_us_virgin_islands_code), context.getString(R.string.country_us_virgin_islands_number), context.getString(R.string.country_us_virgin_islands_name))); countries.add(new Country(context.getString(R.string.country_uzbekistan_code), context.getString(R.string.country_uzbekistan_number), context.getString(R.string.country_uzbekistan_name))); countries.add(new Country(context.getString(R.string.country_vanuatu_code), context.getString(R.string.country_vanuatu_number), context.getString(R.string.country_vanuatu_name))); countries.add(new Country(context.getString(R.string.country_holy_see_vatican_city_state_code), context.getString(R.string.country_holy_see_vatican_city_state_number), context.getString(R.string.country_holy_see_vatican_city_state_name))); countries.add(new Country(context.getString(R.string.country_venezuela_code), context.getString(R.string.country_venezuela_number), context.getString(R.string.country_venezuela_name))); countries.add(new Country(context.getString(R.string.country_viet_nam_code), context.getString(R.string.country_viet_nam_number), context.getString(R.string.country_viet_nam_name))); countries.add(new Country(context.getString(R.string.country_wallis_and_futuna_code), context.getString(R.string.country_wallis_and_futuna_number), context.getString(R.string.country_wallis_and_futuna_name))); countries.add(new Country(context.getString(R.string.country_yemen_code), context.getString(R.string.country_yemen_number), context.getString(R.string.country_yemen_name))); countries.add(new Country(context.getString(R.string.country_zambia_code), context.getString(R.string.country_zambia_number), context.getString(R.string.country_zambia_name))); countries.add(new Country(context.getString(R.string.country_zimbabwe_code), context.getString(R.string.country_zimbabwe_number), context.getString(R.string.country_zimbabwe_name))); Collections.sort(countries, new Comparator<Country>() { @Override public int compare(Country country1, Country country2) { return country1.getName().compareToIgnoreCase(country2.getName()); } }); return countries; } /** * Finds country code by matching substring from left to right from full number. * For example. if full number is +819017901357 * function will ignore "+" and try to find match for first character "8" * if any country found for code "8", will return that country. If not, then it will * try to find country for "81". and so on till first 3 characters ( maximum number of characters * in country code is 3). * * @param preferredCountries countries of preference * @param fullNumber full number ( "+" (optional)+ country code + carrier number) i.e. * +819017901357 / 819017901357 / 918866667722 * @return Country JP +81(Japan) for +819017901357 or 819017901357 * Country IN +91(India) for 918866667722 * null for 2956635321 ( as neither of "2", "29" and "295" matches any country code) */ static Country getByNumber(Context context, List<Country> preferredCountries, String fullNumber) { int firstDigit; if (fullNumber.length() != 0) { if (fullNumber.charAt(0) == '+') { firstDigit = 1; } else { firstDigit = 0; } Country country; for (int i = firstDigit; i < firstDigit + 4; i++) { String code = fullNumber.substring(firstDigit, i); country = getByCode(context, preferredCountries, code); if (country != null) { return country; } } } return null; } /** * Search a country which matches @param code. * * @param preferredCountries list of country with priority, * @param code phone code. i.e 91 or 1 * @return Country that has phone code as @param code. * or returns null if no country matches given code. */ static Country getByCode(Context context, List<Country> preferredCountries, int code) { return getByCode(context, preferredCountries, code + ""); } /** * Search a country which matches @param code. * * @param preferredCountries is list of preference countries. * @param code phone code. i.e "91" or "1" * @return Country that has phone code as @param code. * or returns null if no country matches given code. * if same code (e.g. +1) available for more than one country ( US, canada) , this function will * return preferred country. */ private static Country getByCode(Context context, List<Country> preferredCountries, String code) { //check in preferred countries first if (preferredCountries != null && !preferredCountries.isEmpty()) { for (Country country : preferredCountries) { if (country.getPhoneCode().equals(code)) { return country; } } } for (Country country : CountryUtils.getAllCountries(context)) { if (country.getPhoneCode().equals(code)) { return country; } } return null; } /** * Search a country which matches @param nameCode. * * @param nameCode country name code. i.e US or us or Au. See countries.xml for all code names. * @return Country that has phone code as @param code. * or returns null if no country matches given code. */ static Country getByNameCodeFromCustomCountries(Context context, List<Country> customCountries, String nameCode) { if (customCountries == null || customCountries.size() == 0) { return getByNameCodeFromAllCountries(context, nameCode); } else { for (Country country : customCountries) { if (country.getIso().equalsIgnoreCase(nameCode)) { return country; } } } return null; } /** * Search a country which matches @param nameCode. * * @param nameCode country name code. i.e US or us or Au. See countries.xml for all code names. * @return Country that has phone code as @param code. * or returns null if no country matches given code. */ static Country getByNameCodeFromAllCountries(Context context, String nameCode) { List<Country> countries = CountryUtils.getAllCountries(context); for (Country country : countries) { if (country.getIso().equalsIgnoreCase(nameCode)) { return country; } } return null; } static List<String> getCountryIsoByTimeZone(Context context, String timeZoneId) { Map<String, List<String>> timeZoneAndCountryIsos = getTimeZoneAndCountryISOs(context); return timeZoneAndCountryIsos.get(timeZoneId); } /** * Return list of Map for timezone and iso country. * @param context * @return List of timezone and country. */ private static Map<String, List<String>> getTimeZoneAndCountryISOs(Context context) { if (timeZoneAndCountryISOs != null && !timeZoneAndCountryISOs.isEmpty()) { return timeZoneAndCountryISOs; } timeZoneAndCountryISOs = new HashMap<>(); // Read from raw InputStream inputStream = context.getResources().openRawResource(R.raw.zone1970); BufferedReader buf = new BufferedReader(new InputStreamReader(inputStream)); String lineJustFetched; String[] wordsArray; try { while (true) { lineJustFetched = buf.readLine(); if (lineJustFetched == null) { break; } else { wordsArray = lineJustFetched.split("\t"); // Ignore line which have # as the first character. if(!lineJustFetched.substring(0,1).contains(" if (wordsArray.length >= 3) { // First word is country code or list of country code separate by comma List<String> isos = new ArrayList<>(); Collections.addAll(isos, wordsArray[0].split(",")); // Third word in wordsArray is timezone. timeZoneAndCountryISOs.put(wordsArray[2], isos); } } } } } catch (IOException e) { e.printStackTrace(); } return timeZoneAndCountryISOs; } }
package com.lxt.stackAndQueue; import java.util.Stack; /** * * * * * @author zer0 * */ public class SortStackByStack { public static void sortStackByStack1(Stack<Integer> stack){ Stack<Integer> helps = new Stack<>(); int len = stack.size()-1; System.out.println(""+(len+1)); for(int i = 0; i <= len ; i++){ int min = Integer.MIN_VALUE; for(int j = len - i; j >=0 && !stack.isEmpty(); j int value = stack.pop(); if (min == Integer.MIN_VALUE) { min = value; }else { min = Math.min(min, value); } helps.push(value); } stack.push(min); while(!helps.isEmpty()){ int value = helps.pop(); if (min != value) { stack.push(value); } } } } /** * stack// * @param stack */ public static void sortStackByStack2(Stack<Integer> stack){ Stack<Integer> helps = new Stack<>(); while(!stack.isEmpty()){ int cur = stack.pop(); while(!helps.isEmpty() && helps.peek() < cur){ stack.push(helps.pop()); } helps.push(cur); } while(!helps.isEmpty()){ stack.push(helps.pop()); } } public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(4); stack.push(1); stack.push(5); stack.push(1); stack.push(2); stack.push(3); System.out.println(""+stack); SortStackByStack.sortStackByStack2(stack); System.out.println(""+stack); } }
package liquibase; import java.io.*; import java.text.DateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import liquibase.change.CheckSum; import liquibase.change.core.RawSQLChange; import liquibase.changelog.*; import liquibase.changelog.filter.*; import liquibase.changelog.visitor.*; import liquibase.command.CommandExecutionException; import liquibase.command.CommandFactory; import liquibase.command.LiquibaseCommand; import liquibase.command.core.DropAllCommand; import liquibase.database.Database; import liquibase.database.DatabaseConnection; import liquibase.database.DatabaseFactory; import liquibase.database.ObjectQuotingStrategy; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.OracleDatabase; import liquibase.diff.DiffGeneratorFactory; import liquibase.diff.DiffResult; import liquibase.diff.compare.CompareControl; import liquibase.diff.output.changelog.DiffToChangeLog; import liquibase.exception.DatabaseException; import liquibase.exception.LiquibaseException; import liquibase.exception.LockException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.Executor; import liquibase.executor.ExecutorService; import liquibase.executor.LoggingExecutor; import liquibase.lockservice.DatabaseChangeLogLock; import liquibase.lockservice.LockService; import liquibase.lockservice.LockServiceFactory; import liquibase.logging.LogFactory; import liquibase.logging.Logger; import liquibase.parser.ChangeLogParser; import liquibase.parser.ChangeLogParserFactory; import liquibase.resource.ResourceAccessor; import liquibase.serializer.ChangeLogSerializer; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.InvalidExampleException; import liquibase.snapshot.SnapshotControl; import liquibase.snapshot.SnapshotGeneratorFactory; import liquibase.statement.core.RawSqlStatement; import liquibase.statement.core.UpdateStatement; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Catalog; import liquibase.util.LiquibaseUtil; import liquibase.util.StreamUtil; import liquibase.util.StringUtils; /** * Primary facade class for interacting with Liquibase. * The built in command line, Ant, Maven and other ways of running Liquibase are wrappers around methods in this class. */ public class Liquibase { private DatabaseChangeLog databaseChangeLog; private String changeLogFile; private ResourceAccessor resourceAccessor; protected Database database; private Logger log; private ChangeLogParameters changeLogParameters; private ChangeExecListener changeExecListener; private ChangeLogSyncListener changeLogSyncListener; private boolean ignoreClasspathPrefix = true; /** * Creates a Liquibase instance for a given DatabaseConnection. The Database instance used will be found with {@link DatabaseFactory#findCorrectDatabaseImplementation(liquibase.database.DatabaseConnection)} * * @See DatabaseConnection * @See Database * @see #Liquibase(String, liquibase.resource.ResourceAccessor, liquibase.database.Database) * @see ResourceAccessor */ public Liquibase(String changeLogFile, ResourceAccessor resourceAccessor, DatabaseConnection conn) throws LiquibaseException { this(changeLogFile, resourceAccessor, DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn)); } /** * Creates a Liquibase instance. The changeLogFile parameter must be a path that can be resolved by the passed ResourceAccessor. * If windows style path separators are used for the changeLogFile, they will be standardized to unix style for better cross-system compatib. * * @See DatabaseConnection * @See Database * @see ResourceAccessor */ public Liquibase(String changeLogFile, ResourceAccessor resourceAccessor, Database database) throws LiquibaseException { log = LogFactory.getLogger(); if (changeLogFile != null) { this.changeLogFile = changeLogFile.replace('\\', '/'); //convert to standard / if using absolute path on windows } this.resourceAccessor = resourceAccessor; this.changeLogParameters = new ChangeLogParameters(database); this.database = database; } public Liquibase(DatabaseChangeLog changeLog, ResourceAccessor resourceAccessor, Database database) { log = LogFactory.getLogger(); this.databaseChangeLog = changeLog; if (changeLog != null) { this.changeLogFile = changeLog.getPhysicalFilePath(); } if (this.changeLogFile != null) { changeLogFile = changeLogFile.replace('\\', '/'); //convert to standard / if using absolute path on windows } this.resourceAccessor = resourceAccessor; this.database = database; this.changeLogParameters = new ChangeLogParameters(database); } /** * Return the change log file used by this Liquibase instance. */ public String getChangeLogFile() { return changeLogFile; } /** * Return the log used by this Liquibase instance. */ public Logger getLog() { return log; } /** * Returns the ChangeLogParameters container used by this Liquibase instance. */ public ChangeLogParameters getChangeLogParameters() { return changeLogParameters; } /** * Returns the Database used by this Liquibase instance. */ public Database getDatabase() { return database; } /** * Return ResourceAccessor used by this Liquibase instance. * @deprecated use the newer-terminology version {@link #getResourceAccessor()} */ public ResourceAccessor getFileOpener() { return resourceAccessor; } /** * Return ResourceAccessor used by this Liquibase instance. */ public ResourceAccessor getResourceAccessor() { return resourceAccessor; } /** * Use this function to override the current date/time function used to insert dates into the database. * Especially useful when using an unsupported database. * * @deprecated Should call {@link Database#setCurrentDateTimeFunction(String)} directly */ public void setCurrentDateTimeFunction(String currentDateTimeFunction) { this.database.setCurrentDateTimeFunction(currentDateTimeFunction); } /** * Convience method for {@link #update(Contexts)} that constructs the Context object from the passed string. */ public void update(String contexts) throws LiquibaseException { this.update(new Contexts(contexts)); } /** * Executes Liquibase "update" logic which ensures that the configured {@link Database} is up to date according to the configured changelog file. * To run in "no context mode", pass a null or empty context object. */ public void update(Contexts contexts) throws LiquibaseException { update(contexts, new LabelExpression()); } public void update(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { update(contexts, labelExpression, true); } public void update(Contexts contexts, LabelExpression labelExpression, boolean checkLiquibaseTables) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(true, changeLog, contexts, labelExpression); } ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator changeLogIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog); changeLogIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY); try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } resetServices(); } } public DatabaseChangeLog getDatabaseChangeLog() throws LiquibaseException { if (databaseChangeLog == null) { ChangeLogParser parser = ChangeLogParserFactory.getInstance().getParser(changeLogFile, resourceAccessor); databaseChangeLog = parser.parse(changeLogFile, changeLogParameters, resourceAccessor); } return databaseChangeLog; } protected UpdateVisitor createUpdateVisitor() { return new UpdateVisitor(database, changeExecListener); } protected ChangeLogIterator getStandardChangelogIterator(Contexts contexts, LabelExpression labelExpression, DatabaseChangeLog changeLog) throws DatabaseException { return new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); } public void update(String contexts, Writer output) throws LiquibaseException { this.update(new Contexts(contexts), output); } public void update(Contexts contexts, Writer output) throws LiquibaseException { update(contexts, new LabelExpression(), output); } public void update(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { update(contexts, labelExpression, output, true); } public void update(Contexts contexts, LabelExpression labelExpression, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); LoggingExecutor loggingExecutor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); ExecutorService.getInstance().setExecutor(database, loggingExecutor); outputHeader("Update Database Script"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { update(contexts, labelExpression, checkLiquibaseTables); output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); } public void update(int changesToApply, String contexts) throws LiquibaseException { update(changesToApply, new Contexts(contexts), new LabelExpression()); } public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(changesToApply)); logIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } resetServices(); } } public void update(String tag, String contexts) throws LiquibaseException { update(tag, new Contexts(contexts), new LabelExpression()); } public void update(String tag, Contexts contexts) throws LiquibaseException { update(tag, contexts, new LabelExpression()); } public void update(String tag, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { if (tag == null) { update(contexts, labelExpression); return; } changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new UpToTagChangeSetFilter(tag, ranChangeSetList)); logIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } resetServices(); } } public void update(int changesToApply, String contexts, Writer output) throws LiquibaseException { this.update(changesToApply, new Contexts(contexts), new LabelExpression(), output); } public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); LoggingExecutor loggingExecutor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); ExecutorService.getInstance().setExecutor(database, loggingExecutor); outputHeader("Update " + changesToApply + " Change Sets Database Script"); update(changesToApply, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } resetServices(); ExecutorService.getInstance().setExecutor(database, oldTemplate); } public void update(String tag, String contexts, Writer output) throws LiquibaseException { update(tag, new Contexts(contexts), new LabelExpression(), output); } public void update(String tag, Contexts contexts, Writer output) throws LiquibaseException { update(tag, contexts, new LabelExpression(), output); } public void update(String tag, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { if (tag == null) { update(contexts, labelExpression, output); return; } changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); LoggingExecutor loggingExecutor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); ExecutorService.getInstance().setExecutor(database, loggingExecutor); outputHeader("Update to '" + tag + "' Database Script"); update(tag, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } resetServices(); ExecutorService.getInstance().setExecutor(database, oldTemplate); } private void outputHeader(String message) throws DatabaseException { Executor executor = ExecutorService.getInstance().getExecutor(database); executor.comment("*********************************************************************"); executor.comment(message); executor.comment("*********************************************************************"); executor.comment("Change Log: " + changeLogFile); executor.comment("Ran at: " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date())); DatabaseConnection connection = getDatabase().getConnection(); if (connection != null) { executor.comment("Against: " + connection.getConnectionUserName() + "@" + connection.getURL()); } executor.comment("Liquibase version: " + LiquibaseUtil.getBuildVersion()); executor.comment("*********************************************************************" + StreamUtil.getLineSeparator()); if (database instanceof OracleDatabase) { executor.execute(new RawSqlStatement("SET DEFINE OFF;")); } if (database instanceof MSSQLDatabase && database.getDefaultCatalogName() != null) { executor.execute(new RawSqlStatement("USE " + database.escapeObjectName(database.getDefaultCatalogName(), Catalog.class) + ";")); } } public void rollback(int changesToRollback, String contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, null, contexts, output); } public void rollback(int changesToRollback, Contexts contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, null, contexts, output); } public void rollback(int changesToRollback, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { rollback(changesToRollback, null, contexts, labelExpression, output); } public void rollback(int changesToRollback, String rollbackScript, String contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, rollbackScript, new Contexts(contexts), output); } public void rollback(int changesToRollback, String rollbackScript, Contexts contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, rollbackScript, contexts, new LabelExpression(), output); } public void rollback(int changesToRollback, String rollbackScript, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database)); outputHeader("Rollback " + changesToRollback + " Change(s) Script"); rollback(changesToRollback, rollbackScript, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(int changesToRollback, String contexts) throws LiquibaseException { rollback(changesToRollback, null, contexts); } public void rollback(int changesToRollback, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { rollback(changesToRollback, null, contexts, labelExpression); } public void rollback(int changesToRollback, String rollbackScript, String contexts) throws LiquibaseException { rollback(changesToRollback, rollbackScript, new Contexts(contexts), new LabelExpression()); } public void rollback(int changesToRollback, String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); ChangeLogIterator logIterator = new ChangeLogIterator(database.getRanChangeSetList(), changeLog, new AlreadyRanChangeSetFilter(database.getRanChangeSetList(), ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(changesToRollback)); if (rollbackScript == null) { logIterator.run(new RollbackVisitor(database,changeExecListener), new RuntimeEnvironment(database, contexts, labelExpression)); } else { executeRollbackScript(rollbackScript, contexts, labelExpression); removeRunStatus(logIterator, contexts, labelExpression); } } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Error releasing lock", e); } resetServices(); } } protected void removeRunStatus(ChangeLogIterator logIterator, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { logIterator.run(new ChangeSetVisitor() { @Override public Direction getDirection() { return Direction.REVERSE; } @Override public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Set<ChangeSetFilterResult> filterResults) throws LiquibaseException { database.removeRanStatus(changeSet); database.commit(); } }, new RuntimeEnvironment(database, contexts, labelExpression)); } protected void executeRollbackScript(String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { final Executor executor = ExecutorService.getInstance().getExecutor(database); String rollbackScriptContents; try { Set<InputStream> streams = resourceAccessor.getResourcesAsStream(rollbackScript); if (streams == null || streams.size() == 0) { throw new LiquibaseException("Cannot find rollbackScript "+rollbackScript); } else if (streams.size() > 1) { throw new LiquibaseException("Found multiple rollbackScripts named "+rollbackScript); } rollbackScriptContents = StreamUtil.getStreamContents(streams.iterator().next()); } catch (IOException e) { throw new LiquibaseException("Error reading rollbackScript "+executor+": "+e.getMessage()); } RawSQLChange rollbackChange = new RawSQLChange(rollbackScriptContents); rollbackChange.setSplitStatements(true); rollbackChange.setStripComments(true); try { executor.execute(rollbackChange); } catch (DatabaseException e) { e = new DatabaseException("Error executing rollback script. ChangeSets will still be marked as rolled back: " + e.getMessage(), e); System.err.println(e.getMessage()); log.severe("Error executing rollback script", e); if (changeExecListener != null) { changeExecListener.runFailed(null, databaseChangeLog, database, e); } } database.commit(); } public void rollback(String tagToRollBackTo, String contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts, output); } public void rollback(String tagToRollBackTo, Contexts contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts, output); } public void rollback(String tagToRollBackTo, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts, labelExpression, output); } public void rollback(String tagToRollBackTo, String rollbackScript, String contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, rollbackScript, new Contexts(contexts), output); } public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, rollbackScript, contexts, new LabelExpression(), output); } public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database)); outputHeader("Rollback to '" + tagToRollBackTo + "' Script"); rollback(tagToRollBackTo, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(String tagToRollBackTo, String contexts) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts); } public void rollback(String tagToRollBackTo, Contexts contexts) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts); } public void rollback(String tagToRollBackTo, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { rollback(tagToRollBackTo, null, contexts, labelExpression); } public void rollback(String tagToRollBackTo, String rollbackScript, String contexts) throws LiquibaseException { rollback(tagToRollBackTo, rollbackScript, new Contexts(contexts)); } public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts) throws LiquibaseException { rollback(tagToRollBackTo, rollbackScript, contexts, new LabelExpression()); } public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new AfterTagChangeSetFilter(tagToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); if (rollbackScript == null) { logIterator.run(new RollbackVisitor(database, changeExecListener), new RuntimeEnvironment(database, contexts, labelExpression)); } else { executeRollbackScript(rollbackScript, contexts, labelExpression); removeRunStatus(logIterator, contexts, labelExpression); } } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } } resetServices(); } public void rollback(Date dateToRollBackTo, String contexts, Writer output) throws LiquibaseException { rollback(dateToRollBackTo, null, contexts, output); } public void rollback(Date dateToRollBackTo, String rollbackScript, String contexts, Writer output) throws LiquibaseException { rollback(dateToRollBackTo, new Contexts(contexts), new LabelExpression(), output); } public void rollback(Date dateToRollBackTo, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { rollback(dateToRollBackTo, null, contexts, labelExpression, output); } public void rollback(Date dateToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database)); outputHeader("Rollback to " + dateToRollBackTo + " Script"); rollback(dateToRollBackTo, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(Date dateToRollBackTo, String contexts) throws LiquibaseException { rollback(dateToRollBackTo, null, contexts); } public void rollback(Date dateToRollBackTo, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { rollback(dateToRollBackTo, null, contexts, labelExpression); } public void rollback(Date dateToRollBackTo, String rollbackScript, String contexts) throws LiquibaseException { rollback(dateToRollBackTo, new Contexts(contexts), new LabelExpression()); } public void rollback(Date dateToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new ExecutedAfterChangeSetFilter(dateToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); if (rollbackScript == null) { logIterator.run(new RollbackVisitor(database, changeExecListener), new RuntimeEnvironment(database, contexts, labelExpression)); } else { executeRollbackScript(rollbackScript, contexts, labelExpression); removeRunStatus(logIterator, contexts, labelExpression); } } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } } resetServices(); } public void changeLogSync(String contexts, Writer output) throws LiquibaseException { changeLogSync(new Contexts(contexts), new LabelExpression(), output); } public void changeLogSync(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to add all changesets to database history table"); changeLogSync(contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void changeLogSync(String contexts) throws LiquibaseException { changeLogSync(new Contexts(contexts), new LabelExpression()); } /** * @deprecated use version with LabelExpression */ public void changeLogSync(Contexts contexts) throws LiquibaseException { changeLogSync(contexts, new LabelExpression()); } public void changeLogSync(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); logIterator.run(new ChangeLogSyncVisitor(database, changeLogSyncListener), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } resetServices(); } } public void markNextChangeSetRan(String contexts, Writer output) throws LiquibaseException { markNextChangeSetRan(new Contexts(contexts), new LabelExpression(), output); } public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to add all changesets to database history table"); markNextChangeSetRan(contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void markNextChangeSetRan(String contexts) throws LiquibaseException { markNextChangeSetRan(new Contexts(contexts), new LabelExpression()); } public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(1)); logIterator.run(new ChangeLogSyncVisitor(database), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } resetServices(); } } public void futureRollbackSQL(String contexts, Writer output) throws LiquibaseException { futureRollbackSQL(null, contexts, output, true); } public void futureRollbackSQL(Writer output) throws LiquibaseException { futureRollbackSQL(null, null, new Contexts(), new LabelExpression(), output); } public void futureRollbackSQL(String contexts, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { futureRollbackSQL(null, contexts, output, checkLiquibaseTables); } public void futureRollbackSQL(Integer count, String contexts, Writer output) throws LiquibaseException { futureRollbackSQL(count, new Contexts(contexts), new LabelExpression(), output, true); } public void futureRollbackSQL(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { futureRollbackSQL(null, null, contexts, labelExpression, output); } public void futureRollbackSQL(Integer count, String contexts, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { futureRollbackSQL(count, new Contexts(contexts), new LabelExpression(), output, checkLiquibaseTables); } public void futureRollbackSQL(Integer count, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { futureRollbackSQL(count, contexts, labelExpression, output, true); } public void futureRollbackSQL(Integer count, Contexts contexts, LabelExpression labelExpression, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { futureRollbackSQL(count, null, contexts, labelExpression, output); } public void futureRollbackSQL(String tag, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { futureRollbackSQL(null, tag, contexts, labelExpression, output); } protected void futureRollbackSQL(Integer count, String tag, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { futureRollbackSQL(count, tag, contexts, labelExpression, output, true); } protected void futureRollbackSQL(Integer count, String tag, Contexts contexts, LabelExpression labelExpression, Writer output, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to roll back currently unexecuted changes"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(false, changeLog, contexts, labelExpression); } ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator; if (count == null && tag == null) { logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); } else if (count != null) { ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(count)); final ListVisitor listVisitor = new ListVisitor(); forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression)); logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new ChangeSetFilter() { @Override public ChangeSetFilterResult accepts(ChangeSet changeSet) { return new ChangeSetFilterResult(listVisitor.getSeenChangeSets().contains(changeSet), null, null); } }); } else { List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new UpToTagChangeSetFilter(tag, ranChangeSetList)); final ListVisitor listVisitor = new ListVisitor(); forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression)); logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new ChangeSetFilter() { @Override public ChangeSetFilterResult accepts(ChangeSet changeSet) { return new ChangeSetFilterResult(listVisitor.getSeenChangeSets().contains(changeSet), null, null); } }); } logIterator.run(new RollbackVisitor(database, changeExecListener), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } protected void resetServices() { LockServiceFactory.getInstance().resetAll(); ChangeLogHistoryServiceFactory.getInstance().resetAll(); ExecutorService.getInstance().reset(); } /** * Drops all database objects in the default schema. */ public final void dropAll() throws DatabaseException, LockException { dropAll(new CatalogAndSchema(getDatabase().getDefaultCatalogName(), getDatabase().getDefaultSchemaName())); } /** * Drops all database objects in the passed schema(s). */ public final void dropAll(CatalogAndSchema... schemas) throws DatabaseException { if (schemas == null || schemas.length == 0) { schemas = new CatalogAndSchema[] {new CatalogAndSchema(getDatabase().getDefaultCatalogName(), getDatabase().getDefaultSchemaName())}; } DropAllCommand dropAll = (DropAllCommand) CommandFactory.getInstance().getCommand("dropAll"); dropAll.setDatabase(this.getDatabase()); dropAll.setSchemas(schemas); try { dropAll.execute(); } catch (CommandExecutionException e) { throw new DatabaseException(e); } } /** * 'Tags' the database for future rollback */ public void tag(String tagString) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); getDatabase().tag(tagString); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } } } public boolean tagExists(String tagString) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); return getDatabase().doesTagExist(tagString); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } } } public void updateTestingRollback(String contexts) throws LiquibaseException { updateTestingRollback(new Contexts(contexts), new LabelExpression()); } public void updateTestingRollback(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { updateTestingRollback(null, contexts, labelExpression); } public void updateTestingRollback(String tag, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Date baseDate = new Date(); update(tag, contexts, labelExpression); rollback(baseDate, null, contexts, labelExpression); update(tag, contexts, labelExpression); } public void checkLiquibaseTables(boolean updateExistingNullChecksums, DatabaseChangeLog databaseChangeLog, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { ChangeLogHistoryService changeLogHistoryService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(getDatabase()); changeLogHistoryService.init(); if (updateExistingNullChecksums) { changeLogHistoryService.upgradeChecksums(databaseChangeLog, contexts, labelExpression); } LockServiceFactory.getInstance().getLockService(getDatabase()).init(); } /** * Returns true if it is "save" to migrate the database. * Currently, "safe" is defined as running in an output-sql mode or against a database on localhost. * It is fine to run Liquibase against a "non-safe" database, the method is mainly used to determine if the user * should be prompted before continuing. */ public boolean isSafeToRunUpdate() throws DatabaseException { return getDatabase().isSafeToRunUpdate(); } /** * Display change log lock information. */ public DatabaseChangeLogLock[] listLocks() throws LiquibaseException { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); return LockServiceFactory.getInstance().getLockService(database).listLocks(); } public void reportLocks(PrintStream out) throws LiquibaseException { DatabaseChangeLogLock[] locks = listLocks(); out.println("Database change log locks for " + getDatabase().getConnection().getConnectionUserName() + "@" + getDatabase().getConnection().getURL()); if (locks.length == 0) { out.println(" - No locks"); } for (DatabaseChangeLogLock lock : locks) { out.println(" - " + lock.getLockedBy() + " at " + DateFormat.getDateTimeInstance().format(lock.getLockGranted())); } } public void forceReleaseLocks() throws LiquibaseException { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); LockServiceFactory.getInstance().getLockService(database).forceReleaseLock(); } /** * @deprecated use version with LabelExpression */ public List<ChangeSet> listUnrunChangeSets(Contexts contexts) throws LiquibaseException { return listUnrunChangeSets(contexts, new LabelExpression()); } public List<ChangeSet> listUnrunChangeSets(Contexts contexts, LabelExpression labels) throws LiquibaseException { return listUnrunChangeSets(contexts, labels, true); } protected List<ChangeSet> listUnrunChangeSets(Contexts contexts, LabelExpression labels, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labels); DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(true, changeLog, contexts, labels); } changeLog.validate(database, contexts, labels); ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labels, changeLog); ListVisitor visitor = new ListVisitor(); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labels)); return visitor.getSeenChangeSets(); } /** * @deprecated use version with LabelExpression */ public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts) throws LiquibaseException { return getChangeSetStatuses(contexts, new LabelExpression()); } public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { return getChangeSetStatuses(contexts, labelExpression, true); } /** * Returns the ChangeSetStatuses of all changesets in the change log file and history in the order they would be ran. */ public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(true, changeLog, contexts, labelExpression); } changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog); StatusVisitor visitor = new StatusVisitor(database); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); return visitor.getStatuses(); } public void reportStatus(boolean verbose, String contexts, Writer out) throws LiquibaseException { reportStatus(verbose, new Contexts(contexts), new LabelExpression(), out); } public void reportStatus(boolean verbose, Contexts contexts, Writer out) throws LiquibaseException { reportStatus(verbose, contexts, new LabelExpression(), out); } public void reportStatus(boolean verbose, Contexts contexts, LabelExpression labels, Writer out) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labels); try { List<ChangeSet> unrunChangeSets = listUnrunChangeSets(contexts, labels, false); if (unrunChangeSets.size() == 0) { out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(" is up to date"); out.append(StreamUtil.getLineSeparator()); } else { out.append(String.valueOf(unrunChangeSets.size())); out.append(" change sets have not been applied to "); out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(StreamUtil.getLineSeparator()); if (verbose) { for (ChangeSet changeSet : unrunChangeSets) { out.append(" ").append(changeSet.toString(false)).append(StreamUtil.getLineSeparator()); } } } out.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } public Collection<RanChangeSet> listUnexpectedChangeSets(String contexts) throws LiquibaseException { return listUnexpectedChangeSets(new Contexts(contexts), new LabelExpression()); } public Collection<RanChangeSet> listUnexpectedChangeSets(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); DatabaseChangeLog changeLog = getDatabaseChangeLog(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); ExpectedChangesVisitor visitor = new ExpectedChangesVisitor(database.getRanChangeSetList()); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); return visitor.getUnexpectedChangeSets(); } public void reportUnexpectedChangeSets(boolean verbose, String contexts, Writer out) throws LiquibaseException { reportUnexpectedChangeSets(verbose, new Contexts(contexts), new LabelExpression(), out); } public void reportUnexpectedChangeSets(boolean verbose, Contexts contexts, LabelExpression labelExpression, Writer out) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); try { Collection<RanChangeSet> unexpectedChangeSets = listUnexpectedChangeSets(contexts, labelExpression); if (unexpectedChangeSets.size() == 0) { out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(" contains no unexpected changes!"); out.append(StreamUtil.getLineSeparator()); } else { out.append(String.valueOf(unexpectedChangeSets.size())); out.append(" unexpected changes were found in "); out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(StreamUtil.getLineSeparator()); if (verbose) { for (RanChangeSet ranChangeSet : unexpectedChangeSets) { out.append(" ").append(ranChangeSet.toString()).append(StreamUtil.getLineSeparator()); } } } out.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } /** * Sets checksums to null so they will be repopulated next run */ public void clearCheckSums() throws LiquibaseException { log.info("Clearing database change log checksums"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); UpdateStatement updateStatement = new UpdateStatement(getDatabase().getLiquibaseCatalogName(), getDatabase().getLiquibaseSchemaName(), getDatabase().getDatabaseChangeLogTableName()); updateStatement.addNewColumnValue("MD5SUM", null); ExecutorService.getInstance().getExecutor(database).execute(updateStatement); getDatabase().commit(); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } } resetServices(); } public final CheckSum calculateCheckSum(final String changeSetIdentifier) throws LiquibaseException { if (changeSetIdentifier == null) { throw new LiquibaseException(new IllegalArgumentException("changeSetIdentifier")); } final List<String> parts = StringUtils.splitAndTrim(changeSetIdentifier, "::"); if (parts == null || parts.size() < 3) { throw new LiquibaseException(new IllegalArgumentException("Invalid changeSet identifier: " + changeSetIdentifier)); } return this.calculateCheckSum(parts.get(0), parts.get(1), parts.get(2)); } public CheckSum calculateCheckSum(final String filename, final String id, final String author) throws LiquibaseException { log.info(String.format("Calculating checksum for changeset %s::%s::%s", filename, id, author)); final ChangeLogParameters changeLogParameters = this.getChangeLogParameters(); final ResourceAccessor resourceAccessor = this.getResourceAccessor(); final DatabaseChangeLog changeLog = ChangeLogParserFactory.getInstance().getParser(this.changeLogFile, resourceAccessor).parse(this.changeLogFile, changeLogParameters, resourceAccessor); // TODO: validate? final ChangeSet changeSet = changeLog.getChangeSet(filename, author, id); if (changeSet == null) { throw new LiquibaseException(new IllegalArgumentException("No such changeSet: " + filename + "::" + id + "::" + author)); } return changeSet.generateCheckSum(); } public void generateDocumentation(String outputDirectory) throws LiquibaseException { // call without context generateDocumentation(outputDirectory, new Contexts(), new LabelExpression()); } public void generateDocumentation(String outputDirectory, String contexts) throws LiquibaseException { generateDocumentation(outputDirectory, new Contexts(contexts), new LabelExpression()); } public void generateDocumentation(String outputDirectory, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { log.info("Generating Database Documentation"); changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, new Contexts(), new LabelExpression()); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new DbmsChangeSetFilter(database)); DBDocVisitor visitor = new DBDocVisitor(database); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); visitor.writeHTML(new File(outputDirectory), resourceAccessor); } catch (IOException e) { throw new LiquibaseException(e); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } } // try { // if (!LockService.getExecutor(database).waitForLock()) { // return; // DBDocChangeLogHandler changeLogHandler = new DBDocChangeLogHandler(outputDirectory, this, changeLogFile,resourceAccessor); // runChangeLogs(changeLogHandler); // changeLogHandler.writeHTML(this); // } finally { // releaseLock(); } public DiffResult diff(Database referenceDatabase, Database targetDatabase, CompareControl compareControl) throws LiquibaseException { return DiffGeneratorFactory.getInstance().compare(referenceDatabase, targetDatabase, compareControl); } /** * Checks changelogs for bad MD5Sums and preconditions before attempting a migration */ public void validate() throws LiquibaseException { DatabaseChangeLog changeLog = getDatabaseChangeLog(); changeLog.validate(database); } public void setChangeLogParameter(String key, Object value) { this.changeLogParameters.set(key, value); } /** * Add safe database properties as changelog parameters.<br/> * Safe properties are the ones that doesn't have side effects in liquibase state and also don't change in during the liquibase execution * @param database Database which propeties are put in the changelog * @throws DatabaseException */ private void setDatabasePropertiesAsChangelogParameters(Database database) throws DatabaseException { setChangeLogParameter("database.autoIncrementClause", database.getAutoIncrementClause(null, null)); setChangeLogParameter("database.currentDateTimeFunction", database.getCurrentDateTimeFunction()); setChangeLogParameter("database.databaseChangeLogLockTableName", database.getDatabaseChangeLogLockTableName()); setChangeLogParameter("database.databaseChangeLogTableName", database.getDatabaseChangeLogTableName()); setChangeLogParameter("database.databaseMajorVersion", database.getDatabaseMajorVersion()); setChangeLogParameter("database.databaseMinorVersion", database.getDatabaseMinorVersion()); setChangeLogParameter("database.databaseProductName", database.getDatabaseProductName()); setChangeLogParameter("database.databaseProductVersion", database.getDatabaseProductVersion()); setChangeLogParameter("database.defaultCatalogName", database.getDefaultCatalogName()); setChangeLogParameter("database.defaultSchemaName", database.getDefaultSchemaName()); setChangeLogParameter("database.defaultSchemaNamePrefix", StringUtils.trimToNull(database.getDefaultSchemaName())==null?"":"."+database.getDefaultSchemaName()); setChangeLogParameter("database.lineComment", database.getLineComment()); setChangeLogParameter("database.liquibaseSchemaName", database.getLiquibaseSchemaName()); setChangeLogParameter("database.liquibaseTablespaceName", database.getLiquibaseTablespaceName()); setChangeLogParameter("database.typeName", database.getShortName()); setChangeLogParameter("database.isSafeToRunUpdate", database.isSafeToRunUpdate()); setChangeLogParameter("database.requiresPassword", database.requiresPassword()); setChangeLogParameter("database.requiresUsername", database.requiresUsername()); setChangeLogParameter("database.supportsForeignKeyDisable", database.supportsForeignKeyDisable()); setChangeLogParameter("database.supportsInitiallyDeferrableColumns", database.supportsInitiallyDeferrableColumns()); setChangeLogParameter("database.supportsRestrictForeignKeys", database.supportsRestrictForeignKeys()); setChangeLogParameter("database.supportsSchemas", database.supportsSchemas()); setChangeLogParameter("database.supportsSequences", database.supportsSequences()); setChangeLogParameter("database.supportsTablespaces", database.supportsTablespaces()); } private LockService getLockService() { return LockServiceFactory.getInstance().getLockService(database); } public void setChangeExecListener(ChangeExecListener listener) { this.changeExecListener = listener; } public void setChangeLogSyncListener(ChangeLogSyncListener changeLogSyncListener) { this.changeLogSyncListener = changeLogSyncListener; } public void setIgnoreClasspathPrefix(boolean ignoreClasspathPrefix) { this.ignoreClasspathPrefix = ignoreClasspathPrefix; } public boolean isIgnoreClasspathPrefix() { return ignoreClasspathPrefix; } public void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter, PrintStream outputStream, Class<? extends DatabaseObject>... snapshotTypes) throws DatabaseException, IOException, ParserConfigurationException { generateChangeLog(catalogAndSchema, changeLogWriter, outputStream, null, snapshotTypes); } public void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter, PrintStream outputStream, ChangeLogSerializer changeLogSerializer, Class<? extends DatabaseObject>... snapshotTypes) throws DatabaseException, IOException, ParserConfigurationException { Set<Class<? extends DatabaseObject>> finalCompareTypes = null; if (snapshotTypes != null && snapshotTypes.length > 0) { finalCompareTypes = new HashSet<Class<? extends DatabaseObject>>(Arrays.asList(snapshotTypes)); } SnapshotControl snapshotControl = new SnapshotControl(this.getDatabase(), snapshotTypes); CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[]{new CompareControl.SchemaComparison(catalogAndSchema, catalogAndSchema)}, finalCompareTypes); // compareControl.addStatusListener(new OutDiffStatusListener()); DatabaseSnapshot originalDatabaseSnapshot = null; try { originalDatabaseSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), getDatabase(), snapshotControl); DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(originalDatabaseSnapshot, SnapshotGeneratorFactory.getInstance().createSnapshot(compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), null, snapshotControl), compareControl); changeLogWriter.setDiffResult(diffResult); if(changeLogSerializer != null) { changeLogWriter.print(outputStream, changeLogSerializer); } else { changeLogWriter.print(outputStream); } } catch (InvalidExampleException e) { throw new UnexpectedLiquibaseException(e); } } }
package com.maddyhome.idea.vim.group; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.command.Argument; import com.maddyhome.idea.vim.command.Command; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.command.SelectionType; import com.maddyhome.idea.vim.common.Register; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.handler.CaretOrder; import com.maddyhome.idea.vim.helper.EditorHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * This group works with command associated with copying and pasting text */ public class CopyGroup { /** * Creates the group */ public CopyGroup() { } /** * This yanks the text moved over by the motion command argument. * * @param editor The editor to yank from * @param context The data context * @param count The number of times to yank * @param rawCount The actual count entered by the user * @param argument The motion command argument * @return true if able to yank the text, false if not */ public boolean yankMotion(@NotNull Editor editor, DataContext context, int count, int rawCount, @NotNull Argument argument) { final Command motion = argument.getMotion(); if (motion == null) return false; final CaretModel caretModel = editor.getCaretModel(); final List<Pair.NonNull<Integer, Integer>> ranges = new ArrayList<>(caretModel.getCaretCount()); final Map<Caret, Integer> startOffsets = new HashMap<>(caretModel.getCaretCount()); for (Caret caret : caretModel.getAllCarets()) { final TextRange motionRange = MotionGroup.getMotionRange(editor, caret, context, count, rawCount, argument, true); if (motionRange == null) continue; assert motionRange.size() == 1; ranges.add(Pair.createNonNull(motionRange.getStartOffset(), motionRange.getEndOffset())); startOffsets.put(caret, motionRange.normalize().getStartOffset()); } final SelectionType type = SelectionType.fromCommandFlags(motion.getFlags()); final TextRange range = getTextRange(ranges, type); final SelectionType selectionType = type == SelectionType.CHARACTER_WISE && range.isMultiple() ? SelectionType.BLOCK_WISE : type; return yankRange(editor, range, selectionType, startOffsets); } /** * This yanks count lines of text * * @param editor The editor to yank from * @param count The number of lines to yank * @return true if able to yank the lines, false if not */ public boolean yankLine(@NotNull Editor editor, int count) { final CaretModel caretModel = editor.getCaretModel(); final List<Pair.NonNull<Integer, Integer>> ranges = new ArrayList<>(caretModel.getCaretCount()); for (Caret caret : caretModel.getAllCarets()) { final int start = VimPlugin.getMotion().moveCaretToLineStart(editor, caret); final int end = Math.min(VimPlugin.getMotion().moveCaretToLineEndOffset(editor, caret, count - 1, true) + 1, EditorHelper.getFileSize(editor)); if (end == -1) continue; ranges.add(Pair.createNonNull(start, end)); } final TextRange range = getTextRange(ranges, SelectionType.LINE_WISE); return yankRange(editor, range, SelectionType.LINE_WISE, null); } /** * This yanks a range of text * * @param editor The editor to yank from * @param range The range of text to yank * @param type The type of yank * @return true if able to yank the range, false if not */ public boolean yankRange(@NotNull Editor editor, @Nullable TextRange range, @NotNull SelectionType type, boolean moveCursor) { if (range == null) return false; final SelectionType selectionType = type == SelectionType.CHARACTER_WISE && range.isMultiple() ? SelectionType.BLOCK_WISE : type; final CaretModel caretModel = editor.getCaretModel(); final int[] rangeStartOffsets = range.getStartOffsets(); final int[] rangeEndOffsets = range.getEndOffsets(); if (selectionType == SelectionType.LINE_WISE) { final ArrayList<Pair.NonNull<Integer, Integer>> ranges = new ArrayList<>(caretModel.getCaretCount()); for (int i = 0; i < caretModel.getCaretCount(); i++) { ranges.add(Pair.createNonNull(EditorHelper.getLineStartForOffset(editor, rangeStartOffsets[i]), EditorHelper.getLineEndForOffset(editor, rangeEndOffsets[i]) + 1)); } range = getTextRange(ranges, selectionType); } if (moveCursor) { final Map<Caret, Integer> startOffsets = new HashMap<>(caretModel.getCaretCount()); if (type == SelectionType.BLOCK_WISE) { startOffsets.put(caretModel.getPrimaryCaret(), range.normalize().getStartOffset()); } else { final List<Caret> carets = caretModel.getAllCarets(); for (int i = 0; i < carets.size(); i++) { startOffsets .put(carets.get(i), new TextRange(rangeStartOffsets[i], rangeEndOffsets[i]).normalize().getStartOffset()); } } return yankRange(editor, range, selectionType, startOffsets); } else { return yankRange(editor, range, selectionType, null); } } /** * Pastes text from the last register into the editor. * * @param editor The editor to paste into * @param context The data context * @param count The number of times to perform the paste * @return true if able to paste, false if not */ public boolean putText(@NotNull Editor editor, @NotNull DataContext context, int count, boolean indent, boolean cursorAfter, boolean beforeCursor) { final Register register = VimPlugin.getRegister().getLastRegister(); if (register == null) return false; final SelectionType selectionType = register.getType(); if (selectionType == SelectionType.LINE_WISE && editor.isOneLineMode()) return false; final String text = register.getText(); for (Caret caret : EditorHelper.getOrderedCaretsList(editor, CaretOrder.DECREASING_OFFSET)) { final int startOffset = getStartOffset(editor, caret, selectionType, beforeCursor); if (text == null) { VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, startOffset); VimPlugin.getMark().setChangeMarks(editor, new TextRange(startOffset, startOffset)); continue; } putText(editor, caret, context, text, selectionType, CommandState.SubMode.NONE, startOffset, count, indent, cursorAfter); } return true; } public boolean putVisualRange(@NotNull Editor editor, @NotNull DataContext context, @NotNull TextRange range, int count, boolean indent, boolean cursorAfter) { final Register register = VimPlugin.getRegister().getLastRegister(); VimPlugin.getRegister().resetRegister(); if (register == null) return false; final SelectionType type = register.getType(); if (type == SelectionType.LINE_WISE && editor.isOneLineMode()) return false; final CaretModel caretModel = editor.getCaretModel(); final ArrayList<Pair.NonNull<Integer, Integer>> ranges = new ArrayList<>(caretModel.getCaretCount()); final List<Integer> endLines = new ArrayList<>(caretModel.getCaretCount()); for (int i = 0; i < range.size(); i++) { final int start = range.getStartOffsets()[i]; final int end = range.getEndOffsets()[i]; ranges.add(Pair.createNonNull(start, end)); endLines.add(editor.offsetToLogicalPosition(end).line); } final CommandState.SubMode subMode = CommandState.getInstance(editor).getSubMode(); if (subMode == CommandState.SubMode.VISUAL_LINE) { final int[] starts = new int[caretModel.getCaretCount()]; final int[] ends = new int[caretModel.getCaretCount()]; for (int i = 0; i < ranges.size(); i++) { final Pair.NonNull<Integer, Integer> subRange = ranges.get(i); starts[i] = subRange.first; ends[i] = Math.min(subRange.second + 1, EditorHelper.getFileSize(editor)); } range = new TextRange(starts, ends); } final List<Caret> carets = EditorHelper.getOrderedCaretsList(editor, CaretOrder.DECREASING_OFFSET); for (int i = 0; i < carets.size(); i++) { final Caret caret = carets.get(i); final int index = carets.size() - i - 1; VimPlugin.getChange() .deleteRange(editor, caret, new TextRange(range.getStartOffsets()[index], range.getEndOffsets()[index]), SelectionType.fromSubMode(subMode), false); final int start = ranges.get(index).first; caret.moveToOffset(start); int startOffset = start; if (type == SelectionType.LINE_WISE) { if (subMode == CommandState.SubMode.VISUAL_BLOCK) { startOffset = editor.getDocument().getLineEndOffset(endLines.get(index)) + 1; } else if (subMode != CommandState.SubMode.VISUAL_LINE) { editor.getDocument().insertString(start, "\n"); startOffset = start + 1; } } else if (type != SelectionType.CHARACTER_WISE) { if (subMode == CommandState.SubMode.VISUAL_LINE) { editor.getDocument().insertString(start, "\n"); } } final String text = register.getText(); if (text == null) { VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, startOffset); VimPlugin.getMark().setChangeMarks(editor, new TextRange(startOffset, startOffset)); continue; } putText(editor, caret, context, text, type, subMode, startOffset, count, indent && type == SelectionType.LINE_WISE, cursorAfter); } return true; } /** * This performs the actual insert of the paste * * @param editor The editor to paste into * @param context The data context * @param startOffset The location within the file to paste the text * @param text The text to paste * @param type The type of paste * @param count The number of times to paste the text * @param indent True if pasted lines should be autoindented, false if not * @param cursorAfter If true move cursor to just after pasted text * @param mode The type of highlight prior to the put. * @param caret The caret to insert to */ public void putText(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, @NotNull String text, @NotNull SelectionType type, @NotNull CommandState.SubMode mode, int startOffset, int count, boolean indent, boolean cursorAfter) { if (mode == CommandState.SubMode.VISUAL_LINE && editor.isOneLineMode()) return; if (indent && type != SelectionType.LINE_WISE && mode != CommandState.SubMode.VISUAL_LINE) indent = false; if (type == SelectionType.LINE_WISE && text.length() > 0 && text.charAt(text.length() - 1) != '\n') { text = text + '\n'; } final int endOffset = putTextInternal(editor, caret, context, text, type, mode, startOffset, count, indent); moveCaret(editor, caret, type, mode, startOffset, cursorAfter, endOffset); VimPlugin.getMark().setChangeMarks(editor, new TextRange(startOffset, endOffset)); } private int putTextInternal(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, @NotNull String text, @NotNull SelectionType type, @NotNull CommandState.SubMode mode, int startOffset, int count, boolean indent) { final int endOffset = type != SelectionType.BLOCK_WISE ? putTextInternal(editor, caret, text, startOffset, count) : putTextInternal(editor, caret, context, text, mode, startOffset, count); if (indent) return doIndent(editor, caret, context, startOffset, endOffset); return endOffset; } private int putTextInternal(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, @NotNull String text, @NotNull CommandState.SubMode mode, int startOffset, int count) { final LogicalPosition startPosition = editor.offsetToLogicalPosition(startOffset); final int currentColumn = mode == CommandState.SubMode.VISUAL_LINE ? 0 : startPosition.column; int currentLine = startPosition.line; final int lineCount = StringUtil.getLineBreakCount(text) + 1; if (currentLine + lineCount >= EditorHelper.getLineCount(editor)) { final int limit = currentLine + lineCount - EditorHelper.getLineCount(editor); for (int i = 0; i < limit; i++) { MotionGroup.moveCaret(editor, caret, EditorHelper.getFileSize(editor, true)); VimPlugin.getChange().insertText(editor, caret, "\n"); } } final int maxLen = getMaxSegmentLength(text); final StringTokenizer tokenizer = new StringTokenizer(text, "\n"); int endOffset = startOffset; while (tokenizer.hasMoreTokens()) { String segment = tokenizer.nextToken(); String origSegment = segment; if (segment.length() < maxLen) { segment += StringUtil.repeat(" ", maxLen - segment.length()); if (currentColumn != 0 && currentColumn < EditorHelper.getLineLength(editor, currentLine)) { origSegment = segment; } } final String pad = EditorHelper.pad(editor, context, currentLine, currentColumn); final int insertOffset = editor.logicalPositionToOffset(new LogicalPosition(currentLine, currentColumn)); MotionGroup.moveCaret(editor, caret, insertOffset); final String insertedText = origSegment + StringUtil.repeat(segment, count - 1); VimPlugin.getChange().insertText(editor, caret, insertedText); endOffset += insertedText.length(); if (mode == CommandState.SubMode.VISUAL_LINE) { MotionGroup.moveCaret(editor, caret, endOffset); VimPlugin.getChange().insertText(editor, caret, "\n"); ++endOffset; } else { if (pad.length() > 0) { MotionGroup.moveCaret(editor, caret, insertOffset); VimPlugin.getChange().insertText(editor, caret, pad); endOffset += pad.length(); } } ++currentLine; } return endOffset; } private int putTextInternal(@NotNull Editor editor, @NotNull Caret caret, @NotNull String text, int startOffset, int count) { MotionGroup.moveCaret(editor, caret, startOffset); final String insertedText = StringUtil.repeat(text, count); VimPlugin.getChange().insertText(editor, caret, insertedText); return startOffset + insertedText.length(); } private int getStartOffset(@NotNull Editor editor, @NotNull Caret caret, SelectionType type, boolean beforeCursor) { if (beforeCursor) { return type == SelectionType.LINE_WISE ? VimPlugin.getMotion().moveCaretToLineStart(editor, caret) : caret.getOffset(); } int startOffset; if (type == SelectionType.LINE_WISE) { startOffset = Math.min(editor.getDocument().getTextLength(), VimPlugin.getMotion().moveCaretToLineEnd(editor, caret) + 1); if (startOffset > 0 && startOffset == editor.getDocument().getTextLength() && editor.getDocument().getCharsSequence().charAt(startOffset - 1) != '\n') { editor.getDocument().insertString(startOffset, "\n"); startOffset++; } } else { startOffset = caret.getOffset(); if (!EditorHelper.isLineEmpty(editor, caret.getLogicalPosition().line, false)) { startOffset++; } } if (startOffset > 0 && startOffset > editor.getDocument().getTextLength()) return startOffset - 1; return startOffset; } private void moveCaret(@NotNull Editor editor, @NotNull Caret caret, @NotNull SelectionType type, @NotNull CommandState.SubMode mode, int startOffset, boolean cursorAfter, int endOffset) { int cursorMode; switch (type) { case BLOCK_WISE: if (mode == CommandState.SubMode.VISUAL_LINE) { cursorMode = cursorAfter ? 4 : 1; } else { cursorMode = cursorAfter ? 5 : 1; } break; case LINE_WISE: cursorMode = cursorAfter ? 4 : 3; break; default: if (mode == CommandState.SubMode.VISUAL_LINE) { cursorMode = cursorAfter ? 4 : 1; } else { cursorMode = cursorAfter ? 5 : 2; } break; } switch (cursorMode) { case 1: MotionGroup.moveCaret(editor, caret, startOffset); break; case 2: MotionGroup.moveCaret(editor, caret, endOffset - 1); break; case 3: MotionGroup.moveCaret(editor, caret, startOffset); MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, caret)); break; case 4: MotionGroup.moveCaret(editor, caret, endOffset + 1); break; case 5: int pos = Math.min(endOffset, EditorHelper.getLineEndForOffset(editor, endOffset - 1) - 1); MotionGroup.moveCaret(editor, caret, pos); break; } } private int doIndent(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, int startOffset, int endOffset) { final int startLine = editor.offsetToLogicalPosition(startOffset).line; final int endLine = editor.offsetToLogicalPosition(endOffset - 1).line; final int startLineOffset = editor.getDocument().getLineStartOffset(startLine); final int endLineOffset = editor.getDocument().getLineEndOffset(endLine); VimPlugin.getChange().autoIndentRange(editor, caret, context, new TextRange(startLineOffset, endLineOffset)); return EditorHelper.getLineEndOffset(editor, endLine, true); } private int getMaxSegmentLength(@NotNull String text) { final StringTokenizer tokenizer = new StringTokenizer(text, "\n"); int maxLen = 0; while (tokenizer.hasMoreTokens()) { final String s = tokenizer.nextToken(); maxLen = Math.max(s.length(), maxLen); } return maxLen; } @NotNull private TextRange getTextRange(@NotNull List<Pair.NonNull<Integer, Integer>> ranges, @NotNull SelectionType type) { final int size = ranges.size(); final int[] starts = new int[size]; final int[] ends = new int[size]; switch (type) { case LINE_WISE: starts[size - 1] = ranges.get(size - 1).first; ends[size - 1] = ranges.get(size - 1).second; for (int i = 0; i < size - 1; i++) { final Pair.NonNull<Integer, Integer> range = ranges.get(i); starts[i] = range.first; ends[i] = range.second - 1; } break; case CHARACTER_WISE: for (int i = 0; i < size; i++) { final Pair.NonNull<Integer, Integer> range = ranges.get(i); starts[i] = range.first; ends[i] = range.second; } break; case BLOCK_WISE: assert ranges.size() == 1; } return new TextRange(starts, ends); } private boolean yankRange(@NotNull Editor editor, @NotNull TextRange range, @NotNull SelectionType type, @Nullable Map<Caret, Integer> startOffsets) { if (startOffsets != null) startOffsets.forEach((caret, offset) -> MotionGroup.moveCaret(editor, caret, offset)); return VimPlugin.getRegister().storeText(editor, range, type, false); } }
package net.galaxygaming.dispenser.game; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import net.galaxygaming.dispenser.GameDispenser; import net.galaxygaming.dispenser.task.GameRunnable; import net.galaxygaming.selection.Selection; import net.galaxygaming.util.FormatUtil; import net.galaxygaming.util.LocationUtil; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.metadata.MetadataValue; import org.bukkit.metadata.Metadatable; import org.bukkit.plugin.Plugin; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import net.galaxygaming.dispenser.game.GameLoader; /** * @author t7seven7t */ public abstract class GameBase implements Game { /** The current game state */ protected GameState state = GameState.INACTIVE; /** Name of this game instance */ private String name; /** List of players in this game */ private List<Player> players; /** List of component names for this game */ private List<String> components; /** * The maximum number of players the game can have. * A value of 0 will be interpreted as the maximum * that a list is capable of holding. */ protected int maximumPlayers; /** The minimum number of players before the game can start */ protected int minimumPlayers; /** The length of the countdown period in seconds */ protected int countdownDuration; /** The length of the game in seconds, if -1 the game will never end */ protected int gameTime; /** The option to use a built-in scoreboard */ protected boolean useScoreboard; /** The game's scoreboard */ protected Scoreboard board; /** The board's objective */ protected Objective objective; /** The scores to be set for player. Set to less than 1 to leave out of scoreboard */ protected int playerTagScore, playerCounterScore = 0; /** The scores to be set for the time remaining. Set to less than 1 to leave out of scoreboard */ protected int timeTagScore, timeCounterScore = 0; /** The last recorded amount of players in the game */ protected int lastPlayerCount; /** The last recorded time remaining */ protected int lastTimeRemaining; /** The length of the grace period in seconds */ protected int graceDuration; private GameType type; private GameLoader loader; private FileConfiguration config; private File configFile; private ClassLoader classLoader; private Logger logger; private GameDispenser plugin; Plugin fakePlugin; private Set<Location> signs; private int counter; private int tick; public final void addSign(Location location) { Validate.notNull(location, "Location cannot be null"); signs.add(location); new GameRunnable() { @Override public void run() { updateSigns(); } }.runTask(); } public final void removeSign(Location location) { signs.remove(location); } public final Set<Location> getSigns() { return Collections.unmodifiableSet(signs); } public final void updateSigns() { Iterator<Location> it = signs.iterator(); while (it.hasNext()) { Location loc = it.next(); BlockState state = loc.getBlock().getState(); if (!(state instanceof Sign)) { it.remove(); continue; } Sign sign = (Sign) state; sign.setLine(0, "[" + getType().toString() + "]"); sign.setLine(1, getName()); sign.setLine(2, getState().getFancyName()); sign.setLine(3, FormatUtil.format("{2}{0}/{1}", getPlayers().length, maximumPlayers > 0 ? maximumPlayers : "\u221e", ChatColor.YELLOW)); sign.update(false, false); } } protected final void addComponent(String componentName) { components.add(componentName); } @Override public final List<String> getComponents() { return Lists.newArrayList(components); } @Override public void broadcast(String message, Object... objects) { String formatted = FormatUtil.format("&6" + message, objects); for (Player player : players) { player.sendMessage(formatted); } } protected final ClassLoader getClassLoader() { return classLoader; } @Override public final FileConfiguration getConfig() { return this.config; } @Override public final void save() { List<String> signLocations = Lists.newArrayList(); for (Location location : signs) { signLocations.add(LocationUtil.serializeLocation(location)); } config.set("signs", signLocations); onSave(); try { this.config.save(configFile); } catch (IOException e) { getLogger().log(Level.WARNING, "Error ocurred while saving config", e); } } /** * Gives the file associated with this game's config * @return config file */ protected final File getConfigFile() { return this.configFile; } @Override public final GameLoader getGameLoader() { return this.loader; } @Override public final Logger getLogger() { return this.logger; } @Override public final GameMetadata getMetadata(Metadatable object, String key) { for (MetadataValue v : object.getMetadata(key)) { if (v instanceof GameMetadata) { GameMetadata data = (GameMetadata) v; if (data.getOwningPlugin() == fakePlugin) { return data; } } } return null; } @Override public final void removeMetadata(Metadatable object, String key) { object.removeMetadata(key, fakePlugin); } @Override public final GameDispenser getPlugin() { return this.plugin; } @Override public final GameState getState() { return this.state; } @Override public final void setState(GameState state) { this.state = state; } @Override public final GameType getType() { return this.type; } @Override public final String getName() { return this.name; } @Override public final void setName(String name) { this.name = name; } @Override public final void startCountdown() { if (getState().ordinal() >= GameState.STARTING.ordinal()) { return; } setState(GameState.STARTING); updateSigns(); counter = countdownDuration; } @Override public final void start() { if (!isSetup()) { return; } if (graceDuration > 0) { counter = graceDuration; setState(GameState.GRACE); } else { counter = gameTime; setState(GameState.ACTIVE); } for (Player player : players) { player.setMetadata("gameLastLocation", new GameFixedMetadata(this, player.getLocation().clone())); } onStart(); updateSigns(); } @Override public final void tick() { if (getState().ordinal() > GameState.STARTING.ordinal() && isFinished()) { end(); return; } if (tick % 20 == 0 && counter > 0) { updateScoreboard(); if (counter % 60 == 0 || (counter < 60 && counter % 30 == 0) || (counter <= 5 && counter > 0)) { if (getState().ordinal() == GameState.STARTING.ordinal()) { broadcast(type.getMessages().getMessage("game.countdown.start"), counter); } else if (getState().ordinal() > GameState.GRACE.ordinal()) { broadcast(type.getMessages().getMessage("game.countdown.end"), counter); } } counter if (counter <= 0) { if (getState().ordinal() == GameState.STARTING.ordinal()) { start(); } else if (getState().ordinal() == GameState.GRACE.ordinal()) { setState(GameState.ACTIVE); } else if (getState().ordinal() > GameState.GRACE.ordinal()) { end(); } } if (players.size() == 0) { end(); counter = 0; } } tick++; if (tick >= 20) tick = 0; onTick(); } @Override public final void end() { setState(GameState.INACTIVE); onEnd(); for (Player player : Lists.newArrayList(players.iterator())) { removePlayer(player); } updateSigns(); } @Override public final boolean addPlayer(Player player) { if (players.size() >= maximumPlayers && maximumPlayers > 0) { return false; } if (getState().ordinal() < GameState.STARTING.ordinal()) { setState(GameState.LOBBY); } players.add(player); GameManager.getInstance().addPlayerToGame(player, this); if (players.size() >= minimumPlayers) { startCountdown(); } broadcast(type.getMessages().getMessage("game.broadcastPlayerJoin"), player.getName(), players.size(), maximumPlayers > 0 ? maximumPlayers : "\u221e"); onPlayerJoin(player); updateSigns(); updateScoreboard(); return true; } @Override public final void removePlayer(Player player) { removePlayer(player, false); } @Override public final void removePlayer(Player player, boolean broadcast) { if (broadcast) { broadcast(type.getMessages().getMessage("game.broadcastPlayerLeave"), player.getName(), players.size(), maximumPlayers > 0 ? maximumPlayers : "\u221e"); } GameManager.getInstance().removePlayerFromGame(player); players.remove(player); if (getMetadata(player, "gameLastLocation") != null) { player.teleport((Location) getMetadata(player, "gameLastLocation").value()); removeMetadata(player, "gameLastLocation"); } updateSigns(); updateScoreboard(); } @Override public final Player[] getPlayers() { return players.toArray(new Player[players.size()]); } /* Override the following methods and let * devs choose whether to use them */ @Override public void onSave() {} @Override public void onLoad() {} @Override public void onStart() {} @Override public void onTick() {} @Override public void onEnd() {} @Override public void onPlayerJoin(Player player) {} @Override public void onPlayerLeave(Player player) {} @Override public boolean isFinished() { return false; } @Override public boolean setComponent(String componentName, Location location) { return false; } @Override public boolean setComponent(String componentName, Selection selection) { return false; } @Override public boolean setComponent(String componentName, String[] args) { return false; } @Override public final boolean equals(Object o) { if (o == null) { return false; } if (getClass() != o.getClass()) { return false; } if (getClass() == o.getClass()) { if (this.name.equalsIgnoreCase(((GameBase) o).name)) { return true; } } else if (o.getClass() == String.class) { if (this.name.equalsIgnoreCase((String) o)) { return true; } } return false; } @Override public final int hashCode() { return name.hashCode(); } public final InputStream getResource(String fileName) { Validate.notNull(fileName, "Filename cannot be null"); try { URL url = getClassLoader().getResource(fileName); if (url == null) { return null; } URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); } catch (IOException e) { return null; } } public GameBase() { final ClassLoader classLoader = this.getClass().getClassLoader(); if (!(classLoader instanceof GameClassLoader)) { throw new IllegalStateException("JavaGame requires " + GameClassLoader.class.getName()); } } final void initialize(String name, FileConfiguration config, GameLoader loader, File file, ClassLoader classLoader) { this.name = name; this.config = config; this.loader = loader; this.configFile = file; this.classLoader = classLoader; this.logger = new GameLogger(this, GameDispenser.getInstance()); this.players = Lists.newArrayList(); this.plugin = GameDispenser.getInstance(); this.fakePlugin = new FakePlugin(); this.type = GameType.get(config.getString("type")); this.components = Lists.newArrayList(); this.lastPlayerCount = getPlayers().length; this.signs = Sets.newHashSet(); getConfig().addDefault("minimum players", 2); getConfig().addDefault("maximum players", 0); getConfig().addDefault("countdown duration", 30); getConfig().addDefault("game time", -1); getConfig().addDefault("use scoreboard", true); getConfig().addDefault("grace duration", 5); minimumPlayers = getConfig().getInt("minimum players"); maximumPlayers = getConfig().getInt("maximum players"); countdownDuration = getConfig().getInt("countdown duration"); gameTime = getConfig().getInt("game time"); useScoreboard = getConfig().getBoolean("use scoreboard"); graceDuration = getConfig().getInt("grace duration"); this.lastTimeRemaining = counter; if (getConfig().isList("signs")) { for (String location : getConfig().getStringList("signs")) { signs.add(LocationUtil.deserializeLocation(location)); } } onLoad(); if (useScoreboard) { board = Bukkit.getScoreboardManager().getNewScoreboard(); objective = board.registerNewObjective (ChatColor.translateAlternateColorCodes('&', "&6&l" + getType().toString()), "dummy"); objective.setDisplaySlot(DisplaySlot.SIDEBAR); updateScoreboard(); } onLoad(); for (String key : getConfig().getDefaults().getKeys(false)) { if (getConfig().get(key, null) == null) { getConfig().set(key, getConfig().getDefaults().get(key)); } } } protected void updateScoreboard() { if (!useScoreboard) return; if (playerTagScore > 0) { Score score = objective.getScore(ChatColor.translateAlternateColorCodes('&', "&6&lPlayers")); if (score.getScore() != playerTagScore) score.setScore(playerTagScore); } if (playerCounterScore > 0) { board.resetScores(lastPlayerCount + ""); lastPlayerCount = getPlayers().length; objective.getScore(lastPlayerCount + "").setScore(playerCounterScore); } if (this.timeTagScore > 0) { Score score = objective.getScore(ChatColor.translateAlternateColorCodes('&', "&6&lTime")); if (score.getScore() != timeTagScore) score.setScore(timeTagScore); } if (timeCounterScore > 0) { board.resetScores(lastTimeRemaining + ""); lastTimeRemaining = counter; objective.getScore(lastTimeRemaining + "").setScore(timeCounterScore); } } protected void setBoardForAll() { for (Player player : getPlayers()) { if (player.getScoreboard() != board) player.setScoreboard(board); } } }
package com.opencms.template.cache; import com.opencms.template.CmsCacheDirectives; import java.util.*; /** * This class implements a LRU cache. It uses a Hashtable algorithm with the * chaining method for collision handling. The sequence of the Objects is stored in * an extra chain. Each object has a pointer to the previous and next object in this * chain. If an object is inserted or used it is set to the tail of the chain. If an * object has to be remouved it will be the head object. Only works with more than one element. * * @author Hanjo Riege * @version 1.0 */ public class CmsLruCache { // enables the login. Just for debugging. private static final boolean C_DEBUG = false; // the array to store everthing private CacheItem[] m_cache; // the capacity of the cache private int m_maxSize; // the aktual size of the cache private int m_size = 0; // the head of the time sequence private CacheItem head; // the tail of the time sequence private CacheItem tail; static class CacheItem { Object key; Object value; // the link for the collision hanling CacheItem chain; // links for the time sequence chain CacheItem previous; CacheItem next; } /** * Constructor * @param size The size of the cache. */ public CmsLruCache(int size) { if(C_DEBUG){ System.err.println("--LruCache started with "+size); } m_cache = new CacheItem[size]; m_maxSize = size; } /** * inserts a new object in the cache. If it is there already the value is updated. * @param key The key to find the object. * @param value The object. */ public synchronized void put (Object key, Object value){ int hashIndex = (key.hashCode() & 0x7FFFFFFF) % m_maxSize; CacheItem item = m_cache[hashIndex]; CacheItem newItem = null; if(C_DEBUG){ System.err.println("put in cache: "+key); } if(item != null){ // there is a item allready. Collision. // lets look if the new item was inserted before while(item.chain != null){ if(item.key.equals(key)){ item.value = value; // TODO: put it to the end of the chain return; } item = item.chain; } if(item.key.equals(key)){ item.value = value; //TODO: put it on the end of the chain return; } if(m_size >= m_maxSize){ // cache full, we have to remove the old head CacheItem helper = head.next; if (item == head){ newItem = item; }else{ newItem = head; removeFromTable(head); newItem.chain = null; item.chain = newItem; } newItem.next = null; head = helper; head.previous = null; }else{ m_size++; newItem = new CacheItem(); item.chain = newItem; } }else{ // oh goody, a free place for the new item if(head != null){ if(m_size >= m_maxSize){ // cache full, we have to remove the old head CacheItem helper = head.next; newItem = head; removeFromTable(head); newItem.next = null; newItem.chain = null; head = helper; head.previous = null; }else{ m_size++; newItem = new CacheItem(); } }else{ // first item in the chain newItem = new CacheItem(); m_size++; head = newItem; tail = newItem; } item = m_cache[hashIndex] = newItem; } // the new Item is in the array and in the chain. Fill it. newItem.key = key; newItem.value = value; if(tail != newItem){ tail.next = newItem; newItem.previous = tail; tail = newItem; } } /** * returns the value to the key or null if the key is not in the cache. The found * element has to line up behind the others (set to the tail). * @param key The key for the object. * @return The value. */ public synchronized Object get(Object key){ int hashIndex = (key.hashCode() & 0x7FFFFFFF) % m_maxSize; CacheItem item = m_cache[hashIndex]; if(C_DEBUG){ System.err.println("get from Cache: "+key); //checkCondition(); } while (item != null){ if(item.key.equals(key)){ // got it if(item != tail){ // hinten anstellen if(item != head){ item.previous.next = item.next; }else{ head = head.next; } item.next.previous = item.previous; tail.next = item; item.previous = tail; tail = item; tail.next = null; } return item.value; } item = item.chain; } if(C_DEBUG){ System.err.println(" not found in Cache!!!!"); } return null; } /** * deletes one item from the cache. Not from the sequence chain. * @param oldItem The item to be deleted. */ private void removeFromTable(CacheItem oldItem){ if(C_DEBUG){ System.err.println(" --remove from chaincache: "+oldItem.key); } int hashIndex = ((oldItem.key).hashCode() & 0x7FFFFFFF) % m_maxSize; CacheItem item = m_cache[hashIndex]; if(item == oldItem){ m_cache[hashIndex] = item.chain; }else{ if(item != null){ while(item.chain != null){ if(item.chain == oldItem){ item.chain = item.chain.chain; return; } item = item.chain; } } } } /** * removes one item from the cache and from the sequence chain. */ private void removeItem(CacheItem item){ if(C_DEBUG){ System.err.println("--remove item from cache: "+item.key); } //first remove it from the hashtable removeFromTable(item); // now from the sequence chain if((item != head) && (item != tail)){ item.previous.next = item.next; item.next.previous = item.previous; }else{ if(item == head){ head = item.next; head.previous = null; } if (item == tail){ tail = item.previous; tail.next = null; } } m_size } /** * Deletes all elements that depend on the template. * use only if the cache is for elements. */ public void deleteElementsByTemplate(String templateName){ CacheItem item = head; while (item != null){ if(templateName.equals(((CmsElementDescriptor)item.key).getTemplateName())){ removeItem(item); } item = item.next; } } /** * Deletes all elements that depend on the class. * use only if this cache is for elements. */ public void deleteElementsByClass(String className){ CacheItem item = head; while (item != null){ if(className.equals(((CmsElementDescriptor)item.key).getClassName())){ removeItem(item); } item = item.next; } } /** * Deletes elements after publish. All elements that depend on the * uri and all element that say so have to be removed. * use only if this cache is for elements. */ public synchronized void deleteElementsAfterPublish(){ CacheItem item = head; while (item != null){ if (((A_CmsElement)item.value).getCacheDirectives().shouldRenew()){ removeItem(item); } item = item.next; } } /** * Deletes the uri from the Cache. Use only if this is the cache for uris. * */ public synchronized void deleteUri(String uri){ CacheItem item = head; while (item != null){ if(uri.equals(((CmsUriDescriptor)item.key).getKey())){ removeItem(item); // found the uri, ready. return; } item = item.next; } } /** * Clears the cache completly. */ public synchronized void clearCache(){ if(C_DEBUG){ System.err.println("--LruCache restarted"); } m_cache = new CacheItem[m_maxSize]; m_size = 0; head = null; tail = null; } /** * Gets the Information of max size and size for the cache. * * @return a Vector whith informations about the size of the cache. */ public Vector getCacheInfo(){ if(C_DEBUG){ System.err.println("...Cache size should be:"+ m_size + " by a max size of "+m_maxSize); int count = 0; CacheItem item = head; while (item != null){ count++; item = item.next; } System.err.println("...Cache size is:"+count); } Vector info = new Vector(); info.addElement(new Integer(m_maxSize )); info.addElement(new Integer(m_size)); return info; } /** * used for debuging only. Checks if the Cache is in a valid condition. */ private void checkCondition(){ System.err.println(""); System.err.println("-- Verify condition of Cache"); System.err.println("--size: "+m_size); CacheItem item = head; int count = 1; System.err.println(" System.err.println("--testing content from head to tail:"); while(item!=null){ System.err.println(" --"+count+". "+(String)item.key); count++; item=item.next; } System.err.println(""); System.err.println("--now from tail to head:"); item = tail; count while(item!=null){ System.err.println(" --"+count+". "+(String)item.key); count item=item.previous; } System.err.println("--now what is realy in cache:"); count = 1; for (int i=0; i<m_maxSize; i++){ item = m_cache[i]; System.err.print(" element "+i+" "); if(item == null){ System.err.println(" null"); }else{ System.err.println(" count="+count++ +" "+(String)item.key); while(item.chain != null){ item = item.chain; System.err.println(" chainelement "+" count="+count++ +" "+(String)item.key); } } } System.err.println("--test ready!!"); System.err.println(""); } }
package net.galaxygaming.dispenser.game; import java.io.File; import java.util.Map; import com.google.common.collect.Maps; /** * @author t7seven7t */ public class GameType { private static final Map<String, GameType> lookup = Maps.newConcurrentMap(); private final String name; private final GameDescriptionFile description; private final File dataFolder; GameType(String name, GameDescriptionFile description, File dataFolder) { if (lookup.containsKey(name)) { throw new IllegalStateException("A GameType with the name '" + name + "' already exists."); } this.name = name; this.description = description; this.dataFolder = dataFolder; lookup.put(name, this); } /** * Retrieves the description file defining this game type * @return game description file */ public GameDescriptionFile getDescription() { return this.description; } /** * Gives a folder for data from this game type. Not guaranteed to exist. * @return game type folder */ public File getDataFolder() { return this.dataFolder; } @Override public String toString() { return this.name; } @Override public boolean equals(Object o) { if (o == null) return false; if (getClass() == o.getClass()) { if (this.name.equalsIgnoreCase(((GameType) o).name)) { return true; } } else if (o.getClass() == String.class) { if (this.name.equalsIgnoreCase((String) o)) { return true; } } return false; } @Override public int hashCode() { return name.hashCode(); } public static GameType get(String name) { GameType result = lookup.get(name); if (result == null) { throw new IllegalStateException("GameType '" + name + "' does not exist"); } return result; } static void remove(GameType type) { lookup.remove(type.toString()); } }
package net.rimoto.intlphoneinput; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.telephony.PhoneNumberFormattingTextWatcher; import android.telephony.TelephonyManager; import android.util.AttributeSet; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Spinner; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; import java.util.Locale; public class IntlPhoneInput extends RelativeLayout { private final String DEFAULT_COUNTRY = Locale.getDefault().getCountry(); // UI Views private Spinner mCountrySpinner; private EditText mPhoneEdit; //Adapters private CountrySpinnerAdapter mCountrySpinnerAdapter; private PhoneNumberWatcher mPhoneNumberWatcher = new PhoneNumberWatcher(DEFAULT_COUNTRY); //Util private PhoneNumberUtil mPhoneUtil = PhoneNumberUtil.getInstance(); // Fields private Country mSelectedCountry; private CountriesFetcher.CountryList mCountries; private IntlPhoneInputListener mIntlPhoneInputListener; /** * Constructor * @param context Context */ public IntlPhoneInput(Context context) { super(context); init(); } /** * Constructor * @param context Context * @param attrs AttributeSet */ public IntlPhoneInput(Context context, AttributeSet attrs) { super(context, attrs); init(); } /** * Init after constructor */ private void init() { inflate(getContext(), R.layout.intl_phone_input, this); /**+ * Country spinner */ mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country); mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext()); mCountrySpinner.setAdapter(mCountrySpinnerAdapter); mCountries = CountriesFetcher.getCountries(getContext()); mCountrySpinnerAdapter.addAll(mCountries); mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener); /** * Phone text field */ mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone); mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher); setDefault(); } /** * Hide keyboard from phoneEdit field */ public void hideKeyboard() { InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0); } /** * Set default value * Will try to retrieve phone number from device */ public void setDefault() { try { TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); String phone = telephonyManager.getLine1Number(); if(phone != null && !phone.isEmpty()) { this.setNumber(telephonyManager.getLine1Number()); } else { String iso = telephonyManager.getNetworkCountryIso(); setEmptyDefault(iso); } } catch (SecurityException e) { setEmptyDefault(); } } /** * Set default value with * @param iso ISO2 of country */ public void setEmptyDefault(String iso) { if(iso == null || iso.isEmpty()) { iso = DEFAULT_COUNTRY; } int defaultIdx = mCountries.indexOfIso(iso); mSelectedCountry = mCountries.get(defaultIdx); mCountrySpinner.setSelection(defaultIdx); } /** * Alias for setting empty string of default settings from the device (using locale) */ private void setEmptyDefault() { setEmptyDefault(null); } /** * Set hint number for country */ private void setHint() { if(mPhoneEdit != null) { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE); if (phoneNumber != null) { mPhoneEdit.setHint(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)); } } } /** * Spinner listener */ private AdapterView.OnItemSelectedListener mCountrySpinnerListener = new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mSelectedCountry = mCountrySpinnerAdapter.getItem(position); mPhoneNumberWatcher = new PhoneNumberWatcher(mSelectedCountry.getIso()); setHint(); } @Override public void onNothingSelected(AdapterView<?> parent) {} }; /** * Phone number watcher */ private class PhoneNumberWatcher extends PhoneNumberFormattingTextWatcher { private boolean lastValidity; @SuppressWarnings("unused") public PhoneNumberWatcher() { super(); } //TODO solve it! support for android kitkat @TargetApi(Build.VERSION_CODES.LOLLIPOP) public PhoneNumberWatcher(String countryCode) { super(countryCode); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { super.onTextChanged(s, start, before, count); try { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.parse(s.toString(), mSelectedCountry.getIso()); int countryIdx = mCountries.indexOfIso(mPhoneUtil.getRegionCodeForNumber(phoneNumber)); mCountrySpinner.setSelection(countryIdx); } catch (NumberParseException ignored) {} if(mIntlPhoneInputListener != null) { boolean validity = isValid(); if (validity != lastValidity) { mIntlPhoneInputListener.done(IntlPhoneInput.this, validity); } lastValidity = validity; } } } /** * Set Number * @param number E.164 format or national format(for selected country) */ public void setNumber(String number) { try { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.parse(number, mSelectedCountry.getIso()); mPhoneEdit.setText(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)); int countryIdx = mCountries.indexOfIso(mPhoneUtil.getRegionCodeForNumber(phoneNumber)); mCountrySpinner.setSelection(countryIdx); } catch (NumberParseException ignored){} } /** * Get number * @return Phone number in E.164 format | null on error */ @SuppressWarnings("unused") public String getNumber() { try { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.parse(mPhoneEdit.getText().toString(), mSelectedCountry.getIso()); return mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164); } catch (NumberParseException ignored){ return null; } } public String getText() { return getNumber(); } /** * Get PhoneNumber object * @return PhonenUmber | null on error */ @SuppressWarnings("unused") public Phonenumber.PhoneNumber getPhoneNumber() { try { return mPhoneUtil.parse(mPhoneEdit.getText().toString(), mSelectedCountry.getIso()); } catch (NumberParseException ignored){ return null; } } /** * Get selected country * @return Country */ @SuppressWarnings("unused") public Country getSelectedCountry() { return mSelectedCountry; } /** * Check if number is valid * @return boolean */ @SuppressWarnings("unused") public boolean isValid() { try { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.parse(mPhoneEdit.getText().toString(), mSelectedCountry.getIso()); return mPhoneUtil.isValidNumber(phoneNumber); } catch (NumberParseException ignored){ return false; } } /** * Add validation listener * @param listener IntlPhoneInputListener */ public void setOnValidityChange(IntlPhoneInputListener listener) { mIntlPhoneInputListener = listener; } /** * Simple validation listener */ public interface IntlPhoneInputListener { void done(View view, boolean isValid); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); mPhoneEdit.setEnabled(enabled); mCountrySpinner.setEnabled(enabled); } }
package com.poomoo.edao.activity; import com.poomoo.edao.R; import com.umeng.socialize.bean.SHARE_MEDIA; import com.umeng.socialize.controller.UMServiceFactory; import com.umeng.socialize.controller.UMSocialService; import com.umeng.socialize.media.QQShareContent; import com.umeng.socialize.media.QZoneShareContent; import com.umeng.socialize.media.SinaShareContent; import com.umeng.socialize.media.SmsShareContent; import com.umeng.socialize.media.UMImage; import com.umeng.socialize.sso.QZoneSsoHandler; import com.umeng.socialize.sso.SinaSsoHandler; import com.umeng.socialize.sso.SmsHandler; import com.umeng.socialize.sso.UMQQSsoHandler; import com.umeng.socialize.sso.UMSsoHandler; import com.umeng.socialize.weixin.controller.UMWXHandler; import com.umeng.socialize.weixin.media.CircleShareContent; import com.umeng.socialize.weixin.media.WeiXinShareContent; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; /** * * @ClassName ShareActivity * @Description TODO * @author * @date 2015810 10:00:42 */ public class ShareActivity extends BaseActivity implements OnClickListener { private ImageView imageView_return; private Button button_share; // Activity final UMSocialService mController = UMServiceFactory .getUMSocialService("com.umeng.share"); private static final String content = "http: private static final String website = "http: private static final String title = ""; @Override protected void onCreate(Bundle savedInstanceState) { // TODO super.onCreate(savedInstanceState); setContentView(R.layout.activity_share); setImmerseLayout(findViewById(R.id.share_layout)); init(); configPlatforms(); shareContent(); } private void init() { // TODO imageView_return = (ImageView) findViewById(R.id.share_imageView_return); button_share = (Button) findViewById(R.id.share_button); imageView_return.setOnClickListener(this); button_share.setOnClickListener(this); } private void configPlatforms() { // SSO mController.getConfig().setSsoHandler(new SinaSsoHandler()); // QQQZone addQQQZonePlatform(); addWXPlatform(); addSMS(); } public void shareContent() { UMImage localImage = new UMImage(this, R.drawable.ic_leyidao); // SSO mController.getConfig().setSsoHandler(new SinaSsoHandler()); // QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, // "100424468", "c7394704798a158208a74ab60104f0ba"); WeiXinShareContent weixinContent = new WeiXinShareContent(); weixinContent.setShareContent(content); weixinContent.setTitle(title); weixinContent.setTargetUrl(website); weixinContent.setShareMedia(localImage); mController.setShareMedia(weixinContent); CircleShareContent circleMedia = new CircleShareContent(); circleMedia.setShareContent(content); circleMedia.setTitle(title); circleMedia.setShareMedia(localImage); circleMedia.setTargetUrl(website); mController.setShareMedia(circleMedia); QZoneShareContent qzone = new QZoneShareContent(); qzone.setShareContent(content); qzone.setTargetUrl(website); qzone.setTitle(title); qzone.setShareMedia(localImage); mController.setShareMedia(qzone); QQShareContent qqShareContent = new QQShareContent(); qqShareContent.setShareContent(content); qqShareContent.setTitle(title); qqShareContent.setShareMedia(localImage); qqShareContent.setTargetUrl(website); mController.setShareMedia(qqShareContent); SmsShareContent sms = new SmsShareContent(); sms.setShareContent(content); sms.setShareImage(localImage); mController.setShareMedia(sms); SinaShareContent sinaContent = new SinaShareContent(); sinaContent.setShareContent(content); sinaContent.setShareImage(localImage); mController.setShareMedia(sinaContent); } private void addQQQZonePlatform() { String appId = "100424468"; String appKey = "c7394704798a158208a74ab60104f0ba"; // QQ, QQtarget url UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, appId, appKey); qqSsoHandler.setTargetUrl(website); qqSsoHandler.addToSocialSDK(); // QZone QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, appId, appKey); qZoneSsoHandler.addToSocialSDK(); } /** * @ : * @return */ private void addWXPlatform() { // appSecret // wx967daebe835fbeacAppID, AppID String appId = "wx55e834ca0a0327a6"; String appSecret = "5bb696d9ccd75a38c8a0bfe0675559b3"; UMWXHandler wxHandler = new UMWXHandler(this, appId, appSecret); wxHandler.addToSocialSDK(); UMWXHandler wxCircleHandler = new UMWXHandler(this, appId, appSecret); wxCircleHandler.setToCircle(true); wxCircleHandler.addToSocialSDK(); } private void addSMS() { SmsHandler smsHandler = new SmsHandler(); smsHandler.addToSocialSDK(); } @Override public void onDestroy() { super.onDestroy(); mController.getConfig().cleanListeners(); } @Override public void onClick(View v) { // TODO switch (v.getId()) { case R.id.share_imageView_return: finish(); break; case R.id.share_button: mController.getConfig().setPlatforms(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA, SHARE_MEDIA.TENCENT, SHARE_MEDIA.SMS); mController.openShare(this, false); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); /** SSO */ UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler( requestCode); if (ssoHandler != null) { ssoHandler.authorizeCallBack(requestCode, resultCode, data); } } }
package com.valkryst.VTerminal.component; import lombok.ToString; @ToString public class Image extends Layer { /** * Constructs a new Image. * * @param columnIndex * The x-axis (column) coordinate of the top-left character. * * @param rowIndex * The y-axis (row) coordinate of the top-left character. * * @param width * The width, in characters. * * @param height * The height, in characters. */ public Image(int columnIndex, int rowIndex, int width, int height) { super(columnIndex, rowIndex, width, height); } }
package next.operator.linebot.talker; import next.operator.ChineseTokens; import next.operator.linebot.service.RespondentReadable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * [][]NN * : N or N */ @Service public class NoiseTalker implements RespondentReadable { @Autowired private ChineseTokens chineseTokens; final Pattern readPattern = Pattern.compile("([\\u4e00-\\u9fa5A-Za-z]+?)(\\1[\\u4e00-\\u9fa5A-Za-z]*)"); final String[] response = {"", ""}; final String[] suffixes = {"", "", "", "", ""}; @Override public boolean isReadable(String message) { return readPattern.matcher(message).find(); } @Override public String talk(String message) { final Matcher matcher = readPattern.matcher(message); if (matcher.find()) { final String keyWord = chineseTokens.run(matcher.group(2))[0]; return response[(int) (Math.random() * response.length)] + keyWord + suffixes[(int) (Math.random() * suffixes.length)]; } else { return null; } } }
package com.wmbest.sabrowser; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ListView; import android.widget.TextView; import android.content.Context; import android.widget.BaseAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.apache.http.impl.client.DefaultHttpClient; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.ClientProtocolException; import org.apache.http.HttpResponse; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import android.util.Log; import org.w3c.tidy.*; import org.w3c.dom.*; import java.util.ArrayList; public class SABrowserActivity extends Activity { private static final String TAG = "SABrowserActivity"; private static final int FORUM_LIST_RETURNED = 1; private static final int ERROR = -1; private ArrayList<String> mForumTitleList; private Handler mHandler; private ListView mForumList; private ProgressDialog mLoadingDialog; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "Entered onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.main); mForumList = (ListView) findViewById(R.id.forum_list); mForumTitleList = new ArrayList<String>(); mHandler = new Handler() { public void handleMessage(Message aMessage) { mLoadingDialog.dismiss(); switch(aMessage.what) { case FORUM_LIST_RETURNED: mForumList.setAdapter(new ForumsListAdapter(SABrowserActivity.this, mForumTitleList)); break; case ERROR: Log.e(TAG, "ERRORRRRR"); break; } } }; mLoadingDialog = ProgressDialog.show(SABrowserActivity.this, "Loading", "Fetching list of forums...", true); // mHandler.post(fetchForumsList); new PreloadThread(mHandler).start(); } private class ForumsListAdapter extends BaseAdapter { private ArrayList<String> mItems; private LayoutInflater mInflater; public ForumsListAdapter(Context aContext, ArrayList<String> aItems) { mItems = aItems; mInflater = LayoutInflater.from(aContext); } public View getView(int aPosition, View aConvertView, ViewGroup aParent) { View forumItem; // Recycle old View's if the list is long if (aConvertView == null) { forumItem = mInflater.inflate(R.layout.forum_list_item, null); } else { forumItem = aConvertView; } TextView title = (TextView) forumItem.findViewById(R.id.forum_name); title.setText(mItems.get(aPosition)); return forumItem; } public int getCount() { return mItems.size(); } public Object getItem(int aPosition) { return mItems.get(aPosition); } public long getItemId(int aPosition) { return aPosition; } } private Runnable fetchForumsList = new Runnable() { public void run() { Message msgResponse = Message.obtain(); msgResponse.setTarget(mHandler); String websiteData = null; try { DefaultHttpClient client = new DefaultHttpClient(); URI uri = new URI("http://forums.somethingawful.com/"); HttpGet method = new HttpGet(uri); HttpResponse res = client.execute(method); Log.d(TAG, "Created Objects, Now Creating Stream"); InputStream data = res.getEntity().getContent(); Log.d(TAG, "Create Tidy"); Tidy tidy = new Tidy(); Log.d(TAG, "Parse DOM"); Document dom = tidy.parseDOM(data, null); Log.d(TAG, "DOM Parsed printing results"); NodeList nl = dom.getElementsByTagName("a"); for(int i = 0; i < nl.getLength(); ++i) { Element a = (Element)nl.item(i); Log.d(TAG, "Item: " + a.getFirstChild().getNodeName() ); if(a.getAttribute("class").equals("forum")) { mForumTitleList.add(((Text)a.getFirstChild()).getData()); } } msgResponse.what = FORUM_LIST_RETURNED; } catch (DOMException e) { e.printStackTrace(); msgResponse.what = ERROR; } catch (ClientProtocolException e) { e.printStackTrace(); msgResponse.what = ERROR; } catch (IOException e) { e.printStackTrace(); msgResponse.what = ERROR; } catch (URISyntaxException e) { e.printStackTrace(); msgResponse.what = ERROR; } catch (Exception e) { Log.i(TAG, e.toString()); msgResponse.what = ERROR; } msgResponse.sendToTarget(); } }; private class PreloadThread extends Thread { Handler mHandler; PreloadThread(Handler aHandler) { mHandler = aHandler; } public void run() { Message msgResponse = Message.obtain(); msgResponse.setTarget(mHandler); String websiteData = null; try { DefaultHttpClient client = new DefaultHttpClient(); URI uri = new URI("http://forums.somethingawful.com/"); HttpGet method = new HttpGet(uri); HttpResponse res = client.execute(method); Log.d(TAG, "Created Objects, Now Creating Stream"); InputStream data = res.getEntity().getContent(); Log.d(TAG, "Create Tidy"); Tidy tidy = new Tidy(); Log.d(TAG, "Parse DOM"); Document dom = tidy.parseDOM(data, null); Log.d(TAG, "DOM Parsed printing results"); NodeList nl = dom.getElementsByTagName("a"); for(int i = 0; i < nl.getLength(); ++i) { Element a = (Element)nl.item(i); Log.d(TAG, "Item: " + a.getFirstChild().getNodeName() ); if(a.getAttribute("class").equals("forum")) { mForumTitleList.add(((Text)a.getFirstChild()).getData()); } } msgResponse.what = FORUM_LIST_RETURNED; } catch (DOMException e) { e.printStackTrace(); msgResponse.what = ERROR; } catch (ClientProtocolException e) { e.printStackTrace(); msgResponse.what = ERROR; } catch (IOException e) { e.printStackTrace(); msgResponse.what = ERROR; } catch (URISyntaxException e) { e.printStackTrace(); msgResponse.what = ERROR; } catch (Exception e) { Log.i(TAG, e.toString()); msgResponse.what = ERROR; } msgResponse.sendToTarget(); } } }
package nl.tudelft.jpacman.game; import java.util.List; import nl.tudelft.jpacman.board.Direction; import nl.tudelft.jpacman.level.Level; import nl.tudelft.jpacman.level.Player; import com.google.common.collect.ImmutableList; /** * A game with one player and a single level. * * @author Jeroen Roosen */ public class SinglePlayerGame extends Game { /** * The player of this game. */ private final Player player; /** * The level of this game. */ private final Level level; /** * Create a new single player game for the provided level and player. * * @param p * The player. * @param l * The level. */ protected SinglePlayerGame(Player p, Level l) { assert p != null; assert l != null; this.player = p; this.level = l; level.registerPlayer(p); } @Override public List<Player> getPlayers() { return ImmutableList.of(player); } @Override public Level getLevel() { return level; } }
package no.nlb.quickbase.dump; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Dumps a table from Quickbase to a XML file */ public class QuickbaseTableDump { private static final int MAX_ROWS_PER_REQUEST = 100; private static final String ENCODING = "iso-8859-1"; public static class QuickbaseClient { private HttpClient client; private String apptoken; private String url; private String ticket = null; public QuickbaseClient(String apptoken, String domain, String table, String username, String password) { this.client = HttpClientBuilder.create().build(); this.apptoken = apptoken; this.url = "https://"+domain+"/db/main"; QuickbaseRequest authRequest = newRequest("API_Authenticate"); authRequest.setParameter("username", username); authRequest.setParameter("password", password); authRequest.setParameter("hours", "24"); QuickbaseResponse response = authRequest.send(); ticket = response.get("ticket"); this.url = "https://"+domain+"/db/"+table; } public QuickbaseRequest newRequest(String action) { QuickbaseRequest request = new QuickbaseRequest(client, url, action); request.setParameter("encoding", ENCODING); request.setParameter("apptoken", apptoken); if (ticket != null) { request.setParameter("ticket", ticket); } return request; } } private static class QuickbaseRequest { Map<String,String> parameters; HttpClient client; String url; String action; public QuickbaseRequest(HttpClient client, String url, String action) { parameters = new HashMap<String,String>(); this.client = client; this.url = url; this.action = action; } public QuickbaseResponse send() { String postString = "<qdbapi>"; for (String key : parameters.keySet()) { postString += "<"+key+">"; // assume key is valid QName postString += parameters.get(key).replaceAll("<", "&lt;").replaceAll("<", "&gt;").replaceAll("&", "&amp;"); postString += "</"+key+">"; } postString += "</qdbapi>"; byte[] postBytes = null; try { postBytes = postString.getBytes(ENCODING); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } HttpPost post = new HttpPost(url); post.setHeader("QUICKBASE-ACTION", action); post.setHeader(HttpHeaders.CONTENT_TYPE, "application/xml"); HttpEntity postEntity = new ByteArrayEntity(postBytes); post.setEntity(postEntity); HttpResponse response = null; try { response = client.execute(post); } catch (IOException|ParseException e) { e.printStackTrace(); System.exit(1); } try { HttpEntity entity = response.getEntity(); return new QuickbaseResponse(removeControlCharacters(EntityUtils.toString(entity,ENCODING))); } catch (IOException|ParseException e) { e.printStackTrace(); System.exit(1); } return null; } public static String removeControlCharacters(String value) { String newValue = ""; final int length = value.length(); for (int offset = 0; offset < length; ) { final int codepoint = value.codePointAt(offset); if (codepoint <= 8 || codepoint >= 14 && codepoint <= 31 || codepoint >= 128 && codepoint <= 132 || codepoint >= 134 && codepoint <= 159) { //System.err.println("removing codepoint: "+codepoint); } else { newValue += value.charAt(offset); } offset += Character.charCount(codepoint); } return newValue; } public void setParameter(String key, String value) { parameters.put(key, value); } } private static class QuickbaseResponse { public String responseString = null; private Document xml = null; private Map<String,String> results = null; public QuickbaseResponse(String responseString) { this.responseString = responseString; } private void parseResults() { if (results != null) return; String s = new String(responseString); results = new HashMap<String,String>(); while (s.length() > 0) { s = s.replaceAll("(?s)^.*?<([a-z])", "$1"); String key = s.replaceAll("(?s)>.*", "").replaceAll("\\s",""); if ("qdbapi".equals(key)) continue; if (key.contains("<")) { s = s.replaceAll("(?s)^.*?<[^>]*", ""); continue; } if ("".equals(key)) break; s = s.replaceAll("(?s)^[^>]*>", ""); String value = s.replaceAll("(?s)<.*",""); results.put(key, value); s = s.replaceAll("(?s)^.*?</[^>]*>", ""); } } public Document xml() { if (xml != null) return xml; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream stream = new ByteArrayInputStream(responseString.getBytes(ENCODING)); xml = documentBuilder.parse(stream); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); System.exit(1); } return xml; } public String get(String key) { parseResults(); return results.get(key); } public Map<String,Map<String,String>> getFields() { Map<String,Map<String,String>> fields = new HashMap<String,Map<String,String>>(); NodeList fieldElements = xml().getElementsByTagName("field"); for (int i = 0; i < fieldElements.getLength(); i++) { Element fieldElement = (Element)fieldElements.item(i); Map<String,String> fieldValues = new HashMap<String,String>(); NodeList fieldChildNodes = fieldElement.getChildNodes(); for (int j = 0; j < fieldChildNodes.getLength(); j++) { // iterate elements inside field element Node fieldChildNode = fieldChildNodes.item(j); if (fieldChildNode.getNodeType() == Node.ELEMENT_NODE) { String name = fieldChildNode.getNodeName(); String value = null; NodeList childNodes = fieldChildNode.getChildNodes(); for (int k = 0; k < childNodes.getLength(); k++) { // iterate nodes inside field value element to check for content Node childNode = childNodes.item(k); if (childNode.getNodeType() == Node.ELEMENT_NODE) { // ignore elements with complex content value = null; break; } if (childNode.getNodeType() == Node.TEXT_NODE) { value = childNode.getNodeValue(); } } if (value != null) { fieldValues.put(name, value); } } } fieldValues.put("base_type", fieldElement.getAttribute("base_type")); fieldValues.put("field_type", fieldElement.getAttribute("field_type")); fieldValues.put("mode", fieldElement.getAttribute("mode")); fieldValues.put("role", fieldElement.getAttribute("role")); fields.put(fieldElement.getAttribute("id"), fieldValues); } return fields; } public String getRecordIdId() { Map<String,Map<String,String>> fields = getFields(); for (String id : fields.keySet()) { if ("recordid".equals(fields.get(id).get("role"))) { return id; } } return null; } public Map<String,Map<String,String>> getRecords() { Map<String,Map<String,String>> records = new HashMap<String,Map<String,String>>(); NodeList recordElements = xml().getElementsByTagName("record"); for (int i = 0; i < recordElements.getLength(); i++) { Element recordElement = (Element)recordElements.item(i); Map<String,String> recordValues = new HashMap<String,String>(); NodeList recordChildNodes = recordElement.getChildNodes(); for (int j = 0; j < recordChildNodes.getLength(); j++) { // iterate elements inside record element Node recordChildNode = recordChildNodes.item(j); if (recordChildNode.getNodeType() == Node.ELEMENT_NODE) { String name = recordChildNode.getNodeName(); if ("f".equals(name)) { name = ((Element)recordChildNode).getAttribute("id"); } String value = null; NodeList childNodes = recordChildNode.getChildNodes(); for (int k = 0; k < childNodes.getLength(); k++) { // iterate nodes inside record value element to check for content Node childNode = childNodes.item(k); if (childNode.getNodeType() == Node.ELEMENT_NODE) { // ignore elements with complex content value = null; break; } if (childNode.getNodeType() == Node.TEXT_NODE) { try { //value = URLEncoder.encode(childNode.getNodeValue(), ENCODING); value = childNode.getNodeValue(); } catch (DOMException e) { e.printStackTrace(); System.exit(1); } } } if (value != null) { recordValues.put(name, value); } } } records.put(recordElement.getAttribute("rid"), recordValues); } return records; } } public static void main(String[] args) { String appToken = System.getenv("QUICKBASE_APP_TOKEN"); String domain = System.getenv("QUICKBASE_DOMAIN"); String username = System.getenv("QUICKBASE_USERNAME"); String password = System.getenv("QUICKBASE_PASSWORD"); String table = System.getenv("QUICKBASE_TABLE"); if (appToken == null || "".equals(appToken)) { System.err.println("Missing environment variable: QUICKBASE_APP_TOKEN"); System.exit(1); } else if (domain == null || "".equals(domain)) { System.err.println("Missing environment variable: QUICKBASE_DOMAIN"); System.exit(1); } else if (username == null || "".equals(username)) { System.err.println("Missing environment variable: QUICKBASE_USERNAME"); System.exit(1); } else if (password == null || "".equals(password)) { System.err.println("Missing environment variable: QUICKBASE_PASSWORD"); System.exit(1); } else if (table == null || "".equals(table)) { System.err.println("Missing environment variable: QUICKBASE_TABLE"); System.exit(1); } QuickbaseClient client = new QuickbaseClient(appToken, domain, table, username, password); QuickbaseRequest request; QuickbaseResponse response, schema; Map<String, Map<String, String>> records; String combinedResponse = ""; // find id of row containing record id request = client.newRequest("API_GetSchema"); schema = request.send(); String recordIdId = schema.getRecordIdId(); // find lowest record id request = client.newRequest("API_DoQuery"); request.setParameter("query", ""); request.setParameter("clist", recordIdId); request.setParameter("slist", recordIdId); request.setParameter("options", "sortorder-A.num-1"); request.setParameter("includeRids", "1"); request.setParameter("fmt", "structured"); response = request.send(); records = response.getRecords(); Integer startRecordId = null; for (String recordId : records.keySet()) { startRecordId = new Integer(recordId); assert(startRecordId != null); } //System.err.println("startRecordId: "+startRecordId); // find highest record id request = client.newRequest("API_DoQuery"); request.setParameter("query", ""); request.setParameter("clist", recordIdId); request.setParameter("slist", recordIdId); request.setParameter("options", "sortorder-D.num-1"); request.setParameter("includeRids", "1"); request.setParameter("fmt", "structured"); response = request.send(); records = response.getRecords(); Integer endRecordId = null; for (String recordId : records.keySet()) { endRecordId = new Integer(recordId); assert(endRecordId != null); } //System.err.println("endRecordId: "+endRecordId); for (int page = 0; startRecordId + page * MAX_ROWS_PER_REQUEST <= endRecordId; page++) { int from = startRecordId + page * MAX_ROWS_PER_REQUEST; int to = startRecordId + (page+1) * MAX_ROWS_PER_REQUEST; request = client.newRequest("API_DoQuery"); request.setParameter("query", "{'"+recordIdId+"'.GTE.'"+from+"'}AND{'"+recordIdId+"'.LT.'"+to+"'}"); request.setParameter("clist", "a"); request.setParameter("slist", recordIdId); request.setParameter("includeRids", "1"); request.setParameter("fmt", "structured"); response = request.send(); //System.err.println("found "+response.getRecords().size()+" records in record id range ["+from+","+to+")"); if ("".equals(combinedResponse)) { combinedResponse += response.responseString.replaceAll("(?s)(<records[^>]*>[^<]*).*", "$1"); } combinedResponse += response.responseString.replaceAll("(?s).*<records[^>]*>[^<]*", "").replaceAll("(?s)</records.*", ""); } if (!"".equals(combinedResponse)) { combinedResponse += response.responseString.replaceAll("(?s).*(</records)", "$1"); } //response = new QuickbaseResponse(combinedResponse); //System.err.println("Found a total of "+response.getRecords().size()+" records"); System.out.println(combinedResponse); } }
package org.amc.game.chessserver; import com.google.gson.Gson; import org.amc.game.chess.IllegalMoveException; import org.amc.game.chess.Move; import org.amc.game.chess.Player; import org.amc.game.chessserver.JsonChessGameView.JsonChessGame; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.DestinationVariable; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.annotation.SendToUser; import org.springframework.stereotype.Controller; import java.security.Principal; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.SESSION_ATTRIBUTES; /** * Handles a WebSocket message received for a move in a chess game * * @author Adrian Mclaughlin * */ @Controller public class StompController { private static final Logger logger = Logger.getLogger(StompController.class); private Map<Long, ServerChessGame> gameMap; /** * STOMP messaging object to send stomp message to objects */ private SimpMessagingTemplate template; private static final String ERROR_MSG_NOT_ENOUGH_PLAYERS = "Error:Move on game(%d) which hasn't got two players"; private static final String ERROR_MSG_GAME_OVER = "Error:Move on game(%d) which has finished"; @MessageMapping("/move/{gameUUID}") @SendToUser(value = "/queue/updates", broadcast = false) public void registerMove(Principal user, @Header(SESSION_ATTRIBUTES) Map<String, Object> wsSession, @DestinationVariable long gameUUID, @Payload String moveString) { logger.debug(String.format("USER(%s)'s move received for game:%d", user.getName(), gameUUID)); Player player = (Player) wsSession.get("PLAYER"); logger.debug("PLAYER:" + player); ServerChessGame game = gameMap.get(gameUUID); String message = ""; if (game.getCurrentStatus().equals(ServerChessGame.status.IN_PROGRESS)) { message = moveChessPiece(game, player, moveString); } else if (game.getCurrentStatus().equals(ServerChessGame.status.AWAITING_PLAYER)) { message = String.format(ERROR_MSG_NOT_ENOUGH_PLAYERS, gameUUID); } else if (game.getCurrentStatus().equals(ServerChessGame.status.FINISHED)) { message = String.format(ERROR_MSG_GAME_OVER, gameUUID); } logger.error(message); sendMessageToUser(user, message); } private String moveChessPiece(ServerChessGame game, Player player, String moveString) { String message = ""; try { game.move(player, getMoveFromString(moveString)); } catch (IllegalMoveException e) { message = "Error:" + e.getMessage(); } catch (MalformedMoveException mme) { message = "Error:" + mme.getMessage(); } return message; } private Move getMoveFromString(String moveString) { MoveEditor convertor = new MoveEditor(); convertor.setAsText(moveString); logger.debug(convertor.getValue()); return (Move) convertor.getValue(); } /** * Sends a reply to the user * * @param user * User to receive message * @param message * containing either an error message or information update */ private void sendMessageToUser(Principal user, String message) { MessageType type = (message.equals("")) ? MessageType.INFO : MessageType.ERROR; template.convertAndSendToUser(user.getName(), "/queue/updates", message, getHeaders(type)); } private Map<String, Object> getHeaders(MessageType type) { Map<String, Object> headers = new HashMap<String, Object>(); headers.put(StompConstants.MESSAGE_HEADER_TYPE.getValue(), type); return headers; } @MessageMapping("/get/{gameUUID}") @SendToUser(value = "/queue/updates", broadcast = false) public void getChessBoard(Principal user, @Header(SESSION_ATTRIBUTES) Map<String, Object> wsSession, @DestinationVariable long gameUUID, @Payload String message) { ServerChessGame serverGame = gameMap.get(gameUUID); Gson gson = new Gson(); JsonChessGame jcb = new JsonChessGame(serverGame.getChessGame()); logger.debug(wsSession.get("PLAYER") + " requested update for game:" + gameUUID); template.convertAndSendToUser(user.getName(), "/queue/updates", gson.toJson(jcb), getHeaders(MessageType.UPDATE)); } @Resource(name = "gameMap") public void setGameMap(Map<Long, ServerChessGame> gameMap) { this.gameMap = gameMap; } /** * For adding a {@link SimpMessagingTemplate} object to be used for send * STOMP messages * * @param template * SimpMessagingTemplate */ @Autowired public void setTemplate(SimpMessagingTemplate template) { this.template = template; } }
package org.bitrepository.webservice; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import org.bitrepository.BasicClient; import org.bitrepository.BasicClientFactory; import org.bitrepository.GetFileIDsResults; /** * The class exposes the REST webservices provided by the Bitrepository-webclient using Jersey. */ @Path("/reposervice") public class Reposervice { private BasicClient client; public Reposervice() { client = BasicClientFactory.getInstance(); } /** * putFile exposes the possibility of uploading a file to the bitrepository collection that the webservice * is configured to use. The three parameters are all mandatory. * @param fileID Filename of the file to be put in the bitrepository. * @param fileSize Size of the file en bytes * @param url Place where the bitrepository pillars can fetch the file from * @return A string indicating if the request was successfully started or has been rejected. */ @GET @Path("/putfile/") @Produces("text/plain") public String putFile( @QueryParam("fileID") String fileID, @QueryParam("fileSize") long fileSize, @QueryParam("url") String URL, @QueryParam("putChecksum") String putChecksum, @QueryParam("putChecksumType") String putChecksumType, @QueryParam("putSalt") String putSalt, @QueryParam("approveChecksumType") String approveChecksumType, @QueryParam("approveSalt") String approveSalt) throws WebserviceIllegalArgumentException { try { WebserviceInputChecker.checkFileIDParameter(fileID); WebserviceInputChecker.checkURLParameter(URL); WebserviceInputChecker.checkChecksumParameter(putChecksum); WebserviceInputChecker.checkSaltParameter(putSalt); WebserviceInputChecker.checkSaltParameter(approveSalt); String approveChecksumTypeStr = null; if(approveChecksumType != null && !approveChecksumType.equals("disabled")) { approveChecksumTypeStr = approveChecksumType; } return client.putFile(fileID, fileSize, makeUrl(URL), putChecksum, putChecksumType, putSalt, approveChecksumTypeStr, approveSalt); } catch (IllegalArgumentException e) { throw new WebserviceIllegalArgumentException(e.getMessage()); } } /** * getFile exposes the possibility of downloading a file from the bitrepository collection that the webservice * is configured to use. The two parameters are all mandatory. * @param fileID Filename of the file to be downloaded in the bitrepository. * @param url Place where the bitrepository pillars can upload the file to. * @return A string indicating if the request was successfully started or has been rejected. */ @GET @Path("/getfile/") @Produces("text/plain") public String getFile( @QueryParam("fileID") String fileID, @QueryParam("url") String URL) throws WebserviceIllegalArgumentException { WebserviceInputChecker.checkFileIDParameter(fileID); WebserviceInputChecker.checkURLParameter(URL); try { return client.getFile(fileID, makeUrl(URL)); } catch (IllegalArgumentException e) { throw new WebserviceIllegalArgumentException(e.getMessage()); } } /** * Lists files that has completed upload from the collection. */ @GET @Path("/getfile/getCompletedFiles/") @Produces("text/html") public String getCompletedFiles() { return client.getCompletedFiles(); } /** * getLog gets the log of events that has happened since the webclient were started. The log contains a textual description * of all events that has occurred, both successes and failures. * @return The log in a textual format. */ @GET @Path("/getLog") @Produces("text/plain") public String getLog() { return client.getLog(); } @GET @Path("/getPillarList/") @Produces("text/json") public String getPillarList() { StringBuilder sb = new StringBuilder(); sb.append("["); List<String> pillars = client.getPillarList(); Iterator<String> it = pillars.iterator(); while(it.hasNext()) { String pillar = it.next(); sb.append("{\"optionValue\":\"" + pillar + "\", \"optionDisplay\": \"" + pillar + "\"}"); if(it.hasNext()) { sb.append(","); } } sb.append("]"); return sb.toString(); } /** * getHtmlLog gets the log of events that has happened since the webclient were started. The log contains a textual description * of all events that has occurred, both successes and failures. * @return The log is formatted with HTML. */ @GET @Path("/getHtmlLog") @Produces("text/html") public String getHtmlLog() { return client.getHtmlLog(); } /** * getShortHtmlLog gets the latests 25 log entries in reverse order. The log contains a textual description * of all events that has occurred, both successes and failures. * @return The log is formatted with HTML. */ @GET @Path("/getShortHtmlLog") @Produces("text/html") public String getShortHtmlLog() { return client.getShortHtmlLog(); } /** * getSettingsSummary provides a summary of some important settings of the Bitrepository collection, herein: * - The message bus which that is communicated with * - The Pillars in the collection * - The Bitrepository collection ID * @return The current settings formatted as HTML */ @GET @Path("/getSettingsSummary") @Produces("text/plain") public String getSummarySettings() { return client.getSettingsSummary(); } /** * getChecksumsHtml exposes the possibility of requesting checksums for the files present in the Bitrepository. * The two first parameters are mandatory. * @param fileIDs List of filenames to get checksums for. FileIDs should be seperated by a '\n' * @param checksumType The type of checksum algorithm that the requested checksum should be in. * The type needs to be one supported by all pillars in the collection. * @param salt A string to alter the preconditions of calculating a checksum. Will result in the returned checksum * being of type hmac:<checksumType>. The salt parameter is optional. * @return A HTML page containing a table of the requested fileIDs and their checksums, or an error message. */ @GET @Path("getChecksumsHtml") @Produces("text/html") public String getChecksumsHtml( @QueryParam("fileID") String fileID, @QueryParam("checksumType") String checksumType, @QueryParam("salt") String salt) throws WebserviceIllegalArgumentException { WebserviceInputChecker.checkFileIDParameter(fileID); WebserviceInputChecker.checkChecksumTypeParameter(checksumType); WebserviceInputChecker.checkSaltParameter(salt); Map<String, Map<String, String>> result = client.getChecksums(fileID, checksumType, salt); if(result == null) { return "<html><body><b>Failed!</b></body></html>"; } StringBuilder sb = new StringBuilder(); sb.append("<html><body><table>"); Set<String> returnedFileIDs = result.keySet(); ArrayList <String> pillarIDList = new ArrayList<String>(); sb.append("<tr> <td><b>File Id:</b></td><td>&nbsp;</td>"); for(String fileId : returnedFileIDs) { Set<String> pillarIDs = result.get(fileId).keySet(); for(String pillarID : pillarIDs) { pillarIDList.add(pillarID); sb.append("<td><b>Checksums from " + pillarID + ":</b></td>"); } break; } sb.append("</tr>"); for(String fileId : returnedFileIDs) { sb.append("<tr> <td> " + fileId + "</td><td>&nbsp;</td>"); for(String pillarID : pillarIDList) { if(result.get(fileId).containsKey(pillarID)) { sb.append("<td> " + result.get(fileId).get(pillarID) + " </td>"); } else { sb.append("<td> unknown </td>"); } } sb.append("</tr>"); } sb.append("</table></body></html>"); return sb.toString(); } /** * getChecksums exposes the possibility of requesting checksums for the files present in the Bitrepository. * The two first parameters are mandatory. * @param fileIDs List of filenames to get checksums for. FileIDs should be seperated by a '\n' * @param checksumType The type of checksum algorithm that the requested checksum should be in. * The type needs to be one supported by all pillars in the collection. * @param salt A string to alter the preconditions of calculating a checksum. Will result in the returned checksum * being of type hmac:<checksumType>. The salt parameter is optional. * @return A tab separated table containing the requested fileIDs and their checksums, or an error message. */ @GET @Path("getChecksums") @Produces("text/plain") public String getChecksums( @QueryParam("fileID") String fileID, @QueryParam("checksumType") String checksumType, @QueryParam("salt") String salt) throws WebserviceIllegalArgumentException { WebserviceInputChecker.checkFileIDParameter(fileID); WebserviceInputChecker.checkChecksumTypeParameter(checksumType); WebserviceInputChecker.checkSaltParameter(salt); Map<String, Map<String, String>> result = client.getChecksums(fileID, checksumType, salt); if(result == null) { return "Failed!"; } StringBuilder sb = new StringBuilder(); Set<String> returnedFileIDs = result.keySet(); ArrayList <String> pillarIDList = new ArrayList<String>(); sb.append("FileID \t"); for(String fileId : returnedFileIDs) { Set<String> pillarIDs = result.get(fileId).keySet(); for(String pillarID : pillarIDs) { pillarIDList.add(pillarID); sb.append(pillarID + "\t"); } break; } sb.append("\n"); for(String fileId : returnedFileIDs) { sb.append(fileId + "\t"); for(String pillarID : pillarIDList) { if(result.get(fileId).containsKey(pillarID)) { sb.append(result.get(fileId).get(pillarID) + "\t"); } else { sb.append("unknown \t"); } } sb.append("\n"); } return sb.toString(); } /** * getFileIDsHtml exposes the possibility of requesting listing of files present in the Bitrepository. * Of the two parameters at least one may not be empty. * @param fileIDs List of filenames to be listed. FileIDs should be seperated by a '\n' * @param allFileIDs Boolean indicating to get a list of all files in the Bitrepository collection. * Setting this will override any files set in by the fileIDs parameter. * @return A HTML page containing a table containing the requested fileIDs and which pillars have answered. * The entry of each fileID is color coded to indicate whether all pillars have answered on that particular file. * In case of an error, an error message is returned instead. */ @GET @Path("getFileIDsHtml") @Produces("text/html") public String getFileIDsHtml( @QueryParam("fileIDs") String fileIDs, @QueryParam("allFileIDs") boolean allFileIDs) throws WebserviceIllegalArgumentException { GetFileIDsResults results = client.getFileIDs(fileIDs, allFileIDs); if(results.getResults() == null) { return "<p>Get file ID's provided no results.</p>"; } StringBuilder sb = new StringBuilder(); sb.append("<html><head><style> #good{background-color:#31B404;} #bad{background-color:#B40404;} " + "td{padding: 5px;}</style></head><body>"); sb.append("<table> <tr valign=\"top\"> \n <td>"); sb.append("<table> <tr> <th> <b>File Id:</b> </th> <th>&nbsp;&nbsp;" + "</th><th><b>Number of answers </b></th></tr>"); Set<String> IDs = results.getResults().keySet(); String status; for(String ID : IDs) { if(results.getResults().get(ID).size() == results.getPillarList().size()) { status = "good"; } else { status = "bad"; } sb.append("<tr><td id=" + status + ">" + ID + "</td><td></td><td>" + results.getResults().get(ID).size() +"</td></tr>"); } sb.append("</table> </td> <td>&nbsp;&nbsp;</td><td><table><tr> <th> <b> Pillar list</b> </th> </tr>"); for(String pillar : results.getPillarList()) { sb.append("<tr><td>" + pillar + "</td></tr>"); } sb.append("</table></td> </tr> </table></body></html>"); return sb.toString(); } /** * getFileIDs exposes the possibility of requesting listing of all files present in the Bitrepository. * @return A string containing one fileID per line. */ @GET @Path("getFileIDs") @Produces("text/plain") public String getFileIDs() { GetFileIDsResults results = client.getFileIDs("", true); StringBuilder sb = new StringBuilder(); if(results.getResults() != null) { for(String ID : results.getResults().keySet()) { sb.append(ID + "\n"); } } return sb.toString(); } @GET @Path("deleteFile") @Produces("text/html") public String deleteFile( @QueryParam("fileID") String fileID, @QueryParam("pillarID") String pillarID, @QueryParam("deleteChecksum") String deleteChecksum, @QueryParam("deleteChecksumType") String deleteChecksumType, @QueryParam("deleteChecksumSalt") String deleteChecksumSalt, @QueryParam("approveChecksumType") String approveChecksumType, @QueryParam("approveChecksumSalt") String approveChecksumSalt) throws WebserviceIllegalArgumentException { WebserviceInputChecker.checkFileIDParameter(fileID); WebserviceInputChecker.checkPillarIDParameter(pillarID); WebserviceInputChecker.checkChecksumParameter(deleteChecksum); try { return client.deleteFile(fileID, pillarID, deleteChecksum, deleteChecksumType, deleteChecksumSalt, approveChecksumType, approveChecksumSalt); } catch (IllegalArgumentException e) { throw new WebserviceIllegalArgumentException(e.getMessage()); } } @GET @Path("replaceFile") @Produces("text/html") public String replaceFile( @QueryParam("fileID") String fileID, @QueryParam("pillarID") String pillarID, @QueryParam("oldFileChecksum") String oldFileChecksum, @QueryParam("oldFileChecksumType") String oldFileChecksumType, @QueryParam("oldFileChecksumSalt") String oldFileChecksumSalt, @QueryParam("oldFileRequestChecksumType") String oldFileRequestChecksumType, @QueryParam("oldFileRequestChecksumSalt") String oldFileRequestChecksumSalt, @QueryParam("url") String url, @QueryParam("fileSize") String fileSize, @QueryParam("newFileChecksum") String newFileChecksum, @QueryParam("newFileChecksumType") String newFileChecksumType, @QueryParam("newFileChecksumSalt") String newFileChecksumSalt, @QueryParam("newFileRequestChecksumType") String newFileRequestChecksumType, @QueryParam("newFileRequestChecksumSalt") String newFileRequestChecksumSalt) throws WebserviceIllegalArgumentException { WebserviceInputChecker.checkFileIDParameter(fileID); WebserviceInputChecker.checkFileSizeParameter(fileSize); WebserviceInputChecker.checkPillarIDParameter(pillarID); WebserviceInputChecker.checkURLParameter(url); WebserviceInputChecker.checkChecksumTypeParameter(oldFileChecksumType); WebserviceInputChecker.checkChecksumParameter(oldFileChecksum); WebserviceInputChecker.checkSaltParameter(oldFileChecksumSalt); //WebserviceInputChecker.checkChecksumTypeParameter(oldFileRequestChecksumType); WebserviceInputChecker.checkSaltParameter(oldFileRequestChecksumSalt); WebserviceInputChecker.checkChecksumTypeParameter(newFileChecksumType); WebserviceInputChecker.checkChecksumParameter(newFileChecksum); WebserviceInputChecker.checkSaltParameter(newFileChecksumSalt); WebserviceInputChecker.checkSaltParameter(newFileRequestChecksumSalt); //WebserviceInputChecker.checkChecksumTypeParameter(newFileRequestChecksumType); try { return client.replaceFile(fileID, pillarID, oldFileChecksum, oldFileChecksumType, oldFileChecksumSalt, oldFileRequestChecksumType, oldFileRequestChecksumSalt, makeUrl(url), Long.parseLong(fileSize), newFileChecksum, newFileChecksumType, newFileChecksumSalt, newFileRequestChecksumType, newFileRequestChecksumSalt); } catch (IllegalArgumentException e) { throw new WebserviceIllegalArgumentException(e.getMessage()); } } private URL makeUrl(String urlStr) { try { return new URL(urlStr); } catch (MalformedURLException e) { throw new WebserviceIllegalArgumentException(urlStr + " is not a valid url"); } } }
package org.buildoop.storm.bolts; import backtype.storm.task.TopologyContext; import backtype.storm.topology.BasicOutputCollector; import backtype.storm.topology.IBasicBolt; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Map; import org.elasticsearch.common.joda.time.format.DateTimeFormat; import org.elasticsearch.common.joda.time.format.ISODateTimeFormat; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import java.util.UUID; import static backtype.storm.utils.Utils.tuple; @SuppressWarnings("serial") public class KafkaParserBolt implements IBasicBolt { private String index; private String type; private int i = 1000; private boolean simulated = true; //private String type; public static final Logger log = LoggerFactory .getLogger(KafkaParserBolt.class); @SuppressWarnings("rawtypes") public void prepare(Map stormConf, TopologyContext context) { index = (String) stormConf.get("elasticsearch.index"); type = (String) stormConf.get("elasticsearch.type"); simulated = ((String)stormConf.get("other.simulated")).equals("true")?true:false; //this.type = (String) stormConf.get("elasticsearch.type"); } public void execute(Tuple input, BasicOutputCollector collector) { String kafkaEvent = new String(input.getBinary(0)); if (kafkaEvent.length()>0) { JSONObject objAux = new JSONObject(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(kafkaEvent); JSONObject jsonObject = (JSONObject) obj; String message = (String) jsonObject.get("message"); JSONObject extraData = (JSONObject) jsonObject.get("extraData"); objAux.put("message",message); objAux.put("ciid",extraData.get("ciid")); objAux.put("item",extraData.get("item")); objAux.put("hostname",extraData.get("hostname")); objAux.put("delivery",extraData.get("delivery")); log.debug(message); int inicio = message.indexOf("keedio.datagenerator: ")+"keedio.datagenerator: ".length(); //System.out.println(message.substring(inicio, inicio + 19)); objAux.put("timestamp",this.transformDate(message.substring(inicio, inicio + 19), "yyyy-MM-dd hh:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSSZ")); objAux.put("vdc", extraData.get("vdc")); } catch (Exception e) { //e.printStackTrace(); log.debug("Erro al parsear mensaje"); } collector.emit(tuple(String.valueOf(UUID.randomUUID()),index, (String)objAux.get("delivery"), objAux.toString())); } } private String transformDate(String date, String originPtt, String finalPtt) { try { SimpleDateFormat sdf1 = new SimpleDateFormat(originPtt); Date date1 = sdf1.parse(date); date1.setYear(new Date().getYear()); if (simulated) date1=new Date(); SimpleDateFormat sdf2 = new SimpleDateFormat(finalPtt); return sdf2.format(date1); } catch (Exception e) { return ""; } } public void cleanup() { } public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("id", "index", "type", "document")); } @Override public Map<String, Object> getComponentConfiguration() { return null; } }
package org.ccci.gto.android.common.util; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; public final class IOUtils { // 640K should be enough for anybody -Bill Gates // (Bill Gates never actually said this) private static final int DEFAULT_BUFFER_SIZE = 640 * 1024; private static final int EOF = -1; public static void closeQuietly(@Nullable final Closeable handle) { if (handle != null) { try { handle.close(); } catch (final IOException e) { // suppress the error } } } public static void closeQuietly(@Nullable final HttpURLConnection conn) { if (conn != null) { conn.disconnect(); } } public static long copy(@NonNull final InputStream in, @NonNull final OutputStream out) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; long count = 0; int n; while (EOF != (n = in.read(buffer))) { out.write(buffer, 0, n); count += n; } return count; } @NonNull public static String readString(@NonNull final InputStream in) throws IOException { final BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), DEFAULT_BUFFER_SIZE); final StringBuilder out = new StringBuilder(); final char[] buffer = new char[DEFAULT_BUFFER_SIZE]; int n; while (EOF != (n = reader.read(buffer, 0, buffer.length))) { out.append(buffer, 0, n); } return out.toString(); } }
package org.dada.core; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.locks.Lock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A ServiceFactory that returns a proxy for its target, invocations upon which are queued and executed on another thread. * It may be sensible to execute invocations returning values directly on the calling Thread. * * @author jules * * @param <T> */ public class AsynchronousServiceFactory<T> implements ServiceFactory<T> { private final Logger log = LoggerFactory.getLogger(AsynchronousServiceFactory.class); private final ExecutorService executorService; private final Class<?>[] interfaces; private final Lock lock; public AsynchronousServiceFactory(Class<?>[] interfaces, ExecutorService executorService, Lock lock) { this.interfaces = Arrays.copyOf(interfaces, interfaces.length); this.executorService = executorService; this.lock = lock; } protected class Invocation implements Runnable { private final T target; private final Method method; private final Object[] args; protected Invocation(T target, Method method, Object[] args) { lock.lock(); this.target = target; this.method = method; this.args = args; } @Override public void run() { try { method.invoke(target, args); } catch (Throwable t) { log.error("problem during async invocation ({})", this, t); } finally { lock.unlock(); } } @Override public String toString() { return "<" + getClass().getSimpleName() + ":" + target + "." + method + ": " + Arrays.toString(args) + ">"; } } @SuppressWarnings("unchecked") @Override public T decouple(final T target) { InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getReturnType() == Void.TYPE) { // async invocation executorService.execute(new Invocation(target, method, args)); return null; } else { // sync invocation return method.invoke(method.getDeclaringClass().equals(Object.class) ? this : target, args); } } @Override public String toString() { return "<" + getClass().getEnclosingClass().getSimpleName() + "." + getClass().getInterfaces()[0].getSimpleName() + ">"; } }; return (T)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, handler); } @Override public T client(String endPoint) throws Exception { // TODO Auto-generated method stub throw new UnsupportedOperationException("NYI"); } @Override public void server(T target, String endPoint) throws Exception { // TODO Auto-generated method stub throw new UnsupportedOperationException("NYI"); } // used to expose Invocation to test harness protected Invocation createInvocation(T target, Method method, Object[] args) { return new Invocation(target, method, args); } }
package org.esupportail.smsu.web.ws; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.esupportail.smsu.business.MemberManager; import org.esupportail.smsu.business.MessageManager; import org.esupportail.smsu.business.SendSmsManager; import org.esupportail.smsu.business.ServiceManager; import org.esupportail.smsu.business.beans.Member; import org.esupportail.smsu.exceptions.CreateMessageException; import org.esupportail.smsu.exceptions.SmsuForbiddenException; import org.esupportail.smsu.exceptions.ldap.LdapUserNotFoundException; import org.esupportail.smsu.exceptions.ldap.LdapWriteException; import org.esupportail.smsu.web.beans.UIMessage; import org.esupportail.smsu.web.beans.UINewMessage; import org.esupportail.smsu.web.beans.UIService; import org.esupportail.smsu.web.controllers.InvalidParameterException; import org.esupportail.smsuapi.exceptions.InsufficientQuotaException; import org.esupportail.smsuapi.utils.HttpException; import javax.inject.Inject; import org.springframework.beans.factory.annotation.Required; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/") public class WsController { private final Logger logger = Logger.getLogger(getClass()); protected static enum MembershipStatus {PENDING, OK}; @Inject private MessageManager messageManager; @Inject private SendSmsManager sendSmsManager; @Inject private MemberManager memberManager; @Inject private ServiceManager serviceManager; private List<String> authorizedClientNames; @RequestMapping(method = RequestMethod.POST, value = "/sms") public UIMessage sendSMSAction(@RequestBody UINewMessage msg, HttpServletRequest request) throws CreateMessageException { if(checkClient(request)) { sendSmsManager.contentValidation(msg.content); if (msg.mailToSend != null) { sendSmsManager.mailsValidation(msg.mailToSend); } int messageId = sendSmsManager.sendMessage(msg, request); return messageManager.getUIMessage(messageId, null); } else { throw new SmsuForbiddenException("You can't call this WS from this remote address"); } } @RequestMapping(method = RequestMethod.GET, value = "/member/{login}") public Member getMember(@PathVariable("login") String login, HttpServletRequest request) { if(checkClient(request)) { Member member = null; try { member = memberManager.getMember(login); } catch (LdapUserNotFoundException e) { logger.warn("getValidCgMember on " + login + " failed - user not found", e); } return member; } else { throw new SmsuForbiddenException("You can't call this WS from this remote address"); } } @RequestMapping(method = RequestMethod.POST, value = "/member") public MembershipStatus saveMember(@RequestBody Member member, HttpServletRequest request) throws LdapUserNotFoundException, LdapWriteException, HttpException, InsufficientQuotaException { if(checkClient(request)) { logger.debug("Save data of a member"); if (StringUtils.isEmpty(member.getPhoneNumber())) { if (member.getValidCG()) throw new InvalidParameterException("ADHESION.ERROR.PHONEREQUIRED"); } else { memberManager.validatePhoneNumber(member.getPhoneNumber()); } // save datas into LDAP boolean pending = memberManager.saveOrUpdateMember(member); return pending ? MembershipStatus.PENDING : MembershipStatus.OK; } else { throw new SmsuForbiddenException("You can't call this WS from this remote address"); } } @RequestMapping(method = RequestMethod.POST, value = "/validCode") public Boolean validCode(@RequestBody Member member, HttpServletRequest request) throws LdapUserNotFoundException, LdapWriteException, HttpException, InsufficientQuotaException { if(checkClient(request)) { logger.debug("Valid code of a member"); // check if the code is correct // and accept definitely the user inscription if the code is correct final boolean valid = memberManager.valid(member); return valid; } else { throw new SmsuForbiddenException("You can't call this WS from this remote address"); } } @RequestMapping(method = RequestMethod.GET, value = "/services") public List<UIService> getUIServices(HttpServletRequest request) { if(checkClient(request)) { return serviceManager.getAllUIServices(); } else { throw new SmsuForbiddenException("You can't call this WS from this remote address"); } } @RequestMapping(method = RequestMethod.GET, value = "/member/{login}/adhServicesAvailable") public List<UIService> getUIServicesAdh(@PathVariable("login") String login, HttpServletRequest request) { if(checkClient(request)) { return serviceManager.getUIServicesAdhFctn(login); } else { throw new SmsuForbiddenException("You can't call this WS from this remote address"); } } /** * Check if the client is authorized. */ protected boolean checkClient(HttpServletRequest request) { InetAddress client = getClient(request); if (client == null) { throw new RuntimeException("could not resolve the client of the web service"); } for (String authorizedClientName : authorizedClientNames) { try { if (client.equals(InetAddress.getByName(authorizedClientName))) { return true; } } catch (UnknownHostException e) { logger.warn("could not resolve authorized client [" + authorizedClientName + "]", e); } } logger.warn("client [" + client.getHostName() + "] is not authorized"); return false; } /** * @return the client. */ protected InetAddress getClient(HttpServletRequest request) { String remoteAddr = request.getRemoteAddr(); try { return InetAddress.getByName(remoteAddr); } catch (UnknownHostException e) { logger.info("could not resolve remote address : " + remoteAddr, e); return null; } } @Required @Value("${smsu.ws.authorizedClientNames}") public void setAuthorizedClientNames(String authorizedClientNamesWithComa) { authorizedClientNamesWithComa = authorizedClientNamesWithComa.replaceAll(" ", ""); authorizedClientNames = Arrays.asList(StringUtils.split(authorizedClientNamesWithComa, ",")); logger.info("WS authorizedClientNames : " + authorizedClientNames); } }
package org.jtrfp.trcl.objects; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.Model; import org.jtrfp.trcl.World; import org.jtrfp.trcl.ai.ObjectBehavior; public class RigidMobileObject extends MobileObject { private Vector3D velocity = Vector3D.ZERO; private Vector3D drag = Vector3D.ZERO; public RigidMobileObject(Model model, ObjectBehavior behavior, World world) {super(model, behavior, world);} /** * @return the velocity */ public Vector3D getVelocity() { return velocity; } /** * @param velocity the velocity to set */ public void setVelocity(Vector3D velocity) { this.velocity = velocity; } /** * @return the drag */ public Vector3D getDrag() { return drag; } /** * @param drag the drag to set */ public void setDrag(Vector3D drag) { this.drag = drag; } }//end RigidMobileObject
package org.lightmare.jpa.datasource; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Properties; import java.util.Set; import javax.naming.Context; import javax.sql.DataSource; import org.apache.log4j.Logger; import org.lightmare.config.Configuration; import org.lightmare.jndi.JndiManager; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Parses XML and property files to initialize and cache {@link DataSource} * objects * * @author levan * */ public class Initializer { // Caches already initialized data source file paths private static final Set<String> INITIALIZED_SOURCES = Collections .synchronizedSet(new HashSet<String>()); // Caches already initialized data source JNDI names private static final Set<String> INITIALIZED_NAMES = Collections .synchronizedSet(new HashSet<String>()); /** * Container for connection configuration properties * * @author levan * */ public static enum ConnectionConfig { DRIVER_PROPERTY("driver"), // driver USER_PROPERTY("user"), // user PASSWORD_PROPERTY("password"), // password URL_PROPERTY("url"), // URL JNDI_NAME_PROPERTY("jndiname"), // JNDI name NAME_PROPERTY("name");// name public String name; private ConnectionConfig(String name) { this.name = name; } } public static final Logger LOG = Logger.getLogger(Initializer.class); private Initializer() { } private static boolean checkForDataSource(String path) { return ObjectUtils.available(path); } public static String getJndiName(Properties properties) { String jndiName = properties .getProperty(ConnectionConfig.JNDI_NAME_PROPERTY.name); return jndiName; } /** * Loads jdbc driver class * * @param driver */ public static void initializeDriver(String driver) throws IOException { MetaUtils.initClassForName(driver); } /** * Initialized data source from passed file path * * @throws IOException */ public static void initializeDataSource(String path) throws IOException { boolean valid = checkForDataSource(path) && ObjectUtils.notTrue(Initializer.checkDSPath(path)); if (valid) { FileParsers parsers = new FileParsers(); parsers.parseStandaloneXml(path); } } /** * Initializes data sources from passed {@link Configuration} instance * * @throws IOException */ public static void initializeDataSources(Configuration config) throws IOException { Collection<String> paths = config.getDataSourcePath(); if (ObjectUtils.available(paths)) { for (String path : paths) { initializeDataSource(path); } } } /** * Initializes and registers {@link DataSource} object in jndi by * {@link Properties} {@link Context} * * @param poolingProperties * @param dataSource * @param jndiName * @throws IOException */ public static void registerDataSource(Properties properties) throws IOException { InitDataSource initDataSource = InitDataSourceFactory.get(properties); initDataSource.create(); // Caches jndiName for data source String jndiName = getJndiName(properties); INITIALIZED_NAMES.add(jndiName); } public static void setDsAsInitialized(String datasourcePath) { INITIALIZED_SOURCES.add(datasourcePath); } public static void removeInitialized(String datasourcePath) { INITIALIZED_SOURCES.remove(datasourcePath); } public static boolean checkDSPath(String datasourcePath) { return INITIALIZED_SOURCES.contains(datasourcePath); } /** * Closes and removes from {@link Context} data source with specified JNDI * name * * @param jndiName * @throws IOException */ public static void close(String jndiName) throws IOException { JndiManager jndiManager = new JndiManager(); DataSource dataSource = jndiManager.lookup(jndiName); if (ObjectUtils.notNull(dataSource)) { cleanUp(dataSource); } dataSource = null; jndiManager.unbind(jndiName); INITIALIZED_NAMES.remove(jndiName); } /** * Closes and removes from {@link Context} all initialized and cached data * sources * * @throws IOException */ public static void closeAll() throws IOException { Set<String> dataSources = new HashSet<String>(INITIALIZED_NAMES); for (String jndiName : dataSources) { close(jndiName); } } /** * Closes and removes from {@link Context} all data sources from passed file * path * * @param dataSourcePath * @throws IOException */ public static void undeploy(String dataSourcePath) throws IOException { Collection<String> jndiNames = FileParsers .dataSourceNames(dataSourcePath); if (ObjectUtils.available(dataSourcePath)) { for (String jndiName : jndiNames) { close(jndiName); } } removeInitialized(dataSourcePath); } /** * Cleans and destroys passed {@link DataSource} instance * * @param dataSource */ public static void cleanUp(DataSource dataSource) { InitDataSourceFactory.destroy(dataSource); } }
package org.minimalj.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.minimalj.repository.list.QueryResultList; public class SerializationContainer implements Serializable { private static final long serialVersionUID = 1L; private transient Object object; @SuppressWarnings({ "rawtypes", "unchecked" }) public static Serializable wrap(Object object) { if (object instanceof List && !(object instanceof QueryResultList)) { List list = (List) object; ArrayList arrayList = new ArrayList<>(((List) object).size()); for (int i = 0; i<list.size(); i++) { arrayList.add(wrap(list.get(i))); } return arrayList; } else if (object instanceof Serializable) { return (Serializable) object; } else { SerializationContainer container = new SerializationContainer(); container.object = object; return container; } } @SuppressWarnings({ "rawtypes", "unchecked" }) public static Object unwrap(Object container) { if (container instanceof List && !(container instanceof QueryResultList)) { List list = (List) container; for (int i = 0; i<list.size(); i++) { list.set(i, unwrap(list.get(i))); } return list; } else if (container instanceof SerializationContainer) { return ((SerializationContainer) container).object; } else { return container; } } private void writeObject(ObjectOutputStream out) throws IOException { EntityWriter writer = new EntityWriter(out); writer.write(object); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { EntityReader reader = new EntityReader(in); object = reader.read(); } }
package mockit; import org.junit.*; import static org.junit.Assert.*; public final class ExpectationsForConstructorsTest { public static class BaseCollaborator { protected int value; protected BaseCollaborator() { value = -1; } protected BaseCollaborator(int value) { this.value = value; } protected boolean add(Integer i) { return i != null; } } static class Collaborator extends BaseCollaborator { Collaborator() {} Collaborator(int value) { super(value); } } @SuppressWarnings({"UnusedDeclaration"}) public abstract static class AbstractCollaborator extends BaseCollaborator { protected AbstractCollaborator(int value) { super(value); } protected AbstractCollaborator(boolean b, int value) { super(value); } protected abstract void doSomething(); } @Test public void mockAllConstructors() { new Expectations() { final Collaborator unused = null; { new Collaborator(); new Collaborator(123); } }; assertEquals(0, new Collaborator().value); assertEquals(0, new Collaborator(123).value); } @Test public void mockOnlyOneConstructorSpecifyingUseOfNoArgsSuperConstructor() { new Expectations() { @Mocked("(int): ()") final Collaborator unused = null; { new Collaborator(123); } }; assertEquals(-1, new Collaborator().value); assertEquals(-1, new Collaborator(123).value); } @Test public void mockOnlyNoArgsConstructorSpecifyingUseOfSuperConstructorWithArgs() { new Expectations() { @Mocked("(): (int)") final Collaborator unused = null; { new Collaborator(); } }; assertEquals(0, new Collaborator().value); assertEquals(123, new Collaborator(123).value); } @Test public void partiallyMockAbstractClass(final AbstractCollaborator mock) { new Expectations() { { mock.doSomething(); } }; mock.doSomething(); } @Test public void mockSubclassSpecifyingConstructorArgsMethod() { new Expectations() { @Mocked(methods = "add", constructorArgsMethod = "getConstructorArguments") Collaborator mock; { mock.add(5); result = true; } @SuppressWarnings({"UnusedDeclaration"}) private Object[] getConstructorArguments(int value) { return new Object[] {100}; } }; assertTrue(new Collaborator().add(5)); } @Test(expected = IllegalArgumentException.class) public void mockSubclassSpecifyingNonExistentConstructorArgsMethod() { new Expectations() { @Mocked(constructorArgsMethod = "nonExistent") Collaborator mock; }; } @Ignore @Test public void mockAbstractClassSpecifyingConstructorArgsMethod( @Mocked(methods = "doSomething", constructorArgsMethod = "getConstructorArguments") final AbstractCollaborator mock) { new Expectations() { { mock.doSomething(); } }; mock.doSomething(); } @SuppressWarnings({"UnusedDeclaration"}) private Object[] getConstructorArguments(boolean b, int value) { return new Object[] {true, 100}; } }
package org.nohope.reflection; import org.apache.commons.lang3.ArrayUtils; import org.nohope.typetools.StringUtils; import javax.annotation.Nonnull; import java.lang.reflect.*; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; import static org.nohope.reflection.ModifierMatcher.*; //import static java.lang.reflect.Modifier.PUBLIC; /** * Set of introspection utils aimed to reduce problems caused by reflecting * native/inherited types. * <p/> * This class extensively uses "types compatibility" term which means: * <p/> * Types are compatible if: * 1. source type can be auto(un)boxed to target type * 2. source type is child of target type * 3. source and target are array types then one of these rules should be * applied to their component types. * * @author <a href="mailto:ketoth.xupack@gmail.com">ketoth xupack</a> * @since 8/12/11 5:42 PM */ public final class IntrospectionUtils { /** * Default stake trace depth for method invocation. */ private static final int DEFAULT_INVOKE_DEPTH = 3; /** * Method name for constructor (value: "new"). * */ private static final String CONSTRUCTOR = "new"; /** * list of java primitive types. */ private static final List<Class<?>> PRIMITIVES = new ArrayList<>(); /** * lookup map for matching primitive types and their object wrappers. */ private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS = new HashMap<>(); static { PRIMITIVES.add(Byte.TYPE); PRIMITIVES.add(Short.TYPE); PRIMITIVES.add(Integer.TYPE); PRIMITIVES.add(Long.TYPE); PRIMITIVES.add(Float.TYPE); PRIMITIVES.add(Double.TYPE); PRIMITIVES.add(Boolean.TYPE); PRIMITIVES.add(Character.TYPE); PRIMITIVES_TO_WRAPPERS.put(Byte.TYPE, Byte.class); PRIMITIVES_TO_WRAPPERS.put(Short.TYPE, Short.class); PRIMITIVES_TO_WRAPPERS.put(Integer.TYPE, Integer.class); PRIMITIVES_TO_WRAPPERS.put(Long.TYPE, Long.class); PRIMITIVES_TO_WRAPPERS.put(Float.TYPE, Float.class); PRIMITIVES_TO_WRAPPERS.put(Double.TYPE, Double.class); PRIMITIVES_TO_WRAPPERS.put(Boolean.TYPE, Boolean.class); PRIMITIVES_TO_WRAPPERS.put(Character.TYPE, Character.class); } /** * Utility class constructor. */ private IntrospectionUtils() { } /** * @return list of primitive types */ public static List<Class<?>> getPrimitives() { return new ArrayList<>(PRIMITIVES); } /** * Returns referenced wrapper for primitive type. * * @param p class suppose to be a primitive * @return wrapper for primitive, {@code null} if passed type is not a * primitive */ public static Class<?> primitiveToWrapper(final Class p) { return PRIMITIVES_TO_WRAPPERS.get(p); } /** * Returns boxed version of given primitive type (if actually it is a * primitive type). * * @param type type to translate * @return boxed primitive class or class itself if not primitive. */ public static Class<?> tryFromPrimitive(final Class type) { if (type == null || !type.isPrimitive()) { return type; } return primitiveToWrapper(type); } public static <T> T newInstance(final Class<T> type, final Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { final Constructor<T> constructor = searchConstructor(type, getClasses(args)); final Class[] signature = constructor.getParameterTypes(); try { final Object[] params = adaptTo(args, signature); // request privileges AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { constructor.setAccessible(true); return null; } }); return constructor.newInstance(params); } catch (final ClassCastException e) { throw cantInvoke(type, CONSTRUCTOR, signature, args, e); } } public static Object invoke(final Object instance, final String methodName, final Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { return invoke(instance, and(PUBLIC, not(ABSTRACT)), methodName, args); } public static Object invoke(@Nonnull final Object instance, final IModifierMatcher matcher, final String methodName, final Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final Method method = searchMethod(instance, matcher, methodName, getClasses(args)); final Class[] sig = method.getParameterTypes(); try { final Object[] params = adaptTo(args, sig); final int flags = method.getModifiers(); final Class<?> clazz = instance.getClass(); final int classFlags = clazz.getModifiers(); // request privileges for non-public method/instance class/parent class if (!PUBLIC.matches(flags) || !PUBLIC.matches(classFlags) || clazz != method.getDeclaringClass()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { method.setAccessible(true); return null; } }); } return method.invoke(instance, params); } catch (final ClassCastException e) { throw cantInvoke(instance.getClass(), methodName, sig, args, e); } } /** * Checks if target class is assignable from source class in terms of * auto(un)boxing. if given classes are array types then recursively checks * if their component types are assignable from each other. * <p/> * Note: assignable means inheritance: * <pre> * target * ^ * | * source * </pre> * * @param target target class * @param source source class * @return {@code true} if target is assignable from source */ public static boolean isAssignable(final Class target, final Class source) { if (target == null || source == null) { throw new IllegalArgumentException("classes"); } if (target.isArray() && source.isArray()) { return isAssignable(target.getComponentType(), source.getComponentType()); } return tryFromPrimitive(target).isAssignableFrom(tryFromPrimitive(source)); } /** * Checks if given arrays of types are compatible. * * @param targets array of types * @param sources array of types * @return {@code true} if types are compatible */ public static boolean areTypesCompatible(final Class[] targets, final Class[] sources) { // check if types are "varargs-compatible" if (sources.length != targets.length) { return false; } for (int i = 0; i < targets.length; i++) { // if we got null here then types are definitely compatible // (if target is not a primitive) if (sources[i] == null) { if (targets[i].isPrimitive()) { return false; } continue; } if (!isAssignable(targets[i], sources[i])) { return false; } } return true; } /** * Checks if types compatible in term of varargs. * * @param targets target types * @param sources source types * @return {@code true} if types are vararg-compatible */ public static boolean areTypesVarargCompatible(final Class[] targets, final Class[] sources) { if (!isVarargs(targets)) { return areTypesCompatible(targets, sources); } final Class[] flat = flattenVarargs(targets); final int flatSize = flat.length; final int srcSize = sources.length; // last vararg can be omitted if (srcSize == flatSize - 1) { return areTypesCompatible(ArrayUtils.subarray(flat, 0, flatSize - 1), sources); } // not a vararg if (srcSize == flatSize) { return areTypesCompatible(flat, sources); } // vararg should be assembled if (srcSize > flatSize) { final Class vararg = flat[flatSize - 1]; for (int i = flatSize; i < srcSize; i++) { if (!isAssignable(vararg, sources[i])) { return false; } } return areTypesCompatible(flat, ArrayUtils.subarray(sources, 0, flatSize)); } return false; } /** * Searches for constructor of given type compatible with given signature. * * @param type type * @param signature signature * @param <T> type of object for search * @return constructor compatible with given signature * @throws NoSuchMethodException if no or more than one constructor found */ @SuppressWarnings("unchecked") private static <T> Constructor<T> searchConstructor( final Class<T> type, final Class[] signature) throws NoSuchMethodException { final Constructor[] constructors = type.getDeclaredConstructors(); Constructor found = null; Constructor vararg = null; int varargsFound = 0; for (final Constructor constructor : constructors) { final Class[] types = constructor.getParameterTypes(); // Check for signature types compatibility if (areTypesCompatible(types, signature)) { if (found != null) { // we got one compatible constructor already... throw tooMuch(type, CONSTRUCTOR, signature, ALL); } found = constructor; } else if (areTypesVarargCompatible(types, signature)) { vararg = constructor; varargsFound++; } } // there is no such constructor at all... if (found == null) { if (varargsFound > 1) { throw tooMuch(type, CONSTRUCTOR, signature, ALL); } if (varargsFound == 1) { return vararg; } throw notFound(type, CONSTRUCTOR, signature, ALL); } // this _should_ be an Constructor<T> huh? return (Constructor<T>) found; } /** * Checks if lower method overrides higher method. * * @param higher method used to be higher in class hierarchy * @param lower method used to be lower in class hierarchy * @return true if lower overrides higher */ public static boolean isOverridden(final Method higher, final Method lower) { return higher.getDeclaringClass().isAssignableFrom(lower.getDeclaringClass()) && Arrays.deepEquals(higher.getParameterTypes(), lower.getParameterTypes()); } /** * Searches for <b>public</b> method of given instance with given name * and compatible signature. * * @param instance instance * @param methodName method name * @param signature method signature * @return constructor compatible with given signature * @throws NoSuchMethodException if no or more than one method found * * @see #searchMethod(Object, IModifierMatcher, String, Class[]) */ public static Method searchMethod(final Object instance, final String methodName, final Class... signature) throws NoSuchMethodException { return searchMethod(instance, and(PUBLIC, not(ABSTRACT)), methodName, signature); } /** * Searches for method with given modifiers (public methods will be always * included in search) of given instance with given name and compatible signature. * * <p /> * Example usage: * <pre> * searchMethod(this, * {@link Modifier#PRIVATE PRIVATE} | {@link Modifier#PROTECTED PROTECTED}, * "invokeMe"); * </pre> * * @param instance instance * @param methodName method name * @param signature method signature * @return constructor compatible with given signature * @throws NoSuchMethodException if no or more than one method found */ public static Method searchMethod(final Object instance, final IModifierMatcher matcher, final String methodName, final Class... signature) throws NoSuchMethodException { final Class type; if (instance instanceof Class) { type = (Class) instance; } else { type = instance.getClass(); } final Set<Method> mth = new HashSet<>(); Class<?> parent = type; while (parent != null) { for (final Method m : parent.getDeclaredMethods()) { if (!methodName.equals(m.getName())) { continue; } final int flags = m.getModifiers(); if (matcher.matches(flags) /*(flags & modifiers) == modifiers || ((modifiers & PACKAGE_DEFAULT) != 0 && (flags & ~PACKAGE_DEFAULT) == 0)*/ ) { /* Here we need to ensure no overridden methods from parent will be added in search result */ boolean toBeAdded = true; for (final Method added : mth) { if (isOverridden(m, added)) { // skipping overridden methods from parent toBeAdded = false; break; } } if (toBeAdded) { mth.add(m); } } } parent = parent.getSuperclass(); } final Method[] methods = mth.toArray(new Method[mth.size()]); Method found = null; Method vararg = null; int varargsFound = 0; for (final Method method : methods) { final Class[] types = method.getParameterTypes(); // Check for signature types compatibility if (areTypesCompatible(types, signature)) { if (found != null) { // we got one compatible method already... throw tooMuch(type, methodName, signature, matcher); } found = method; } else if (areTypesVarargCompatible(types, signature)) { vararg = method; varargsFound++; } } // there is no such method at all... if (found == null) { switch (varargsFound) { case 0: throw notFound(type, methodName, signature, matcher); case 1: return vararg; default: throw tooMuch(type, methodName, signature, matcher); } } return found; } /** * Shrinks array component type to common parent type of all array elements. * * @param array given array * @return casted array */ public static Object shrinkType(final Object[] array) { if (array.length == 0) { return array; } int firstNotNull = -1; for (int i = 0; i < array.length; i++) { if (null != array[i]) { firstNotNull = i; break; } } // array of nulls if (firstNotNull == -1) { return array; } Class<?> common = array[firstNotNull].getClass(); for (int i = firstNotNull; i < array.length; i++) { final Object element = array[i]; if (element != null) { // can't be null common = findCommonParent(element.getClass(), common); } } return shrinkTypeTo(array, common); } /** * Finds superclass common for passed classes. * <p/> * Note: this method passes through interface classes. * * @param c1 first class * @param c2 second class * @return common parent class if exists {@code null} otherwise */ public static Class<?> findCommonParent(final Class<?> c1, final Class<?> c2) { if (c1 == null) { return c2; } if (c2 == null) { return c1; } if (isAssignable(c1, c2)) { return c1; } if (isAssignable(c2, c1)) { return c2; } Class c1Parent = tryFromPrimitive(c1).getSuperclass(); while (c1Parent != null && !c2.isInterface()) { if (isAssignable(c1Parent, c2)) { return c1Parent; } c1Parent = c1Parent.getSuperclass(); } // c1 or c2 is an interface (which not yet supported) return null; } public static <T> Object shrinkTypeTo(final Object source, final Class<T> clazz) { if (source == null || !source.getClass().isArray()) { throw new IllegalArgumentException("array expected"); } if (source.getClass().getComponentType() == clazz) { return source; } final int arrayLength = Array.getLength(source); final Object result = Array.newInstance(clazz, arrayLength); // zero length array if (arrayLength == 0) { if (isAssignable(source.getClass().getComponentType(), clazz)) { return result; } throw arrayCastError(source, clazz); } for (int i = 0; i < arrayLength; i++) { Object origin = Array.get(source, i); try { // in case if we got multidimensional array if (origin != null && origin.getClass().isArray() && clazz.isArray()) { origin = shrinkTypeTo(origin, clazz.getComponentType()); } Array.set(result, i, origin); } catch (IllegalArgumentException e) { throw arrayCastError(origin, clazz, e); } } return result; } /** * Shrinks component type of given array to given type. * * @param source array to be casted * @param clazz desired type * @param <T> desired type * @return casted array */ public static <T> Object shrinkTypeTo(final Object[] source, final Class<T> clazz) { return shrinkTypeTo((Object) source, clazz); } /** * Creates object array from given object. If object is of array type * then shrinking it to {@link Object} type, else wraps it with new * {@link Object[]} instance. * * @param source object * @return array of objects * @see #shrinkTypeTo(Object, Class) */ public static Object[] toObjArray(final Object source) { if (source == null) { return null; } if (!source.getClass().isArray()) { return new Object[]{source}; } return (Object[]) shrinkTypeTo(source, Object.class); } /** * @return name of method which called this method */ public static String reflectSelfName() { return getMethodName(0); } /** * @return name of method which called method invoked this method */ public static String reflectCallerName() { return getMethodName(1); } /** * Transforms list of objects to list of their canonical names. * * @param arguments list of objects * @return canonical names for given object types */ public static String[] getClassNames(final Object... arguments) { return getClassNames(getClasses(arguments)); } public static String getCanonicalClassName(final Object obj) { return obj == null ? null : obj.getClass().getCanonicalName(); } /** * Transforms list of classes to list of their canonical names. * * @param arguments list of classes * @return canonical names for given classes */ private static String[] getClassNames(final Class... arguments) { final String[] names = new String[arguments.length]; { int i = 0; for (final Class clazz : arguments) { names[i++] = (clazz == null) ? null : clazz.getCanonicalName(); } } return names; } /** * Returns list of types of given list of objects. * * @param arguments array of object * @return array of classes of given objects */ private static Class[] getClasses(final Object... arguments) { final Class[] signature = new Class[arguments.length]; { int i = 0; for (final Object argument : arguments) { signature[i++] = (argument == null) ? null : argument.getClass(); } } return signature; } /** * Returns class for given type. * * @param type type * @return class object */ public static Class<?> getClass(final Type type) { if (type instanceof Class) { return (Class) type; } if (type instanceof ParameterizedType) { return getClass(((ParameterizedType) type).getRawType()); } if (type instanceof GenericArrayType) { final Type componentType = ((GenericArrayType) type) .getGenericComponentType(); final Class<?> componentClass = getClass(componentType); if (componentClass != null) { return Array.newInstance(componentClass, 0).getClass(); } } return null; } /** * Returns component type of last class in given signature of classes. * * @param signature signature of types * @return vararg component type */ private static Class getVarargComponentType(final Class[] signature) { return signature[signature.length - 1].getComponentType(); } /** * Casts list of objects to a given list of types. * Node: types of objects should be already compatible with given list of * types. * * @param objects list of objects to cast to * @param types corresponding types * @return list of objects casted to given list of types */ static Object[] adaptTo(final Object[] objects, final Class[] types) { final int argsLength = objects.length; final int typesLength = types.length; final List<Object> result = new ArrayList<>(); if (argsLength == typesLength) { for (int i = 0; i < argsLength; i++) { final Class type = types[i]; final Object object = objects[i]; if (type.isArray() && object != null) { final Class<?> component = type.getComponentType(); result.add(shrinkTypeTo(object, component)); continue; } result.add(objects[i]); } } else if (isVarargs(types)) { final Class<?> clazz = getVarargComponentType(types); // vararg should be defaulted if (argsLength == typesLength - 1) { return adaptTo(ArrayUtils.add(objects, Array.newInstance(clazz, 0)), types); } // aggregate last arguments if (argsLength > typesLength) { final int varargIndex = typesLength - 1; final Object[] newParams = ArrayUtils.subarray(objects, 0, varargIndex); final Object[] varargRest = ArrayUtils.subarray(objects, varargIndex, argsLength); return adaptTo(ArrayUtils.add(newParams, varargRest), types); } } return result.toArray(); } /** * Tricky method to get object wrapper for primitive type. * * @param clazz class * @param <T> type * @return referenced wrapper class for all primitive types passe */ static <T> Class autoBox(final Class<T> clazz) { return Array.get(Array.newInstance(clazz, 1), 0).getClass(); } /** * Constructs array type of given type. * * @param clazz type * @param depth resulted array dimension * @param <T> type * @return array type of given type with passed dimension */ static <T> Class<?> toArrayType(final Class<T> clazz, final int depth) { Class result = clazz; for (int i = 0; i < depth; i++) { result = Array.newInstance(result, 0).getClass(); } return result; } /** * Checks if given signature is possible vararg-like signature. * * @param signature array of classes * @return {@code true} if last element is type of array */ private static boolean isVarargs(final Class[] signature) { final int length = signature.length; return length > 0 && signature[length - 1].isArray(); } /** * Make last argument argument of vararg signature "flat". * * @param signature array of classes * @return new signature */ static Class[] flattenVarargs(final Class[] signature) { if (isVarargs(signature)) { final Class[] result = signature.clone(); final int length = signature.length; result[length - 1] = signature[length - 1].getComponentType(); return result; } return signature; } /** * Returns method name in current thread stack. * * @param stackDepthShift position in stack to get deeper called method * @return method name */ private static String getMethodName(final int stackDepthShift) { final StackTraceElement[] currStack = Thread.currentThread().getStackTrace(); // Find caller function name return currStack[DEFAULT_INVOKE_DEPTH + stackDepthShift] .getMethodName(); } /** * Helper function for constructing exception. * * @param message exceptional message * @param type type affected * @param methodName method * @param signature method signature * @return constructed exception */ private static NoSuchMethodException abort(final String message, final Class type, final String methodName, final Class[] signature, final IModifierMatcher matcher) { return new NoSuchMethodException(String.format(message, type.getCanonicalName(), methodName, StringUtils.join(getClassNames(signature)), matcher)); } /** * Constructs exception for too much found method. * * @param type type affected * @param methodName method * @param signature method signature * @return constructed exception */ private static NoSuchMethodException tooMuch( final Class type, final String methodName, final Class[] signature, final IModifierMatcher matcher) { return abort("More than one method %s#%s found conforms signature [%s] and matcher %s", type, methodName, signature, matcher); } /** * Constructs exception for not found exception. * * @param type type affected * @param methodName method name * @param signature method signature * @return constructed exception */ private static NoSuchMethodException notFound( final Class type, final String methodName, final Class[] signature, final IModifierMatcher matcher) { return abort("No methods %s#%s found to conform signature [%s] and matcher %s", type, methodName, signature, matcher); } /** * Constructs {@link ClassCastException} for array casting error case. * * @param elem element of array caused cast exception * @param clazz type of array * @param cause original exception * @return {@link ClassCastException} instance */ private static ClassCastException arrayCastError(final Object elem, final Class clazz, final Throwable cause) { final ClassCastException ex = new ClassCastException(String.format( "Unexpected value %s (%s) for array of type %s" , elem , elem == null ? "unknown" : elem.getClass().getCanonicalName() , clazz.getCanonicalName())); ex.initCause(cause); throw ex; } /** * Constructs {@link ClassCastException} for array casting error case. * * @param src source array * @param clazz type of destination array * @return {@link ClassCastException} instance */ private static ClassCastException arrayCastError(final Object src, final Class clazz) { throw new ClassCastException(String.format( "Incompatible types found - source %s destination %s[]" , src.getClass().getCanonicalName() , clazz.getCanonicalName())); } /** * Constructs {@link NoSuchMethodException} in case when found method * can't be invoked. * * @param type type of object * @param methodName method name failed invocation * @param signature method signature * @param args arguments was passed to method * @param cause original exception * @return {@link NoSuchMethodException} instance */ private static NoSuchMethodException cantInvoke(final Class type, final String methodName, final Class[] signature, final Object[] args, final Throwable cause) { final NoSuchMethodException e = new NoSuchMethodException(String.format( "Unable to invoke method %s#%s(%s) with parameters [%s]" , type.getCanonicalName() , methodName , StringUtils.join(getClassNames(signature)) , StringUtils.join(args))); return (NoSuchMethodException) e.initCause(cause); } }
package liquid; import java.awt.geom.Rectangle2D; import java.lang.InterruptedException; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.JFrame; import lombok.extern.java.Log; import lombok.val; import org.jbox2d.collision.shapes.CircleShape; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.BodyType; import org.jbox2d.dynamics.FixtureDef; import org.jbox2d.dynamics.World; @Log public class Launcher { /* Solver */ private static final float DT = 1f / 30f; // seconds private static final int V_ITERATIONS = 8; private static final int P_ITERATIONS = 3; /* World */ private static final float WIDTH = 50f; private static final float HEIGHT = 70f; private static final float THICKNESS = 1f; private static final Vec2 GRAVITY = new Vec2(0, -20f); private static final Rectangle2D VIEW = new Rectangle2D.Float(WIDTH / -2, HEIGHT / -2, WIDTH, HEIGHT); private static final long FLIP_RATE = 5000L; /* Balls */ private static final int BALLS = 150; private static final float BALL_RADIUS = 0.75f; private static final float BALL_DENSITY = 1f; private static final float BALL_FRICTION = 0.1f; private static final float BALL_RESTITUTION = 0.4f; public static void main(String[] args) { /* Fix for poor OpenJDK performance. */ System.setProperty("sun.java2d.pmoffscreen", "false"); val world = new World(GRAVITY, false); val viewer = new Viewer(world, VIEW); JFrame frame = new JFrame("Fun Liquid"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(viewer); frame.setResizable(false); frame.pack(); frame.setVisible(true); /* Set up the containment box. */ buildContainer(world); /* Add a ball. */ Random rng = new Random(); for (int i = 0; i < BALLS; i++) { addBall(world, (rng.nextFloat() - 0.5f) * (WIDTH - BALL_RADIUS), (rng.nextFloat() - 0.5f) * (HEIGHT - BALL_RADIUS)); } val exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(new Runnable() { public void run() { world.step(DT, V_ITERATIONS, P_ITERATIONS); viewer.repaint(); if (System.currentTimeMillis() / FLIP_RATE % 2 == 0) { world.setGravity(GRAVITY.negate()); } else { world.setGravity(GRAVITY); } } }, 0L, (long) (DT * 1000.0), TimeUnit.MILLISECONDS); } private static void buildContainer(World world) { BodyDef def = new BodyDef(); PolygonShape box = new PolygonShape(); Body side; def.position = new Vec2(WIDTH / 2, 0); box.setAsBox(THICKNESS / 2, HEIGHT / 2); world.createBody(def).createFixture(box, 0f); def.position = new Vec2(-WIDTH / 2, 0); box.setAsBox(THICKNESS / 2, HEIGHT / 2); world.createBody(def).createFixture(box, 0f); def.position = new Vec2(0, HEIGHT / 2); box.setAsBox(WIDTH / 2, THICKNESS / 2); world.createBody(def).createFixture(box, 0f); def.position = new Vec2(0, -HEIGHT / 2); box.setAsBox(WIDTH / 2, THICKNESS / 2); world.createBody(def).createFixture(box, 0f); } private static void addBall(World world, float x, float y) { BodyDef def = new BodyDef(); def.position = new Vec2(x, y); def.type = BodyType.DYNAMIC; CircleShape circle = new CircleShape(); circle.m_radius = BALL_RADIUS; FixtureDef mass = new FixtureDef(); mass.shape = circle; mass.density = BALL_DENSITY; mass.friction = BALL_FRICTION; mass.restitution = BALL_RESTITUTION; world.createBody(def).createFixture(mass); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DragSource; import java.awt.dnd.DropTargetAdapter; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.Objects; import java.util.Optional; import java.util.TooManyListenersException; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.swing.*; import javax.swing.plaf.LayerUI; import javax.swing.plaf.basic.BasicButtonUI; import javax.swing.plaf.metal.MetalTabbedPaneUI; public final class MainPanel extends JPanel { private final DnDTabbedPane tabbedPane = new DnDTabbedPane(); private MainPanel(TransferHandler handler, LayerUI<DnDTabbedPane> layerUI) { super(new BorderLayout()); DnDTabbedPane sub = new DnDTabbedPane(); sub.addTab("Title aa", new JLabel("aaa")); sub.addTab("Title bb", new JScrollPane(new JTree())); sub.addTab("Title cc", new JScrollPane(new JTextArea("JTextArea cc"))); tabbedPane.addTab("JTree 00", new JScrollPane(new JTree())); tabbedPane.addTab("JLabel 01", new JLabel("Test")); tabbedPane.addTab("JTable 02", new JScrollPane(new JTable(10, 3))); tabbedPane.addTab("JTextArea 03", new JScrollPane(new JTextArea("JTextArea 03"))); tabbedPane.addTab("JLabel 04", new JLabel("<html>11111111<br>13412341234123446745")); tabbedPane.addTab("null 05", null); tabbedPane.addTab("JTabbedPane 06", sub); tabbedPane.addTab("Title 000000000000000007", new JScrollPane(new JTree())); // ButtonTabComponent IntStream.range(0, tabbedPane.getTabCount()).forEach(this::setTabComponent); DnDTabbedPane sub2 = new DnDTabbedPane(); sub2.addTab("Title aaa", new JLabel("aaa")); sub2.addTab("Title bbb", new JScrollPane(new JTree())); sub2.addTab("Title ccc", new JScrollPane(new JTextArea("JTextArea ccc"))); tabbedPane.setName("JTabbedPane#main"); sub.setName("JTabbedPane#sub1"); sub2.setName("JTabbedPane#sub2"); DropTargetListener listener = new TabDropTargetAdapter(); Stream.of(tabbedPane, sub, sub2).forEach(t -> { t.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); t.setTransferHandler(handler); try { t.getDropTarget().addDropTargetListener(listener); } catch (TooManyListenersException ex) { ex.printStackTrace(); UIManager.getLookAndFeel().provideErrorFeedback(t); } }); JPanel p = new JPanel(new GridLayout(2, 1)); p.add(new JLayer<>(tabbedPane, layerUI)); p.add(new JLayer<>(sub2, layerUI)); add(p); add(makeCheckBoxPanel(), BorderLayout.NORTH); setPreferredSize(new Dimension(320, 240)); } private void setTabComponent(int i) { tabbedPane.setTabComponentAt(i, new ButtonTabComponent(tabbedPane)); tabbedPane.setToolTipTextAt(i, "tooltip: " + i); } private Component makeCheckBoxPanel() { JCheckBox tc = new JCheckBox("Top", true); tc.addActionListener(e -> tabbedPane.setTabPlacement( tc.isSelected() ? SwingConstants.TOP : SwingConstants.RIGHT)); JCheckBox sc = new JCheckBox("SCROLL_TAB_LAYOUT", true); sc.addActionListener(e -> tabbedPane.setTabLayoutPolicy( sc.isSelected() ? JTabbedPane.SCROLL_TAB_LAYOUT : JTabbedPane.WRAP_TAB_LAYOUT)); JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT)); p.add(tc); p.add(sc); return p; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } TabTransferHandler handler = new TabTransferHandler(); JCheckBoxMenuItem check = new JCheckBoxMenuItem("Ghost image: Heavyweight"); check.addActionListener(e -> { boolean b = ((AbstractButton) e.getSource()).isSelected(); handler.setDragImageMode(b ? DragImageMode.HEAVYWEIGHT : DragImageMode.LIGHTWEIGHT); }); JMenu menu = new JMenu("Debug"); menu.add(check); JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); LayerUI<DnDTabbedPane> layerUI = new DropLocationLayerUI(); JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel(handler, layerUI)); frame.setJMenuBar(menuBar); frame.pack(); frame.setLocationRelativeTo(null); Point pt = frame.getLocation(); pt.translate(360, 60); JFrame sub = new JFrame("sub"); sub.getContentPane().add(new MainPanel(handler, layerUI)); sub.pack(); sub.setLocation(pt); frame.setVisible(true); sub.setVisible(true); } } class DnDTabbedPane extends JTabbedPane { private static final int SCROLL_SZ = 20; // Test private static final int BUTTON_SZ = 30; // XXX 30 is magic number of scroll button size private static final Rectangle RECT_BACKWARD = new Rectangle(); private static final Rectangle RECT_FORWARD = new Rectangle(); // private final DropMode dropMode = DropMode.INSERT; protected int dragTabIndex = -1; private transient DnDTabbedPane.DropLocation dropLocation; public static final class DropLocation extends TransferHandler.DropLocation { private final int index; // public boolean canDrop = true; // index >= 0; private DropLocation(Point p, int index) { super(p); this.index = index; } public int getIndex() { return index; } // @Override public String toString() { // return getClass().getName() // + "[dropPoint=" + getDropPoint() + "," // + "index=" + index + "," // + "insert=" + isInsert + "]"; } private void clickArrowButton(String actionKey) { JButton forwardButton = null; JButton backwardButton = null; for (Component c : getComponents()) { if (c instanceof JButton) { if (Objects.isNull(forwardButton)) { forwardButton = (JButton) c; } else if (Objects.isNull(backwardButton)) { backwardButton = (JButton) c; } } } JButton button = "scrollTabsForwardAction".equals(actionKey) ? forwardButton : backwardButton; Optional.ofNullable(button).filter(JButton::isEnabled).ifPresent(JButton::doClick); // // ArrayIndexOutOfBoundsException // Optional.ofNullable(getActionMap()) // .map(am -> am.get(actionKey)) // .filter(Action::isEnabled) // .ifPresent(a -> a.actionPerformed(new ActionEvent(this, ACTION_PERFORMED, null, 0, 0))); // // ActionMap map = getActionMap(); // // if (Objects.nonNull(map)) { // // Action action = map.get(actionKey); // // if (Objects.nonNull(action) && action.isEnabled()) { // // action.actionPerformed(new ActionEvent(this, ACTION_PERFORMED, null, 0, 0)); } public void autoScrollTest(Point pt) { Rectangle r = getTabAreaBounds(); // int tabPlacement = getTabPlacement(); // if (tabPlacement == TOP || tabPlacement == BOTTOM) { int arrowBoxSize = SCROLL_SZ + BUTTON_SZ; if (isTopBottomTabPlacement(getTabPlacement())) { RECT_BACKWARD.setBounds(r.x, r.y, SCROLL_SZ, r.height); RECT_FORWARD.setBounds(r.x + r.width - arrowBoxSize, r.y, arrowBoxSize, r.height); } else { // if (tabPlacement == LEFT || tabPlacement == RIGHT) { RECT_BACKWARD.setBounds(r.x, r.y, r.width, SCROLL_SZ); RECT_FORWARD.setBounds(r.x, r.y + r.height - arrowBoxSize, r.width, arrowBoxSize); } if (RECT_BACKWARD.contains(pt)) { clickArrowButton("scrollTabsBackwardAction"); } else if (RECT_FORWARD.contains(pt)) { clickArrowButton("scrollTabsForwardAction"); } } protected DnDTabbedPane() { super(); Handler h = new Handler(); addMouseListener(h); addMouseMotionListener(h); addPropertyChangeListener(h); } // @Override TransferHandler.DropLocation dropLocationForPoint(Point p) { public DnDTabbedPane.DropLocation tabDropLocationForPoint(Point p) { // assert dropMode == DropMode.INSERT : "Unexpected drop mode"; for (int i = 0; i < getTabCount(); i++) { if (getBoundsAt(i).contains(p)) { return new DnDTabbedPane.DropLocation(p, i); } } if (getTabAreaBounds().contains(p)) { return new DnDTabbedPane.DropLocation(p, getTabCount()); } return new DnDTabbedPane.DropLocation(p, -1); // switch (dropMode) { // case INSERT: // for (int i = 0; i < getTabCount(); i++) { // if (getBoundsAt(i).contains(p)) { // return new DnDTabbedPane.DropLocation(p, i); // if (getTabAreaBounds().contains(p)) { // return new DnDTabbedPane.DropLocation(p, getTabCount()); // break; // case USE_SELECTION: // case ON: // case ON_OR_INSERT: // default: // assert false : "Unexpected drop mode"; // break; // return new DnDTabbedPane.DropLocation(p, -1); } public final DnDTabbedPane.DropLocation getDropLocation() { return dropLocation; } // public Object updateTabDropLocation(DropLocation location, Object state, boolean forDrop) { public void updateTabDropLocation(DnDTabbedPane.DropLocation location, boolean forDrop) { DnDTabbedPane.DropLocation old = dropLocation; if (Objects.isNull(location) || !forDrop) { dropLocation = new DnDTabbedPane.DropLocation(new Point(), -1); } else { dropLocation = location; } firePropertyChange("dropLocation", old, dropLocation); // return state; } public void exportTab(int dragIndex, JTabbedPane target, int targetIndex) { System.out.println("exportTab"); final Component cmp = getComponentAt(dragIndex); final String title = getTitleAt(dragIndex); final Icon icon = getIconAt(dragIndex); final String toolTipText = getToolTipTextAt(dragIndex); final boolean isEnabled = isEnabledAt(dragIndex); Component tab = getTabComponentAt(dragIndex); if (tab instanceof ButtonTabComponent) { tab = new ButtonTabComponent(target); } remove(dragIndex); target.insertTab(title, icon, cmp, toolTipText, targetIndex); target.setEnabledAt(targetIndex, isEnabled); target.setTabComponentAt(targetIndex, tab); target.setSelectedIndex(targetIndex); if (tab instanceof JComponent) { ((JComponent) tab).scrollRectToVisible(tab.getBounds()); } } public void convertTab(int prev, int next) { System.out.println("convertTab"); // if (next < 0 || prev == next) { // return; final Component cmp = getComponentAt(prev); final Component tab = getTabComponentAt(prev); final String title = getTitleAt(prev); final Icon icon = getIconAt(prev); final String tip = getToolTipTextAt(prev); final boolean isEnabled = isEnabledAt(prev); int tgtIndex = prev > next ? next : next - 1; remove(prev); insertTab(title, icon, cmp, tip, tgtIndex); setEnabledAt(tgtIndex, isEnabled); // When you drag and drop a disabled tab, it finishes enabled and selected. // pointed out by dlorde if (isEnabled) { setSelectedIndex(tgtIndex); } // I have a component in all tabs (JLabel with an X to close the tab) // and when I move a tab the component disappear. // pointed out by Daniel Dario Morales Salas setTabComponentAt(tgtIndex, tab); } // public Rectangle getTabAreaBounds() { // Rectangle tabbedRect = getBounds(); // Component c = getSelectedComponent(); // return tabbedRect; // int xx = tabbedRect.x; // int yy = tabbedRect.y; // Rectangle compRect = getSelectedComponent().getBounds(); // int tabPlacement = getTabPlacement(); // if (tabPlacement == TOP) { // tabbedRect.height = tabbedRect.height - compRect.height; // } else if (tabPlacement == BOTTOM) { // tabbedRect.y = tabbedRect.y + compRect.y + compRect.height; // tabbedRect.height = tabbedRect.height - compRect.height; // } else if (tabPlacement == LEFT) { // tabbedRect.width = tabbedRect.width - compRect.width; // } else { // if (tabPlacement == RIGHT) { // tabbedRect.x = tabbedRect.x + compRect.x + compRect.width; // tabbedRect.width = tabbedRect.width - compRect.width; // tabbedRect.translate(-xx, -yy); // // tabbedRect.grow(2, 2); // return tabbedRect; public Rectangle getTabAreaBounds() { Rectangle tabbedRect = getBounds(); int xx = tabbedRect.x; int yy = tabbedRect.y; Rectangle compRect = Optional.ofNullable(getSelectedComponent()) .map(Component::getBounds) .orElseGet(Rectangle::new); int tabPlacement = getTabPlacement(); if (isTopBottomTabPlacement(tabPlacement)) { tabbedRect.height = tabbedRect.height - compRect.height; if (tabPlacement == BOTTOM) { tabbedRect.y += compRect.y + compRect.height; } } else { tabbedRect.width = tabbedRect.width - compRect.width; if (tabPlacement == RIGHT) { tabbedRect.x += compRect.x + compRect.width; } } tabbedRect.translate(-xx, -yy); // tabbedRect.grow(2, 2); return tabbedRect; } public static boolean isTopBottomTabPlacement(int tabPlacement) { return tabPlacement == SwingConstants.TOP || tabPlacement == SwingConstants.BOTTOM; } private class Handler extends MouseAdapter implements PropertyChangeListener { // , BeforeDrag private Point startPt; private final int dragThreshold = DragSource.getDragThreshold(); // Toolkit tk = Toolkit.getDefaultToolkit(); // Integer dragThreshold = (Integer) tk.getDesktopProperty("DnD.gestureMotionThreshold"); // PropertyChangeListener @Override public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if ("dropLocation".equals(propertyName)) { // System.out.println("propertyChange: dropLocation"); repaint(); } } // MouseListener @Override public void mousePressed(MouseEvent e) { DnDTabbedPane src = (DnDTabbedPane) e.getComponent(); boolean isOnlyOneTab = src.getTabCount() <= 1; if (isOnlyOneTab) { startPt = null; return; } Point tabPt = e.getPoint(); // e.getDragOrigin(); int idx = src.indexAtLocation(tabPt.x, tabPt.y); // disabled tab, null component problem. // pointed out by daryl. NullPointerException: i.e. addTab("Tab", null) boolean flag = idx < 0 || !src.isEnabledAt(idx) || Objects.isNull(src.getComponentAt(idx)); startPt = flag ? null : tabPt; } @Override public void mouseDragged(MouseEvent e) { Point tabPt = e.getPoint(); // e.getDragOrigin(); if (Objects.nonNull(startPt) && startPt.distance(tabPt) > dragThreshold) { DnDTabbedPane src = (DnDTabbedPane) e.getComponent(); TransferHandler th = src.getTransferHandler(); // When a tab runs rotation occurs, a tab that is not the target is dragged. // pointed out by Arjen int idx = src.indexAtLocation(tabPt.x, tabPt.y); int selIdx = src.getSelectedIndex(); boolean isRotateTabRuns = !(src.getUI() instanceof MetalTabbedPaneUI) && src.getTabLayoutPolicy() == JTabbedPane.WRAP_TAB_LAYOUT && idx != selIdx; dragTabIndex = isRotateTabRuns ? selIdx : idx; th.exportAsDrag(src, e, TransferHandler.MOVE); startPt = null; } } } } enum DragImageMode { HEAVYWEIGHT, LIGHTWEIGHT } class TabDropTargetAdapter extends DropTargetAdapter { private void clearDropLocationPaint(Component c) { if (c instanceof DnDTabbedPane) { DnDTabbedPane t = (DnDTabbedPane) c; t.updateTabDropLocation(null, false); t.setCursor(Cursor.getDefaultCursor()); } } @Override public void drop(DropTargetDropEvent e) { Component c = e.getDropTargetContext().getComponent(); System.out.println("DropTargetListener#drop: " + c.getName()); clearDropLocationPaint(c); } @Override public void dragExit(DropTargetEvent e) { Component c = e.getDropTargetContext().getComponent(); System.out.println("DropTargetListener#dragExit: " + c.getName()); clearDropLocationPaint(c); } @Override public void dragEnter(DropTargetDragEvent e) { Component c = e.getDropTargetContext().getComponent(); System.out.println("DropTargetListener#dragEnter: " + c.getName()); } // @Override public void dragOver(DropTargetDragEvent e) { // // System.out.println("dragOver"); // @Override public void dropActionChanged(DropTargetDragEvent e) { // System.out.println("dropActionChanged"); } class DnDTabData { public final DnDTabbedPane tabbedPane; protected DnDTabData(DnDTabbedPane tabbedPane) { this.tabbedPane = tabbedPane; } } class TabTransferHandler extends TransferHandler { protected final DataFlavor localObjectFlavor = new DataFlavor(DnDTabData.class, "DnDTabData"); protected DnDTabbedPane source; protected final JLabel label = new JLabel() { // Free the pixel: GHOST drag and drop, over multiple windows @Override public boolean contains(int x, int y) { return false; } }; protected final JWindow dialog = new JWindow(); protected DragImageMode mode = DragImageMode.LIGHTWEIGHT; public void setDragImageMode(DragImageMode dragMode) { this.mode = dragMode; setDragImage(null); } protected TabTransferHandler() { super(); System.out.println("TabTransferHandler"); // localObjectFlavor = new ActivationDataFlavor( // DnDTabbedPane.class, DataFlavor.javaJVMLocalObjectMimeType, "DnDTabbedPane"); dialog.add(label); // dialog.setAlwaysOnTop(true); // Web Start dialog.setOpacity(.5f); // AWTUtilities.setWindowOpacity(dialog, .5f); // JDK 1.6.0 DragSource.getDefaultDragSource().addDragSourceMotionListener(e -> { Point pt = e.getLocation(); pt.translate(5, 5); // offset dialog.setLocation(pt); }); } @Override protected Transferable createTransferable(JComponent c) { System.out.println("createTransferable"); if (c instanceof DnDTabbedPane) { source = (DnDTabbedPane) c; } // return new DataHandler(c, localObjectFlavor.getMimeType()); return new Transferable() { @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] {localObjectFlavor}; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return Objects.equals(localObjectFlavor, flavor); } @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (isDataFlavorSupported(flavor)) { return new DnDTabData(source); } else { throw new UnsupportedFlavorException(flavor); } } }; } @Override public boolean canImport(TransferHandler.TransferSupport support) { // System.out.println("canImport"); if (!support.isDrop() || !support.isDataFlavorSupported(localObjectFlavor)) { boolean b = support.isDataFlavorSupported(localObjectFlavor); System.out.println("canImport:" + support.isDrop() + " " + b); return false; } support.setDropAction(TransferHandler.MOVE); TransferHandler.DropLocation tdl = support.getDropLocation(); Point pt = tdl.getDropPoint(); DnDTabbedPane target = (DnDTabbedPane) support.getComponent(); target.autoScrollTest(pt); DnDTabbedPane.DropLocation dl = target.tabDropLocationForPoint(pt); int idx = dl.getIndex(); // if (!isWebStart()) { // // System.out.println("local"); // try { // source = (DnDTabbedPane) support.getTransferable().getTransferData(localObjectFlavor); // } catch (Exception ex) { // ex.printStackTrace(); boolean canDrop; boolean inArea = target.getTabAreaBounds().contains(pt) && idx >= 0; if (target.equals(source)) { // System.out.println("target == source"); canDrop = inArea && idx != target.dragTabIndex && idx != target.dragTabIndex + 1; } else { // System.out.format("tgt!=src%n tgt: %s%n src: %s", target.getName(), source.getName()); canDrop = Optional.ofNullable(source) .map(c -> !c.isAncestorOf(target)) .orElse(false) && inArea; } // [JDK-6700748] // Cursor flickering during D&D when using CellRendererPane with validation - Java Bug System target.setCursor(canDrop ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop); support.setShowDropLocation(canDrop); // dl.canDrop = canDrop; target.updateTabDropLocation(dl, canDrop); return canDrop; } // private static boolean isWebStart() { // try { // ServiceManager.lookup("javax.jnlp.BasicService"); // return true; // } catch (UnavailableServiceException ex) { // return false; private BufferedImage makeDragTabImage(DnDTabbedPane tabs) { Rectangle rect = tabs.getBoundsAt(tabs.dragTabIndex); int w = tabs.getWidth(); int h = tabs.getHeight(); BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics g = img.createGraphics(); tabs.paint(g); g.dispose(); if (rect.x < 0) { rect.translate(-rect.x, 0); } if (rect.y < 0) { rect.translate(0, -rect.y); } if (rect.x + rect.width > img.getWidth()) { rect.width = img.getWidth() - rect.x; } if (rect.y + rect.height > img.getHeight()) { rect.height = img.getHeight() - rect.y; } return img.getSubimage(rect.x, rect.y, rect.width, rect.height); } @Override public int getSourceActions(JComponent c) { System.out.println("getSourceActions"); if (c instanceof DnDTabbedPane) { DnDTabbedPane src = (DnDTabbedPane) c; if (src.dragTabIndex < 0) { return TransferHandler.NONE; } if (mode == DragImageMode.HEAVYWEIGHT) { label.setIcon(new ImageIcon(makeDragTabImage(src))); dialog.pack(); dialog.setVisible(true); } else { setDragImage(makeDragTabImage(src)); } return TransferHandler.MOVE; } return TransferHandler.NONE; } @Override public boolean importData(TransferHandler.TransferSupport support) { // System.out.println("importData"); DnDTabbedPane target = (DnDTabbedPane) support.getComponent(); DnDTabbedPane.DropLocation dl = target.getDropLocation(); try { DnDTabData data = (DnDTabData) support.getTransferable().getTransferData(localObjectFlavor); DnDTabbedPane src = data.tabbedPane; int index = dl.getIndex(); // boolean insert = dl.isInsert(); if (target.equals(src)) { src.convertTab(src.dragTabIndex, index); // getTargetTabIndex(e.getLocation())); } else { src.exportTab(src.dragTabIndex, target, index); } return true; } catch (UnsupportedFlavorException | IOException ex) { return false; } } @Override protected void exportDone(JComponent c, Transferable data, int action) { System.out.println("exportDone"); DnDTabbedPane src = (DnDTabbedPane) c; src.updateTabDropLocation(null, false); src.repaint(); if (mode == DragImageMode.HEAVYWEIGHT) { dialog.setVisible(false); } } } class DropLocationLayerUI extends LayerUI<DnDTabbedPane> { private static final int LINE_SZ = 3; private static final Rectangle LINE_RECT = new Rectangle(); @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); if (c instanceof JLayer) { JLayer<?> layer = (JLayer<?>) c; DnDTabbedPane tabbedPane = (DnDTabbedPane) layer.getView(); Optional.ofNullable(tabbedPane.getDropLocation()) .filter(loc -> loc.getIndex() >= 0) .ifPresent(loc -> { Graphics2D g2 = (Graphics2D) g.create(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f)); g2.setPaint(Color.RED); initLineRect(tabbedPane, loc); g2.fill(LINE_RECT); g2.dispose(); }); // DnDTabbedPane.DropLocation loc = tabbedPane.getDropLocation(); // if (Objects.nonNull(loc) && loc.getIndex() >= 0) { // Graphics2D g2 = (Graphics2D) g.create(); // g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f)); // g2.setPaint(Color.RED); // initLineRect(tabbedPane, loc); // g2.fill(LINE_RECT); // g2.dispose(); } } private static void initLineRect(JTabbedPane tabbedPane, DnDTabbedPane.DropLocation loc) { int index = loc.getIndex(); int a = Math.min(index, 1); // index == 0 ? 0 : 1; Rectangle r = tabbedPane.getBoundsAt(a * (index - 1)); if (DnDTabbedPane.isTopBottomTabPlacement(tabbedPane.getTabPlacement())) { LINE_RECT.setBounds(r.x - LINE_SZ / 2 + r.width * a, r.y, LINE_SZ, r.height); } else { LINE_RECT.setBounds(r.x, r.y - LINE_SZ / 2 + r.height * a, r.width, LINE_SZ); } } } class ButtonTabComponent extends JPanel { protected final JTabbedPane tabbedPane; protected ButtonTabComponent(JTabbedPane tabbedPane) { super(new FlowLayout(FlowLayout.LEFT, 0, 0)); this.tabbedPane = Objects.requireNonNull(tabbedPane, "TabbedPane is null"); setOpaque(false); JLabel label = new JLabel() { @Override public String getText() { int i = tabbedPane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { return tabbedPane.getTitleAt(i); } return null; } @Override public Icon getIcon() { int i = tabbedPane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { return tabbedPane.getIconAt(i); } return null; } }; add(label); label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); JButton button = new TabButton(); TabButtonHandler handler = new TabButtonHandler(); button.addActionListener(handler); button.addMouseListener(handler); add(button); setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); } private class TabButtonHandler extends MouseAdapter implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int i = tabbedPane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { tabbedPane.remove(i); } } @Override public void mouseEntered(MouseEvent e) { Component component = e.getComponent(); if (component instanceof AbstractButton) { AbstractButton button = (AbstractButton) component; button.setBorderPainted(true); } } @Override public void mouseExited(MouseEvent e) { Component component = e.getComponent(); if (component instanceof AbstractButton) { AbstractButton button = (AbstractButton) component; button.setBorderPainted(false); } } } } class TabButton extends JButton { private static final int SZ = 17; private static final int DELTA = 6; protected TabButton() { super(); setUI(new BasicButtonUI()); setToolTipText("close this tab"); setContentAreaFilled(false); setFocusable(false); setBorder(BorderFactory.createEtchedBorder()); setBorderPainted(false); setRolloverEnabled(true); } @Override public Dimension getPreferredSize() { return new Dimension(SZ, SZ); } @Override public void updateUI() { // we don't want to update UI for this button } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setStroke(new BasicStroke(2)); g2.setPaint(Color.BLACK); if (getModel().isRollover()) { g2.setPaint(Color.ORANGE); } if (getModel().isPressed()) { g2.setPaint(Color.BLUE); } g2.drawLine(DELTA, DELTA, getWidth() - DELTA - 1, getHeight() - DELTA - 1); g2.drawLine(getWidth() - DELTA - 1, DELTA, DELTA, getHeight() - DELTA - 1); g2.dispose(); } }
package org.smoothbuild.parse; import static com.google.common.base.Predicates.not; import static com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.Sets.filter; import static java.util.function.Function.identity; import static org.smoothbuild.parse.arg.ArgsStringHelper.argsToString; import static org.smoothbuild.parse.arg.ArgsStringHelper.assignedArgsToString; import static org.smoothbuild.util.Lists.filter; import static org.smoothbuild.util.Maybe.maybe; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import org.smoothbuild.lang.function.Functions; import org.smoothbuild.lang.function.base.Name; import org.smoothbuild.lang.function.base.ParameterInfo; import org.smoothbuild.lang.type.Type; import org.smoothbuild.lang.type.TypeSystem; import org.smoothbuild.lang.type.Types; import org.smoothbuild.parse.arg.ArgsStringHelper; import org.smoothbuild.parse.arg.ParametersPool; import org.smoothbuild.parse.arg.TypedParametersPool; import org.smoothbuild.parse.ast.ArgNode; import org.smoothbuild.parse.ast.Ast; import org.smoothbuild.parse.ast.CallNode; import org.smoothbuild.parse.ast.FuncNode; import org.smoothbuild.util.Maybe; import com.google.common.collect.ImmutableMultimap; public class AssignArgsToParams { private final TypeSystem typeSystem; @Inject public AssignArgsToParams(TypeSystem typeSystem) { this.typeSystem = typeSystem; } public Maybe<Ast> run(Functions functions, Ast ast) { List<ParseError> errors = new ArrayList<>(); new AstVisitor() { @Override public void visitCall(CallNode call) { super.visitCall(call); Set<ParameterInfo> parameters = functionParameters(call); if (parameters == null) { return; } if (assignNamedArguments(call, parameters)) { return; } if (assignNamelessArguments(call, parameters)) { return; } failWhenUnassignedRequiredParameterIsLeft(errors, call, parameters); } private Set<ParameterInfo> functionParameters(CallNode call) { Name name = call.name(); if (functions.contains(name)) { return new HashSet<>(functions.get(name).signature().parameters()); } if (ast.nameToFunctionMap().containsKey(name)) { FuncNode function = ast.nameToFunctionMap().get(name); if (function.has(List.class)) { return new HashSet<>(function.get(List.class)); } } return null; } private boolean assignNamedArguments(CallNode call, Set<ParameterInfo> parameters) { boolean failed = false; List<ArgNode> namedArgs = filter(call.args(), ArgNode::hasName); Map<Name, ParameterInfo> map = parameters .stream() .collect(toImmutableMap(p -> p.name(), identity())); for (ArgNode arg : namedArgs) { ParameterInfo parameter = map.get(arg.name()); Type paramType = parameter.type(); if (typeSystem.canConvert(arg.get(Type.class), paramType)) { arg.set(ParameterInfo.class, parameter); parameters.remove(parameter); } else { failed = true; errors.add(new ParseError(arg, "Type mismatch, cannot convert argument '" + arg.name() + "' of type '" + arg.get(Type.class).name() + "' to '" + paramType.name() + "'.")); } } return failed; } private boolean assignNamelessArguments(CallNode call, Set<ParameterInfo> parameters) { ParametersPool parametersPool = new ParametersPool(typeSystem, filter(parameters, not(ParameterInfo::isRequired)), filter(parameters, ParameterInfo::isRequired)); ImmutableMultimap<Type, ArgNode> namelessArgs = call .args() .stream() .filter(a -> !a.hasName()) .collect(toImmutableListMultimap(a -> a.get(Type.class), a -> a)); for (Type type : Types.allTypes()) { Collection<ArgNode> availableArguments = namelessArgs.get(type); int argsSize = availableArguments.size(); if (0 < argsSize) { TypedParametersPool availableTypedParams = parametersPool.assignableFrom(type); if (argsSize == 1 && availableTypedParams.hasCandidate()) { ArgNode onlyArgument = availableArguments.iterator().next(); ParameterInfo candidateParameter = availableTypedParams.candidate(); onlyArgument.set(ParameterInfo.class, candidateParameter); parametersPool.take(candidateParameter); parameters.remove(candidateParameter); } else { String message = ambiguousAssignmentErrorMessage( call, availableArguments, availableTypedParams); errors.add(new ParseError(call, message)); return true; } } } return false; } private void failWhenUnassignedRequiredParameterIsLeft(List<ParseError> errors, CallNode call, Set<ParameterInfo> parameters) { Set<ParameterInfo> unassignedRequiredParameters = filter(parameters, p -> p.isRequired()); if (!unassignedRequiredParameters.isEmpty()) { errors.add(new ParseError(call, missingRequiredArgsMessage(call, unassignedRequiredParameters))); return; } } private String missingRequiredArgsMessage(CallNode call, Set<ParameterInfo> missingRequiredParameters) { return "Not all parameters required by '" + call.name() + "' function has been specified.\n" + "Missing required parameters:\n" + ParameterInfo.iterableToString(missingRequiredParameters) + "All correct 'parameters <- arguments' assignments:\n" + ArgsStringHelper.assignedArgsToString(call); } private String ambiguousAssignmentErrorMessage(CallNode call, Collection<ArgNode> availableArgs, TypedParametersPool availableTypedParams) { String assignmentList = assignedArgsToString(call); if (availableTypedParams.isEmpty()) { return "Can't find parameter(s) of proper type in '" + call.name() + "' function for some nameless argument(s):\n" + "List of assignments that were successfully detected so far is following:\n" + assignmentList + "List of arguments for which no parameter could be found is following:\n" + argsToString(availableArgs); } else { return "Can't decide unambiguously to which parameters in '" + call.name() + "' function some nameless arguments should be assigned:\n" + "List of assignments that were successfully detected is following:\n" + assignmentList + "List of nameless arguments that caused problems:\n" + argsToString(availableArgs) + "List of unassigned parameters of desired type is following:\n" + availableTypedParams.toFormattedString(); } } }.visitAst(ast); return maybe(ast, errors); } }