answer
stringlengths
17
10.2M
package hex.gram; import hex.DataInfo; import hex.FrameTask; import jsr166y.CountedCompleter; import jsr166y.ForkJoinTask; import jsr166y.RecursiveAction; import sun.misc.Unsafe; import water.*; import water.nbhm.UtilUnsafe; import water.util.ArrayUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ForkJoinPool; public final class Gram extends Iced<Gram> { boolean _hasIntercept; public double[][] _xx; double[] _diag; public final int _diagN; final int _denseN; int _fullN; final static int MIN_TSKSZ=10000; public Gram() {_diagN = _denseN = _fullN = 0; _hasIntercept = false; } public Gram(DataInfo dinfo) {this(dinfo.fullN(), dinfo.largestCat(), dinfo._nums, dinfo._cats,true);} public Gram(int N, int diag, int dense, int sparse, boolean hasIntercept) { _hasIntercept = hasIntercept; _fullN = N + (_hasIntercept?1:0); _xx = new double[_fullN - diag][]; _diag = MemoryManager.malloc8d(_diagN = diag); _denseN = dense; for( int i = 0; i < (_fullN - _diagN); ++i ) _xx[i] = MemoryManager.malloc8d(diag + i + 1); } public Gram(Gram g){ _diagN = g._diagN; _denseN = g._denseN; _fullN = g._fullN; _hasIntercept = g._hasIntercept; if(g._diag != null)_diag = g._diag.clone(); if(g._xx != null){ _xx = g._xx.clone(); for(int i = 0; i < _xx.length; ++i) _xx[i] = _xx[i].clone(); } } public Gram(double[][] xx) { this(xx.length, 0, xx.length, 0, false); for( int i = 0; i < _xx.length; ++i ) { for( int j = 0; j < _xx[i].length; ++j ) { _xx[i][j] = xx[i][j]; } } } public void dropIntercept(){ if(!_hasIntercept) throw new IllegalArgumentException("Has no intercept"); double [][] xx = new double[_xx.length-1][]; for(int i = 0; i < xx.length; ++i) xx[i] = _xx[i]; _xx = xx; _hasIntercept = false; --_fullN; } public final int fullN(){return _fullN;} public double _diagAdded; public void addDiag(double [] ds) { int i = 0; for(;i < Math.min(_diagN,ds.length); ++i) _diag[i] += ds[i]; for(;i < ds.length; ++i) _xx[i-_diagN][i] += ds[i]; } public double get(int i, int j) { if(j > i) { int k = i; i = j; j = k; } if(i < _diagN) return(j == i)?_diag[i]:0; return _xx[i-_diagN][j]; } public void addDiag(double d) {addDiag(d,false);} public void addDiag(double d, boolean add2Intercept) { _diagAdded += d; for( int i = 0; i < _diag.length; ++i ) _diag[i] += d; int ii = (!_hasIntercept || add2Intercept)?0:1; for( int i = 0; i < _xx.length - ii; ++i ) _xx[i][_xx[i].length - 1] += d; } public double sparseness(){ double [][] xx = getXX(); double nzs = 0; for(int i = 0; i < xx.length; ++i) for(int j = 0; j < xx[i].length; ++j) if(xx[i][j] != 0) nzs += 1; return nzs/(xx.length*xx.length); } public double diagSum(){ double res = 0; if(_diag != null){ for(double d:_diag) res += d; } if(_xx != null){ for(double [] x:_xx)res += x[x.length-1]; } return res; } public double diagAvg(){ double res = 0; int n = 0; if(_diag != null){ n += _diag.length; for(double d:_diag) res += d; } if(_xx != null){ n += _xx.length; for(double [] x:_xx)res += x[x.length-1]; } return res/n; } public double diagMin(){ double res = Double.POSITIVE_INFINITY; if(_diag != null) for(double d:_diag) if(d < res)res = d; if(_xx != null) for(int i = 0; i < _xx.length-1; ++i){ final double [] x = _xx[i]; if(x[x.length-1] < res)res = x[x.length-1]; } return res; } private static double f_eps = 1e-8; private static final int MIN_PAR = 1000; private final void updateZij(int i, int j, double [][] Z, double [] gamma) { double [] Zi = Z[i]; double Zij = Zi[j]; for (int k = 0; k < j; ++k) Zij -= gamma[k] * Zi[k]; Zi[j] = Zij; } private final void updateZ(final double [] gamma, final double [][] Z, int j){ for (int i = j + 1; i < Z.length; ++i) // update xj to zj // updateZij(i,j,Z,gamma); } private final void updateUnitMatrix_ij(final double [] gamma, final double [][] unit_matrix, int i, int j) { double unit_ij = unit_matrix[i][j]; double[] unit_i = unit_matrix[i]; for (int k = i; k < j; ++k) unit_ij -= gamma[k] * unit_i[k]; unit_i[j] = unit_ij; } private final void updateUnitMatrix(final double [] gamma, int j, final double [][] unit_matrix) { for (int i = 0; i < unit_matrix.length; ++i) updateUnitMatrix_ij(gamma,unit_matrix,i,j); } /** * Compute Cholesky decompostion by computing partial QR decomposition (R == LU). * * The advantage of this method over the standard solve is that it can deal with Non-SPD matrices. * Gram matrix comes out as Non-SPD if we have co-linear columns. * QR decomposition can identify co-linear (redundant) columns and remove them from the dataset. * * QR computation: * QR is computed using Gram-Schmidt elimination, using Gram matrix instead of the underlying dataset. * * Gram-schmidt decomposition can be computed as follows: (from "The Eelements of Statistical Learning") * 1. set z0 = x0 = 1 (Intercept) * 2. for j = 1:p * for l = 1:j-1 * gamma_jl = dot(x_l,x_j)/dot(x_l,x_l) * zj = xj - sum(gamma_j[l]*x_l) * if(zj ~= 0) xj was redundant (co-linear) * Zjs are orthogonal projections of xk and form base of the X space. (dot(z_i,z_j) == 0 for i != j) * In the end, gammas contain (Scaled) R from the QR decomp which is == LU from cholesky decomp. * * * Note that all of these operations can be be computed from the Gram matrix only, as gram matrix contains * dot(x_i,x_j) for i = 1..N, j = 1..N * * We can obviously compute gamma_lk directly, instead of replacing xk with zk, we fix the gram matrix. * When doing that, we need to replace dot(xi,xk) with dot(xi,zk) for all i. * There are two cases, * 1) dot(xk,xk) -> dot(zk,zk) * dot(xk - sum(gamma_l*x_l,xk - sum(gamma_l*x_l) * = dot(xk,xk) - 2* sum(gamma_l*dot(x_i,x_k) + sum(gamma_l*sum(gamma_k*dot(x_l,x_k))) * (can be simplified using the fact that dot(zi,zj) == 0 for i != j * 2) dot(xi,xk) -> dot(xi,zk) for i != k * dot(xi, xj - sum(gamma_l*x_l)) * = dot(xi, xj) - dot(xi,sum(gamma_l*x_l)) * = dot(xi,xj) - sum(gamma_l*dot(xi,x_l)) (linear combination * * The algorithm then goes as follows: * for j = 1:n * for l = 1:j-1 * compute gamma_jl * update gram by replacing xk with zk = xk- sum(gamma_jl*s*xl); * * @param dropped_cols - empty list which will be filled with co-linear columns removed during computation * @return Cholesky - cholesky decomposition fo the gram */ public Cholesky qrCholesky(ArrayList<Integer> dropped_cols) { final double [][] Z = getXX(true); // put intercept first int icpt_id = Z.length-1; double d = Z[0][0]; Z[0][0] = Z[icpt_id][icpt_id]; Z[icpt_id][icpt_id] = d; for(int i = 1; i < Z.length-1; ++i) { d = Z[i][0]; Z[i][0] = Z[icpt_id][i]; Z[icpt_id][i] = d; } // todo add diagonal hack to save on the largest categorical variable final double [][] R = new double[Z.length][]; final double [] ZdiagInv = new double[Z.length]; for(int i = 0; i < Z.length; ++i) ZdiagInv[i] = 1.0/Z[i][i]; for(int j = 0; j < Z.length; ++j) { final double [] gamma = R[j] = new double[j+1]; for(int l = 0; l <= j; ++l) // compute gamma_l_j gamma[l] = Z[j][l]*ZdiagInv[l]; double zjj = Z[j][j]; for(int k = 0; k < j; ++k) // only need the diagonal, the rest is 0 (dot product of orthogonal vectors) zjj += gamma[k] * (gamma[k] * Z[k][k] - 2*Z[j][k]); ZdiagInv[j] = 1./zjj; if(-f_eps < zjj && zjj < f_eps) { // co-linear column, drop it! zjj = 0; dropped_cols.add(j); ZdiagInv[j] = 0; } Z[j][j] = zjj; int jchunk = Math.max(1,MIN_PAR/(Z.length-j)); int nchunks = (Z.length - j - 1)/jchunk; nchunks = Math.min(nchunks,H2O.NUMCPUS); if(nchunks <= 1) { // single trheaded update updateZ(gamma,Z,j); } else { // multi-threaded update final int fjchunk = (Z.length - 1 - j)/nchunks; int rem = Z.length - 1 - j - fjchunk*nchunks; for(int i = Z.length-rem; i < Z.length; ++i) updateZij(i,j,Z,gamma); RecursiveAction[] ras = new RecursiveAction[nchunks]; final int fj = j; int k = 0; for (int i = j + 1; i < Z.length-rem; i += fjchunk) { // update xj to zj // final int fi = i; ras[k++] = new RecursiveAction() { @Override protected final void compute() { int max_i = Math.min(fi+fjchunk,Z.length); for(int i = fi; i < max_i; ++i) updateZij(i,fj,Z,gamma); } }; } ForkJoinTask.invokeAll(ras); } } // update the R - we computed Rt/sqrt(diag(Z)) which we can directly use to solve the problem if(R.length < 500) for(int i = 0; i < R.length; ++i) for (int j = 0; j <= i; ++j) R[i][j] *= Math.sqrt(Z[j][j]); else { RecursiveAction [] ras = new RecursiveAction[R.length]; for(int i = 0; i < ras.length; ++i) { final int fi = i; final double [] Rrow = R[i]; ras[i] = new RecursiveAction() { @Override protected void compute() { for (int j = 0; j <= fi; ++j) Rrow[j] *= Math.sqrt(Z[j][j]); } }; } ForkJoinTask.invokeAll(ras); } // drop the ignored cols if(dropped_cols.isEmpty()) return new Cholesky(R,new double[0], true); double [][] Rnew = new double[R.length-dropped_cols.size()][]; for(int i = 0; i < Rnew.length; ++i) Rnew[i] = new double[i+1]; int j = 0; for(int i = 0; i < R.length; ++i) { if(Z[i][i] == 0) continue; int k = 0; for(int l = 0; l <= i; ++l) { if(k < dropped_cols.size() && l == dropped_cols.get(k)) { ++k; continue; } Rnew[j][l - k] = R[i][l]; } ++j; } if((dropped_cols.get(dropped_cols.size()-1)) == ZdiagInv.length-1){ dropped_cols.remove(dropped_cols.size()-1); dropped_cols.add(0,0); // first and last columns are switched so that the intercept is the first drugin the QR decomp } return new Cholesky(Rnew,new double[0], true); } public String toString(){ if(_fullN >= 1000){ if(_denseN >= 1000) return "Gram(" + _fullN + ")"; else return "diag:\n" + Arrays.toString(_diag) + "\ndense:\n" + ArrayUtils.pprint(getDenseXX()); } else return ArrayUtils.pprint(getXX()); } static public class InPlaceCholesky { final double _xx[][]; // Lower triangle of the symmetric matrix. private boolean _isSPD; private InPlaceCholesky(double xx[][], boolean isspd) { _xx = xx; _isSPD = isspd; } static private class BlockTask extends RecursiveAction { final double[][] _xx; final int _i0, _i1, _j0, _j1; public BlockTask(double xx[][], int ifr, int ito, int jfr, int jto) { _xx = xx; _i0 = ifr; _i1 = ito; _j0 = jfr; _j1 = jto; } @Override public void compute() { for (int i=_i0; i < _i1; i++) { double rowi[] = _xx[i]; for (int k=_j0; k < _j1; k++) { double rowk[] = _xx[k]; double s = 0.0; for (int jj = 0; jj < k; jj++) s += rowk[jj]*rowi[jj]; rowi[k] = (rowi[k] - s) / rowk[k]; } } } } public static InPlaceCholesky decompose_2(double xx[][], int STEP, int P) { boolean isspd = true; final int N = xx.length; P = Math.max(1, P); for (int j=0; j < N; j+=STEP) { // update the upper left triangle. final int tjR = Math.min(j+STEP, N); for (int i=j; i < tjR; i++) { double rowi[] = xx[i]; double d = 0.0; for (int k=j; k < i; k++) { double rowk[] = xx[k]; double s = 0.0; for (int jj = 0; jj < k; jj++) s += rowk[jj]*rowi[jj]; rowi[k] = s = (rowi[k] - s) / rowk[k]; d += s*s; } for (int jj = 0; jj < j; jj++) { double s = rowi[jj]; d += s*s; } d = rowi[i] - d; isspd = isspd && (d > 0.0); rowi[i] = Math.sqrt(Math.max(0.0, d)); } if (tjR == N) break; // update the lower strip int i = tjR; Futures fs = new Futures(); int rpb = 0; // rows per block int p = P; // concurrency while ( tjR*(rpb=(N - tjR)/p)<Gram.MIN_TSKSZ && p>1) --p; while (p fs.add(new BlockTask(xx,i,i+rpb,j,tjR).fork()); i += rpb; } new BlockTask(xx,i,N,j,tjR).compute(); fs.blockForPending(); } return new InPlaceCholesky(xx, isspd); } public double[][] getL() { return _xx; } public boolean isSPD() { return _isSPD; } } public Cholesky cholesky(Cholesky chol) { return cholesky(chol,true,""); } /** * Compute the Cholesky decomposition. * * In case our gram starts with diagonal submatrix of dimension N, we exploit this fact to reduce the complexity of the problem. * We use the standard decomposition of the Cholesky factorization into submatrices. * * We split the Gram into 3 regions (4 but we only consider lower diagonal, sparse means diagonal region in this context): * diagonal * diagonal*dense * dense*dense * Then we can solve the Cholesky in 3 steps: * 1. We solve the diagonal part right away (just do the sqrt of the elements). * 2. The diagonal*dense part is simply divided by the sqrt of diagonal. * 3. Compute Cholesky of dense*dense - outer product of Cholesky of diagonal*dense computed in previous step * * @param chol * @return the Cholesky decomposition */ public Cholesky cholesky(Cholesky chol, boolean parallelize,String id) { long start = System.currentTimeMillis(); if( chol == null ) { double[][] xx = _xx.clone(); for( int i = 0; i < xx.length; ++i ) xx[i] = xx[i].clone(); chol = new Cholesky(xx, _diag.clone()); } final Cholesky fchol = chol; final int sparseN = _diag.length; final int denseN = _fullN - sparseN; // compute the cholesky of the diagonal and diagonal*dense parts if( _diag != null ) for( int i = 0; i < sparseN; ++i ) { double d = 1.0 / (chol._diag[i] = Math.sqrt(_diag[i])); for( int j = 0; j < denseN; ++j ) chol._xx[j][i] = d*_xx[j][i]; } ForkJoinTask [] fjts = new ForkJoinTask[denseN]; // compute the outer product of diagonal*dense //Log.info("SPARSEN = " + sparseN + " DENSEN = " + denseN); final int[][] nz = new int[denseN][]; for( int i = 0; i < denseN; ++i ) { final int fi = i; fjts[i] = new RecursiveAction() { @Override protected void compute() { int[] tmp = new int[sparseN]; double[] rowi = fchol._xx[fi]; int n = 0; for( int k = 0; k < sparseN; ++k ) if (rowi[k] != .0) tmp[n++] = k; nz[fi] = Arrays.copyOf(tmp, n); } }; } ForkJoinTask.invokeAll(fjts); for( int i = 0; i < denseN; ++i ) { final int fi = i; fjts[i] = new RecursiveAction() { @Override protected void compute() { double[] rowi = fchol._xx[fi]; int[] nzi = nz[fi]; for( int j = 0; j <= fi; ++j ) { double[] rowj = fchol._xx[j]; int[] nzj = nz[j]; double s = 0; for (int t=0,z=0; t < nzi.length && z < nzj.length; ) { int k1 = nzi[t]; int k2 = nzj[z]; if (k1 < k2) { t++; continue; } else if (k1 > k2) { z++; continue; } else { s += rowi[k1] * rowj[k1]; t++; z++; } } rowi[j + sparseN] = _xx[fi][j + sparseN] - s; } } }; } ForkJoinTask.invokeAll(fjts); // compute the cholesky of dense*dense-outer_product(diagonal*dense) double[][] arr = new double[denseN][]; for( int i = 0; i < arr.length; ++i ) arr[i] = Arrays.copyOfRange(fchol._xx[i], sparseN, sparseN + denseN); int p = Runtime.getRuntime().availableProcessors(); InPlaceCholesky d = InPlaceCholesky.decompose_2(arr, 10, p); fchol.setSPD(d.isSPD()); arr = d.getL(); for( int i = 0; i < arr.length; ++i ) System.arraycopy(arr[i], 0, fchol._xx[i], sparseN, i + 1); return chol; } public double[][] getXX(){return getXX(false);} public double[][] getXX(boolean lowerDiag) { final int N = _fullN; double[][] xx = new double[N][]; for( int i = 0; i < N; ++i ) xx[i] = MemoryManager.malloc8d(lowerDiag?i+1:N); for( int i = 0; i < _diag.length; ++i ) xx[i][i] = _diag[i]; for( int i = 0; i < _xx.length; ++i ) { for( int j = 0; j < _xx[i].length; ++j ) { xx[i + _diag.length][j] = _xx[i][j]; if(!lowerDiag) xx[j][i + _diag.length] = _xx[i][j]; } } return xx; } public double[][] getDenseXX() { final int N = _denseN; double[][] xx = new double[N][]; for( int i = 0; i < N; ++i ) xx[i] = MemoryManager.malloc8d(N); for( int i = 0; i < _xx.length; ++i ) { for( int j = _diagN; j < _xx[i].length; ++j ) { xx[i][j-_diagN] = _xx[i][j]; xx[j-_diagN][i] = _xx[i][j]; } } return xx; } public void add(Gram grm) { ArrayUtils.add(_xx,grm._xx); ArrayUtils.add(_diag,grm._diag); } public final boolean hasNaNsOrInfs() { for( int i = 0; i < _xx.length; ++i ) for( int j = 0; j < _xx[i].length; ++j ) if( Double.isInfinite(_xx[i][j]) || Double.isNaN(_xx[i][j]) ) return true; for( double d : _diag ) if( Double.isInfinite(d) || Double.isNaN(d) ) return true; return false; } public static final class Cholesky { public final double[][] _xx; protected final double[] _diag; private boolean _isSPD; private final boolean _icptFirst; public Cholesky(double[][] xx, double[] diag) { _xx = xx; _diag = diag; _icptFirst = false; } public Cholesky(double[][] xx, double[] diag, boolean icptFirst) { _xx = xx; _diag = diag; _icptFirst = icptFirst; _isSPD = true; } public double [] getInvDiag(){ final double [] res = new double[_xx.length + _diag.length]; RecursiveAction [] ras = new RecursiveAction[res.length]; for(int i = 0; i < ras.length; ++i) { final int fi = i; ras[i] = new RecursiveAction() { @Override protected void compute() { double [] tmp = new double[res.length]; tmp[fi] = 1; solve(tmp); res[fi] = tmp[fi]; } }; } ForkJoinTask.invokeAll(ras); return res; } public double[][] getXX() { final int N = _xx.length+_diag.length; double[][] xx = new double[N][]; for( int i = 0; i < N; ++i ) xx[i] = MemoryManager.malloc8d(N); for( int i = 0; i < _diag.length; ++i ) xx[i][i] = _diag[i]; for( int i = 0; i < _xx.length; ++i ) { for( int j = 0; j < _xx[i].length; ++j ) { xx[i + _diag.length][j] = _xx[i][j]; xx[j][i + _diag.length] = _xx[i][j]; } } return xx; } public double[][] getL() { final int N = _xx.length+_diag.length; double[][] xx = new double[N][]; for( int i = 0; i < N; ++i ) xx[i] = MemoryManager.malloc8d(N); for( int i = 0; i < _diag.length; ++i ) xx[i][i] = _diag[i]; for( int i = 0; i < _xx.length; ++i ) { for( int j = 0; j < _xx[i].length; ++j ) { xx[i + _diag.length][j] = _xx[i][j]; } } return xx; } public double sparseness(){ double [][] xx = getXX(); double nzs = 0; for(int i = 0; i < xx.length; ++i) for(int j = 0; j < xx[i].length; ++j) if(xx[i][j] != 0) nzs += 1; return nzs/(xx.length*xx.length); } @Override public String toString() { return ""; } public static abstract class DelayedTask extends RecursiveAction { private static final Unsafe U; private static final long PENDING; private int _pending; static { try { U = UtilUnsafe.getUnsafe();; PENDING = U.objectFieldOffset (CountedCompleter.class.getDeclaredField("pending")); } catch (Exception e) { throw new Error(e); } } public DelayedTask(int pending){ _pending = pending;} public final void tryFork(){ int c = _pending; while(c != 0 && !U.compareAndSwapInt(this,PENDING,c,c-1)) c = _pending; // System.out.println(" tryFork of " + this + ". c = " + c); if(c == 0) fork(); } } private final class BackSolver2 extends CountedCompleter { // private final AtomicIntegerArray _rowPtrs; // private final int [] _rowPtrs; final BackSolver2 [] _tasks; volatile private int _endPtr; final double [] _y; final int _row; private final int _blocksz; private final int _rblocksz; private final CountedCompleter _cmp; public BackSolver2(CountedCompleter cmp, double [] y, int blocksz, int rBlock){ this(cmp,y.length-1,y,new BackSolver2[(y.length-_diag.length)/rBlock],blocksz,rBlock,(y.length-_diag.length)/rBlock-1); _cmp.addToPendingCount(_tasks.length-1); int row = _diag.length + (y.length - _diag.length) % _rblocksz + _rblocksz - 1; for(int i = 0; i < _tasks.length-1; ++i, row += _rblocksz) _tasks[i] = new BackSolver2(_cmp, row, _y, _tasks, _blocksz,rBlock,i); assert row == y.length-1; _tasks[_tasks.length-1] = this; } public BackSolver2(CountedCompleter cmp,int row,double [] y, BackSolver2 [] tsks, int iBlock, int rBlock, int tid){ super(cmp); _cmp = cmp; _row = row; _y = y; _tasks = tsks; _blocksz = iBlock; _rblocksz = rBlock; _endPtr = _row+1; _tid =tid; } final int _tid; @Override public void compute() { int rEnd = _row - _rblocksz; if(rEnd < _diag.length + _rblocksz) rEnd = _diag.length; int bStart = Math.max(0,rEnd - rEnd % _blocksz); assert _tid == _tasks.length-1 || bStart >= _tasks[_tid+1]._endPtr; for(int i = 0; i < _rblocksz; ++i) { final double [] x = _xx[_row-_diag.length-i]; final double yr = _y[_row - i] /= x[_row - i]; for(int j = bStart; j < (_row-i); ++j) _y[j] -= yr * x[j]; } boolean first = true; for(; bStart >= _blocksz; bStart -= _blocksz){ final int bEnd = bStart - _blocksz; if(_tid != _tasks.length-1) while(_tasks[_tid+1]._endPtr > bEnd) Thread.yield(); // synchronization :/ for(int r = _row; r >= rEnd; --r){ final double [] x = _xx[r-_diag.length]; final double yr = _y[r]; for(int i = bStart-1; i >= bEnd; --i) _y[i] -= _y[r] * x[i]; } _endPtr = bEnd; if (first && _tid > 0 && (bEnd <= _row - 2*_rblocksz - _blocksz)) { // first go -> launch next row _tasks[_tid - 1].fork(); first = false; } } assert bStart == 0; tryComplete(); } @Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter cc){ return true; } } private final class BackSolver extends CountedCompleter { final int _diagLen; final double[] _y; final DelayedTask [][] _tasks; BackSolver(double [] y, int kBlocksz, int iBlocksz){ final int n = y.length; _y = y; int kRem = _xx.length % kBlocksz; int M = _xx.length/kBlocksz + (kRem == 0?0:1);; int N = n / iBlocksz; // iRem is added to the diagonal block _tasks = new DelayedTask[M][]; int rsz = N; for(int i = M-1; i >= 0; --i) _tasks[i] = new DelayedTask[rsz _diagLen = _diag == null?0:_diag.length; // Solve L'*X = Y; int kFrom = _diagLen + _xx.length-1; int kTo = _diagLen + _xx.length; int iFrom = n; int pending = 0; int rem = 0; if(kRem > 0){ rem = 1; int k = _tasks.length-1; int i = _tasks[k].length-1; iFrom = i*iBlocksz; kTo = kFrom - kRem + 1; _tasks[k][i] = new BackSolveDiagTsk(0,k,kFrom,kTo,iFrom); for(int j = 0; j < _tasks[k].length-1; ++j) _tasks[k][j] = new BackSolveInnerTsk(pending,M-1,j,kFrom,kTo, j*iBlocksz,(j+1)*iBlocksz); pending = 1; } for( int k = _tasks.length-1-rem; k >= 0; --k) { kFrom = kTo -1; kTo -= kBlocksz; int ii = _tasks[k].length-1; iFrom = ii*iBlocksz; _tasks[k][_tasks[k].length-1] = new BackSolveDiagTsk(0,k,kFrom,kTo,iFrom); for(int i = 0; i < _tasks[k].length-1; ++i) _tasks[k][i] = new BackSolveInnerTsk(pending,k,i,i+iBlocksz,kFrom,kTo, i*iBlocksz); pending = 1; } addToPendingCount(_tasks[0].length-1); } @Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter caller){ try { for (ForkJoinTask[] ary : _tasks) for (ForkJoinTask fjt : ary) fjt.cancel(true); } catch(Throwable t){} return true; } @Override public void compute() { _tasks[_tasks.length-1][_tasks[_tasks.length-1].length-1].fork(); } final class BackSolveDiagTsk extends DelayedTask { final int _kfrom, _kto,_ifrom, _row; public BackSolveDiagTsk(int pending, int row, int kfrom, int kto, int ifrom) { super(pending); _row = row; _kfrom = kfrom; _kto = kto; _ifrom = ifrom; } @Override protected void compute() { if(BackSolver.this.isCompletedAbnormally()) return; try { // same as single threaded solve, // except we do only a (lower diagonal) square block here // and we (try to) launch dependents in the end for (int k = _kfrom; k >= _kto; --k) { _y[k] /= _xx[k - _diagLen][k]; for (int i = _ifrom; i < k; ++i) _y[i] -= _y[k] * _xx[k - _diagLen][i]; } if (_row == 0) tryComplete(); // the last row of task completes the parent // try to fork the whole row to the left // (tryFork will fork task t iff all of it's dependencies are done) for (int i = 0; i < _tasks[_row].length - 1; ++i) _tasks[_row][i].tryFork(); } catch(Throwable t){ t.printStackTrace(); BackSolver.this.completeExceptionally(t); } } @Override public String toString(){ return ("DiagTsk, ifrom = " + _ifrom + ", kto = " + _kto); } } final class BackSolveInnerTsk extends DelayedTask { final int _kfrom, _kto, _ifrom, _ito, _row, _col; public BackSolveInnerTsk(int pending,int row, int col, int kfrom, int kto, int ifrom, int ito) { super(pending); _kfrom = kfrom; _kto = kto; _ifrom = ifrom; _ito = ito; _col = col; _row = row; } @Override public void compute() { if(BackSolver.this.isCompletedAbnormally()) return; try { // same as single threaded solve, // except we do only a (lower diagonal) square block here // and we (try to) launch dependents in the end for (int k = _kfrom; k >= _kto; --k) { final double yk = _y[k]; final double [] x = _xx[k-_diagLen]; for (int i = _ifrom; i < _ito; ++i) _y[i] -= yk * x[i]; } if (_row == 0) tryComplete(); // try to fork task directly above else _tasks[_row - 1][_col].tryFork(); } catch(Throwable t){ t.printStackTrace(); BackSolver.this.completeExceptionally(t); } } @Override public String toString(){ return ("InnerTsk, ifrom = " + _ifrom + ", kto = " + _kto); } } } public ParSolver parSolver(CountedCompleter cmp, double[] y, int iBlock, int rBlock){ return new ParSolver(cmp,y, iBlock, rBlock);} public final class ParSolver extends CountedCompleter { final double [] y; final int _iBlock; final int _rBlock; private ParSolver(CountedCompleter cmp, double [] y, int iBlock, int rBlock){ super(cmp); this.y = y; _iBlock = iBlock; _rBlock = rBlock; } @Override public void compute() { // long t = System.currentTimeMillis(); if( !isSPD() ) throw new NonSPDMatrixException(); assert _xx.length + _diag.length == y.length:"" + _xx.length + " + " + _diag.length + " != " + y.length; // diagonal for( int k = 0; k < _diag.length; ++k ) y[k] /= _diag[k]; // rest final int n = y.length; // Solve L*Y = B; for( int k = _diag.length; k < n; ++k ) { double d = 0; for( int i = 0; i < k; i++ ) d += y[i] * _xx[k - _diag.length][i]; y[k] = (y[k]-d)/_xx[k - _diag.length][k]; } // System.out.println("st part done in " + (System.currentTimeMillis()-t)); // do the dense bit in parallel if(y.length >= 0) { addToPendingCount(1); new BackSolver2(this, y, _iBlock,_rBlock).fork(); } else { // too small, solve single threaded // Solve L'*X = Y; for( int k = n - 1; k >= _diag.length; --k ) { y[k] /= _xx[k - _diag.length][k]; for( int i = 0; i < k; ++i ) y[i] -= y[k] * _xx[k - _diag.length][i]; } } tryComplete(); } @Override public void onCompletion(CountedCompleter caller){ // diagonal for( int k = _diag.length - 1; k >= 0; --k ) y[k] /= _diag[k]; } } /** * Find solution to A*x = y. * * Result is stored in the y input vector. May throw NonSPDMatrix exception in case Gram is not * positive definite. * * @param y */ public final void solve(double[] y) { if( !isSPD() ) throw new NonSPDMatrixException(); if(_icptFirst) { double d = y[y.length-1]; y[y.length-1] = y[0]; y[0] = d; } // diagonal for( int k = 0; k < _diag.length; ++k ) y[k] /= _diag[k]; // rest final int n = _xx[_xx.length-1].length; // Solve L*Y = B; for( int k = _diag.length; k < n; ++k ) { double d = 0; for( int i = 0; i < k; i++ ) d += y[i] * _xx[k - _diag.length][i]; y[k] = (y[k]-d)/_xx[k - _diag.length][k]; } // Solve L'*X = Y; for( int k = n - 1; k >= _diag.length; --k ) { y[k] /= _xx[k - _diag.length][k]; for( int i = 0; i < k; ++i ) y[i] -= y[k] * _xx[k - _diag.length][i]; } // diagonal for( int k = _diag.length - 1; k >= 0; --k ) y[k] /= _diag[k]; if(_icptFirst) { double d = y[y.length-1]; y[y.length-1] = y[0]; y[0] = d; } } public final boolean isSPD() {return _isSPD;} public final void setSPD(boolean b) {_isSPD = b;} } public final void addRowSparse(DataInfo.Row r, double w) { final int intercept = _hasIntercept?1:0; final int denseRowStart = _fullN - _denseN - _diagN - intercept; // we keep dense numbers at the right bottom of the matrix, -1 is for intercept final int denseColStart = _fullN - _denseN - intercept; assert _denseN + denseRowStart == _xx.length-intercept; final double [] interceptRow = _hasIntercept?_xx[_xx.length-1]:null; // nums for(int i = 0; i < r.nNums; ++i) { int cid = r.numIds[i]; final double [] mrow = _xx[cid - _diagN]; final double d = w*r.numVals[i]; for(int j = 0; j <= i; ++j) mrow[r.numIds[j]] += d*r.numVals[j]; if(_hasIntercept) interceptRow[cid] += d; // intercept*x[i] // nums * cats for(int j = 0; j < r.nBins; ++j) mrow[r.binIds[j]] += d; } if(_hasIntercept){ // intercept*intercept interceptRow[interceptRow.length-1] += w; // intercept X cat for(int j = 0; j < r.nBins; ++j) interceptRow[r.binIds[j]] += w; } final boolean hasDiag = (_diagN > 0 && r.nBins > 0 && r.binIds[0] < _diagN); // cat X cat for(int i = hasDiag?1:0; i < r.nBins; ++i){ final double [] mrow = _xx[r.binIds[i] - _diagN]; for(int j = 0; j <= i; ++j) mrow[r.binIds[j]] += w; } // DIAG if(hasDiag && r.nBins > 0) _diag[r.binIds[0]] += w; } public final void addRow(DataInfo.Row row, double w) { if(row.numIds == null) addRowDense(row,w); else addRowSparse(row, w); } public final void addRowDense(DataInfo.Row row, double w) { final int intercept = _hasIntercept?1:0; final int denseRowStart = _fullN - _denseN - _diagN - intercept; // we keep dense numbers at the right bottom of the matrix, -1 is for intercept final int denseColStart = _fullN - _denseN - intercept; assert _denseN + denseRowStart == _xx.length-intercept; final double [] interceptRow = _hasIntercept?_xx[_denseN + denseRowStart]:null; // nums for(int i = 0; i < _denseN; ++i) if(row.numVals[i] != 0) { final double [] mrow = _xx[i+denseRowStart]; final double d = w * row.numVals[i]; for(int j = 0; j <= i; ++j) if(row.numVals[j] != 0) mrow[j+denseColStart] += d* row.numVals[j]; if(_hasIntercept) interceptRow[i+denseColStart] += d; // intercept*x[i] // nums * cats for(int j = 0; j < row.nBins; ++j) mrow[row.binIds[j]] += d; } if(_hasIntercept){ // intercept*intercept interceptRow[_denseN+denseColStart] += w; // intercept X cat for(int j = 0; j < row.nBins; ++j) interceptRow[row.binIds[j]] += w; } final boolean hasDiag = (_diagN > 0 && row.nBins > 0 && row.binIds[0] < _diagN); // cat X cat for(int i = hasDiag?1:0; i < row.nBins; ++i){ final double [] mrow = _xx[row.binIds[i] - _diagN]; for(int j = 0; j <= i; ++j) mrow[row.binIds[j]] += w; } // DIAG if(hasDiag) _diag[row.binIds[0]] += w; } public void mul(double x){ if(_diag != null)for(int i = 0; i < _diag.length; ++i) _diag[i] *= x; for(int i = 0; i < _xx.length; ++i) for(int j = 0; j < _xx[i].length; ++j) _xx[i][j] *= x; } public double [] mul(double [] x){ double [] res = MemoryManager.malloc8d(x.length); mul(x,res); return res; } private double [][] XX = null; public void mul(double [] x, double [] res){ Arrays.fill(res,0); if(XX == null) XX = getXX(false); for(int i = 0; i < XX.length; ++i){ double d = 0; double [] xi = XX[i]; for(int j = 0; j < XX.length; ++j) d += xi[j]*x[j]; res[i] = d; } } // public void mul(double [] x, double [] res){ // Arrays.fill(res,0); // for(int i = 0; i < _diagN; ++i) // res[i] = x[i] * _diag[i]; // for(int ii = 0; ii < _xx.length; ++ii){ // final int n = _xx[ii].length-1; // double [] xi = _xx[ii]; // int i = ii + _diagN; // double d = res[i]; // for(int j = 0; j < n; ++j) { // double e = xi[j]; // d += x[j] * e; // standard matrix mul, row * vec, except short (only up to diag) // x[i] += x[i]*e; // d += _xx[ii][n]*x[n]; // diagonal element // res[i] = d; /** * Task to compute gram matrix normalized by the number of observations (not counting rows with NAs). * in R's notation g = t(X)%*%X/nobs, nobs = number of rows of X with no NA. * @author tomasnykodym */ public static class GramTask extends FrameTask<GramTask> { public Gram _gram; public long _nobs; public GramTask(Key jobKey, DataInfo dinfo){ super(jobKey,dinfo); } @Override protected boolean chunkInit(){ _gram = new Gram(_dinfo.fullN(), _dinfo.largestCat(), _dinfo._nums, _dinfo._cats, false); return true; } @Override protected void processRow(long gid, DataInfo.Row r) { double w = 1; // todo add weights to dinfo? _gram.addRow(r, w); ++_nobs; } @Override protected void chunkDone(long n){ double r = 1.0/_nobs; _gram.mul(r); } @Override public void reduce(GramTask gt){ double r1 = (double)_nobs/(_nobs+gt._nobs); _gram.mul(r1); double r2 = (double)gt._nobs/(_nobs+gt._nobs); gt._gram.mul(r2); _gram.add(gt._gram); _nobs += gt._nobs; } } public static class NonSPDMatrixException extends RuntimeException {} }
package at.fh.swenga.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.context.request.WebRequest; import at.fh.swenga.model.UserModel; @Controller public class TowanController { @RequestMapping(value = {"/", "index"}) public String showWelcome() { return "index"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLogin() { return "login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String doLogin() { return "home"; } @RequestMapping(value = "/home") public String showHome() { return "home"; } @RequestMapping(value = "/profile") public String showProfile() { return "profile"; } @RequestMapping(value = "/forum") public String showForum() { return "forum"; } @RequestMapping(value = "/game") public String showGame() { return "game"; } @RequestMapping(value = "/settings") public String showSettings() { return "settings"; } @RequestMapping(value = "/impressum") public String showAbout() { return "impressum"; } @RequestMapping(value = "/forgottenpwd") public String showForgottenPwd() { return "forgottenpwd"; } @ExceptionHandler(Exception.class) public String handleAllException(Exception ex) { return "error"; } }
package ca.patricklam.judodb.client; import java.util.Date; import com.google.gwt.core.client.JavaScriptObject; public class ServiceData extends JavaScriptObject { protected ServiceData() {} public final native String getID() /*-{ return this.id; }-*/; /** returns date d'inscription in DB format */ public final native String getDateInscription() /*-{ return this.date_inscription == null ? "" : this.date_inscription; }-*/; public final native void setDateInscription(String date_inscription) /*-{ this.date_inscription = date_inscription; }-*/; public final native String getSaisons() /*-{ return this.saisons == null ? "" : this.saisons; }-*/; public final native void setSaisons(String saisons) /*-{ this.saisons = saisons; }-*/; public final native String getClubID() /*-{ return this.club_id; }-*/; public final native void setClubID(String club_id) /*-{ this.club_id = club_id; }-*/; public final native boolean getSansAffiliation() /*-{ return this.sans_affiliation != '0'; }-*/; public final native void setSansAffiliation(boolean sans_affiliation) /*-{ this.sans_affiliation = sans_affiliation ? "1" : "0"; }-*/; public final native boolean getAffiliationInitiation() /*-{ return this.affiliation_initiation != '0'; }-*/; public final native void setAffiliationInitiation(boolean affiliation_initiation) /*-{ this.affiliation_initiation = affiliation_initiation ? "1" : "0"; }-*/; public final native boolean getAffiliationEcole() /*-{ return this.affiliation_ecole != '0'; }-*/; public final native void setAffiliationEcole(boolean affiliation_ecole) /*-{ this.affiliation_ecole = affiliation_ecole ? "1" : "0"; }-*/; public final native String getCours() /*-{ return this.cours; }-*/; public final native void setCours(String cours) /*-{ this.cours = cours; }-*/; public final native int getSessionCount() /*-{ return (this.sessions == null || this.sessions == "") ? 2 : parseInt(this.sessions); }-*/; public final native void setSessionCount(int sessions) /*-{ this.sessions = sessions.toString(); }-*/; public final native boolean getPasseport() /*-{ return this.passeport != '0'; }-*/; public final native void setPasseport(boolean passeport) /*-{ this.passeport = passeport ? "1" : "0"; }-*/; public final native boolean getResident() /*-{ return this.resident != '0'; }-*/; public final native void setResident(boolean resident) /*-{ this.resident = resident ? "1" : "0"; }-*/; public final native int getEscompteType() /*-{ return this.escompte == null ? 0 : parseInt(this.escompte); }-*/; public final native void setEscompteType(int escompte) /*-{ this.escompte = escompte.toString(); }-*/; public final native String getCasSpecialNote() /*-{ return this.cas_special_note; }-*/; public final native void setCasSpecialNote(String cas_special_note) /*-{ this.cas_special_note = cas_special_note; }-*/; public final native String getCasSpecialPct() /*-{ return this.cas_special_pct == null ? "-1" : this.cas_special_pct; }-*/; public final native void setCasSpecialPct(String cas_special_pct) /*-{ this.cas_special_pct = cas_special_pct; }-*/; public final native String getEscompteFrais() /*-{ return (this.escompte_special == null || this.escompte_special == "") ? "0" : this.escompte_special; }-*/; public final native void setEscompteFrais(String escompteFrais) /*-{ this.escompte_special = escompteFrais; }-*/; public final native String getJudogi() /*-{ return this.judogi == "" ? "0" : this.judogi; }-*/; public final native void setJudogi(String judogi) /*-{ this.judogi = judogi; }-*/; public final native String getCategorieFrais() /*-{ return this.categorie_frais == null ? "0" : this.categorie_frais; }-*/; public final native void setCategorieFrais(String categorie_frais) /*-{ this.categorie_frais = categorie_frais; }-*/; public final native String getAffiliationFrais() /*-{ return this.affiliation_frais == null ? "0" : this.affiliation_frais; }-*/; public final native void setAffiliationFrais(String affiliation_frais) /*-{ this.affiliation_frais = affiliation_frais; }-*/; public final native String getSuppFrais() /*-{ return this.supp_frais == null ? "0" : this.supp_frais; }-*/; public final native void setSuppFrais(String supp_frais) /*-{ this.supp_frais = supp_frais; }-*/; public final native String getFrais() /*-{ return this.frais == null ? "0" : this.frais; }-*/; public final native void setFrais(String frais) /*-{ this.frais = frais; }-*/; public final native boolean getVerification() /*-{ return this.verification != '0'; }-*/; public final native void setVerification(boolean verification) /*-{ this.verification = verification ? "1" : "0"; }-*/; public final native boolean getSolde() /*-{ return this.solde!= '0'; }-*/; public final native void setSolde(boolean solde) /*-{ this.solde = solde ? "1" : "0"; }-*/; public final void inscrireAujourdhui() { setDateInscription(Constants.DB_DATE_FORMAT.format(new Date())); } public static final native ServiceData newServiceData() /*-{ return { id: null, club_id: "", date_inscription: "", saisons: "", sans_affiliation: "0", affiliation_initiation: "0", affiliation_ecole: "0", cours: "0", sessions: "2", passeport: "0", resident: "0", judogi: "0.0", escompte: "0", categorie_frais: "0.0", affiliation_frais: "0.0", supp_frais: "0.0", frais: "0.0", cas_special_note: "", escompte_special: "", verification: "0", solde: "0" }; }-*/; }
package cn.updev.Message.Template; public class BasicTemplate { private String title; private String content; public BasicTemplate(String title, String content) { this.content = content; this.title = title; } public String getTitle(){ return "[SpongeTime]" + this.title; } public String getContent(){ String rnt = "<body style=\"background-color: #f2f4f8\"><div style=\"margin-top: 10px; width: 96%; margin-left: 2%;box-shadow:2px 2px 5px #ccc;\">"+ "<div id=\"HEADER\" style=\"padding: 15px; background-color: "<div id=\"BODY\" style=\"padding: 20px; background-color: #fff;\"><h2>"+this.title+"</h2>"+ "<p>" + this.content + "</p><hr/>" + "<p style=\"font-size: 10px;\">* </p>" + "</div><div id=\"FOOTER\" style=\"padding: 10px; padding-left: 15px; background-color: "</div></div></body></html>"; return rnt; } }
package com.baasbox.android.spi; import com.baasbox.android.json.JsonObject; public interface CredentialStore { Credentials get(boolean forceLoad); void set(Credentials credentials); Credentials updateToken(String sessionToken); void updateProfile(JsonObject profile); JsonObject readProfile(); }
package com.backendless.push; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.app.RemoteInput; import android.util.Log; import com.backendless.Backendless; import com.backendless.messaging.Action; import com.backendless.messaging.AndroidPushTemplate; import com.backendless.messaging.PublishOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class PushTemplateHelper { private static Map<String, AndroidPushTemplate> pushNotificationTemplates; public static Map<String, AndroidPushTemplate> getPushNotificationTemplates() { return pushNotificationTemplates; } public static void setPushNotificationTemplates( Map<String, AndroidPushTemplate> pushNotificationTemplates, byte[] rawTemplates ) { PushTemplateHelper.pushNotificationTemplates = Collections.unmodifiableMap( pushNotificationTemplates ); savePushTemplates( rawTemplates ); } private static void savePushTemplates( byte[] rawBytes ) { try { JSONArray jsonArray = new JSONArray( new String( rawBytes)); JSONObject templates = jsonArray.getJSONObject( 1 ); Backendless.savePushTemplates( templates.toString() ); } catch( JSONException e ) { Log.w( PushTemplateHelper.class.getSimpleName(), "Cannot deserialize AndroidPushTemplate to JSONObject.", e ); } } static Notification convertFromTemplate( Context context, AndroidPushTemplate template, String messageText, int messageId ) { // Notification channel ID is ignored for Android 7.1.1 (API level 25) and lower. NotificationCompat.Builder notificationBuilder; // android.os.Build.VERSION_CODES.O == 26 if( android.os.Build.VERSION.SDK_INT >= 26 ) { final String channelId = Backendless.getApplicationId() + ":" + template.getName(); NotificationManager notificationManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE ); NotificationChannel notificationChannel = notificationManager.getNotificationChannel( channelId ); if( notificationChannel == null ) { notificationChannel = PushTemplateHelper.createNotificationChannel( channelId, template ); notificationManager.createNotificationChannel( notificationChannel ); } notificationBuilder = new NotificationCompat.Builder( context.getApplicationContext(), channelId ); notificationBuilder.setDefaults( Notification.DEFAULT_ALL ); if( template.getColorized() != null ) notificationBuilder.setColorized( template.getColorized() ); if( template.getBadge() != null ) notificationBuilder.setBadgeIconType( template.getBadge() ); else notificationBuilder.setBadgeIconType( Notification.BADGE_ICON_NONE ); if( template.getCancelAfter() != null && template.getCancelAfter() != 0 ) notificationBuilder.setTimeoutAfter( template.getCancelAfter() ); } else { notificationBuilder = new NotificationCompat.Builder( context.getApplicationContext() ); notificationBuilder.setDefaults( Notification.DEFAULT_ALL ); if (template.getPriority() != null) notificationBuilder.setPriority( template.getPriority() ); else notificationBuilder.setPriority( Notification.PRIORITY_DEFAULT ); if( template.getButtonTemplate().getSound() != null ) notificationBuilder.setSound( Uri.parse( template.getButtonTemplate().getSound() ) ); if( template.getButtonTemplate().getVibrate() != null ) { long[] vibrate = new long[ template.getButtonTemplate().getVibrate().length ]; int index = 0; for( long l : template.getButtonTemplate().getVibrate() ) vibrate[ index++ ] = l; notificationBuilder.setVibrate( vibrate ); } if (template.getButtonTemplate().getVisibility() != null) notificationBuilder.setVisibility( template.getButtonTemplate().getVisibility() ); else notificationBuilder.setVisibility( template.getButtonTemplate().getVisibility() ); } try { InputStream is = (InputStream) new URL( template.getAttachmentUrl() ).getContent(); Bitmap bitmap = BitmapFactory.decodeStream( is ); if( bitmap != null ) notificationBuilder.setStyle( new NotificationCompat.BigPictureStyle().bigPicture( bitmap ) ); else Log.i( PushTemplateHelper.class.getSimpleName(), "Cannot convert rich media for notification into bitmap." ); } catch( IOException e ) { Log.e( PushTemplateHelper.class.getSimpleName(), "Cannot receive rich media for notification." ); } int icon = 0; if( template.getIcon() != null ) icon = context.getResources().getIdentifier( template.getIcon(), "drawable", context.getPackageName() ); if( icon == 0 ) icon = context.getResources().getIdentifier( "ic_launcher", "drawable", context.getPackageName() ); if( icon != 0 ) notificationBuilder.setSmallIcon( icon ); if (template.getLightsColor() != null && template.getLightsOnMs() != null && template.getLightsOffMs() != null) notificationBuilder.setLights(template.getLightsColor(), template.getLightsOnMs(), template.getLightsOffMs()); if (template.getColorCode() != null) notificationBuilder.setColor( template.getColorCode() ); if (template.getCancelOnTap() != null) notificationBuilder.setAutoCancel( template.getCancelOnTap() ); else notificationBuilder.setAutoCancel( false ); notificationBuilder .setShowWhen( true ) .setWhen( System.currentTimeMillis() ) .setContentTitle( template.getFirstRowTitle() ) .setSubText( template.getThirdRowTitle() ) .setTicker( template.getTickerText() ) .setContentText( messageText ); Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage( context.getPackageName() ); notificationIntent.putExtra( BackendlessBroadcastReceiver.EXTRA_MESSAGE_ID, messageId ); notificationIntent.putExtra( PublishOptions.TEMPLATE_NAME, template.getName() ); notificationIntent.putExtra( PublishOptions.MESSAGE_TAG, messageText ); notificationIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); PendingIntent contentIntent = PendingIntent.getActivity( context, messageId * 3, notificationIntent, 0 ); notificationBuilder.setContentIntent( contentIntent ); if (template.getButtonTemplate().getActions() != null) { List<NotificationCompat.Action> actions = createActions( context, template.getButtonTemplate().getActions(), template.getName(), messageId, messageText ); for( NotificationCompat.Action action : actions ) notificationBuilder.addAction( action ); } return notificationBuilder.build(); } static private List<NotificationCompat.Action> createActions( Context context, Action[] actions, String templateName, int messageId, String messageText ) { List<NotificationCompat.Action> notifActions = new ArrayList<>(); int i = 1; for( Action a : actions ) { Intent actionIntent = new Intent( a.getTitle() ); actionIntent.setClassName( context, a.getId() ); actionIntent.putExtra( BackendlessBroadcastReceiver.EXTRA_MESSAGE_ID, messageId ); actionIntent.putExtra( PublishOptions.MESSAGE_TAG, messageText ); actionIntent.putExtra( PublishOptions.TEMPLATE_NAME, templateName ); actionIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); // user should use messageId and tag(templateName) to cancel notification. PendingIntent pendingIntent = PendingIntent.getActivity( context, messageId * 3 + i++, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT ); NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder( 0, a.getTitle(), pendingIntent ); if( a.getOptions() == 1 ) { RemoteInput remoteInput = new RemoteInput.Builder( PublishOptions.INLINE_REPLY ).build(); actionBuilder.setAllowGeneratedReplies( true ).addRemoteInput( remoteInput ); } notifActions.add( actionBuilder.build() ); } return notifActions; } static private NotificationChannel createNotificationChannel( final String channelId, final AndroidPushTemplate template ) { NotificationChannel notificationChannel = new NotificationChannel( channelId, template.getName(), NotificationManager.IMPORTANCE_DEFAULT ); notificationChannel.setShowBadge( template.getButtonTemplate().getShowBadge() ); notificationChannel.setImportance( template.getPriority() ); // NotificationManager.IMPORTANCE_DEFAULT if( template.getButtonTemplate().getSound() != null ) notificationChannel.setSound( Uri.parse( template.getButtonTemplate().getSound() ), null ); notificationChannel.enableLights( true ); notificationChannel.setLightColor( template.getLightsColor() ); if( template.getButtonTemplate().getVibrate() != null ) { long[] vibrate = new long[ template.getButtonTemplate().getVibrate().length ]; int index = 0; for( long l : template.getButtonTemplate().getVibrate() ) vibrate[ index++ ] = l; notificationChannel.setVibrationPattern( vibrate ); } if (template.getButtonTemplate().getVisibility() != null) notificationChannel.setLockscreenVisibility( template.getButtonTemplate().getVisibility() ); else notificationChannel.setLockscreenVisibility( Notification.VISIBILITY_PUBLIC ); if( template.getButtonTemplate().getBypassDND() != null ) notificationChannel.setBypassDnd( template.getButtonTemplate().getBypassDND() ); else notificationChannel.setBypassDnd( false ); return notificationChannel; } static void showNotification( final Context context, final Notification notification, final String tag, final int messageId ) { final NotificationManagerCompat notificationManager = NotificationManagerCompat.from( context.getApplicationContext() ); Handler handler = new Handler( Looper.getMainLooper() ); handler.post( new Runnable() { @Override public void run() { notificationManager.notify( tag, messageId, notification ); } } ); } static void restorePushTemplates() { String rawTemplates = Backendless.getPushTemplatesAsJson(); if (rawTemplates == null) { pushNotificationTemplates = Collections.emptyMap(); return; } Map<String, AndroidPushTemplate> templates; try { templates = (Map<String, AndroidPushTemplate>) weborb.util.io.Serializer.fromBytes( rawTemplates.getBytes(), weborb.util.io.Serializer.JSON, false ); pushNotificationTemplates = Collections.unmodifiableMap( templates); } catch( IOException e ) { pushNotificationTemplates = Collections.emptyMap(); Log.w( PushTemplateHelper.class.getSimpleName(), "Cannot deserialize AndroidPushTemplate to JSONObject.", e ); } } }
package com.coolweather.app.model; import java.util.ArrayList; import java.util.List; import com.coolweather.app.db.CoolWeatherOpenHelper; import android.app.ListFragment; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class CoolWeatherDB { public static final String DB_NAME = "cool_weather"; public static final int VERSION = 1; private static CoolWeatherDB coolWeatherDB; private SQLiteDatabase db; private CoolWeatherDB(Context context) { CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context, DB_NAME, null, VERSION); db = dbHelper.getWritableDatabase(); } public synchronized static CoolWeatherDB getInstance(Context context) { if (coolWeatherDB == null) { coolWeatherDB = new CoolWeatherDB(context); } return coolWeatherDB; } public void saveProvince(Province province) { if (province != null) { ContentValues values = new ContentValues(); values.put("province_name", province.getProvinceName()); values.put("province_code", province.getProvinceCode()); db.insert("Province", null, values); } } public List<Province> loadProvinces() { List<Province> list = new ArrayList<>(); Cursor cursor = db .query("Province", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor .getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor .getColumnIndex("province_code"))); list.add(province); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return list; } public void saveCity(City city) { if (city != null) { ContentValues values = new ContentValues(); values.put("city_name", city.getCityName()); values.put("city_code", city.getCityCode()); values.put("province_id", city.getProvinceId()); db.insert("City", null, values); } } public List<City> loadCities(int provinceId) { List<City> list = new ArrayList<>(); Cursor cursor = db.query("City", null, "provide_id = ?", new String[] { String.valueOf(provinceId) }, null, null, null); if (cursor.moveToFirst()) { do { City city = new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor .getColumnIndex("city_name"))); city.setCityCode(cursor.getString(cursor .getColumnIndex("city_code"))); city.setProvinceId(provinceId); list.add(city); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return list; } public void saveCounty(County county) { if (county != null) { ContentValues values = new ContentValues(); values.put("county_name", county.getCountyName()); values.put("county_code", county.getCountyCode()); values.put("city_id", county.getCityId()); db.insert("County", null, values); } } public List<County> loadCounties(int cityId) { List<County> list = new ArrayList<>(); Cursor cursor = db.query("County", null, "city_id = ?", new String[] { String.valueOf(cityId) }, null, null, null); if (cursor.moveToFirst()) { do { County county = new County(); county.setId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyName(cursor.getString(cursor .getColumnIndex("county_name"))); county.setCountyCode(cursor.getString(cursor .getColumnIndex("county_code"))); county.setCityId(cityId); list.add(county); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return list; } }
package com.ecyrd.jspwiki.render; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.jdom.Content; import org.jdom.Element; import org.jdom.Text; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.parser.PluginContent; import com.ecyrd.jspwiki.parser.WikiDocument; /** * Implements DOM-to-Creole rendering. * * @author Janne Jalkanen */ public class CreoleRenderer extends WikiRenderer { private static final String LI = "li"; private static final String UL = "ul"; private static final String OL = "ol"; private static final String P = "p"; private static final String A = "a"; private static final String PRE = "pre"; /** * Contains element, start markup, end markup */ private static final String[] ELEMENTS = { "i" , " "b" , "**" , "**", "h2", "== " , " ==", "h3", "=== " , " ===", "h4", "==== " , " ====", "hr", " "tt", "<<{{>>", "<<}}>>" }; private int m_listCount = 0; private char m_listChar = 'x'; private List m_plugins = new ArrayList(); public CreoleRenderer( WikiContext ctx, WikiDocument doc ) { super( ctx, doc ); } /** * Renders an element into the StringBuffer given * @param ce * @param sb */ private void renderElement( Element ce, StringBuffer sb ) { String endEl = ""; for( int i = 0; i < ELEMENTS.length; i+=3 ) { if( ELEMENTS[i].equals(ce.getName()) ) { sb.append( ELEMENTS[i+1] ); endEl = ELEMENTS[i+2]; } } if( UL.equals(ce.getName()) ) { m_listCount++; m_listChar = '*'; } else if( OL.equals(ce.getName()) ) { m_listCount++; m_listChar = ' } else if( LI.equals(ce.getName()) ) { for(int i = 0; i < m_listCount; i++ ) sb.append( m_listChar ); sb.append(" "); } else if( A.equals(ce.getName()) ) { String href = ce.getAttributeValue("href"); String text = ce.getText(); if( href.equals(text) ) { sb.append("[["+href+"]]"); } else { sb.append("[["+href+"|"+text+"]]"); } // Do not render anything else return; } else if( PRE.equals(ce.getName()) ) { sb.append("{{{"); sb.append( ce.getText() ); sb.append("}}}"); return; } // Go through the children for( Iterator i = ce.getContent().iterator(); i.hasNext(); ) { Content c = (Content)i.next(); if( c instanceof PluginContent ) { PluginContent pc = (PluginContent)c; if( pc.getPluginName().equals("Image") ) { sb.append("{{"+pc.getParameter("src")+"}}"); } else { m_plugins.add(pc); sb.append( "<<"+pc.getPluginName()+" "+m_plugins.size()+">>" ); } } else if( c instanceof Text ) { sb.append( ((Text)c).getText() ); } else if( c instanceof Element ) { renderElement( (Element)c, sb ); } } if( UL.equals(ce.getName()) || OL.equals(ce.getName()) ) { m_listCount } else if( P.equals(ce.getName()) ) { sb.append("\n"); } sb.append(endEl); } public String getString() throws IOException { StringBuffer sb = new StringBuffer(1000); Element ce = m_document.getRootElement(); // Traverse through the entire tree of everything. renderElement( ce, sb ); return sb.toString(); } }
package com.fsck.k9.preferences; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import android.content.SharedPreferences; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.R; import com.fsck.k9.Account.FolderMode; import com.fsck.k9.Account.ScrollButtons; import com.fsck.k9.crypto.Apg; import com.fsck.k9.mail.store.StorageManager; import com.fsck.k9.preferences.Settings.*; public class AccountSettings { public static final Map<String, SettingsDescription> SETTINGS; static { Map<String, SettingsDescription> s = new LinkedHashMap<String, SettingsDescription>(); s.put("archiveFolderName", new StringSetting("Archive")); s.put("autoExpandFolderName", new StringSetting("INBOX")); s.put("automaticCheckIntervalMinutes", new IntegerResourceSetting(-1, R.array.account_settings_check_frequency_values)); s.put("chipColor", new ColorSetting(0xFF0000FF)); s.put("cryptoApp", new StringSetting(Apg.NAME)); s.put("cryptoAutoSignature", new BooleanSetting(false)); s.put("defaultQuotedTextShown", new BooleanSetting(Account.DEFAULT_QUOTED_TEXT_SHOWN)); s.put("deletePolicy", new DeletePolicySetting(Account.DELETE_POLICY_NEVER)); s.put("displayCount", new IntegerResourceSetting(K9.DEFAULT_VISIBLE_LIMIT, R.array.account_settings_display_count_values)); s.put("draftsFolderName", new StringSetting("Drafts")); s.put("enableMoveButtons", new BooleanSetting(false)); s.put("expungePolicy", new StringResourceSetting(Account.EXPUNGE_IMMEDIATELY, R.array.account_setup_expunge_policy_values)); s.put("folderDisplayMode", new EnumSetting(FolderMode.class, FolderMode.NOT_SECOND_CLASS)); s.put("folderPushMode", new EnumSetting(FolderMode.class, FolderMode.FIRST_CLASS)); s.put("folderSyncMode", new EnumSetting(FolderMode.class, FolderMode.FIRST_CLASS)); s.put("folderTargetMode", new EnumSetting(FolderMode.class, FolderMode.NOT_SECOND_CLASS)); s.put("goToUnreadMessageSearch", new BooleanSetting(false)); s.put("hideButtonsEnum", new EnumSetting(ScrollButtons.class, ScrollButtons.NEVER)); s.put("hideMoveButtonsEnum", new EnumSetting(ScrollButtons.class, ScrollButtons.NEVER)); s.put("idleRefreshMinutes", new IntegerResourceSetting(24, R.array.idle_refresh_period_values)); s.put("inboxFolderName", new StringSetting("INBOX")); s.put("led", new BooleanSetting(true)); s.put("ledColor", new ColorSetting(0xFF0000FF)); s.put("localStorageProvider", new StorageProviderSetting()); s.put("maxPushFolders", new IntegerRangeSetting(0, 100, 10)); s.put("maximumAutoDownloadMessageSize", new IntegerResourceSetting(32768, R.array.account_settings_autodownload_message_size_values)); s.put("maximumPolledMessageAge", new IntegerResourceSetting(-1, R.array.account_settings_message_age_values)); s.put("messageFormat", new EnumSetting(Account.MessageFormat.class, Account.DEFAULT_MESSAGE_FORMAT)); s.put("messageReadReceipt", new BooleanSetting(Account.DEFAULT_MESSAGE_READ_RECEIPT)); s.put("notificationUnreadCount", new BooleanSetting(true)); s.put("notifyMailCheck", new BooleanSetting(false)); s.put("notifyNewMail", new BooleanSetting(false)); s.put("notifySelfNewMail", new BooleanSetting(true)); s.put("pushPollOnConnect", new BooleanSetting(true)); s.put("quotePrefix", new StringSetting(Account.DEFAULT_QUOTE_PREFIX)); s.put("quoteStyle", new EnumSetting(Account.QuoteStyle.class, Account.DEFAULT_QUOTE_STYLE)); s.put("replyAfterQuote", new BooleanSetting(Account.DEFAULT_REPLY_AFTER_QUOTE)); s.put("ring", new BooleanSetting(true)); s.put("ringtone", new RingtoneSetting("content://settings/system/notification_sound")); s.put("saveAllHeaders", new BooleanSetting(true)); s.put("searchableFolders", new EnumSetting(Account.Searchable.class, Account.Searchable.ALL)); s.put("sentFolderName", new StringSetting("Sent")); s.put("showPicturesEnum", new EnumSetting(Account.ShowPictures.class, Account.ShowPictures.NEVER)); s.put("signatureBeforeQuotedText", new BooleanSetting(false)); s.put("spamFolderName", new StringSetting("Spam")); s.put("subscribedFoldersOnly", new BooleanSetting(false)); s.put("syncRemoteDeletions", new BooleanSetting(true)); s.put("trashFolderName", new StringSetting("Trash")); s.put("useCompression.MOBILE", new BooleanSetting(true)); s.put("useCompression.OTHER", new BooleanSetting(true)); s.put("useCompression.WIFI", new BooleanSetting(true)); s.put("vibrate", new BooleanSetting(false)); s.put("vibratePattern", new IntegerResourceSetting(0, R.array.account_settings_vibrate_pattern_values)); s.put("vibrateTimes", new IntegerResourceSetting(5, R.array.account_settings_vibrate_times_label)); SETTINGS = Collections.unmodifiableMap(s); } public static Map<String, String> validate(Map<String, String> importedSettings, boolean useDefaultValues) { return Settings.validate(SETTINGS, importedSettings, useDefaultValues); } public static Map<String, String> getAccountSettings(SharedPreferences storage, String uuid) { Map<String, String> result = new HashMap<String, String>(); String prefix = uuid + "."; for (String key : SETTINGS.keySet()) { String value = storage.getString(prefix + key, null); if (value != null) { result.put(key, value); } } return result; } /** * An integer resource setting. * * <p> * Basically a {@link PseudoEnumSetting} that is initialized from a resource array containing * integer strings. * </p> */ public static class IntegerResourceSetting extends PseudoEnumSetting<Integer> { private final Map<Integer, String> mMapping; public IntegerResourceSetting(int defaultValue, int resId) { super(defaultValue); Map<Integer, String> mapping = new HashMap<Integer, String>(); String[] values = K9.app.getResources().getStringArray(resId); for (String value : values) { int intValue = Integer.parseInt(value); mapping.put(intValue, value); } mMapping = Collections.unmodifiableMap(mapping); } @Override protected Map<Integer, String> getMapping() { return mMapping; } @Override public Object fromString(String value) throws InvalidSettingValueException { try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new InvalidSettingValueException(); } } } /** * A string resource setting. * * <p> * Basically a {@link PseudoEnumSetting} that is initialized from a resource array. * </p> */ public static class StringResourceSetting extends PseudoEnumSetting<String> { private final Map<String, String> mMapping; public StringResourceSetting(String defaultValue, int resId) { super(defaultValue); Map<String, String> mapping = new HashMap<String, String>(); String[] values = K9.app.getResources().getStringArray(resId); for (String value : values) { mapping.put(value, value); } mMapping = Collections.unmodifiableMap(mapping); } @Override protected Map<String, String> getMapping() { return mMapping; } @Override public Object fromString(String value) throws InvalidSettingValueException { if (!mMapping.containsKey(value)) { throw new InvalidSettingValueException(); } return value; } } /** * The notification ringtone setting. */ public static class RingtoneSetting extends SettingsDescription { public RingtoneSetting(String defaultValue) { super(defaultValue); } @Override public Object fromString(String value) { //TODO: add validation return value; } } /** * The storage provider setting. */ public static class StorageProviderSetting extends SettingsDescription { public StorageProviderSetting() { super(null); } @Override public Object getDefaultValue() { return StorageManager.getInstance(K9.app).getDefaultProviderId(); } @Override public Object fromString(String value) { StorageManager storageManager = StorageManager.getInstance(K9.app); Map<String, String> providers = storageManager.getAvailableProviders(); if (providers.containsKey(value)) { return value; } throw new RuntimeException("Validation failed"); } } /** * The delete policy setting. */ public static class DeletePolicySetting extends PseudoEnumSetting<Integer> { private Map<Integer, String> mMapping; public DeletePolicySetting(int defaultValue) { super(defaultValue); Map<Integer, String> mapping = new HashMap<Integer, String>(); mapping.put(Account.DELETE_POLICY_NEVER, "NEVER"); mapping.put(Account.DELETE_POLICY_ON_DELETE, "DELETE"); mapping.put(Account.DELETE_POLICY_MARK_AS_READ, "MARK_AS_READ"); mMapping = Collections.unmodifiableMap(mapping); } @Override protected Map<Integer, String> getMapping() { return mMapping; } @Override public Object fromString(String value) throws InvalidSettingValueException { try { Integer deletePolicy = Integer.parseInt(value); if (mMapping.containsKey(deletePolicy)) { return deletePolicy; } } catch (NumberFormatException e) { /* do nothing */ } throw new InvalidSettingValueException(); } } }
package com.hp.hpl.jena.rdf.arp.impl; import java.io.InterruptedIOException; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.hp.hpl.jena.iri.*; import com.hp.hpl.jena.rdf.arp.ALiteral; import com.hp.hpl.jena.rdf.arp.ARPErrorNumbers; import com.hp.hpl.jena.rdf.arp.ARPHandlers; import com.hp.hpl.jena.rdf.arp.AResource; import com.hp.hpl.jena.rdf.arp.FatalParsingErrorException; import com.hp.hpl.jena.rdf.arp.ParseException; import com.hp.hpl.jena.rdf.arp.StatementHandler; import com.hp.hpl.jena.rdf.arp.states.Frame; import com.hp.hpl.jena.rdf.arp.states.FrameI; import com.hp.hpl.jena.rdf.arp.states.LookingForRDF; import com.hp.hpl.jena.rdf.arp.states.StartStateRDForDescription; /** * This class converts SAX events into a stream of encapsulated events suitable * for the RDF parser. In effect, this is the RDF lexer. updates by kers to * handle exporting namespace prefix maps. * * @author jjc */ public class XMLHandler extends LexicalHandlerImpl implements ARPErrorNumbers, Names { boolean encodingProblems = false; protected Map idsUsed = new HashMap(); public void triple(ANode s, ANode p, ANode o) { StatementHandler stmt; boolean bad=s.isTainted() || p.isTainted() || o.isTainted(); if (bad) { stmt = handlers.getBadStatementHandler(); } else { stmt = handlers.getStatementHandler(); } AResourceInternal subj = (AResourceInternal) s; AResourceInternal pred = (AResourceInternal) p; if (!bad) subj.setHasBeenUsed(); if (o instanceof AResource) { AResourceInternal obj = (AResourceInternal) o; if (!bad) obj.setHasBeenUsed(); stmt.statement(subj, pred, obj); } else stmt.statement(subj, pred, (ALiteral) o); } // This is the current frame. FrameI frame; public void startPrefixMapping(String prefix, String uri) throws SAXParseException { checkNamespaceURI(uri); handlers.getNamespaceHandler().startPrefixMapping(prefix, uri); } public void endPrefixMapping(String prefix) { handlers.getNamespaceHandler().endPrefixMapping(prefix); } public Locator getLocator() { return locator; } Locator locator; public void setDocumentLocator(Locator locator) { this.locator = locator; } static final private boolean DEBUG = false; public void startElement(String uri, String localName, String rawName, Attributes atts) throws SAXException { if (Thread.interrupted()) throw new WrappedException(new InterruptedIOException()); FrameI oldFrame = frame; frame = frame.startElement(uri, localName, rawName, atts); if (DEBUG) System.err.println("<" + rawName + "> :: " + getSimpleName(oldFrame.getClass()) + " + getSimpleName(frame.getClass())); } public void endElement(String uri, String localName, String rawName) throws SAXException { frame.endElement(); frame = frame.getParent(); if (DEBUG) System.err.println("</" + rawName + "> :: < + getSimpleName(frame.getClass())); } static public String getSimpleName(Class c) { String rslt[] = c.getName().split("\\."); return rslt[rslt.length - 1]; } public void characters(char ch[], int start, int length) throws SAXException { frame.characters(ch, start, length); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { // Never called. characters(ch, start, length); } void setUserData(String nodeId, Object v) { nodeIdUserData.put(nodeId, v); } Object getUserData(String nodeId) { return nodeIdUserData.get(nodeId); } public void comment(char[] ch, int start, int length) throws SAXParseException { frame.comment(ch, start, length); } public void processingInstruction(String target, String data) throws SAXException { frame.processingInstruction(target, data); } public void warning(Taint taintMe,int id, String msg) throws SAXParseException { if (options.getErrorMode()[id] != EM_IGNORE) warning(taintMe,id, location(), msg); } void warning(Taint taintMe, int id, Location loc, String msg) throws SAXParseException { if (options.getErrorMode()[id] != EM_IGNORE) warning(taintMe, id, new ParseException(id, loc, msg) { private static final long serialVersionUID = 1990910846204964756L; }); } void generalError( int id, Exception e) throws SAXParseException { Location where = new Location(locator); // System.err.println(e.getMessage()); warning(null, id, new ParseException(id, where, e)); } void warning(Taint taintMe, int id, SAXParseException e) throws SAXParseException { try { switch (options.getErrorMode()[id]) { case EM_IGNORE: break; case EM_WARNING: handlers.getErrorHandler().warning(e); break; case EM_ERROR: if (taintMe != null) taintMe.taint(); handlers.getErrorHandler().error(e); break; case EM_FATAL: handlers.getErrorHandler().fatalError(e); break; } } catch (SAXParseException xx) { throw xx; } catch (SAXException ee) { throw new WrappedException(ee); } if (e instanceof ParseException && ((ParseException) e).isPromoted()) throw e; if (options.getErrorMode()[id] == EM_FATAL) { // If we get here, we shouldn't go on // throw an error into Jena. throw new FatalParsingErrorException(); } } public void error(SAXParseException e) throws SAXParseException { warning(null,ERR_SAX_ERROR, e); } public void warning(SAXParseException e) throws SAXParseException { warning(null,WARN_SAX_WARNING, e); } public void fatalError(SAXParseException e) throws SAXException { warning(null,ERR_SAX_FATAL_ERROR, e); // If we get here, we shouldn't go on // throw an error into Jena. throw new FatalParsingErrorException(); } /** * @param v */ public void endLocalScope(ANode v) { if (handlers.getExtendedHandler() != ARPHandlersImpl.nullScopeHandler) { ARPResource bn = (ARPResource) v; if (!bn.getHasBeenUsed()) return; if (bn.hasNodeID()) { // save for later end scope if (handlers.getExtendedHandler().discardNodesWithNodeID()) return; String bnodeID = bn.nodeID; if (!nodeIdUserData.containsKey(bnodeID)) nodeIdUserData.put(bnodeID, null); } else { handlers.getExtendedHandler().endBNodeScope(bn); } } } public void endRDF() { handlers.getExtendedHandler().endRDF(); } public void startRDF() { handlers.getExtendedHandler().startRDF(); } boolean ignoring(int eCode) { return options.getErrorMode()[eCode] == EM_IGNORE; } protected AbsXMLContext initialContext(String base, String lang) throws SAXParseException { return initialContextWithBase(base).withLang(this,lang); } protected void checkBadURI(Taint taintMe,RDFURIReference uri) throws SAXParseException { if (uri.isRDFURIReference() || !uri.isVeryBad()) return; // TODO: extract good message String msg = "todo <"+uri+">"; // e.getMessage(); // if (msg.endsWith(uri)) { // msg = msg.substring(0,msg.length()-uri.length())+"<"+uri+">"; // } else { // msg = "<" + uri + "> " + msg; // URI uri2; // uri2. warning(taintMe,WARN_MALFORMED_URI, "Bad URI: " + msg); } private AbsXMLContext initialContextWithBase(String base) throws SAXParseException { // TODO: base tainting if (base == null) { warning(null,IGN_NO_BASE_URI_SPECIFIED, "Base URI not specified for input file; local URI references will be in error."); return new XMLNullContext(this, ERR_RESOLVING_URI_AGAINST_NULL_BASE); } else if (base.equals("")) { warning(null,IGN_NO_BASE_URI_SPECIFIED, "Base URI specified as \"\"; local URI references will not be resolved."); return new XMLNullContext(this, WARN_RESOLVING_URI_AGAINST_EMPTY_BASE); } else { return new XMLContext(this,base); } } /* private XMLContext initialContextWithBasex(String base) throws SAXParseException { XMLContext rslt = new XMLContext(this, base); RDFURIReference b = rslt.getURI(); if (base == null) { warning(null,IGN_NO_BASE_URI_SPECIFIED, "Base URI not specified for input file; local URI references will be in error."); } else if (base.equals("")) { warning(null,IGN_NO_BASE_URI_SPECIFIED, "Base URI specified as \"\"; local URI references will not be resolved."); } else { checkBadURI(null,b); // Warnings on bad base. // if (b.isVeryBad()||b.isRelative()) { // return } return rslt; } */ private ARPOptionsImpl options = new ARPOptionsImpl(); private ARPHandlersImpl handlers = new ARPHandlersImpl(); StatementHandler getStatementHandler() { return handlers.getStatementHandler(); } public ARPHandlers getHandlers() { return handlers; } public ARPOptionsImpl getOptions() { return options; } public void setOptionsWith(ARPOptionsImpl newOpts) { options = newOpts.copy(); } public void setHandlersWith(ARPHandlersImpl newHh) { handlers = newHh.copy(); } private Map nodeIdUserData; public void initParse(String base, String lang) throws SAXParseException { nodeIdUserData = new HashMap(); idsUsed = new HashMap(); if (getOptions().getEmbedding()) frame = new LookingForRDF(this, initialContext(base, lang)); else frame = new StartStateRDForDescription(this, initialContext(base, lang)); } /** * This method must be always be called after parsing, e.g. in a finally * block. * */ void afterParse() { while (frame != null) { frame.abort(); frame = frame.getParent(); } // endRDF(); endBnodeScope(); } void endBnodeScope() { if (handlers.getExtendedHandler() != ARPHandlersImpl.nullScopeHandler) { Iterator it = nodeIdUserData.keySet().iterator(); while (it.hasNext()) { String nodeId = (String) it.next(); ARPResource bn = new ARPResource(this, nodeId); handlers.getExtendedHandler().endBNodeScope(bn); } } } public Location location() { return new Location(locator); } private IRIFactory factory; IRIFactory iriFactory() { if (factory == null) { if (locator != null) factory = new IRIFactory(locator); else factory = new IRIFactory(new Locator() { public int getColumnNumber() { return locator == null ? -1 : locator.getColumnNumber(); } public int getLineNumber() { return locator == null ? -1 : locator.getLineNumber(); } public String getPublicId() { return locator == null ? null : locator.getPublicId(); } public String getSystemId() { return locator == null ? null : locator.getSystemId(); } }); } return factory; } private void checkNamespaceURI(String uri) throws SAXParseException { ((Frame) frame).checkEncoding(null,uri); if (uri.length() != 0) { RDFURIReference u = iriFactory().create(uri); if (!u.isAbsolute()) { warning(null, WARN_RELATIVE_NAMESPACE_URI_DEPRECATED, "The namespace URI: <" + uri + "> is relative. Such use has been deprecated by the W3C, and may result in RDF interoperability failures. Use an absolute namespace URI."); } if (!u.toASCIIString().equals(u.toString())) warning(null, WARN_BAD_NAMESPACE_URI, "Non-ascii characters in a namespace URI may not be completely portable: <" + u.toString() + ">. Resulting RDF URI references are legal."); if (uri.startsWith(rdfns) && !uri.equals(rdfns)) warning(null,WARN_BAD_RDF_NAMESPACE_URI, "Namespace URI ref <" + uri + "> may not be used in RDF/XML."); if (uri.startsWith(xmlns) && !uri.equals(xmlns)) warning(null,WARN_BAD_XML_NAMESPACE_URI, "Namespace URI ref <" + uri + "> may not be used in RDF/XML."); } } }
package com.madphysicist.tools.util; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.ListIterator; /** * Manages the tasks of path construction and lookup. Lookup is done in a linear * fashion according to the order in which items are added. For a concrete * implementation pertaining to file system paths, see {@link FilePathManager}. * * @param <T> the type of element in the path. * @param <U> the type of object obtained when an element is appended to the * path. * @author Joseph Fox-Rabinovitz * @version 1.0.0, 03 Dec 2012 - J. Fox-Rabinovitz - Created * @since 1.0.1 */ public abstract class PathManager<T, U> implements Serializable, Iterable<T> { /** * The list of path elements. The order of the elements is significant for * how items will be found. * * @serial * @since 1.0.0 */ private final List<T> path; public PathManager() { this.path = new ArrayList<>(); } public PathManager(T[] initialPath) { this(Arrays.asList(initialPath)); } @SuppressWarnings("OverridableMethodCallInConstructor") public PathManager(Collection<T> initialPath) { this.path = new ArrayList<>(); if(initialPath != null) { addElements(initialPath); } } public void addElement(T element) { if(element == null) { throw new NullPointerException("adding null element"); } path.add(element); } public void addElements(T[] elements) { addElements(Arrays.asList(elements)); } public void addElements(Collection<T> elements) { for(T element : elements) { addElement(element); } } public void removeElement(T element) { if(element == null) { throw new NullPointerException("removing null element"); } path.remove(element); } public void removeElements(T[] elements) { removeElements(Arrays.asList(elements)); } public void removeElements(Collection<T> elements) { for(T element : elements) { removeElement(element); } } public int indexOf(T element) { return path.indexOf(element); } public boolean contains(T element) { return path.contains(element); } public boolean exists(Object item) { return whichElement(item) != null; } public T whichElement(Object item) { for(T element : path) { if(contains(element, item)) { return element; } } return null; } public U which(Object item) { return combine(whichElement(item), item); } public String toString() { if(path.isEmpty()) { return super.toString() + ": <Empty Path>"; } StringBuilder sb = new StringBuilder(super.toString()); sb.append('\n'); for(T element : path) { sb.append(getElementString(element)).append('\n'); } return sb.toString(); } public String getElementString(T element) { return element.toString(); } @Override public ListIterator<T> iterator() { return path.listIterator(); } /** * Checks if the specified manager is equal to this one. The managers are * considered equal if an only if they are of the exact same class and * contain the same elements in the same order. A return value of {@code * true} can be used as an indicator of the fact that this object and the * one being compared to are of the same class. * * @param o the object to compare this one to. * @return {@code true} if both objects have the exact same class and the * same elements in the same order. * @since 1.0.0 */ @Override public boolean equals(Object o) { if(this.getClass() == o.getClass()) { return this.path.equals(((PathManager<?, ?>)o).path); } return false; } @Override public int hashCode() { return HashUtilities.hashCode(path); } public abstract boolean contains(T element, Object item); public abstract U combine(T element, Object item); }
package com.mmtech.mysample; import java.awt.Dimension; import java.awt.Toolkit; public class MySampleApplication { SampleFrame sampleframe; public MySampleApplication() { /** * uses ToolKit and screen size to set up and display JFrame Class SampleFrame */ Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize(); int frameWidth = 1097;//(int)(screensize.getWidth()*0.75); int frameHeight = (int)(screensize.getHeight()*0.75); sampleframe = new SampleFrame(); sampleframe.setTitle("Sample App V3.0"); sampleframe.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); sampleframe.setPreferredSize(new Dimension(frameWidth,frameHeight)); sampleframe.setSize(new Dimension(frameWidth,frameHeight)); sampleframe.pack(); sampleframe.setLocationRelativeTo(null); sampleframe.setVisible(true); } public static void main(String[] args) { /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { MySampleApplication main = new MySampleApplication(); } }); } }
package com.valkryst.VTerminal.component; import com.valkryst.VTerminal.Screen; import com.valkryst.VTerminal.Tile; import com.valkryst.VTerminal.builder.ButtonBuilder; import com.valkryst.VTerminal.palette.ColorPalette; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.ToString; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; @ToString public class Button extends Component { /** Whether or not the button is in the normal state. */ private boolean isInNormalState = true; /** whether or not the button is in the hovered state. */ private boolean isInHoveredState = false; /** Whether or not the button is in the pressed state. */ private boolean isInPressedState = false; /** The background color for when the button is in the normal state. */ protected Color backgroundColor_normal; /** The foreground color for when the button is in the normal state. */ protected Color foregroundColor_normal; /** The background color for when the button is in the hover state. */ protected Color backgroundColor_hover; /** The foreground color for when the button is in the hover state. */ protected Color foregroundColor_hover; /** The background color for when the button is in the pressed state. */ protected Color backgroundColor_pressed; /** The foreground color for when the button is in the pressed state. */ protected Color foregroundColor_pressed; /** The function to run when the button is clicked. */ @Getter @Setter @NonNull private Runnable onClickFunction; /** * Constructs a new AsciiButton. * * @param builder * The builder to use. * * @throws NullPointerException * If the builder is null. */ public Button(final @NonNull ButtonBuilder builder) { super(builder.getDimensions(), builder.getPosition()); colorPalette = builder.getColorPalette(); backgroundColor_normal = colorPalette.getButton_defaultBackground(); foregroundColor_normal = colorPalette.getButton_defaultForeground(); backgroundColor_hover = colorPalette.getButton_hoverBackground(); foregroundColor_hover = colorPalette.getButton_hoverForeground(); backgroundColor_pressed = colorPalette.getButton_pressedBackground(); foregroundColor_pressed = colorPalette.getButton_pressedForeground(); this.onClickFunction = builder.getOnClickFunction(); // Set the button's text: final char[] text = builder.getText().toCharArray(); final Tile[] tiles = super.tiles.getRow(0); for (int x = 0; x < tiles.length; x++) { tiles[x].setCharacter(text[x]); tiles[x].setBackgroundColor(backgroundColor_normal); tiles[x].setForegroundColor(foregroundColor_normal); } } @Override public void createEventListeners(final Screen parentScreen) { if (parentScreen == null || super.eventListeners.size() > 0) { return; } final MouseListener mouseListener = new MouseListener() { @Override public void mouseClicked(final MouseEvent e) {} @Override public void mousePressed(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { if (intersects(parentScreen.getMousePosition())) { setStatePressed(); } } } @Override public void mouseReleased(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { if (isInPressedState) { onClickFunction.run(); } if (intersects(parentScreen.getMousePosition())) { setStateHovered(); } else { setStateNormal(); } } } @Override public void mouseEntered(final MouseEvent e) {} @Override public void mouseExited(final MouseEvent e) {} }; final MouseMotionListener mouseMotionListener = new MouseMotionListener() { @Override public void mouseDragged(final MouseEvent e) {} @Override public void mouseMoved(final MouseEvent e) { if (intersects(parentScreen.getMousePosition())) { setStateHovered(); } else { setStateNormal(); } } }; super.eventListeners.add(mouseListener); super.eventListeners.add(mouseMotionListener); } @Override public void setColorPalette(final ColorPalette colorPalette, final boolean redraw) { if (colorPalette == null) { return; } // Set the instance variables. this.colorPalette = colorPalette; this.backgroundColor_normal = colorPalette.getButton_defaultBackground(); this.foregroundColor_normal = colorPalette.getButton_defaultForeground(); this.backgroundColor_pressed = colorPalette.getButton_pressedBackground(); this.foregroundColor_pressed = colorPalette.getButton_pressedForeground(); this.backgroundColor_hover = colorPalette.getButton_hoverBackground(); this.foregroundColor_hover = colorPalette.getButton_hoverForeground(); // Determine the colors to color the tiles with. final Color backgroundColor; final Color foregroundColor; if (isInPressedState) { backgroundColor = backgroundColor_pressed; foregroundColor = foregroundColor_pressed; } else if (isInHoveredState) { backgroundColor = backgroundColor_hover; foregroundColor = foregroundColor_hover; } else { backgroundColor = backgroundColor_normal; foregroundColor = foregroundColor_normal; } for (int y = 0 ; y < super.tiles.getHeight() ; y++) { for (int x = 0 ; x < super.tiles.getWidth() ; x++) { final Tile tile = super.tiles.getTileAt(x, y); tile.setBackgroundColor(backgroundColor); tile.setForegroundColor(foregroundColor); } } if (redraw) { try { redrawFunction.run(); } catch (final IllegalStateException ignored) { } } } /** Sets the button state to normal if the current state allows for the normal state to be set. */ protected void setStateNormal() { boolean canSetState = isInNormalState == false; canSetState &= isInHoveredState || isInPressedState; if (canSetState) { isInNormalState = true; isInHoveredState = false; isInPressedState = false; setColors(backgroundColor_normal, foregroundColor_normal); redrawFunction.run(); } } /** Sets the button state to hovered if the current state allows for the normal state to be set. */ protected void setStateHovered() { boolean canSetState = isInNormalState || isInPressedState; canSetState &= isInHoveredState == false; if (canSetState) { isInNormalState = false; isInHoveredState = true; isInPressedState = false; setColors(backgroundColor_hover, foregroundColor_hover); redrawFunction.run(); } } /** Sets the button state to pressed if the current state allows for the normal state to be set. */ protected void setStatePressed() { boolean canSetState = isInNormalState || isInHoveredState; canSetState &= isInPressedState == false; if (canSetState) { isInNormalState = false; isInHoveredState = false; isInPressedState = true; setColors(backgroundColor_pressed, foregroundColor_pressed); redrawFunction.run(); } } /** * Sets the back/foreground colors of all characters to the specified colors. * * @param backgroundColor * The new background color. * * @param foregroundColor * The new foreground color. */ private void setColors(final Color backgroundColor, final Color foregroundColor) { for (final Tile tile : super.tiles.getRow(0)) { if (backgroundColor != null) { tile.setBackgroundColor(backgroundColor); } if (foregroundColor != null) { tile.setForegroundColor(foregroundColor); } } } /** * Sets the text displayed on the button. * * The button will not change in size, so it will not show more text than it can currently display. * * @param text * The new text. */ public void setText(final String text) { final char[] chars = (text == null ? new char[0] : text.toCharArray()); for (int x = 0 ; x < super.tiles.getWidth() ; x++) { if (x < chars.length) { super.tiles.getTileAt(x, 0).setCharacter(chars[x]); } else { super.tiles.getTileAt(x, 0).setCharacter(' '); } } } }
/*/ Mirror Core * wckd Development * Brett Crawford */ package com.wckd_dev.mirror.core; import java.util.Scanner; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.graphics.Matrix; import android.graphics.PointF; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore.Images; import android.util.FloatMath; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.Toast; public class MirrorActivity extends Activity implements OnTouchListener { private final String TAG = "wckd"; /* Intent variables */ protected final static String MIRROR_MESSAGE = "com.wckd_dev.mirror.core.MESSAGE"; private String intentMessage; private String store; protected String version; /* Constants for Calling Dialogs */ protected static final int WELCOME_DIALOG = 1; protected static final int SNAPSHOT_DIALOG = 2; protected static final int SNAPSHOT_SIZE = 3; protected static final int PHOTOSTRIP_DIALOG = 4; protected static final int FRAME_STYLE_DIALOG = 5; protected static final int ZOOM_DIALOG = 6; protected static final int EXPOSURE_DIALOG = 7; protected static final int THEME_DIALOG = 8; protected static final int APP_INFO_DIALOG = 9; protected static final int HELP_DIALOG = 10; protected static final int FRONT_CAMERA_NOT_FOUND = 11; protected static final int CAMERA_NOT_FOUND = 12; protected static final int UPGRADE = 13; protected static final int RATE = 14; protected static final int PAUSE_DIALOG = 15; protected static final int WELCOME_ONE_DIALOG = 16; protected static final int WELCOME_TWO_DIALOG = 17; /** Change between 1 and 2 to display one time messages to users after upgrades */ private final int INFO_DIALOGS = 1; // v2.3 set to 1 for release /* Preferences Strings*/ protected static final String APP_PREFERENCES = "AppPrefs"; protected static final String APP_PREFERENCES_ORIENTATION = "Orientation"; protected static final String APP_PREFERENCES_REVERSE = "Reverse"; protected static final String APP_PREFERENCES_FLIP = "Flip"; protected static final String APP_PREFERENCES_FRAME = "Frame"; protected static final String APP_PREFERENCES_FRAME_CHANGED = "FrameChanged"; protected static final String APP_PREFERENCES_INITIAL_LOAD = "InitialLoad"; protected static final String APP_PREFERENCES_INITIAL_PAUSE = "InitialPause"; protected static final String APP_PREFERENCES_INITIAL_SNAPSHOT = "InitialSnapshot"; protected static final String APP_PREFERENCES_INITIAL_PHOTOBOOTH = "InitialPhotoBooth"; protected static final String APP_PREFERENCES_THEME = "Theme"; protected static final String APP_PREFERENCES_EXPOSURE = "Exposure"; protected static final String APP_PREFERENCES_WHITE_BALANCE = "WhiteBalance"; protected static final String APP_PREFERENCES_ZOOM = "Zoom"; protected static final String APP_PREFERENCES_HAS_RATED = "HasRated"; protected static final String APP_PREFERENCES_USE_COUNT = "UseCount"; protected static final String APP_PREFERENCES_SNAPSHOT_SIZE = "SnapshotSize"; /* Preferences */ private int reversePref; private int flipPref; private int orientationPref; private int frameModePref; private int framePacksPref; private int initialLoadPref; private int initialPausePref; private int initialSnapshotPref; private int initialPhotoBoothPref; protected int themePref; private String themeColor; private int exposurePref; private int whiteBalancePref; private float zoomPrefF; protected int hasRatedPref; private int useCountPref; private int snapshotSizePref; /* Camera */ private int numberOfCameras; private int currentCameraId; private int backCameraId; private int frontCameraId; private int photoBoothCount = 0; // Paid Only /* Flags */ private boolean isPaused = false; private boolean isPreviewStopped = false; private boolean isBackCameraFound = false; private boolean isFrontCameraFound = false; private boolean isUsingFrontCamera = false; protected boolean isZoomSupported = false; protected boolean isExposureSupported = false; private boolean isWhiteBalanceSupported = false; private boolean isFullscreen = true; private boolean isMirrorMode = true; private boolean isFlipMode = false; private boolean isPortrait; private boolean isPauseButtonVisible = false; private boolean isSnapshotButtonVisible = false; private boolean isPhotoBoothButtonVisible = false; /* Objects */ private Camera camera = null; private MirrorView mirrorView; protected SharedPreferences appSettings; protected Dialog dialog; private MenuItem menuItemWhiteBalance; private MenuItem menuItemMirrorModeOn; private MenuItem menuItemMirrorModeOff; private Animation slideUp, slideDown; private Animation rightSlideIn, rightSlideOut; private Animation leftSlideIn, leftSlideOut; private ImageButton pause, takeSnapshot, takePhotoBooth; protected FrameManager frameMgr; private Snapshot snapshot; // Paid/Ads Only protected Snapshot.ImageSize imageSize = Snapshot.ImageSize.LARGE; // Paid/Ads Only private PhotoBooth booth; // Paid/Ads Only /* Touch */ private Matrix matrix; private Matrix savedMatrix; private static final int NONE = 0; private static final int PRESS = 1; private static final int DRAG = 2; private static final int ZOOM = 3; private int touchState = NONE; private PointF start = new PointF(); private PointF mid = new PointF(); private float startDist = 1f; private float lastDist = 0f; private float minDist = 10f; private float zoomRate = 0f; /* Store Links */ protected static String rateLink; protected static String upgradeAdsLink; protected static String upgradePaidLink; protected static String frameLink; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initIntentInfo(); initPrefs(); initTheme(); initWindowFeatures(); initContentView(); initMirrorView(); initFrameManager(); initCamera(); initPauseButton(); initSnapshotButton(); initPhotoBoothButton(); initOnTouchListener(); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); loadCamera(); } @Override protected void onPause() { super.onPause(); unloadCamera(); // Save preferences Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_REVERSE, Integer.toString(reversePref)); editor.putString(APP_PREFERENCES_FLIP, Integer.toString(flipPref)); editor.putString(APP_PREFERENCES_ORIENTATION, Integer.toString(orientationPref)); editor.putString(APP_PREFERENCES_FRAME, Integer.toString(frameModePref)); editor.putString(APP_PREFERENCES_FRAME_CHANGED, Integer.toString(framePacksPref)); editor.putString(APP_PREFERENCES_EXPOSURE, Integer.toString(exposurePref)); editor.putString(APP_PREFERENCES_WHITE_BALANCE, Integer.toString(whiteBalancePref)); editor.putString(APP_PREFERENCES_ZOOM, Integer.toString(Math.round(zoomPrefF))); editor.putString(APP_PREFERENCES_HAS_RATED, Integer.toString(hasRatedPref)); editor.putString(APP_PREFERENCES_USE_COUNT, Integer.toString(useCountPref)); editor.putString(APP_PREFERENCES_SNAPSHOT_SIZE, Integer.toString(snapshotSizePref)); editor.commit(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onBackPressed() { if(hasRatedPref == 0 && useCountPref > 6) displayDialog(RATE); else { useCountPref++; MirrorActivity.this.finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); if(reversePref == 0) { mirrorView.mirrorMode(false); isMirrorMode = false; } if(flipPref == 0) { (menu.findItem(R.id.menu_options_flip_mode_off)).setChecked(true); // mirrorView.flipMode(false); // isFlipMode = false; } else { (menu.findItem(R.id.menu_options_flip_mode_on)).setChecked(true); mirrorView.flipMode(true); isFlipMode = true; } if(Math.round(zoomPrefF) > 0) setZoom(Math.round(zoomPrefF)); // Set the zoom preference if(exposurePref != -999) { // If exposure pref is valid try { setExposure(exposurePref); // Set the exposure preference } catch(RuntimeException e) { // No action taken. Exposure settings will not be used. } } menuItemWhiteBalance = menu.findItem(R.id.menu_options_white_balance); if(whiteBalancePref != 0) setWhiteBalance(whiteBalancePref); // Set the white balance preference if(numberOfCameras > 1) { (menu.findItem(R.id.menu_options_switch_camera)).setEnabled(true); (menu.findItem(R.id.menu_options_switch_camera)).setVisible(true); } if(isPortrait) { (menu.findItem(R.id.menu_options_screen_rotation_portrait)).setChecked(true); } else { (menu.findItem(R.id.menu_options_screen_rotation_landscape)).setChecked(true); } if(version.compareTo("free") != 0) { if(snapshotSizePref == 2) { (menu.findItem(R.id.menu_options_snapshot_size_small)).setChecked(true); } else if(snapshotSizePref == 1) { (menu.findItem(R.id.menu_options_snapshot_size_medium)).setChecked(true); } else { (menu.findItem(R.id.menu_options_snapshot_size_large)).setChecked(true); } Log.d(TAG, "onCreateOptionsMenu: snapshotSizePref: " + snapshotSizePref); } else { (menu.findItem(R.id.menu_options_snapshot_size)).setEnabled(false); (menu.findItem(R.id.menu_options_snapshot_size)).setVisible(false); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menuItemWhiteBalance = menu.findItem(R.id.menu_options_white_balance); menuItemMirrorModeOn = menu.findItem(R.id.menu_options_mirror_mode_on); menuItemMirrorModeOff = menu.findItem(R.id.menu_options_mirror_mode_off); //menuItemFlipModeOn = menu.findItem(R.id.menu_options_flip_mode_on); //menuItemFlipModeOff = menu.findItem(R.id.menu_options_flip_mode_off); if(reversePref == 0) { menuItemMirrorModeOff.setChecked(true); } //if(flipPref == 0) { // menuItemFlipModeOff.setChecked(true); if(snapshotSizePref == 2) { (menu.findItem(R.id.menu_options_snapshot_size_small)).setChecked(true); } else if(snapshotSizePref == 1) { (menu.findItem(R.id.menu_options_snapshot_size_medium)).setChecked(true); } else { (menu.findItem(R.id.menu_options_snapshot_size_large)).setChecked(true); } Log.d(TAG, "onPrepareOptionsMenu: snapshotSizePref: " + snapshotSizePref); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean result = false; int id = item.getItemId(); /* Snapshot */ if(id == R.id.menu_snapshot_snapshot) { if(isSnapshotButtonVisible) { // Hide snapshot button takeSnapshot.startAnimation(rightSlideOut); takeSnapshot.setVisibility(View.INVISIBLE); isSnapshotButtonVisible = false; } else { // Show snapshot button if(isPhotoBoothButtonVisible) { takePhotoBooth.startAnimation(leftSlideOut); takePhotoBooth.setVisibility(View.INVISIBLE); isPhotoBoothButtonVisible = false; booth = null; // Paid Only photoBoothCount = 0; // Paid Only } if(isPauseButtonVisible) { pause.startAnimation(slideDown); pause.setVisibility(View.INVISIBLE); isPauseButtonVisible = false; } takeSnapshot.startAnimation(rightSlideIn); takeSnapshot.setVisibility(View.VISIBLE); isSnapshotButtonVisible = true; showSnapshotDialog(); } result = true; } /* Photobooth */ else if(id == R.id.menu_snapshot_photobooth) { showPhotoBoothDialog(); if(isPhotoBoothButtonVisible) { takePhotoBooth.startAnimation(leftSlideOut); takePhotoBooth.setVisibility(View.INVISIBLE); isPhotoBoothButtonVisible = false; booth = null; // Paid Only photoBoothCount = 0; // Paid Only } else { if(isSnapshotButtonVisible) { takeSnapshot.startAnimation(rightSlideOut); takeSnapshot.setVisibility(View.INVISIBLE); isSnapshotButtonVisible = false; } if(isPauseButtonVisible) { pause.startAnimation(slideDown); pause.setVisibility(View.INVISIBLE); isPauseButtonVisible = false; } takePhotoBooth.startAnimation(leftSlideIn); takePhotoBooth.setVisibility(View.VISIBLE); isPhotoBoothButtonVisible = true; } result = true; } /* Pause */ else if(id == R.id.menu_pause) { showPauseDialog(); if(isPauseButtonVisible) { pause.startAnimation(slideDown); pause.setVisibility(View.INVISIBLE); isPauseButtonVisible = false; } else { if(isPhotoBoothButtonVisible) { takePhotoBooth.startAnimation(leftSlideOut); takePhotoBooth.setVisibility(View.INVISIBLE); isPhotoBoothButtonVisible = false; booth = null; // Paid Only photoBoothCount = 0; // Paid Only } if(isSnapshotButtonVisible) { takeSnapshot.startAnimation(rightSlideOut); takeSnapshot.setVisibility(View.INVISIBLE); isSnapshotButtonVisible = false; } pause.startAnimation(slideUp); pause.setVisibility(View.VISIBLE); isPauseButtonVisible = true; } result = true; } /* Frames */ else if(id == R.id.menu_frame) { displayDialog(FRAME_STYLE_DIALOG); result = true; } /* Zoom */ else if(id == R.id.menu_options_zoom) { displayDialog(ZOOM_DIALOG); result = true; } /* Exposure */ else if(id == R.id.menu_options_exposure) { displayDialog(EXPOSURE_DIALOG); result = true; } /* White Balance Auto */ else if(id == R.id.menu_options_white_balance_auto) { if(isWhiteBalanceSupported) setWhiteBalance(0); else Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); result = true; } /* White Balance Daylight */ else if(id == R.id.menu_options_white_balance_daylight) { if(isWhiteBalanceSupported) setWhiteBalance(1); else Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); result = true; } /* White Balance Incandescent */ else if(id == R.id.menu_options_white_balance_incandescent) { if(isWhiteBalanceSupported) setWhiteBalance(2); else Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); result = true; } /* White Balance Fluorescent */ else if(id == R.id.menu_options_white_balance_fluorescent) { if(isWhiteBalanceSupported) setWhiteBalance(3); else Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); result = true; } /* Mirror Mode On */ else if(id == R.id.menu_options_mirror_mode_on) { if(!isMirrorMode) { mirrorView.mirrorMode(true); isMirrorMode = true; reversePref = 1; item.setChecked(true); } result = true; } /* Mirror Mode Off */ else if(id == R.id.menu_options_mirror_mode_off) { if(isMirrorMode) { mirrorView.mirrorMode(false); isMirrorMode = false; reversePref = 0; item.setChecked(true); } result = true; } /* Flip Mode On */ else if(id == R.id.menu_options_flip_mode_on) { flipPref = 1; isFlipMode = true; item.setChecked(true); mirrorView.flipMode(true); } /* Flip Mode Off */ else if(id == R.id.menu_options_flip_mode_off) { flipPref = 0; isFlipMode = false; item.setChecked(true); mirrorView.flipMode(false); } /* Switch Camera */ else if(id == R. id.menu_options_switch_camera) { unloadCamera(); if(isUsingFrontCamera) { currentCameraId = backCameraId; isUsingFrontCamera = false; } else { currentCameraId = frontCameraId; isUsingFrontCamera = true; } loadCamera(); result = true; } /* Screen Rotation Portrait */ else if(id == R.id.menu_options_screen_rotation_portrait) { if(!isPortrait) { isMirrorMode = true; reversePref = 1; mirrorView.mirrorMode(true); menuItemMirrorModeOn.setChecked(true); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); mirrorView.isPortrait = isPortrait = true; camera.setDisplayOrientation(90); setFrame(0); orientationPref = 0; item.setChecked(true); } result = true; } /* Screen Rotation Landscape */ else if(id == R.id.menu_options_screen_rotation_landscape) { if(isPortrait) { isMirrorMode = true; reversePref = 1; mirrorView.mirrorMode(true); menuItemMirrorModeOn.setChecked(true); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); mirrorView.isPortrait = isPortrait = false; camera.setDisplayOrientation(0); setFrame(0); orientationPref = 1; item.setChecked(true); } result = true; } /* Dark Theme */ else if(id == R.id.menu_options_theme_dark) { themePref = 1; displayDialog(THEME_DIALOG); result = true; } /* Light Theme */ else if(id == R.id.menu_options_theme_light) { themePref = 2; displayDialog(THEME_DIALOG); result = true; } /* RedTheme */ else if(id == R.id.menu_options_theme_red) { if(version.compareTo("free") != 0) { themePref = 3; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Orange Theme */ else if(id == R.id.menu_options_theme_orange) { if(version.compareTo("free") != 0) { themePref = 4; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Green Theme */ else if(id == R.id.menu_options_theme_green) { if(version.compareTo("free") != 0) { themePref = 5; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Purple Theme */ else if(id == R.id.menu_options_theme_purple) { if(version.compareTo("free") != 0) { themePref = 6; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Blue Theme */ else if(id == R.id.menu_options_theme_blue) { if(version.compareTo("free") != 0) { themePref = 7; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Snapshot Size Large */ else if(id == R.id.menu_options_snapshot_size_large) { snapshotSizePref = 0; item.setChecked(true); Log.d(TAG, "Large Selected"); } /* Snapshot Size Medium */ else if(id == R.id.menu_options_snapshot_size_medium) { snapshotSizePref = 1; item.setChecked(true); Log.d(TAG, "Medium Selected"); } /* Snapshot Size Small */ else if(id == R.id.menu_options_snapshot_size_small) { snapshotSizePref = 2; item.setChecked(true); Log.d(TAG, "Small Selected"); } /* App Info */ else if(id == R.id.menu_options_app_info) { displayDialog(APP_INFO_DIALOG); result = true; } /* Help */ else if(id == R.id.menu_options_help) { displayDialog(HELP_DIALOG); result = true; } /* Exit */ else if(id == R.id.menu_exit) { if(hasRatedPref == 0 && useCountPref > 6) displayDialog(RATE); else { useCountPref++; MirrorActivity.this.finish(); } } else result = super.onOptionsItemSelected(item); return result; } private void initIntentInfo() { // Get information from the intent intentMessage = getIntent().getStringExtra(MIRROR_MESSAGE); Scanner message = new Scanner(intentMessage); store = message.next(); version = message.next(); rateLink = message.next(); upgradePaidLink = message.next(); upgradePaidLink = message.next(); frameLink = message.next(); } private void initPrefs() { appSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE); reversePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_REVERSE, "1")); flipPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_FLIP, "0")); orientationPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_ORIENTATION, "0")); frameModePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_FRAME, "0")); framePacksPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_FRAME_CHANGED, "0")); initialLoadPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_LOAD, "0")); initialPausePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_PAUSE, "0")); initialSnapshotPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_SNAPSHOT, "0")); initialPhotoBoothPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_PHOTOBOOTH, "0")); themePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_THEME, "2")); exposurePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_EXPOSURE, "-999")); whiteBalancePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_WHITE_BALANCE, "0")); zoomPrefF = Integer.parseInt(appSettings.getString(APP_PREFERENCES_ZOOM, "0")); hasRatedPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_HAS_RATED, "0")); useCountPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_USE_COUNT, "0")); snapshotSizePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_SNAPSHOT_SIZE, "0")); } private void initTheme() { switch(themePref) { case 1: setTheme(R.style.HoloDark); themeColor = "#33B5E5"; break; case 2: setTheme(R.style.HoloLight); themeColor = "#0099CC"; break; case 3: setTheme(R.style.HoloRed); themeColor = "#CC0000"; break; case 4: setTheme(R.style.HoloOrange); themeColor = "#FF8800"; break; case 5: setTheme(R.style.HoloGreen); themeColor = "#669900"; break; case 6: setTheme(R.style.HoloPurple); themeColor = "#9933CC"; break; case 7: setTheme(R.style.HoloBlue); themeColor = "#0099CC"; break; } } private void initWindowFeatures() { if(orientationPref == 0) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); isPortrait = true; } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); isPortrait = false; } getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } private void initContentView() { setContentView(R.layout.main); } private void initMirrorView() { mirrorView = (MirrorView) findViewById(R.id.mirror_view_view); mirrorView.isFullscreen = true; // App starts in fullscreen mode if(isPortrait) { mirrorView.isPortrait = true; } else { mirrorView.isPortrait = false; } } private void initFrameManager() { int numberOfPacks = 0; frameMgr = new FrameManager(getPackageManager()); Resources res = getResources(); if(version.compareTo("free") == 0) { frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror:drawable/frame_thumb0", null, null), res.getIdentifier("com.wckd_dev.mirror:drawable/frame0", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror:string/frame_no_frame", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror:drawable/frame_thumb1", null, null), res.getIdentifier("com.wckd_dev.mirror:drawable/frame1", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror:string/frame_low_light", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror:drawable/frame_thumb2", null, null), res.getIdentifier("com.wckd_dev.mirror:drawable/frame2", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror:string/frame_soft_gold", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror:drawable/frame_thumb3", null, null), res.getIdentifier("com.wckd_dev.mirror:drawable/frame3", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror:string/frame_brushed", null, null)), res); } else if(version.compareTo("paid") == 0) { frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame_thumb0", null, null), res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame0", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_paid:string/frame_no_frame", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame_thumb1", null, null), res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame1", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_paid:string/frame_low_light", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame_thumb2", null, null), res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame2", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_paid:string/frame_soft_gold", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame_thumb3", null, null), res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame3", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_paid:string/frame_brushed", null, null)), res); } else if(version.compareTo("ads") == 0) { frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame_thumb0", null, null), res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame0", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_ads:string/frame_no_frame", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame_thumb1", null, null), res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame1", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_ads:string/frame_low_light", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame_thumb2", null, null), res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame2", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_ads:string/frame_soft_gold", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame_thumb3", null, null), res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame3", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_ads:string/frame_brushed", null, null)), res); } if(frameMgr.hasCFP1()) numberOfPacks++; if(frameMgr.hasCFP2()) numberOfPacks++; if(frameMgr.hasFFP1()) numberOfPacks++; if(frameMgr.hasFFP2()) numberOfPacks++; if(frameMgr.hasNFP1()) numberOfPacks++; if(frameMgr.hasNFP2()) numberOfPacks++; if(frameMgr.hasVFP()) numberOfPacks++; if(numberOfPacks == framePacksPref) // No new frame packs setFrame(frameModePref); // Restore saved preference else { // Packs have been installed/removed setFrame(0); // Default frame used framePacksPref = numberOfPacks; // Record number of packs installed } } private void initCamera() { // Try to find the ID of the front camera numberOfCameras = Camera.getNumberOfCameras(); CameraInfo cameraInfo = new CameraInfo(); for(int i = 0; i < numberOfCameras && !isFrontCameraFound; i++) { Camera.getCameraInfo(i, cameraInfo); if(cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { backCameraId = i; isBackCameraFound = true; } else if(cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) { frontCameraId = i; isFrontCameraFound = true; } } if(isFrontCameraFound) { // If front camera is found, use front camera currentCameraId = frontCameraId; isUsingFrontCamera = true; } else if(!isFrontCameraFound && isBackCameraFound) { // If no front camera and back is found, use back camera currentCameraId = backCameraId; isUsingFrontCamera = false; displayDialog(FRONT_CAMERA_NOT_FOUND); } else if(!isBackCameraFound && !isFrontCameraFound) {// No cameras found displayDialog(CAMERA_NOT_FOUND); } } private void initPauseButton() { // Prepare pause button pause = (ImageButton) findViewById(R.id.pause_button); slideUp = AnimationUtils.loadAnimation(this, R.anim.slide_up); slideDown = AnimationUtils.loadAnimation(this, R.anim.slide_down); pause.startAnimation(slideDown); pause.setVisibility(View.INVISIBLE); pause.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(isPaused) { mirrorView.startPreview(); isPaused = false; } else { mirrorView.stopPreview(); isPaused = true; } } }); } private void initSnapshotButton() { // Prepare snapshot button takeSnapshot = (ImageButton) findViewById(R.id.snapshot_button); rightSlideIn = AnimationUtils.loadAnimation(this, R.anim.right_slide_in); rightSlideOut = AnimationUtils.loadAnimation(this, R.anim.right_slide_out); takeSnapshot.startAnimation(rightSlideOut); takeSnapshot.setVisibility(View.INVISIBLE); takeSnapshot.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(version.compareTo("free") == 0) { displayDialog(UPGRADE); } else { snapshot = new Snapshot(mirrorView, findViewById(R.id.frame_overlay), getApplicationContext()); if(snapshotSizePref == 2) { imageSize = Snapshot.ImageSize.SMALL; } else if(snapshotSizePref == 1) { imageSize = Snapshot.ImageSize.MEDIUM; } else { imageSize = Snapshot.ImageSize.LARGE; } snapshot.takePhoto(imageSize); try { ContentValues values = snapshot.savePhoto(); MirrorActivity.this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); } catch(Exception e) { e.printStackTrace(); } snapshot = null; } } }); } private void initPhotoBoothButton() { // Prepare photobooth button takePhotoBooth = (ImageButton) findViewById(R.id.photobooth_button); leftSlideIn = AnimationUtils.loadAnimation(this, R.anim.left_slide_in); leftSlideOut = AnimationUtils.loadAnimation(this, R.anim.left_slide_out); takePhotoBooth.startAnimation(leftSlideOut); takePhotoBooth.setVisibility(View.INVISIBLE); takePhotoBooth.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(version.compareTo("free") == 0) { displayDialog(UPGRADE); } else { try { photoBoothCount++; switch(photoBoothCount) { case 1: booth = new PhotoBooth(mirrorView, findViewById(R.id.frame_overlay), getResources(), getApplicationContext()); booth.takePhotoOne(); break; case 2: booth.takePhotoTwo(); break; case 3: booth.takePhotoThree(); break; case 4: booth.takePhotoFour(); booth.createPhotoStrip(); try { ContentValues values = booth.savePhotoStrip(); MirrorActivity.this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); } catch(Exception e) { e.printStackTrace(); throw e; } booth = null; photoBoothCount = 0; break; default: } } catch (Exception e) { e.printStackTrace(); } } } }); } private void initOnTouchListener() { // Initialize onTouchListener ImageView view = (ImageView) findViewById(R.id.invis_button); view.setOnTouchListener(this); matrix = new Matrix(); savedMatrix = new Matrix(); } protected void initExpSeekBar(SeekBar expSeek) { switch(themePref) { case 1: setTheme(R.style.HoloDark); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_dark)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_dark)); break; case 2: setTheme(R.style.HoloLight); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_light)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_light)); break; case 3: setTheme(R.style.HoloRed); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_red)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_red)); break; case 4: setTheme(R.style.HoloOrange); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_orange)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_orange)); break; case 5: setTheme(R.style.HoloGreen); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_green)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_green)); break; case 6: setTheme(R.style.HoloPurple); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_purple)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_purple)); break; case 7: setTheme(R.style.HoloBlue); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_blue)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_blue)); break; } int[] range = mirrorView.getExposureRange(); expSeek.setMax(range[1] - range[0]); expSeek.setProgress(exposurePref == -999 ? (range[1] - range[0]) / 2 : exposurePref); expSeek.setPadding(50, 20, 50, 20); expSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { try { setExposure(seekBar.getProgress()); } catch(RuntimeException e) { } } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { try { setExposure(seekBar.getProgress()); } catch(RuntimeException e) { Toast.makeText(getApplicationContext(), R.string.toast_no_exposure, Toast.LENGTH_SHORT).show(); } } }); } protected void initZoomSeekBar(SeekBar zoomSeek) { switch(themePref) { case 1: setTheme(R.style.HoloDark); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_dark)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_dark)); break; case 2: setTheme(R.style.HoloLight); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_light)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_light)); break; case 3: setTheme(R.style.HoloRed); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_red)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_red)); break; case 4: setTheme(R.style.HoloOrange); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_orange)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_orange)); break; case 5: setTheme(R.style.HoloGreen); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_green)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_green)); break; case 6: setTheme(R.style.HoloPurple); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_purple)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_purple)); break; case 7: setTheme(R.style.HoloBlue); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_blue)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_blue)); break; } zoomSeek.setMax(mirrorView.getZoomMax()); zoomSeek.setProgress(Math.round(zoomPrefF) == -1 ? 0 : Math.round(zoomPrefF)); zoomSeek.setPadding(50, 20, 50, 20); zoomSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { zoomPrefF = seekBar.getProgress(); setZoom(Math.round(zoomPrefF)); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { zoomPrefF = seekBar.getProgress(); setZoom(Math.round(zoomPrefF)); } }); } // TODO - These show<action>Dialog methods could be condensed into one method // or they could be removed in favor of something else private void showWelcomeDialog() { // If first load, display instruction dialog if(initialLoadPref != INFO_DIALOGS) { initialLoadPref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_LOAD, Integer.toString(initialLoadPref)); editor.commit(); //displayDialog(WELCOME_DIALOG); displayCustomDialog(WELCOME_ONE_DIALOG); } } private void showSnapshotDialog() { // If first button press, display instruction dialog if(initialSnapshotPref != INFO_DIALOGS) { initialSnapshotPref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_SNAPSHOT, Integer.toString(initialSnapshotPref)); editor.commit(); displayCustomDialog(SNAPSHOT_DIALOG); } } private void showPhotoBoothDialog() { // If first button press, display instruction dialog if(initialPhotoBoothPref != INFO_DIALOGS) { initialPhotoBoothPref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_PHOTOBOOTH, Integer.toString(initialPhotoBoothPref)); editor.commit(); displayCustomDialog(PHOTOSTRIP_DIALOG); } } private void showPauseDialog() { // If first button press, display instruction dialog if(initialPausePref != INFO_DIALOGS) { initialPausePref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_PAUSE, Integer.toString(initialPausePref)); editor.commit(); displayCustomDialog(PAUSE_DIALOG); } } private void loadCamera() { if(camera == null) { try { camera = Camera.open(currentCameraId); if(isPortrait) camera.setDisplayOrientation(90); else camera.setDisplayOrientation(0); mirrorView.setCamera(camera); Camera.Parameters parameters = camera.getParameters(); isZoomSupported = parameters.isZoomSupported(); if(parameters.getMinExposureCompensation() != 0 || parameters.getMaxExposureCompensation() != 0 ) isExposureSupported = true; if(parameters.getWhiteBalance() != null) isWhiteBalanceSupported = true; } catch(RuntimeException e) { displayDialog(CAMERA_NOT_FOUND); e.printStackTrace(); } if(isPreviewStopped) { mirrorView.startPreview(); isPreviewStopped = false; } } } private void unloadCamera() { if (camera != null) { try { mirrorView.setCamera(null); } catch(RuntimeException e) { Toast.makeText(this, "Error Unloading Camera", Toast.LENGTH_SHORT).show(); } camera.stopPreview(); isPreviewStopped = true; camera.release(); camera = null; } } private void displayDialog(int id) { QustomDialogBuilder builder = new QustomDialogBuilder(this); builder .setTitleColor(themeColor) .setDividerColor(themeColor); DialogManager.buildDialog(this, id, builder); } private void displayCustomDialog(int id) { dialog = new Dialog(this); DialogManager.buildCustomDialog(this, id); } protected void sendBugReport(String subject) { Intent emailIntent = new Intent(android.content.Intent.ACTION_VIEW); emailIntent.setData(Uri.parse("mailto:wckd.dev@gmail.com")); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "" + getResources().getString(R.string.bug_report) + "\n\nStore: " + store + "\nVersion: " + version + "\nBrand: " + android.os.Build.BRAND + "\nManufacturer: " + android.os.Build.MANUFACTURER + "\nModel: " + android.os.Build.MODEL + "\nDevice: " + android.os.Build.DEVICE + "\nCameras: " + numberOfCameras + "\nBack ID: " + backCameraId + "\nFront ID: " + frontCameraId + "\nCurrent ID: " + currentCameraId + "\n" + mirrorView.getDisplayInfo()); startActivity(Intent.createChooser(emailIntent, getResources().getString(R.string.bug_report_send))); MirrorActivity.this.finish(); } protected void setFrame(int position) { ImageView frame = (ImageView) findViewById(R.id.frame_overlay); frame.setImageDrawable(frameMgr.getFrameResId(position)); frameModePref = position; } private void setZoom(int level){ if(isZoomSupported) { mirrorView.zoom(level); } else { Toast.makeText(getApplicationContext(), R.string.toast_no_zoom, Toast.LENGTH_SHORT).show(); } } private void setExposure(int level) throws RuntimeException { try { mirrorView.exposure(level); exposurePref = level; } catch(RuntimeException e) { exposurePref = -999; throw e; } } private void setWhiteBalance(int level) { try { mirrorView.whiteBalance(level); whiteBalancePref = level; // TODO - Why won't this work? App crashes during menu load after icon change // Requesting resource failed because it is too complex /* switch(level) { case 0: menuItemWB.setIcon(R.attr.wbAutoIcon); // drawable.menu_options_white_balance_auto_holo_dark); break; case 1: menuItemWB.setIcon(R.attr.wbDaylightIcon); // drawable.menu_options_white_balance_daylight_holo_dark); break; case 2: menuItemWB.setIcon(R.attr.wbIncanIcon); // drawable.menu_options_white_balance_incandescent_holo_dark); break; case 3: menuItemWB.setIcon(R.attr.wbFluorIcon); // drawable.menu_options_white_balance_fluorescent_holo_dark); break; } */ switch(level) { case 0: if(themePref == 2 || themePref == 4 || themePref == 5 || themePref == 7) menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_auto_holo_light); else menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_auto_holo_dark); break; case 1: if(themePref == 2 || themePref == 4 || themePref == 5 || themePref == 7) menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_daylight_holo_light); else menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_daylight_holo_dark); break; case 2: if(themePref == 2 || themePref == 4 || themePref == 5 || themePref == 7) menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_incandescent_holo_light); else menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_incandescent_holo_dark); break; case 3: if(themePref == 2 || themePref == 4 || themePref == 5 || themePref == 7) menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_fluorescent_holo_light); else menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_fluorescent_holo_dark); break; } } catch(RuntimeException e) { Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); whiteBalancePref = 0; } } @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction() & MotionEvent.ACTION_MASK){ case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); touchState = PRESS; break; case MotionEvent.ACTION_POINTER_DOWN: startDist = spacing(event); if (startDist > minDist) { savedMatrix.set(matrix); midPoint(mid, event); touchState = ZOOM; } break; case MotionEvent.ACTION_UP: if(touchState == PRESS) { float moveDist = spacing(event, start); if(moveDist < minDist) { fullScreenClick(); } } break; case MotionEvent.ACTION_POINTER_UP: if(touchState == ZOOM) { touchState = NONE; } break; case MotionEvent.ACTION_MOVE: if ( (touchState == PRESS && spacing(event, start) > minDist) || touchState == DRAG) { matrix.set(savedMatrix); matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); touchState = DRAG; } else if (touchState == ZOOM) { float nowDist = spacing(event); if (nowDist > minDist) { matrix.set(savedMatrix); float scale = nowDist / startDist; matrix.postScale(scale, scale, mid.x, mid.y); if(nowDist > lastDist) zoomIn(); else zoomOut(); } lastDist = nowDist; } break; } return true; } /** Determine the space between a finger and a saved point */ @SuppressLint("FloatMath") private float spacing(MotionEvent event, PointF point) { float x = event.getX() - point.x; float y = event.getY() - point.y; return FloatMath.sqrt(x * x + y * y); } /** Determine the space between the first two fingers */ @SuppressLint("FloatMath") private float spacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } /** Calculate the mid point of the first two fingers */ private void midPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } private void fullScreenClick() { // Exit fullscreen mode if(isFullscreen) { showWelcomeDialog(); // Show navigation and notification bar getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); getActionBar().show(); // Show action bar isFullscreen = false; mirrorView.isFullscreen = false; } // Enter fullscreen mode else { // Hide notification bar and set navigation bar to low profile getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE); getActionBar().hide(); // Hide action bar isFullscreen = true; mirrorView.isFullscreen = true; } } private void zoomIn() { if(zoomRate == 0f) zoomRate = mirrorView.getZoomMax() * 0.02f; if(zoomPrefF < (mirrorView.getZoomMax() - zoomRate)) { zoomPrefF += zoomRate; setZoom(Math.round(zoomPrefF)); } } private void zoomOut() { if(zoomRate == 0f) zoomRate = mirrorView.getZoomMax() * 0.02f; if(zoomPrefF > (0 + zoomRate)) { zoomPrefF -= zoomRate; setZoom(Math.round(zoomPrefF)); } } }
package com.wrapp.android.webimage; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.widget.ImageView; import java.net.URL; @SuppressWarnings({"UnusedDeclaration"}) public class WebImageView extends ImageView implements ImageRequest.Listener { Handler uiHandler; public WebImageView(Context context) { super(context); initialize(); } public WebImageView(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } public WebImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(); } private void initialize() { uiHandler = new Handler(); } public void setImageUrl(URL imageUrl) { ImageLoader.load(imageUrl, this, false); } public void setImageUrl(URL imageUrl, boolean cacheInMemory) { ImageLoader.load(imageUrl, this, cacheInMemory); } public void onDrawableLoaded(final Drawable drawable) { postToGuiThread(new Runnable() { public void run() { setImageDrawable(drawable); } }); } public void postToGuiThread(Runnable runnable) { uiHandler.post(runnable); } }
package one.kii.kiimate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration @ComponentScan({ "com.sinewang.kiimate.model.core", "one.kii.kiimate.model.core", "com.sinewang.kiimate.status.core", "one.kii.kiimate.status.core"}) @MapperScan({ "com.sinewang.kiimate.model.core", "com.sinewang.kiimate.status.core"}) public class Main { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
package org.apache.jmeter.util; import java.awt.Dimension; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import java.util.MissingResourceException; import java.util.Properties; import java.util.Random; import java.util.ResourceBundle; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.xml.parsers.SAXParserFactory; import org.apache.jmeter.gui.GuiPackage; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.test.UnitTestManager; import org.apache.log.Logger; import org.apache.oro.text.PatternCacheLRU; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.xml.sax.XMLReader; /** * This class contains the static utility methods used by JMeter. * *@author <a href="mailto://stefano@apache.org">Stefano Mazzocchi</a> *@created June 28, 2001 *@version $Revision$ $Date$ */ public class JMeterUtils implements UnitTestManager { private static PatternCacheLRU patternCache = new PatternCacheLRU(1000, new Perl5Compiler()); transient private static Logger log = LoggingManager.getLoggerForClass(); private static final SAXParserFactory xmlFactory; static { SAXParserFactory temp = null; try { temp = SAXParserFactory.newInstance(); } catch (Exception e) { log.error("", e); temp = null; } xmlFactory = temp; } private static Properties appProperties; private static Collection localeChangeListeners = new HashSet(); private static Locale locale; private static ResourceBundle resources; private static ThreadLocal localMatcher = new ThreadLocal() { protected Object initialValue() { return new Perl5Matcher(); } }; //Provide Random numbers to whomever wants one private static Random rand = new Random(); /** * Gets Perl5Matcher for this thread. */ public static Perl5Matcher getMatcher() { return (Perl5Matcher) localMatcher.get(); } /** * This method is used by the init method to load the property file that * may even reside in the user space, or in the classpath under * org.apache.jmeter.jmeter.properties. * *@param file the file to load *@return the Properties from the file */ public static Properties getProperties(String file) { Properties p = new Properties(System.getProperties()); try { File f = new File(file); p.load(new FileInputStream(f)); } catch (Exception e) { try { InputStream is = ClassLoader.getSystemResourceAsStream( "org/apache/jmeter/jmeter.properties"); if (is == null) throw new RuntimeException("Could not read JMeter properties file"); p.load(is); } catch (IOException ex) { // JMeter.fail("Could not read internal resource. " + // "Archive is broken."); } } appProperties = p; LoggingManager.initializeLogging(appProperties); log = LoggingManager.getLoggerForClass(); String loc = appProperties.getProperty("language"); if (loc != null) { setLocale(new Locale(loc, "")); } else { setLocale(Locale.getDefault()); } return p; } public static PatternCacheLRU getPatternCache() { return patternCache; } public void initializeProperties(String file) { System.out.println("Initializing Properties: " + file); getProperties(file); String home = file.substring(0, file.lastIndexOf("/")); home = new File(home + "/..").getAbsolutePath(); System.out.println("Setting JMeter home: " + home); setJMeterHome(home); } public static String[] getSearchPaths() { return new String[] { getJMeterHome() + "/lib/ext" }; } /** * Provide random numbers * @param loc */ public static int getRandomInt(int r) { return rand.nextInt(r); } /** * Changes the current locale: re-reads resource strings and notifies * listeners. * * @author Oliver Rossmueller * @param locale new locale */ public static void setLocale(Locale loc) { locale = loc; resources = ResourceBundle.getBundle( "org.apache.jmeter.resources.messages", locale); notifyLocaleChangeListeners(); } /** * Gets the current locale. * * @author Oliver Rossmueller * @return current locale */ public static Locale getLocale() { return locale; } /** * @author Oliver Rossmueller */ public static void addLocaleChangeListener(LocaleChangeListener listener) { localeChangeListeners.add(listener); } /** * @author Oliver Rossmueller */ public static void removeLocaleChangeListener(LocaleChangeListener listener) { localeChangeListeners.remove(listener); } /** * Notify all listeners interested in locale changes. * * @author Oliver Rossmueller */ private static void notifyLocaleChangeListeners() { LocaleChangeEvent event = new LocaleChangeEvent(JMeterUtils.class, locale); Iterator iterator = localeChangeListeners.iterator(); while (iterator.hasNext()) { LocaleChangeListener listener = (LocaleChangeListener) iterator.next(); listener.localeChanged(event); } } /** * Gets the resource string for this key. * * If the resource is not found, a warning is logged * * @param key the key in the resource file * @return the resource string if the key is found; otherwise, return * "[res_key="+key+"]" */ public static String getResString(String key) { return getResStringDefault(key,"[res_key="+key+"]"); } /** * Gets the resource string for this key. * * If the resource is not found, a warning is logged * * @param key the key in the resource file * @param default - the default value * * @return the resource string if the key is found; * otherwise, return the default * @deprecated Only intended for us in development; use getResStrig(String) normally */ public static String getResString(String key, String defaultValue) { return getResStringDefault(key,defaultValue); } /* * Helper method to do the actual work of fetching resources; * allows getResString(S,S) to be deprecated without affecting getResString(S); */ private static String getResStringDefault(String key, String defaultValue) { if (key == null) { return null; } key = key.replace(' ', '_'); key = key.toLowerCase(); String resString = null; try { resString = resources.getString(key); } catch (MissingResourceException mre) { log.warn("ERROR! Resource string not found: [" + key + "]"); resString = defaultValue; } return resString; } /** * This gets the currently defined appProperties. It can only be called * after the {@link #getProperties(String)} method is called. * * @return The JMeterProperties value */ public static Properties getJMeterProperties() { return appProperties; } /** * This looks for the requested image in the classpath under * org.apache.jmeter.images. <name> * * @param name Description of Parameter * @return The Image value */ public static ImageIcon getImage(String name) { try { return new ImageIcon( JMeterUtils.class.getClassLoader().getResource( "org/apache/jmeter/images/" + name.trim())); } catch (NullPointerException e) { log.warn("no icon for " + name); return null; } } public static String getResourceFileAsText(String name) { try { String lineEnd = System.getProperty("line.separator"); BufferedReader fileReader = new BufferedReader( new InputStreamReader( JMeterUtils.class.getClassLoader().getResourceAsStream( name))); StringBuffer text = new StringBuffer(); String line = "NOTNULL"; while (line != null) { line = fileReader.readLine(); if (line != null) { text.append(line); text.append(lineEnd); } } return text.toString(); } catch (IOException e) { return ""; } } /** * Creates the vector of Timers plugins. * *@param properties Description of Parameter *@return The Timers value */ public static Vector getTimers(Properties properties) { return instantiate( getVector(properties, "timer."), "org.apache.jmeter.timers.Timer"); } /** * Creates the vector of visualizer plugins. * *@param properties Description of Parameter *@return The Visualizers value */ public static Vector getVisualizers(Properties properties) { return instantiate( getVector(properties, "visualizer."), "org.apache.jmeter.visualizers.Visualizer"); } /** * Creates a vector of SampleController plugins. * *@param properties The properties with information about the samplers *@return The Controllers value */ public static Vector getControllers(Properties properties) { String name = "controller."; Vector v = new Vector(); Enumeration names = properties.keys(); while (names.hasMoreElements()) { String prop = (String) names.nextElement(); if (prop.startsWith(name)) { Object o = instantiate( properties.getProperty(prop), "org.apache.jmeter.control.SamplerController"); v.addElement(o); } } return v; } /** * Create a string of class names for a particular SamplerController * *@param properties The properties with info about the samples. *@param name The name of the sampler controller. *@return The TestSamples value */ public static String[] getTestSamples(Properties properties, String name) { return (String[]) getVector(properties, name + ".testsample").toArray( new String[0]); } /** * Create an instance of an org.xml.sax.Parser * * @deprecated use the plain version instead. We are using JAXP! *@param properties The properties file containing the parser's class name *@return The XMLParser value */ public static XMLReader getXMLParser(Properties properties) { return getXMLParser(); } /** * Create an instance of an org.xml.sax.Parser based on the default props. * *@return The XMLParser value */ public static XMLReader getXMLParser() { XMLReader reader = null; try { reader = (XMLReader) instantiate(getPropDefault("xml.parser", "org.apache.xerces.parsers.SAXParser"), "org.xml.sax.XMLReader"); //reader = xmlFactory.newSAXParser().getXMLReader(); } catch (Exception e) { reader = (XMLReader) instantiate(getPropDefault("xml.parser", "org.apache.xerces.parsers.SAXParser"), "org.xml.sax.XMLReader"); } return reader; } /** * Creates the vector of alias strings. * *@param properties Description of Parameter *@return The Alias value */ public static Hashtable getAlias(Properties properties) { return getHashtable(properties, "alias."); } /** * Creates a vector of strings for all the properties that start with a * common prefix. * * @param properties Description of Parameter * @param name Description of Parameter * @return The Vector value */ public static Vector getVector(Properties properties, String name) { Vector v = new Vector(); Enumeration names = properties.keys(); while (names.hasMoreElements()) { String prop = (String) names.nextElement(); if (prop.startsWith(name)) { v.addElement(properties.getProperty(prop)); } } return v; } /** * Creates a table of strings for all the properties that start with a * common prefix. * * @param properties Description of Parameter * @param name Description of Parameter * @return The Hashtable value */ public static Hashtable getHashtable(Properties properties, String name) { Hashtable t = new Hashtable(); Enumeration names = properties.keys(); while (names.hasMoreElements()) { String prop = (String) names.nextElement(); if (prop.startsWith(name)) { t.put( prop.substring(name.length()), properties.getProperty(prop)); } } return t; } /** * Get a int value with default if not present. * *@param propName the name of the property. *@param defaultVal the default value. *@return The PropDefault value */ public static int getPropDefault(String propName, int defaultVal) { int ans; try { ans = (Integer .valueOf( appProperties .getProperty(propName, Integer.toString(defaultVal)) .trim())) .intValue(); } catch (Exception e) { ans = defaultVal; } return ans; } /** * Get a boolean value with default if not present. * *@param propName the name of the property. *@param defaultVal the default value. *@return The PropDefault value */ public static boolean getPropDefault(String propName, boolean defaultVal) { boolean ans; try { String strVal = appProperties .getProperty(propName, (new Boolean(defaultVal)).toString()) .trim(); if (strVal.equalsIgnoreCase("true") || strVal.equalsIgnoreCase("t")) { ans = true; } else if ( strVal.equalsIgnoreCase("false") || strVal.equalsIgnoreCase("f")) { ans = false; } else { ans = ((Integer.valueOf(strVal)).intValue() == 1); } } catch (Exception e) { ans = defaultVal; } return ans; } /** * Get a long value with default if not present. * *@param propName the name of the property. *@param defaultVal the default value. *@return The PropDefault value */ public static long getPropDefault(String propName, long defaultVal) { long ans; try { ans = (Long .valueOf( appProperties .getProperty(propName, Long.toString(defaultVal)) .trim())) .longValue(); } catch (Exception e) { ans = defaultVal; } return ans; } /** * Get a String value with default if not present. * *@param propName the name of the property. *@param defaultVal the default value. *@return The PropDefault value */ public static String getPropDefault(String propName, String defaultVal) { String ans; try { ans = appProperties.getProperty(propName, defaultVal).trim(); } catch (Exception e) { ans = defaultVal; } return ans; } /** * Sets the selection of the JComboBox to the Object 'name' from the list * in namVec. */ public static void selJComboBoxItem( Properties properties, JComboBox combo, Vector namVec, String name) { int idx = namVec.indexOf(name); combo.setSelectedIndex(idx); // Redisplay. combo.updateUI(); return; } /** * Instatiate an object and guarantee its class. * *@param className The name of the class to instantiate. *@param impls The name of the class it subclases. *@return Description of the Returned Value */ public static Object instantiate(String className, String impls) { if (className != null) { className.trim(); } if (impls != null) { // FIXME: Shouldn't this be impls.trim()? className.trim(); } try { Class c = Class.forName(impls); try { Class o = Class.forName(className); Object res = o.newInstance(); if (c.isInstance(res)) { return res; } else { throw new IllegalArgumentException( className + " is not an instance of " + impls); } } catch (ClassNotFoundException e) { log.error( "Error loading class " + className + ": class is not found"); } catch (IllegalAccessException e) { log.error( "Error loading class " + className + ": does not have access"); } catch (InstantiationException e) { log.error( "Error loading class " + className + ": could not instantiate"); } catch (NoClassDefFoundError e) { log.error( "Error loading class " + className + ": couldn't find class " + e.getMessage()); } } catch (ClassNotFoundException e) { log.error("Error loading class " + impls + ": was not found."); } return null; } /** * Instantiate a vector of classes * *@param v Description of Parameter *@param className Description of Parameter *@return Description of the Returned Value */ public static Vector instantiate(Vector v, String className) { Vector i = new Vector(); try { Class c = Class.forName(className); Enumeration elements = v.elements(); while (elements.hasMoreElements()) { String name = (String) elements.nextElement(); try { Object o = Class.forName(name).newInstance(); if (c.isInstance(o)) { i.addElement(o); } } catch (ClassNotFoundException e) { log.error( "Error loading class " + name + ": class is not found"); } catch (IllegalAccessException e) { log.error( "Error loading class " + name + ": does not have access"); } catch (InstantiationException e) { log.error( "Error loading class " + name + ": could not instantiate"); } catch (NoClassDefFoundError e) { log.error( "Error loading class " + name + ": couldn't find class " + e.getMessage()); } } } catch (ClassNotFoundException e) { log.error( "Error loading class " + className + ": class is not found"); } return i; } /** * Tokenize a string into a vector of tokens * *@param string Description of Parameter *@param separator Description of Parameter *@return Description of the Returned Value */ public static Vector tokenize(String string, String separator) { Vector v = new Vector(); StringTokenizer s = new StringTokenizer(string, separator); while (s.hasMoreTokens()) { v.addElement(s.nextToken()); } return v; } /** * Create a button with the netscape style * *@param name Description of Parameter *@param listener Description of Parameter *@return Description of the Returned Value */ public static JButton createButton(String name, ActionListener listener) { JButton button = new JButton(getImage(name + ".on.gif")); button.setDisabledIcon(getImage(name + ".off.gif")); button.setRolloverIcon(getImage(name + ".over.gif")); button.setPressedIcon(getImage(name + ".down.gif")); button.setActionCommand(name); button.addActionListener(listener); button.setRolloverEnabled(true); button.setFocusPainted(false); button.setBorderPainted(false); button.setOpaque(false); button.setPreferredSize(new Dimension(24, 24)); return button; } /** * Create a button with the netscape style * *@param name Description of Parameter *@param listener Description of Parameter *@return Description of the Returned Value */ public static JButton createSimpleButton( String name, ActionListener listener) { JButton button = new JButton(getImage(name + ".gif")); button.setActionCommand(name); button.addActionListener(listener); button.setFocusPainted(false); button.setBorderPainted(false); button.setOpaque(false); button.setPreferredSize(new Dimension(25, 25)); return button; } /** * Takes a String and a tokenizer character, and returns a new array of * strings of the string split by the tokenizer character. * * @param splittee String to be split * @param splitChar Character to split the string on * @param def Default value to place between two split chars that * have nothing between them * @return Array of all the tokens. */ public static String[] split(String splittee, String splitChar, String def) { if (splittee == null || splitChar == null) { return new String[0]; } int spot; while ((spot = splittee.indexOf(splitChar + splitChar)) != -1) { splittee = splittee.substring(0, spot + splitChar.length()) + def + splittee.substring( spot + 1 * splitChar.length(), splittee.length()); } Vector returns = new Vector(); int start = 0; int length = splittee.length(); spot = 0; while (start < length && (spot = splittee.indexOf(splitChar, start)) > -1) { if (spot > 0) { returns.addElement(splittee.substring(start, spot)); } start = spot + splitChar.length(); } if (start < length) { returns.add(splittee.substring(start)); } String[] values = new String[returns.size()]; returns.copyInto(values); return values; } /** * Report an error through a dialog box. * *@param errorMsg the error message. */ public static void reportErrorToUser(String errorMsg) { if (errorMsg == null) { errorMsg = "Unknown error - see log file"; log.warn("Unknown error", new Throwable("errorMsg == null")); } JOptionPane.showMessageDialog( GuiPackage.getInstance().getMainFrame(), errorMsg, "Error", JOptionPane.ERROR_MESSAGE); } /** * Finds a string in an array of strings and returns the * *@param array Array of strings. *@param value String to compare to array values. *@return Index of value in array, or -1 if not in array. */ public static int findInArray(String[] array, String value) { int count = -1; int index = -1; if (array != null && value != null) { while (++count < array.length) { if (array[count] != null && array[count].equals(value)) { index = count; break; } } } return index; } /** * Takes an array of strings and a tokenizer character, and returns a * string of all the strings concatenated with the tokenizer string in * between each one. * * @param splittee Array of Objects to be concatenated. * @param splitChar Object to unsplit the strings with. * @return Array of all the tokens. */ public static String unsplit(Object[] splittee, Object splitChar) { StringBuffer retVal = new StringBuffer(""); int count = -1; while (++count < splittee.length) { if (splittee[count] != null) { retVal.append(splittee[count]); } if (count + 1 < splittee.length && splittee[count + 1] != null) { retVal.append(splitChar); } } return retVal.toString(); } // End Method /** * Takes an array of strings and a tokenizer character, and returns a * string of all the strings concatenated with the tokenizer string in * between each one. * * @param splittee Array of Objects to be concatenated. * @param splitChar Object to unsplit the strings with. * @param def Default value to replace null values in array. * @return Array of all the tokens. */ public static String unsplit( Object[] splittee, Object splitChar, String def) { StringBuffer retVal = new StringBuffer(""); int count = -1; while (++count < splittee.length) { if (splittee[count] != null) { retVal.append(splittee[count]); } else { retVal.append(def); } if (count + 1 < splittee.length) { retVal.append(splitChar); } } return retVal.toString(); } // End Method public static String getJMeterHome() { return jmDir; } public static void setJMeterHome(String home) { jmDir = home; } private static String jmDir; public static final String JMETER = "jmeter"; public static final String ENGINE = "jmeter.engine"; public static final String ELEMENTS = "jmeter.elements"; public static final String GUI = "jmeter.gui"; public static final String UTIL = "jmeter.util"; public static final String CLASSFINDER = "jmeter.util.classfinder"; public static final String TEST = "jmeter.test"; public static final String HTTP = "jmeter.protocol.http"; public static final String JDBC = "jmeter.protocol.jdbc"; public static final String FTP = "jmeter.protocol.ftp"; public static final String JAVA = "jmeter.protocol.java"; public static final String PROPERTIES = "jmeter.elements.properties"; /** * Gets the JMeter Version. * @returns the JMeter version. */ public static String getJMeterVersion() { return JMeterVersion.VERSION; } }
package de.wak_sh.client.backend; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Environment; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.webkit.MimeTypeMap; import android.widget.Toast; import de.wak_sh.client.R; import de.wak_sh.client.SettingsActivity; import de.wak_sh.client.model.FileLink; import de.wak_sh.client.service.JsoupFileService; public class FileDownloader { private Context mContext; private NotificationCompat.Builder mBuilder; private NotificationManager mManager; private int id; public FileDownloader(Context context) { this.mContext = context; } public void download(final FileLink fileLink) { new Thread(new Runnable() { @Override public void run() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(mContext); String path = prefs.getString( SettingsActivity.PREF_STORAGE_LOCATION, Environment.getExternalStorageDirectory() + File.separator + "Download") + File.separator + fileLink.getName(); buildNotification(fileLink.getName()); try { File file = new File(path.replaceAll("\n", "")); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); InputStream is = JsoupFileService.getInstance() .getFileStream(fileLink); BufferedInputStream bis = new BufferedInputStream(is); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffer = new byte[1024]; while (bis.read(buffer) != -1) { bos.write(buffer); } bis.close(); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(mContext, "Möglicherweise ist der Downloadpfad ungültig", Toast.LENGTH_LONG).show(); ; killNotification(null, false); return; } killNotification(path, true); } }).start(); } public void download(final String url, final String filename) { new Thread(new Runnable() { @Override public void run() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(mContext); String path = prefs.getString( SettingsActivity.PREF_STORAGE_LOCATION, Environment.getExternalStorageDirectory() + File.separator + "Download") + File.separator + filename; buildNotification(filename); try { File file = new File(path.replaceAll("\n", "")); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); InputStream is = JsoupFileService.getInstance() .getFileStream(url); BufferedInputStream bis = new BufferedInputStream(is); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffer = new byte[1024]; while (bis.read(buffer) != -1) { bos.write(buffer); } bis.close(); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); killNotification(null, false); return; } killNotification(path, true); } }).start(); } private void buildNotification(String filename) { id = (int) System.currentTimeMillis(); mManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(mContext); mBuilder.setContentTitle(filename); mBuilder.setContentText(mContext.getString(R.string.download)); mBuilder.setSmallIcon(R.drawable.download_animation); mBuilder.setProgress(0, 0, true); mManager.notify(id, mBuilder.build()); } private void killNotification(String path, boolean result) { mBuilder.setAutoCancel(true); mBuilder.setProgress(0, 0, false); if (result) { String extension = MimeTypeMap.getFileExtensionFromUrl(path); String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension( extension); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(path)), mime); PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); mBuilder.setContentText(mContext .getString(R.string.download_complete)); mBuilder.setSmallIcon(R.drawable.ic_menu_goto); mBuilder.setContentIntent(pendingIntent); } else { mBuilder.setContentText(mContext .getString(R.string.download_incomplete)); mBuilder.setSmallIcon(R.drawable.ic_menu_close_clear_cancel); } mManager.notify(id, mBuilder.build()); } }
package edu.cmu.minorthird.text; import edu.cmu.minorthird.text.gui.*; import edu.cmu.minorthird.util.gui.*; import edu.cmu.minorthird.util.*; import java.io.*; import java.util.*; import org.apache.log4j.Logger; /** Maintains assertions about 'types' and 'properties' of * contiguous Spans of these TextToken's. * * @author William Cohen */ public class BasicTextLabels implements MutableTextLabels, Serializable, Visible, Saveable { static private final long serialVersionUID = 1; private final int CURRENT_VERSION_NUMBER = 1; private static Logger log = Logger.getLogger(BasicTextLabels.class); private static final Set EMPTY_SET = new HashSet(); private Map textTokenPropertyMap = new HashMap(); private Set textTokenPropertySet = new HashSet(); private Map spanPropertyMap = new HashMap(); private Map spansWithSomePropertyByDocId = new HashMap(); private Set spanPropertySet = new HashSet(); private Map typeDocumentSetMap = new TreeMap(); private Map closureDocumentSetMap = new HashMap(); private Map textTokenDictMap = new HashMap(); private Set annotatedBySet = new HashSet(); private Map detailMap = new TreeMap(); private AnnotatorLoader loader = new DefaultAnnotatorLoader(); // for statementType = TRIE public Trie trie = null; // don't serialize this, it's too big! transient private TextBase textBase = null; public BasicTextLabels() { this.textBase = null; } public BasicTextLabels(TextBase textBase) { this.textBase = textBase; } /** Import the labels from the parent TextBase */ public BasicTextLabels(SpanTypeTextBase base, TextLabels parentLabels) { this.textBase = base; //labels = new BasicTextLabels(base); Span.Looper parentIterator = parentLabels.instanceIterator(base.spanType); String prevDocId = ""; int docNum = 0; //Reiterate over the spans with spanType in the parent labels while(parentIterator.hasNext()) { Span parentSpan = parentIterator.nextSpan(); String docID = parentSpan.getDocumentId(); if(docID.equals(prevDocId)) docNum++; else docNum=0; Span childDocSpan = base.documentSpan("childTB" + docNum + "-" + docID); //The matching span in the child textbase prevDocId = docID; int childDocStartIndex = parentSpan.getLoTextToken(); Set types = parentLabels.getTypes(); Iterator typeIterator = types.iterator(); //Iterate over span types in the parent textBase while(typeIterator.hasNext()) { String type = (String)typeIterator.next(); Set spansWithType = parentLabels.getTypeSet(type, docID); Iterator spanIterator = spansWithType.iterator(); //Iterate over the spans with a type while(spanIterator.hasNext()) { Span s = (Span)spanIterator.next(); //See if the parent span conains the span if(parentSpan.contains(s) && childDocSpan.size()>=s.getLoTextToken()-childDocStartIndex+s.size() ) { //find the matching span in the child doc span and add it to the child Labels Span subSpan = childDocSpan.subSpan(s.getLoTextToken()-childDocStartIndex, s.size()); addToType(subSpan, type); } } closeTypeInside(type, childDocSpan); } } } public TextBase getTextBase() { return textBase; } public boolean hasDictionary(String dictionary) { return textTokenDictMap.containsKey(dictionary); } public void setTextBase(TextBase textBase) { if (this.textBase!=null) throw new IllegalStateException("textBase already set"); this.textBase = textBase; } /** A convenience method which creates empty labels * containing a single string. */ public BasicTextLabels(String s) { this(new BasicTextBase()); getTextBase().loadDocument("nullId",s); } // maintain annotation history public boolean isAnnotatedBy(String s) { return annotatedBySet.contains(s); } public void setAnnotatedBy(String s) { annotatedBySet.add(s); } public void setAnnotatorLoader(AnnotatorLoader newLoader) { this.loader=newLoader; } public AnnotatorLoader getAnnotatorLoader() { return loader; } public void require(String annotationType,String fileToLoad) { require(annotationType,fileToLoad,loader); } public void require(String annotationType,String fileToLoad,AnnotatorLoader theLoader) { doRequire(this,annotationType,fileToLoad,theLoader); } static public void doRequire(MonotonicTextLabels labels,String annotationType,String fileToLoad,AnnotatorLoader theLoader ) { if (annotationType!=null && !labels.isAnnotatedBy(annotationType)) { if (theLoader==null) theLoader = labels.getAnnotatorLoader(); // use current loader as default Annotator annotator = theLoader.findAnnotator(annotationType,fileToLoad); if (annotator==null) throw new IllegalArgumentException("can't find annotator "+annotationType); // annotate using theLoader for any recursively-required annotations, AnnotatorLoader savedLoader = labels.getAnnotatorLoader(); labels.setAnnotatorLoader(theLoader); annotator.annotate(labels); labels.setAnnotatorLoader(savedLoader); // restore original loader // check that the annotationType is provided if (!labels.isAnnotatedBy(annotationType)) throw new IllegalStateException("didn't provide annotation type: "+annotationType); } } public void annotateWith(String annotationType, String fileToLoad) { annotateWith(this, annotationType, fileToLoad); } static public void annotateWith(MonotonicTextLabels labels, String annotationType, String fileToLoad) { AnnotatorLoader theLoader = labels.getAnnotatorLoader(); Annotator annotator = theLoader.findAnnotator(annotationType, fileToLoad); annotator.annotate(labels); } // maintain dictionaries /** Returns true if the value of the Token is in the named dictionary. */ public boolean inDict(Token token,String dictName) { if (token.getValue()==null) throw new IllegalArgumentException("null token.value?"); Set set = (Set)textTokenDictMap.get(dictName); if (set==null) throw new IllegalArgumentException("undefined dictionary "+dictName); return set.contains(token.getValue()); } /** Associate a dictionary with this labeling. */ public void defineDictionary(String dictName, Set dictionary) { textTokenDictMap.put(dictName,dictionary); if (log.isDebugEnabled()) log.debug("added to token dictionary: " + dictName + " values " + ((Set)textTokenDictMap.get(dictName))); } /** Associate a dictionary from this file */ public void defineDictionary(String dictName, ArrayList fileNames, boolean ignoreCase) { Set wordSet = new HashSet(); AnnotatorLoader theLoader = this.getAnnotatorLoader(); Tokenizer tok = new Tokenizer(); String[] currentEntryTokens; for(int i=0; i<fileNames.size(); i++) { String fileName = (String)fileNames.get(i); InputStream stream = theLoader.findFileResource(fileName); try { LineNumberReader bReader = new LineNumberReader(new BufferedReader(new InputStreamReader(stream))); String s = null; while ((s = bReader.readLine()) != null) { s = s.trim(); // remove trailing blanks // Split the entry into tokens and add it to the set only if there is a single token. // Otherwise give an warning and ignore the entry. currentEntryTokens = tok.splitIntoTokens(s); if (currentEntryTokens.length > 1) { log.warn("Ignoring entry: \'" + s + "\' because it contains more than 1 token. Use a Trie to match against sequences of tokens."); } else { if (ignoreCase) s = s.toLowerCase(); wordSet.add( s ); } } bReader.close(); } catch (IOException ioe) { //parseError("Error when reading " + fileName.toString() + ": " + ioe); ioe.printStackTrace(); } } defineDictionary(dictName, wordSet); } /** Return a trie if defined */ public Trie getTrie() { return trie; } /** Define a trie */ public void defineTrie(ArrayList phraseList) { trie = new Trie(); BasicTextBase tokenizerBase = new BasicTextBase(); for (int i=0; i<phraseList.size(); i++) { String[] toks = tokenizerBase.splitIntoTokens((String)phraseList.get(i)); if (toks.length<=2 || !"\"".equals(toks[0]) || !"\"".equals(toks[toks.length-1])) { trie.addWords( "phrase#"+i, toks ); } else { StringBuffer defFile = new StringBuffer(""); for (int j=1; j<toks.length-1; j++) { defFile.append(toks[j]); } AnnotatorLoader theLoader = this.getAnnotatorLoader(); InputStream stream = theLoader.findFileResource(defFile.toString()); try { LineNumberReader bReader = new LineNumberReader(new BufferedReader(new InputStreamReader(stream))); String s = null; int line=0; while ((s = bReader.readLine()) != null) { line++; String[] words = tokenizerBase.splitIntoTokens(s); trie.addWords(defFile+".line."+line, words); } bReader.close(); } catch (IOException ioe) { //parseError("Error when reading " + defFile.toString() + ": " + ioe); ioe.printStackTrace(); } } // file load } // each phrase } // maintain assertions about properties of Tokens /** Get the property value associated with this Token. */ public String getProperty(Token token,String prop) { return (String)getPropMap(token).get(prop); } /** Get a set of all properties. */ public Set getTokenProperties() { return textTokenPropertySet; } /** Assert that Token textToken has the given value of the given property */ public void setProperty(Token textToken,String prop,String value) { getPropMap(textToken).put(prop,value); textTokenPropertySet.add(prop); } /** Assert that Token textToken has the given value of the given property, * and associate that with some detailed information */ public void setProperty(Token textToken,String prop,String value,Details details) { setProperty(textToken,prop,value); if (details!=null) { detailMap.put(new TokenPropKey(textToken,prop), details); } } private TreeMap getPropMap(Token textToken) { TreeMap map = (TreeMap)textTokenPropertyMap.get(textToken); if (map==null) { map = new TreeMap(); textTokenPropertyMap.put(textToken,map); } return map; } // maintain assertions about properties of spans /** Get the property value associated with this Span. */ public String getProperty(Span span,String prop) { return (String)getPropMap(span).get(prop); } /** Get a set of all properties. */ public Set getSpanProperties() { return spanPropertySet; } /** Find all spans that have a non-null value for this property. */ public Span.Looper getSpansWithProperty(String prop) { TreeSet accum = new TreeSet(); for (Iterator i=spanPropertyMap.keySet().iterator(); i.hasNext(); ) { Span s = (Span)i.next(); if (getProperty(s,prop)!=null) { accum.add(s); } } return new BasicSpanLooper(accum); } /** Find all spans that have a non-null value for this property. */ public Span.Looper getSpansWithProperty(String prop,String id) { TreeSet set = (TreeSet)spansWithSomePropertyByDocId.get(id); if (set==null) return new BasicSpanLooper(Collections.EMPTY_SET); else { TreeSet accum = new TreeSet(); for (Iterator i=set.iterator(); i.hasNext(); ) { Span s = (Span)i.next(); if (getProperty(s,prop)!=null) { accum.add(s); } } return new BasicSpanLooper(accum); } } /** Assert that Span span has the given value of the given property */ public void setProperty(Span span,String prop,String value) { getPropMap(span).put(prop,value); spanPropertySet.add(prop); TreeSet set = (TreeSet)spansWithSomePropertyByDocId.get(span.getDocumentId()); if (set==null) spansWithSomePropertyByDocId.put(span.getDocumentId(),(set=new TreeSet())); set.add(span); } public void setProperty(Span span,String prop,String value,Details details) { setProperty(span,prop,value); if (details!=null) { detailMap.put(new SpanPropKey(span,prop), details); } } private TreeMap getPropMap(Span span) { TreeMap map = (TreeMap)spanPropertyMap.get(span); if (map==null) { map = new TreeMap(); spanPropertyMap.put(span,map); } return map; } // maintain assertions about types of Spans public boolean hasType(Span span,String type) { return getTypeSet(type,span.getDocumentId()).contains(span); } public void addToType(Span span,String type) { if (type==null) throw new IllegalArgumentException("null type added"); lookupTypeSet(type,span.getDocumentId()).add(span); } public void addToType(Span span,String type,Details details) { addToType(span,type); if (details!=null) { detailMap.put(new SpanTypeKey(span,type), details); } } public Set getTypes() { return typeDocumentSetMap.keySet(); } public boolean isType(String type) { return typeDocumentSetMap.get(type)!=null; } public void declareType(String type) { //System.out.println("BasicTextLabels: declareType: "+type); if (type==null) throw new IllegalArgumentException("null type declared"); if (!isType(type)) typeDocumentSetMap.put(type, new TreeMap()); } public Span.Looper instanceIterator(String type) { return new MyNestedSpanLooper(type,false); } public Span.Looper instanceIterator(String type,String documentId) { if (documentId!=null) return new BasicSpanLooper( getTypeSet(type,documentId) ); else return instanceIterator(type); } public void defineTypeInside(String type,Span s,Span.Looper i) { if (type==null || s.getDocumentId()==null) throw new IllegalArgumentException("null type defined"); //System.out.println("BTE type: "+type+" documentId: "+s.getDocumentId()); Set set = lookupTypeSet(type,s.getDocumentId()); // remove all spans currently inside set for (Iterator j=set.iterator(); j.hasNext(); ) { Span t = (Span)j.next(); if (s.contains(t)) j.remove(); } // add spans from i to set while (i.hasNext()) set.add( i.nextSpan() ); // close the type closeTypeInside(type,s); } public Details getDetails(Span span,String type) { SpanTypeKey key = new SpanTypeKey(span,type); Details details = (Details)detailMap.get(key); if (details!=null) return details; else return hasType(span,type) ? Details.DEFAULT : null; } // get the set of spans with a given type in the given document // so that it can be modified protected Set lookupTypeSet(String type,String documentId) { if (type==null || documentId==null) throw new IllegalArgumentException("null type?"); TreeMap documentsWithType = (TreeMap)typeDocumentSetMap.get(type); if (documentsWithType==null) { typeDocumentSetMap.put( type, (documentsWithType = new TreeMap()) ); } //System.out.println("BTE type: "+type+" documentId: "+documentId+" documentsWithType:" + documentsWithType); TreeSet set = (TreeSet)documentsWithType.get(documentId); if (set==null) { documentsWithType.put( documentId, (set = new TreeSet()) ); } return set; } // get the set of spans with a given type in the given document w/o changing it public Set getTypeSet(String type,String documentId) { if (type==null || documentId==null) throw new IllegalArgumentException("null type?"); TreeMap documentsWithType = (TreeMap)typeDocumentSetMap.get(type); if (documentsWithType==null) return Collections.EMPTY_SET; TreeSet set = (TreeSet)documentsWithType.get(documentId); if (set==null) return Collections.EMPTY_SET; return set; } private class ObjectStringKey implements Comparable { Comparable obj; String str; public ObjectStringKey(Comparable o,String s) { this.obj = o; this.str=s; } public int compareTo(Object other) { ObjectStringKey b = (ObjectStringKey)other; String bn = b.obj.getClass().toString(); int tmp = obj.getClass().toString().compareTo(bn); if (tmp!=0) return tmp; tmp = obj.compareTo(b.obj); if (tmp!=0) return tmp; return str.compareTo(b.str); } } private class SpanTypeKey extends ObjectStringKey { public SpanTypeKey(Span span,String type) { super(span,"type:"+type); } } private class SpanPropKey extends ObjectStringKey { public SpanPropKey(Span span,String prop) { super(span,"prop:"+prop); } } private class TokenPropKey extends ObjectStringKey { public TokenPropKey(Token token,String prop) { super(token.getValue(),prop); } } // maintain assertions about where the closed world assumption holds public Span.Looper closureIterator(String type) { return new MyNestedSpanLooper(type,true); } public Span.Looper closureIterator(String type,String documentId) { if (documentId!=null) return new BasicSpanLooper(getClosureSet(type,documentId).iterator()); else return closureIterator(type); } public void closeTypeInside(String type,Span s) { getClosureSet(type,s.getDocumentId()).add(s); } /** * get the set of spans with a given type in the given document */ private Set getClosureSet(String type,String documentId) { TreeMap documentsWithClosure = (TreeMap)closureDocumentSetMap.get(type); if (documentsWithClosure==null) { closureDocumentSetMap.put( type, (documentsWithClosure = new TreeMap()) ); } TreeSet set = (TreeSet)documentsWithClosure.get(documentId); if (set==null) { documentsWithClosure.put( documentId, (set = new TreeSet()) ); } return set; } /** iterate over all spans of a given type */ private class MyNestedSpanLooper implements Span.Looper { private Iterator documentIterator; private Iterator spanIterator; private Span nextSpan; private int estimatedSize; // private boolean getClosures; // if false, get documents public MyNestedSpanLooper(String type,boolean getClosures) { //System.out.println("building MyNestedSpanLooper for "+type+": "+typeDocumentSetMap); Map documentMap = (Map) (getClosures? closureDocumentSetMap.get(type) : typeDocumentSetMap.get(type)); if (documentMap==null) { nextSpan = null; estimatedSize = 0; } else { //iterator over the documents in the map documentIterator = documentMap.entrySet().iterator(); estimatedSize = documentMap.entrySet().size(); spanIterator = null; advance(); } } /** * @return Number of documents with the given type */ public int estimatedSize() { return estimatedSize; } public boolean hasNext() { return nextSpan!=null; } public void remove() { throw new UnsupportedOperationException("can't remove"); } public Object next() { Span result = nextSpan; advance(); return result; } public Span nextSpan() { return (Span)next(); } private void advance() { if (spanIterator!=null && spanIterator.hasNext()) { // get next span in the current document nextSpan = (Span)spanIterator.next(); } else if (documentIterator.hasNext()) { // move to the next document Map.Entry entry = (Map.Entry)documentIterator.next(); spanIterator = ((TreeSet)entry.getValue()).iterator(); advance(); } else { // nothing found nextSpan = null; } } } public String toString() { return "[BasicTextLabels "+typeDocumentSetMap+"]"; } /** Dump of all strings that have textTokenuence with the given property */ public String showTokenProp(TextBase base,String prop) { StringBuffer buf = new StringBuffer(); for (Span.Looper i = base.documentSpanIterator(); i.hasNext(); ) { Span span = i.nextSpan(); for (int j=0; j<span.size(); j++) { Token textToken = span.getToken(j); if (j>0) buf.append(" "); buf.append( textToken.getValue() ); String val = getProperty(textToken,prop); if (val!=null) { buf.append(":"+val); } } buf.append("\n"); } return buf.toString(); } public Viewer toGUI() { return new ZoomingTextLabelsViewer(this); } // Implement Saveable interface. static private final String FORMAT_NAME = "Minorthird TextLabels"; public String[] getFormatNames() { return new String[] {FORMAT_NAME}; } public String getExtensionFor(String s) { return ".labels"; } public void saveAs(File file,String format) throws IOException { if (!format.equals(FORMAT_NAME)) throw new IllegalArgumentException("illegal format "+format); new TextLabelsLoader().saveTypesAsOps(this,file); } public Object restore(File file) throws IOException { throw new UnsupportedOperationException("Cannot load TextLabels object"); } }
package edu.jhu.thrax.hadoop.jobs; import java.io.IOException; import java.util.ArrayList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer; import edu.jhu.thrax.extraction.Labeling; import edu.jhu.thrax.util.FormatUtils; import edu.jhu.thrax.util.Vocabulary; public class VocabularyJob extends ThraxJob { public VocabularyJob() {} public Job getJob(Configuration conf) throws IOException { Job job = new Job(conf, "vocabulary"); job.setJarByClass(VocabularyJob.class); job.setMapperClass(VocabularyJob.Map.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(VocabularyJob.Reduce.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(Text.class); job.setSortComparatorClass(Text.Comparator.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file"))); int maxSplitSize = conf.getInt("thrax.max-split-size", 0); if (maxSplitSize != 0) FileInputFormat.setMaxInputSplitSize(job, maxSplitSize); FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + "vocabulary")); job.setNumReduceTasks(1); return job; } public String getOutputSuffix() { return "vocabulary"; } @Override public String getName() { return "vocabulary"; } private static class Map extends Mapper<LongWritable, Text, Text, IntWritable> { private static final IntWritable ONE = new IntWritable(1); private boolean sourceParsed; private boolean targetParsed; private Labeling labeling; protected void setup(Context context) { Configuration conf = context.getConfiguration(); sourceParsed = conf.getBoolean("thrax.source-is-parsed", false); targetParsed = conf.getBoolean("thrax.target-is-parsed", false); if (conf.get("thrax.grammar", "hiero").equalsIgnoreCase("samt")) { labeling = Labeling.SYNTAX; } else if (conf.get("thrax.grammar", "hiero").equalsIgnoreCase("manual")) { labeling = Labeling.MANUAL; } else { labeling = Labeling.HIERO; } } protected void map(LongWritable key, Text input, Context context) throws IOException, InterruptedException { String[] parts = FormatUtils.P_DELIM.split(input.toString()); if (parts.length < 3) return; if (sourceParsed) extractTokensFromParsed(parts[0], (labeling != Labeling.SYNTAX), context); else extractTokens(parts[0], context); if (targetParsed) extractTokensFromParsed(parts[1], (labeling != Labeling.SYNTAX), context); else extractTokens(parts[1], context); if (labeling == Labeling.MANUAL && parts.length > 3) { String[] labels = FormatUtils.P_SPACE.split(parts[3].trim()); for (String label : labels) context.write(new Text("[" + label), ONE); } } protected void extractTokens(String input, Context context) throws IOException, InterruptedException { String[] tokens = FormatUtils.P_SPACE.split(input); for (String token : tokens) context.write(new Text(token), ONE); } protected void extractTokensFromParsed(String input, boolean terminals_only, Context context) throws IOException, InterruptedException { int from = 0, to = 0; boolean seeking = true; boolean nonterminal = false; char current; if (input == null || input.isEmpty() || input.charAt(0) != '(') return; // Run through entire (potentially parsed) sentence. while (from < input.length() && to < input.length()) { if (seeking) { // Seeking mode: looking for the start of the next symbol. current = input.charAt(from); if (current == '(' || current == ')' || current == ' ') { // We skip brackets and spaces. ++from; } else { // Found a non spacing symbol, go into word filling mode. to = from + 1; seeking = false; nonterminal = (input.charAt(from - 1) == '('); } } else { // Word filling mode. Advance to until we hit the end or spacing. current = input.charAt(to); if (current == ' ' || current == ')' || current == '(') { // Word ended. if (terminals_only) { if (!nonterminal) context.write(new Text(input.substring(from, to)), ONE); } else { if (nonterminal) { String nt = input.substring(from, to); if (nt.equals(",")) nt = "COMMA"; context.write(new Text("[" + nt), ONE); } else { context.write(new Text(input.substring(from, to)), ONE); } } from = to + 1; seeking = true; } else { ++to; } } } } } private static class Reduce extends Reducer<Text, IntWritable, IntWritable, Text> { private ArrayList<String> nonterminals; private boolean allowConstituent = true; private boolean allowCCG = true; private boolean allowConcat = true; private boolean allowDoubleConcat = true; protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); nonterminals = new ArrayList<String>(); allowConstituent = conf.getBoolean("thrax.allow-constituent-label", true); allowCCG = conf.getBoolean("thrax.allow-ccg-label", true); allowConcat = conf.getBoolean("thrax.allow-concat-label", true); allowDoubleConcat = conf.getBoolean("thrax.allow-double-plus", true); } protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { // We get word counts in here that might be used for something, but are currently ignored. String token = key.toString(); if (token == null || token.isEmpty()) throw new RuntimeException("Unexpected empty token."); if (token.charAt(0) == '[') nonterminals.add(token); else Vocabulary.id(token); context.progress(); } protected void cleanup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); combineNonterminals(conf); int size = Vocabulary.size(); for (int i = 1; i < size; ++i) context.write(new IntWritable(i), new Text(Vocabulary.word(i))); } private void combineNonterminals(Configuration conf) { if (allowConstituent) addNonterminals(nonterminals); if (allowConcat) { ArrayList<String> concatenated = joinNonterminals("+", nonterminals); addNonterminals(concatenated); } if (allowCCG) { ArrayList<String> forward = joinNonterminals("/", nonterminals); addNonterminals(forward); ArrayList<String> backward = joinNonterminals("\\", nonterminals); addNonterminals(backward); } if (allowDoubleConcat) { ArrayList<String> concat = joinNonterminals("+", nonterminals); ArrayList<String> double_concat = joinNonterminals("+", concat); addNonterminals(double_concat); } Vocabulary.id(FormatUtils.markup(conf.get("thrax.default-nt", "X"))); Vocabulary.id(FormatUtils.markup(conf.get("thrax.full-sentence-nt", "_S"))); } private ArrayList<String> joinNonterminals(String glue, ArrayList<String> prefixes) { ArrayList<String> joined = new ArrayList<String>(); for (String prefix : prefixes) for (String nt : nonterminals) joined.add(prefix + glue + nt.substring(1)); return joined; } private static void addNonterminals(ArrayList<String> nts) { for (String nt : nts) Vocabulary.id(nt + "]"); } } }
package edu.wpi.first.wpilibj.ultimateascent; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationEnhancedIO; import edu.wpi.first.wpilibj.DriverStationEnhancedIO.EnhancedIOException; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.DigitalIOButton; import edu.wpi.first.wpilibj.lib.Utils; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. // Joystick stick = new Joystick(port); // Button button = new JoystickButton(stick, buttonNumber); // Another type of button you can create is a DigitalIOButton, which is // a button or switch hooked up to the cypress module. These are useful if // you want to build a customized operator interface. // Button button = new DigitalIOButton(1); // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); // Constants. private final int DRIVE_LEFT_AXIS = 2; private final int DRIVE_RIGHT_AXIS = 4; private final int DRIVE_THROTTLE_AXIS = 2; private final int DRIVE_WHEEL_AXIS = 3; private DriverStationEnhancedIO io = DriverStation.getInstance().getEnhancedIO(); // Joysticks. private final Joystick driverPad = new Joystick(RobotMap.PAD_DRIVER); private double capAndBand(double value) { value = Utils.deadband(value, .075, -1); value = Utils.deadband(value, .075, 0); value = Utils.deadband(value, .075, 1); return Utils.limit(value, -1, 1); } private double scaleAnalog(double voltageIn) { double normalized = (2 * voltageIn / 3.25) - 1; return normalized; } private double getIOAnalog(int port) { double in; try { in = io.getAnalogIn(port); } catch(EnhancedIOException ex) { return 0; } double refined = capAndBand(scaleAnalog(in)); return refined; } private boolean getIODigital(int port) { boolean in = false; try { in = !io.getDigital(port); //active low } catch(EnhancedIOException ex) { } return in; } // Returns value of the left joystick. public double getDriveLeft() { return driverPad.getRawAxis(DRIVE_LEFT_AXIS); } // Returns the value of the right joystick. public double getDriveRight() { return driverPad.getRawAxis(DRIVE_RIGHT_AXIS); } public double getDriveThrottle() { return getIOAnalog(1); } public double getDriveWheel() { return getIOAnalog(3); } public boolean getDriveQuickTurn() throws EnhancedIOException { return getIODigital(3); } }
package battle; import java.time.Duration; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; public class Status { private final String name; private final String description; private final Duration duration; private int stackSize; /** * States whether the status increases in stack size when equivalent Status * objects are combined with it. */ private final boolean stacks; /** * States whether or not this status stuns the fighter. Stunned fighters do * not decrement their skill cooldowns and cannot execute skills. */ private final boolean stuns; /** * States whether or not the Status object defeats the fighter. Defeated * Fighter objects allow their team to lose a battle if all other ally * fighters are also defeated. */ private final boolean defeats; /** * States whether or not the status should be visible to the user of the * client. */ private final boolean hidden; private final Predicate<Fighter> applyCondition; private final Predicate<Fighter> removeCondition; /** * List of handler objects that who's methods are called during appropriate * state changes in the Status object. */ private final Set<StatusHandler> listeners; /** * The Fighter object that the status belongs to. Value should remain null * until the status has been applied using the {@link #onApply(battle.Fighter) * onApply} method. */ private Fighter owner; /** * Used within this class to track when to decrement the stack size of the * status when it combined with Status objects that have a finite in duration * and are stackable. */ private class Stack { int stackSize; Duration duration; Stack(int stackSize, Duration duration) { this.stackSize = stackSize; this.duration = duration; } } /** * List of Stack objects representing the stack size and duration of other * statuses combined into this. */ private final List<Stack> stackList; /** * Initializes the object so that all internal field variables that can be * explicitly set are done so through the given parameters. See the {@link * StatusBuilder} class which allows you to create Status object using a * builder pattern. * @param name {@see #name} * @param description {@see #description} * @param duration {@see #duration} * @param stackSize {@see #stackSize} * @param stacks {@see #stacks} * @param stuns {@see #stuns} * @param defeats {@see #defeats} * @param hidden {@see #hidden} * @param applyCondition {@see #applyCondition} * @param removeCondition {@see #removeCondition} * @param listeners {@see #listeners} */ public Status(String name, String description, Duration duration, int stackSize, boolean stacks, boolean stuns, boolean defeats, boolean hidden, Predicate<Fighter> applyCondition, Predicate<Fighter> removeCondition, List<StatusHandler> listeners) { if (name == null) { throw new IllegalArgumentException("description cannot be null"); } this.name = name; if (description == null) { throw new IllegalArgumentException("description cannot be null"); } this.description = description; if (duration == null) { throw new IllegalArgumentException("duration cannot be null"); } this.duration = duration; if (stackSize < 0) { throw new IllegalArgumentException("stacks cannot be negative"); } this.stackSize = stackSize; this.stacks = stacks; this.stuns = stuns; this.defeats = defeats; this.hidden = hidden; if (applyCondition == null) { throw new IllegalArgumentException("Condition for application cannot be" + " null"); } this.applyCondition = applyCondition; if (removeCondition == null) { throw new IllegalArgumentException("Condition for removal cannot be" + " null"); } this.removeCondition = removeCondition; this.listeners = new HashSet<>(listeners); this.owner = null; this.stackList = new ArrayList<>(); this.stackList.add(new Stack(stackSize, duration)); } /** * Initializes a copy of the given Status object such that direct changes to * the state of either the original or the copy have no affect on the other. * Some copied parameters are purposefully not deep. It is assumed that all * {@link StatusHandler} objects passed to handle events should be copied by * reference so as not to duplicate potentially large listeners. {@link * Predicate} objects passed to test various conditions are also copied by * reference and therefore must be immutable in regards to its {@code test} * method. A copy is based on the stack size and duration of when the the * status was first created. Copies are always without an owner, even if the * original has one, thus making the value always {@code null}. * @param copyOf object which the copy is made from. */ public Status(Status copyOf) { this.name = copyOf.name; this.description = copyOf.description; this.duration = copyOf.duration; this.stackSize = copyOf.stackSize; this.stacks = copyOf.stacks; this.stuns = copyOf.stuns; this.defeats = copyOf.defeats; this.hidden = copyOf.hidden; this.applyCondition = copyOf.applyCondition; this.removeCondition = copyOf.removeCondition; this.listeners = new HashSet<>(copyOf.listeners); this.owner = null; this.stackList = new ArrayList<>(); this.stackList.add(new Stack(stackSize, duration)); } /** * Adds to the list of handler objects that who's methods are called during * appropriate state changes in the Status object. * @param listener object to handle state changes. */ public void addListener(StatusHandler listener) { if (listener == null) { throw new IllegalArgumentException("Listeners cannot be null"); } listeners.add(listener); } public boolean canCombine(Status status) { return (status != null) && status.name.equals(name) && (status.stacks == this.stacks) && (status.defeats == this.defeats) && (status.stuns == this.stuns) && (status.hidden == this.hidden) && ((status.isInstant() == status.isInstant()) || (status.isFinite() == this.isFinite()) || (status.isInfinite() == this.isInfinite())); } public void combineWith(Status status) { if (!canCombine(status)) { throw new IllegalArgumentException("Status cannot be combined."); } if (isStackable()) { if (isFinite()) { stackList.addAll(status.stackList); } else { stackList.get(0).stackSize += status.stackList.get(0).stackSize; } } else { if (isFinite()) { stackList.get(0).duration.plus(status.stackList.get(0).duration); } } } public void removeDuration(Duration amount) { if (amount.isNegative()) throw new IllegalArgumentException(" Cannot " + "remove negative time from a status."); if (!isInfinite()) { if (getDuration().compareTo(amount) <= 0) { stackList.clear(); if (owner != null) owner.removeStatus(this); } else { for (Stack s : stackList) { if (s.duration.compareTo(amount) <= 0) { stackList.remove(s); } else { s.duration = s.duration.minus(amount); } } } } } public void removeStacks(int amount) { if (amount < 0) throw new IllegalArgumentException("Cannnot remove " + "negative stacks from a status."); if (amount >= getStackSize()) { stackList.clear(); if (owner != null) owner.removeStatus(this); } else { stackList.sort((a, b) -> b.duration.compareTo(a.duration)); for (int i = 0; i < amount; i++) { if (--stackList.get(0).stackSize <= 0) stackList.remove(0); } } } /** * Returns {@code true} if the object is an instance of Status and the name * value of this status and the assumed status are equal. This is to ensure * that {@link Fighter} objects fail to apply a status with a duplicate name * and attempt to combine them instead. * @param obj the status to test equality with. * @return {@code true} if the given status is equivalent. */ @Override public boolean equals(Object obj) { if (!(obj instanceof Status)) return false; return this.name.equals(((Status)obj).getName()); } /** * Returns a description of the status and how it is intended to interact with * Fighter objects it is applied to, as well as its interactions with other * Status objects on the same fighter. * @return description of the status */ public String getDescription() { return description; } /** * The time before this status expires. Zero means the Status has an instant * duration and should expire as soon as it is applied. Less then zero means * duration is infinite. * @return time before the status expires. */ public Duration getDuration() { if (stackList.isEmpty()) return Duration.ZERO; Duration currentDuration = stackList.get(0).duration; for (Stack s : stackList) { if (currentDuration.compareTo(s.duration) < 0) { currentDuration = s.duration; } } return currentDuration; } /** * Name of the status. Identifies the status from unrelated Status objects. * @return name of the Status. */ public String getName() { return name; } /** * The Fighter object that the status belongs to. * @return the owner of the status. */ public Fighter getOwner() { return owner; } /** * The current number of stacks. * @return stack size. */ public int getStackSize() { int currentSize = 0; for (Stack s : stackList) { currentSize += s.stackSize; } return currentSize; } @Override public int hashCode() { return this.name.hashCode(); } /** * Returns true if the Status object defeats the fighter. Defeated Fighter * objects allow their team to lose a battle if all other ally fighters are * also defeated. * @return true if this defeats the fighter it is applied to. */ public boolean isDefeating() { return defeats; } /** * Returns {@code true} if the status should be removed as soon as it is * applied. This is indicated my setting the duration value to {@code ZERO}. * @return true if this is an instant status. */ public boolean isFinite() { return !isInfinite() && !isInstant(); } /** * Returns true is the status should be hidden from client users. * @return true if this is hidden from user. */ public boolean isHidden() { return hidden; } /** * Returns {@code true} if the status should be unable to expire due to * passing time. This is indicated my setting the duration value to a * negative value. * @return true if this is an instant status. */ public boolean isInfinite() { return this.duration.isNegative(); } /** * Returns {@code true} if the status should be removed as soon as it is * applied. This is indicated my setting the duration value to {@code ZERO}. * @return true if this is an instant status. */ public boolean isInstant() { return this.duration.isZero(); } /** * Returns true if the status increases in stack size when equivalent Status * objects are added to it. * @return true if this is stacks. */ public boolean isStackable() { return stacks; } /** * Returns true if this status stuns the fighter. Stunned fighters do not * decrement their skill cooldowns and cannot execute skills. * @return true if the Status stuns the Unit it is applied to. */ public boolean isStunning() { return stuns; } /** * Event method for when this Status is applied. * @param newOwner the Unit the Status is being applied to. * @return true if status can be applied to the target owner. */ public boolean onApply(Fighter newOwner) { if (!applyCondition.test(owner)) return false; this.owner = newOwner; for (StatusHandler handler : listeners) { handler.onStatusApplication(this); } return true; } /** * Event method for when this status is removed. * @return true if the status can be removed from its owner. */ public boolean onRemove() { if (!removeCondition.test(owner)) return false; owner = null; for (StatusHandler handler : listeners) { handler.onStatusRemoval(this); } return true; } /** * Removes a handler object from the list of listeners who's methods are * called during appropriate state changes in the Status object. * @param listener the object to be removed. * @return true if the object was successfully removed. */ public boolean removeListener(StatusHandler listener) { return this.listeners.remove(listener); } @Override public String toString() { return this.name; } }
package gov.nih.nci.ncicb.cadsr.semconn; import gov.nih.nci.common.net.*; import gov.nih.nci.evs.domain.*; import gov.nih.nci.evs.query.*; //import gov.nih.nci.semantic.util.Configuration; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressEvent; import gov.nih.nci.system.applicationservice.*; import gov.nih.nci.system.dao.EVSDAOFactory; import gov.nih.nci.system.delegator.*; import org.apache.log4j.*; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; public class EVSImpl extends SubjectClass{ private static String vocabularyName; private static Logger log = Logger.getLogger(EVSImpl.class.getName()); private ArrayList evsValues; private EVSQuery evsQuery; private String serverURL; private ArrayList possibleOptions; private ArrayList separateWords; ApplicationService appService; //private Configuration properties; public EVSImpl() { vocabularyName = Configuration.getVocabularyName(); serverURL = Configuration.getServerURL(); appService = ApplicationService.getRemoteInstance(serverURL); } /** * get tagged values * * @param umlEntities * * @return */ public List getTaggedValues(List umlEntities) throws Exception { evsValues = new ArrayList(); evsQuery = new EVSQueryImpl(); possibleOptions = new ArrayList(); separateWords = new ArrayList(); try { HashMap map = null; ProgressEvent event = new ProgressEvent(); event.setMessage("Searching EVS..."); event.setGoal(umlEntities.size()); for (int i = 0; i < umlEntities.size(); i++) { event.setStatus(i); notify(event); map = (HashMap) umlEntities.get(i); String name = (String) map.get(Configuration.getUMLEntityCol()); //System.out.println("\noriginal string before call evaluateString: " + name + " \n"); //evaluate string to insert underscore between words..(if the name has multiple words) evaluateString(name); //System.out.println("name: "+name); //populate modifieddate, verified fields map.put(Configuration.getModifiedDateCol(), null); map.put(Configuration.getVerifiedFlagCol(), "0"); //get evs values //getEVSValues(name, map); List ret = getEVSValues(map); //add the return result to the list. If no result returned, must add //the original map. if (ret!=null && (!ret.isEmpty())){ evsValues.addAll(ret); }else{ evsValues.add(map); } possibleOptions.clear(); separateWords.clear(); } notifyEventDone("Searching EVS finished"); //debug //testOutput(evsValues); } catch (Exception e) { log.error("Exception in getTaggedValues: " + e.getMessage()); e.printStackTrace(); throw new Exception("Exception in getTaggedValues: " + e.getMessage()); } return evsValues; } /** * copy values to new hash * * @param entitiesMap * @param newMap */ private void copyHash( HashMap entitiesMap, HashMap newMap) { for (Iterator iter = entitiesMap.keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); newMap.put(key, entitiesMap.get(key)); } } /** * Gets concept code for the given name * * @param name * * @return */ private String getConceptCode(String name) throws Exception { //System.out.println("EVSImpl - getConceptCode..."+name); String code = null; try { //getting concept code evsQuery = new EVSQueryImpl(); //System.out.println("evsQuery.getConceptCodeByName " + name); evsQuery.getConceptCodeByName(vocabularyName, name); code = (String) getObject(evsQuery); //System.out.println("Getting concept code for "+name); if (code != null) { //System.out.println("Concept code = "+ code ); } else { //System.out.println("Cannot locate concept code..."); } } catch (Exception e) { log.error( "Exception occured while getting concept code: " + e.getMessage()); throw new Exception( "Exception occured while getting concept code: " + e.getMessage()); } return code; } /** * Gets evs values * * @param entitiesMap * * @throws Exception */ private List getEVSValues(HashMap entitiesMap) throws Exception { //System.out.print("."); //System.out.println("getEVSValues...."); //get uml class and uml entity String umlClass = (String) entitiesMap.get(Configuration.getUMLClassCol()); String umlEntity = (String) entitiesMap.get(Configuration.getUMLEntityCol()); String classification = null; //if the umlclass and uml entity are equal, then it is class.. else it is attribute if (umlClass.equalsIgnoreCase(umlEntity)) { classification = Configuration.getClassTag(); } else { classification = Configuration.getAttributeTag(); } HashMap newlyFound = new HashMap(); // go through loops of possible options String name = ""; boolean search = false; // only want to search individual term once //System.out.println("possibleOptions size = " + possibleOptions.size()); for (int i = 0; i < possibleOptions.size(); i++) { name = (String) possibleOptions.get(i); //System.out.println("possibleOptions: " + name); if (newlyFound.containsKey(name)){ continue; //loop to next option. } String conceptCode = getConceptCode(name); //System.out.println("conceptCode = " + conceptCode); if (conceptCode != null) { HashMap found = new HashMap(); copyHash(entitiesMap, found); found.put(Configuration.getConceptCodeCol(), conceptCode); found.put(Configuration.getConceptName(), name); found.put(Configuration.getClassificationCol(), classification); //System.out.println("calling getProperties...."+ conceptCode); getProperties(name, found); newlyFound.put(name, found); //Future: multiple code enhancement.. //Assuming that we get the secondary concept codes from the properties } else { //System.out.println("\n11111calling get synonyms... when conceptcode is null"); //concept is null.... get synonyms String[] concepts = getSynonyms(name); boolean first = true; HashMap newMap = null; //System.out.println("concepts length = " + concepts.length); //add each concept (synonym) as a new record if ((concepts.length == 0) && !search) { search = true; //System.out.println("search individual word when concept code synonyms is null"); for (int j = 0; j < separateWords.size(); j++) { name = separateWords.get(j).toString(); //System.out.println("separate word: " + name); if (newlyFound.containsKey(name)){ continue; //loop to next seperate words. } conceptCode = getConceptCode(name); //System.out.println("concept code = " + conceptCode); if (conceptCode != null) { HashMap found = new HashMap(); copyHash(entitiesMap, found); found.put(Configuration.getConceptCodeCol(), conceptCode); found.put(Configuration.getConceptName(), name); found.put(Configuration.getClassificationCol(), classification); //System.out.println("calling getProperties...."+ conceptCode); getProperties(name, found); newlyFound.put(name, found); } else { String[] concepts1 = getSynonyms(name); boolean first1 = true; HashMap newMap1 = null; //System.out.println("concepts1 length = " + concepts1.length); for (int k = 0; k < concepts1.length; k++) { name = concepts1[k]; //get conceptcode for each concept //conceptCode = getConceptCode(name); //System.out.println("calling getConcept code...(for synonyms)... name: " + name ); if (newlyFound.containsKey(name)){ continue; //loop to next seperate words. } conceptCode = getConceptCode(name); //System.out.println("\n22222concept code = " + conceptCode); if (conceptCode != null) { //System.out.println("Concept code = "+ conceptCode+ "\tname= "+ name); if (first1) { //System.out.println("first1.. block adding to entitiesMap"); //add first one to the existing map HashMap found = new HashMap(); copyHash(entitiesMap, found); found.put( Configuration.getConceptCodeCol(), conceptCode); found.put(Configuration.getConceptName(), name); found.put( Configuration.getClassificationCol(), classification); //System.out.println("getProperties..."); getProperties(name, found); newlyFound.put(name, found); first1 = false; } else { //since, multiple synonyms, create new map and add to it //create new HashMap HashMap found = new HashMap(); //copy all other values from the above entitiesMap copyHash(entitiesMap, found); //System.out.println("adding EVS values...."); found.put(Configuration.getConceptCodeCol(), conceptCode); found.put(Configuration.getConceptName(), name); found.put( Configuration.getClassificationCol(), classification); //getProperties //System.out.println("getProperties..."); getProperties(name, found); //add this new map to the list newlyFound.put(name, found); } } } } } } else { for (int k = 0; k < concepts.length; k++) { name = concepts[k]; //get conceptcode for each concept if (newlyFound.containsKey(name)){ continue; //loop to next seperate words. } conceptCode = getConceptCode(name); //System.out.println("\n22222concept code = " + conceptCode); if (conceptCode != null) { //System.out.println("Concept code = "+ conceptCode+ "\tname= "+ name); if (first) { //add first one to the existing map HashMap found = new HashMap(); copyHash(entitiesMap, found); found.put(Configuration.getConceptCodeCol(), conceptCode); found.put(Configuration.getConceptName(), name); found.put( Configuration.getClassificationCol(), classification); //System.out.println("getProperties..."); getProperties(name, found); newlyFound.put(name, found); first = false; } else { //since, multiple synonyms, create new map and add to it //create new HashMap HashMap found = new HashMap(); //copy all other values from the above entitiesMap copyHash(entitiesMap, found); //System.out.println("adding EVS values...."); found.put(Configuration.getConceptCodeCol(), conceptCode); found.put(Configuration.getConceptName(), name); found.put( Configuration.getClassificationCol(), classification); //getProperties //System.out.println("getProperties..."); getProperties(name, found); //add this new map to the list newlyFound.put(name, found); } } else // go through loop of individual words { //System.out.println("search individual word when concept code is null"); for (int j = 0; j < separateWords.size(); j++) { name = separateWords.get(j).toString(); //System.out.println("separate word: " + name); if (newlyFound.containsKey(name)){ continue; //loop to next seperate words. } conceptCode = getConceptCode(name); if (conceptCode != null) { HashMap found = new HashMap(); copyHash(entitiesMap, found); found.put( Configuration.getConceptCodeCol(), conceptCode); found.put(Configuration.getConceptName(), name); found.put( Configuration.getClassificationCol(), classification); //System.out.println("calling getProperties...."+ conceptCode); getProperties(name, found); newlyFound.put(name, found); } } } } } } } // end for loop //for testing if (newlyFound==null || newlyFound.isEmpty()){ return null; }else{ return new ArrayList(newlyFound.values()); } } /* private void getEVSValues(HashMap entitiesMap) throws Exception { //System.out.print("."); //System.out.println("getEVSValues...."); //get uml class and uml entity String umlClass = (String) entitiesMap.get(Configuration.getUMLClassCol()); String umlEntity = (String) entitiesMap.get(Configuration.getUMLEntityCol()); String classification = null; //if the umlclass and uml entity are equal, then it is class.. else it is attribute if (umlClass.equalsIgnoreCase(umlEntity)) { classification = Configuration.getClassTag(); } else { classification = Configuration.getAttributeTag(); } // go through loops of possible options String name = ""; boolean search = false; // only want to search individual term once //System.out.println("possibleOptions size = " + possibleOptions.size()); for (int i = 0; i < possibleOptions.size(); i++) { Object temp = possibleOptions.get(i); name = temp.toString(); //System.out.println("possibleOptions: " + name); String conceptCode = getConceptCode(name); //System.out.println("conceptCode = " + conceptCode); if (conceptCode != null) { entitiesMap.put(Configuration.getConceptCodeCol(), conceptCode); entitiesMap.put(Configuration.getConceptName(), name); entitiesMap.put(Configuration.getClassificationCol(), classification); //System.out.println("calling getProperties...."+ conceptCode); getProperties(name, entitiesMap); //Future: multiple code enhancement.. //Assuming that we get the secondary concept codes from the properties } else { //System.out.println("\n11111calling get synonyms... when conceptcode is null"); //concept is null.... get synonyms String[] concepts = getSynonyms(name); boolean first = true; HashMap newMap = null; //System.out.println("concepts length = " + concepts.length); //add each concept (synonym) as a new record if ((concepts.length == 0) && !search) { search = true; //System.out.println("search individual word when concept code synonyms is null"); for (int j = 0; j < separateWords.size(); j++) { name = separateWords.get(j).toString(); //System.out.println("separate word: " + name); conceptCode = getConceptCode(name); //System.out.println("concept code = " + conceptCode); if (conceptCode != null) { entitiesMap.put(Configuration.getConceptCodeCol(), conceptCode); entitiesMap.put(Configuration.getConceptName(), name); entitiesMap.put( Configuration.getClassificationCol(), classification); //System.out.println("calling getProperties...."+ conceptCode); getProperties(name, entitiesMap); } else { String[] concepts1 = getSynonyms(name); boolean first1 = true; HashMap newMap1 = null; //System.out.println("concepts1 length = " + concepts1.length); for (int k = 0; k < concepts1.length; k++) { name = concepts1[k]; //get conceptcode for each concept //conceptCode = getConceptCode(name); //System.out.println("calling getConcept code...(for synonyms)... name: " + name ); conceptCode = getConceptCode(name); //System.out.println("\n22222concept code = " + conceptCode); if (conceptCode != null) { //System.out.println("Concept code = "+ conceptCode+ "\tname= "+ name); if (first1) { //System.out.println("first1.. block adding to entitiesMap"); //add first one to the existing map entitiesMap.put( Configuration.getConceptCodeCol(), conceptCode); entitiesMap.put(Configuration.getConceptName(), name); entitiesMap.put( Configuration.getClassificationCol(), classification); //System.out.println("getProperties..."); getProperties(name, entitiesMap); first1 = false; } else { //since, multiple synonyms, create new map and add to it //create new HashMap newMap1 = new HashMap(); //copy all other values from the above entitiesMap copyHash(entitiesMap, newMap1); //System.out.println("adding EVS values...."); newMap1.put(Configuration.getConceptCodeCol(), conceptCode); newMap1.put(Configuration.getConceptName(), name); newMap1.put( Configuration.getClassificationCol(), classification); //getProperties //System.out.println("getProperties..."); getProperties(name, newMap1); //add this new map to the list evsValues.add(newMap1); } } } } } } else { for (int k = 0; k < concepts.length; k++) { name = concepts[k]; //get conceptcode for each concept conceptCode = getConceptCode(name); //System.out.println("\n22222concept code = " + conceptCode); if (conceptCode != null) { //System.out.println("Concept code = "+ conceptCode+ "\tname= "+ name); if (first) { //add first one to the existing map entitiesMap.put(Configuration.getConceptCodeCol(), conceptCode); entitiesMap.put(Configuration.getConceptName(), name); entitiesMap.put( Configuration.getClassificationCol(), classification); //System.out.println("getProperties..."); getProperties(name, entitiesMap); first = false; } else { //since, multiple synonyms, create new map and add to it //create new HashMap newMap = new HashMap(); //copy all other values from the above entitiesMap copyHash(entitiesMap, newMap); //System.out.println("adding EVS values...."); newMap.put(Configuration.getConceptCodeCol(), conceptCode); newMap.put(Configuration.getConceptName(), name); newMap.put( Configuration.getClassificationCol(), classification); //getProperties //System.out.println("getProperties..."); getProperties(name, newMap); //add this new map to the list evsValues.add(newMap); } } else // go through loop of individual words { //System.out.println("search individual word when concept code is null"); for (int j = 0; j < separateWords.size(); j++) { name = separateWords.get(j).toString(); //System.out.println("separate word: " + name); conceptCode = getConceptCode(name); if (conceptCode != null) { entitiesMap.put( Configuration.getConceptCodeCol(), conceptCode); entitiesMap.put(Configuration.getConceptName(), name); entitiesMap.put( Configuration.getClassificationCol(), classification); //System.out.println("calling getProperties...."+ conceptCode); getProperties(name, entitiesMap); } } } } } } } // end for loop } */ private String[] getConceptCodes(String name) throws Exception { //System.out.println("EVSImpl - getConceptCodes..."); String[] codes = null; try { //getting concept code evsQuery.getConceptCodeByName(vocabularyName, name); //System.out.println("Getting concept code for "+name); codes = (String[]) getObjects(evsQuery); /* if(getObjects(evsQuery)!=null){ codes = (String[])getObjects(evsQuery); System.out.println("Concept code = "+ codes ); } else{ System.out.println("Cannot locate concept code..."); } */ } catch (Exception e) { log.error( "Exception occured while getting concept code: " + e.getMessage()); throw new Exception( "Exception occured while getting concept code: " + e.getMessage()); } return codes; } /** * get synonyms * * @param name * * @return */ private String[] getSynonyms(String name) throws Exception { //System.out.println("getSynonyms..."); String[] concepts = null; try { //evsQuery.getConceptWithPropertyMatching(vocabularyName, "Synonym", name, Configuration.getLimit()); evsQuery.getConceptWithPropertyMatching( vocabularyName, "Synonym", name, 3); //List results = getResults(evsQuery); Object[] results = getObjects(evsQuery); concepts = new String[results.length]; for (int i = 0; i < results.length; i++) { concepts[i] = (String) results[i]; //System.out.println(concepts[i]); } } catch (Exception e) { log.error("Exception occured while getting synonyms: " + e.getMessage()); throw new Exception( "Exception occured while getting synonyms: " + e.getMessage()); } return concepts; } /** * Gets properties for the given name, and parse the properties. * * @param name * * @throws Exception */ private void getProperties( String name, HashMap entitiesMap) throws Exception { //System.out.println("EVSImpl getProperties..."); try { evsQuery = new EVSQueryImpl(); evsQuery.getPropertiesByConceptName(vocabularyName, name); //System.out.println("Getting properties for "+name); //Property[] properties = null;//(Property [])getObjects(evsQuery); List prop = getResults(evsQuery); Property[] properties = new Property[prop.size()]; for (int i = 0; i < prop.size(); i++) { properties[i] = (Property) prop.get(i); } String propName = null; String propValue = null; HashMap definitionsHash = new HashMap(); String preferredName = null; String hashKey = null; String hashValue = null; for (int i = 0; i < properties.length; i++) { propName = properties[i].getName(); propValue = properties[i].getValue(); //System.out.println("Name: "+propName); //System.out.println("Value: "+propValue); /** * Future enhancement for multiple concept codes Assuming that we get * secondary concept codes with some classifications to it.. then add * this as a new entry in the list.. */ Vector valueVector = null; //Definitions if (propName.equalsIgnoreCase("DEFINITION")) { hashKey = null; hashValue = null; valueVector = getPropertyElements(propValue); for (int j = 0; j < valueVector.size(); j++) { String key = (String) valueVector.elementAt(j); String value = getPropertyElementValue(key, propValue); //System.out.println("\t\tkey: "+key); //System.out.println("\t\tvalue: "+value); if (key.equalsIgnoreCase("DEF-SOURCE")) { hashKey = value; } else if (key.equalsIgnoreCase("DEF-DEFINITION")) { hashValue = value; } } definitionsHash.put(hashKey, hashValue); } //Preferred Name if (propName.equalsIgnoreCase("PREFERRED_NAME")) { entitiesMap.put(Configuration.getPreferredNameCol(), propValue); } } //add definition, definitionsource to the map String definition = null; String definitionSource = null; if (definitionsHash != null) { //If there is a NCI,, add it.. //else add the next one..(whatever we got) if (definitionsHash.containsKey("NCI")) { definitionSource = "NCI"; definition = (String) definitionsHash.get("NCI"); } else { Iterator iter = definitionsHash.keySet().iterator(); while (iter.hasNext()) { definitionSource = (String) iter.next(); definition = (String) definitionsHash.get(definitionSource); break; } } //add this to map entitiesMap.put( Configuration.getDefinitionSourceCol(), definitionSource); entitiesMap.put(Configuration.getDefinitionCol(), definition); } } catch (Exception e) { log.error( "Exception occured while getting properties: " + e.getMessage()); throw new Exception( "Exception occured while getting properties: " + e.getMessage()); } } /** * Parse the value * * @param value * * @return */ private Vector getPropertyElements(String value) { Vector vector = new Vector(); String s1 = value; for (int i = s1.indexOf("</"); i != -1; i = s1.indexOf("</")) { s1 = s1.substring(i + 1); int j = s1.indexOf(">"); String s2 = s1.substring(1, j); vector.add(s2.trim()); } return vector; } /** * Parse the element value * * @param s * @param s1 * * @return */ private String getPropertyElementValue( String s, String s1) { Vector vector; Vector vector1; s = s.trim(); vector = getPropertyElements(s1); vector1 = parseXML(s1); if (vector1.size() != vector.size()) { return ""; } int i; i = -1; int j = 0; do { if (j >= vector.size()) { break; } if (s.equalsIgnoreCase((String) vector.elementAt(j))) { i = j; break; } j++; } while (true); if (i == -1) { return ""; } return (String) vector1.elementAt(i); } /** * Parse the string (string is in xml format) * * @param s * * @return */ private Vector parseXML(String s) { Vector vector = new Vector(); StringTokenizer stringtokenizer = new StringTokenizer(s, "<"); boolean flag = true; String s2; String s1 = s2 = ""; try { while (stringtokenizer.hasMoreTokens()) { String s3 = stringtokenizer.nextToken(); if (flag) { int i = s3.indexOf(">"); s2 = s3.substring(0, i); s1 = s1 + s3.substring(i + 1); String s4 = stringtokenizer.nextToken(); if (s4.startsWith("/")) { String s6 = s3.substring(i + 1); vector.add(s6); } else { s1 = s1 + "<" + s4; flag = false; } } else if (!s3.equalsIgnoreCase("/" + s2 + ">")) { String s5 = stringtokenizer.nextToken(); s1 = s1 + "<" + s3; if (!s5.equalsIgnoreCase("/" + s2 + ">")) { s1 = s1 + "<" + s5; } else { vector.add(s1); flag = true; } } else { vector.add(s1); flag = true; } } } catch (Exception exception) { log.error("Exception: " + exception.getMessage()); exception.printStackTrace(); return null; } return vector; } /** * This method adds underscore in between the words (eg: converts GeneHomolog * to Gene_Homolog) * * @param name */ private void evaluateString(String name) { //remove package name if the name is a class name if (name!=null){ int index = name.lastIndexOf("."); name = name.substring(index+1); } Set optionSet = new HashSet(); optionSet.add(name); char firstChar = name.charAt(0); firstChar = Character.toUpperCase(firstChar); if (name.indexOf("_") > 0) { String temp = Character.toString(firstChar) + name.substring(1); optionSet.add(temp); } String temp = firstChar + name.substring(1).toLowerCase(); optionSet.add(temp); String evaluatedString = null;; StringBuffer wholeWords = new StringBuffer(); StringBuffer tempSeparateWord = new StringBuffer(); char[] chars = name.toCharArray(); StringBuffer sb = new StringBuffer(); boolean first = true; int index = 0; for (int i = 0; i < chars.length; i++) { //Character c = new Character(chars[i]); //System.out.println("inside loop i = " +i); if (Character.isUpperCase(chars[i])) { if ((i > 1) && ((i - index) > 1)) { //System.out.println("Inside capital if"); first = false; sb.append("_").append(chars[i]); separateWords.add(tempSeparateWord); tempSeparateWord = null; tempSeparateWord = new StringBuffer(); tempSeparateWord.append(chars[i]); wholeWords.append(" ").append(chars[i]); } else { wholeWords.append(chars[i]); tempSeparateWord.append(chars[i]); sb.append(chars[i]); } index = i; } else { if (chars[i] != '_') { sb.append(chars[i]); wholeWords.append(chars[i]); tempSeparateWord.append(chars[i]); } } } //System.out.println("Converted string: "+sb.toString()); //if the string contains "_", then make the first character uppercase if (!first) { char c = Character.toUpperCase(sb.charAt(0)); sb.deleteCharAt(0); sb.insert(0, c); char c1 = Character.toUpperCase(wholeWords.charAt(0)); wholeWords.deleteCharAt(0); wholeWords.insert(0, c1); } optionSet.add(sb.toString()); optionSet.add(wholeWords.toString()); if (separateWords.size() > 0) { /* StringBuffer tmp = (StringBuffer)separateWords.get(0); char c2 = Character.toUpperCase(tmp.charAt(0)); tmp.deleteCharAt(0); tmp.insert(0, c2); separateWords.remove(0); separateWords.add(0, tmp); */ String temp2 = separateWords.get(separateWords.size() - 1).toString(); if (tempSeparateWord != null) { temp = tempSeparateWord.toString(); if (temp2.compareToIgnoreCase(temp) != 0) { separateWords.add(temp); } } } possibleOptions = new ArrayList(optionSet); optionSet = null;//garbage collection ready //testing for (int i=0; i<possibleOptions.size();i++){ System.out.println("options["+i+"]=" + possibleOptions.get(i)); } for (int i=0; i<separateWords.size();i++){ System.out.println("separateWords["+i+"]=" + separateWords.get(i)); } return; } /////////////////testing//////////////////// private void testOutput(ArrayList attList) { for (int i = 0; i < attList.size(); i++) { HashMap map = (HashMap) attList.get(i); for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); String value = (String) map.get(key); //System.out.println(key+" = "+value); } } } private Object getObject(EVSQuery evsQuery) throws Exception { //System.out.println("EVSImpl - getObject"); Object object = null; try { List resultList = getResults(evsQuery); if (resultList.size() > 0) { object = resultList.get(0); //System.out.println("Object - "+ object); } } catch (Exception ex) { log.error("Exception: " + ex.getMessage()); throw new Exception(ex.getMessage()); } return object; } private Object[] getObjects(EVSQuery evsQuery) throws Exception { //System.out.println("EVSImpl - getObjects"); Object[] objectArray = null; try { List resultList = getResults(evsQuery); objectArray = new Object[resultList.size()]; if (resultList.size() == 1) { objectArray[0] = resultList.get(0); } else { for (int i = 0; i < resultList.size(); i++) { if (resultList.get(i) != null) { objectArray[i] = resultList.get(i); } } } } catch (Exception ex) { log.error("Exception: " + ex.getMessage()); throw new Exception(ex.getMessage()); } //System.out.println("Object array size = "+ objectArray.length); return objectArray; } private List getResults(EVSQuery evsQuery) throws Exception { List results = new ArrayList(); try { if (serverURL == null) { if (Configuration.getServerURL() == null) { //System.out.println("Cannot locate serverURL in semantic properties"); throw new Exception("Cannot locate serverURL in semantic properties"); } serverURL = Configuration.getServerURL(); } if (appService == null) { appService = ApplicationService.getRemoteInstance(serverURL); } //System.out.println("calling appService.eveSearch()"); results = appService.evsSearch(evsQuery); //System.out.println("Application service returned "+ results.size()); } catch (Exception ex) { log.error("Exception: " + ex.getMessage()); ex.printStackTrace(); throw new Exception(ex.getMessage()); } return results; } }
package imj; import static net.sourceforge.aprog.tools.Tools.debugPrint; import static net.sourceforge.aprog.tools.Tools.unchecked; import static net.sourceforge.aprog.tools.Tools.usedMemory; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.prefs.Preferences; import javax.swing.ProgressMonitor; import loci.formats.IFormatReader; import loci.formats.ImageReader; import org.junit.Test; /** * @author codistmonk (creation 2013-01-31) */ public final class ImageWranglerTest { @Test public final void test1() { final TicToc timer = new TicToc(); // final String imageId = "test/imj/12003.jpg"; // final String imageId = "../Libraries/images/16088-4.png"; final String imageId = "../Libraries/images/42628.svs"; debugPrint("Loading image:", new Date(timer.tic())); final Image image = ImageWrangler.INSTANCE.load(imageId); debugPrint("Done:", "time:", timer.toc(), "memory:", usedMemory()); ImageComponent.show(imageId, image); } } /** * @author codistmonk (creation 2013-01-31) */ final class ImageWrangler { private final Preferences preferences; private ImageWrangler() { this.preferences = Preferences.userNodeForPackage(this.getClass()); } public final Image load(final String imageId) { final String fileId = this.preferences.get("image:" + imageId, null); final File maybeExistsingFile = new File(fileId == null ? "" : fileId); if (fileId == null || !(maybeExistsingFile.exists() && maybeExistsingFile.isFile())) { final IFormatReader reader = new ImageReader(); try { reader.setId(imageId); final int rowCount = reader.getSizeY(); final int columnCount = reader.getSizeX(); debugPrint("Allocating"); final LinearStorage result = new LinearStorage(rowCount, columnCount, false); debugPrint("Allocated in file:", result.getFile()); final int optimalTileRowCount = reader.getOptimalTileHeight(); final int optimalTileColumnCount = reader.getOptimalTileWidth(); final int channelCount = reader.getSizeC(); final int bufferRowCount; final int bufferColumnCount; final ProgressMonitor progressMonitor = new ProgressMonitor(null, "Loading", null, 0, rowCount - 1); result.getMetadata().put("channelCount", channelCount); debugPrint("rowCount:", rowCount, "columnCount:", columnCount); debugPrint("channelCount:", channelCount); debugPrint("optimalTileRowCount:", optimalTileRowCount, "optimalTileColumnCount:", optimalTileColumnCount); if (optimalTileRowCount < rowCount || optimalTileColumnCount < columnCount) { bufferRowCount = optimalTileRowCount; bufferColumnCount = optimalTileColumnCount; } else { bufferRowCount = 4; bufferColumnCount = columnCount; } final byte[] buffer = new byte[bufferRowCount * bufferColumnCount * channelCount]; for (int y = 0; y < rowCount && !progressMonitor.isCanceled(); y += bufferRowCount) { final int h = y + bufferRowCount <= rowCount ? bufferRowCount : rowCount - y; final int endRowIndex = y + h; for (int x = 0; x < columnCount && !progressMonitor.isCanceled(); x += bufferColumnCount) { final int w = x + bufferColumnCount <= columnCount ? bufferColumnCount : columnCount - x; final int endColumnIndex = x + w; final int channelSize = h * w; reader.openBytes(0, buffer, x, y, w, h); for (int rowIndex = y, yy = 0; rowIndex < endRowIndex; ++rowIndex, ++yy) { for (int columnIndex = x, xx = 0; columnIndex < endColumnIndex; ++columnIndex, ++xx) { final int i = yy * w + xx; int value = 0x000000FF; switch (channelCount) { default: case 1: value = unsigned(buffer[i]); break; case 4: // alpha value = unsigned(buffer[i + (channelCount - 1) * channelSize]); case 3: final int red = unsigned(buffer[i + 0 * channelSize]); final int green = unsigned(buffer[i + 1 * channelSize]); final int blue = unsigned(buffer[i + 2 * channelSize]); value = (value << 24) | (red << 16) | (green << 8) | blue; break; } result.setValue(rowIndex, columnIndex, value); } } } progressMonitor.setProgress(y); } progressMonitor.close(); this.preferences.put("image:" + imageId, result.getFile().toString()); return result; } catch (final Exception exception) { throw unchecked(exception); } finally { try { reader.close(); } catch (final IOException exception) { throw unchecked(exception); } } } return LinearStorage.open(new File(fileId)); } public static final ImageWrangler INSTANCE = new ImageWrangler(); public static final int unsigned(final byte value) { return value & 0x000000FF; } }
import com.rethinkdb.RethinkDB; import com.rethinkdb.gen.exc.ReqlError; import com.rethinkdb.gen.exc.ReqlQueryLogicError; import com.rethinkdb.model.MapObject; import com.rethinkdb.model.OptArgs; import com.rethinkdb.net.Connection; import com.rethinkdb.net.Cursor; import gen.TestingFramework; import junit.framework.Assert; import org.junit.*; import org.junit.rules.ExpectedException; import java.time.OffsetDateTime; import java.util.Arrays; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class RethinkDBTest{ public static final RethinkDB r = RethinkDB.r; Connection<?> conn; public static final String dbName = "javatests"; public static final String tableName = "atest"; @Rule public ExpectedException expectedEx = ExpectedException.none(); @BeforeClass public static void oneTimeSetUp() throws Exception { Connection<?> conn = TestingFramework.createConnection(); try{ r.dbCreate(dbName).run(conn); } catch(ReqlError e){} try { r.db(dbName).wait_().run(conn); r.db(dbName).tableCreate(tableName).run(conn); r.db(dbName).table(tableName).wait_().run(conn); } catch(ReqlError e){} conn.close(); } @AfterClass public static void oneTimeTearDown() throws Exception { Connection<?> conn = TestingFramework.createConnection(); try { r.db(dbName).tableDrop(tableName).run(conn); r.dbDrop(dbName).run(conn); } catch(ReqlError e){} conn.close(); } @Before public void setUp() throws Exception { conn = TestingFramework.createConnection(); r.db(dbName).table(tableName).delete().run(conn); } @After public void tearDown() throws Exception { conn.close(); } @Test public void testBooleans() throws Exception { Boolean t = r.expr(true).run(conn); Assert.assertEquals(t.booleanValue(), true); Boolean f = r.expr(false).run(conn); Assert.assertEquals(f.booleanValue(), false); String trueType = r.expr(true).typeOf().run(conn); Assert.assertEquals(trueType, "BOOL"); String falseString = r.expr(false).coerceTo("string").run(conn); Assert.assertEquals(falseString, "false"); Boolean boolCoerce = r.expr(true).coerceTo("bool").run(conn); Assert.assertEquals(boolCoerce.booleanValue(), true); } @Test public void testNull() { Object o = r.expr(null).run(conn); Assert.assertEquals(o, null); String nullType = r.expr(null).typeOf().run(conn); Assert.assertEquals(nullType, "NULL"); String nullCoerce = r.expr(null).coerceTo("string").run(conn); Assert.assertEquals(nullCoerce, "null"); Object n = r.expr(null).coerceTo("null").run(conn); Assert.assertEquals(n, null); } @Test public void testString() { String str = r.expr("str").run(conn); Assert.assertEquals(str, "str"); String unicode = r.expr("").run(conn); Assert.assertEquals(unicode, ""); String strType = r.expr("foo").typeOf().run(conn); Assert.assertEquals(strType, "STRING"); String strCoerce = r.expr("foo").coerceTo("string").run(conn); Assert.assertEquals(strCoerce, "foo"); Number nmb12 = r.expr("-1.2").coerceTo("NUMBER").run(conn); Assert.assertEquals(nmb12, -1.2); Long nmb10 = r.expr("0xa").coerceTo("NUMBER").run(conn); Assert.assertEquals(nmb10.longValue(), 10L); } @Test public void testDate() { OffsetDateTime date = OffsetDateTime.now(); OffsetDateTime result = r.expr(date).run(conn); Assert.assertEquals(date, result); } @Test public void testCoerceFailureDoubleNegative() { expectedEx.expect(ReqlQueryLogicError.class); expectedEx.expectMessage("Could not coerce `--1.2` to NUMBER."); r.expr("--1.2").coerceTo("NUMBER").run(conn); } @Test public void testCoerceFailureTrailingNegative() { expectedEx.expect(ReqlQueryLogicError.class); expectedEx.expectMessage("Could not coerce `-1.2-` to NUMBER."); r.expr("-1.2-").coerceTo("NUMBER").run(conn); } @Test public void testCoerceFailureInfinity() { expectedEx.expect(ReqlQueryLogicError.class); expectedEx.expectMessage("Non-finite number: inf"); r.expr("inf").coerceTo("NUMBER").run(conn); } @Test public void testSplitEdgeCases() { List<String> emptySplitNothing = r.expr("").split().run(conn); Assert.assertEquals(emptySplitNothing, Arrays.asList()); List<String> nullSplit = r.expr("").split(null).run(conn); Assert.assertEquals(nullSplit, Arrays.asList()); List<String> emptySplitSpace = r.expr("").split(" ").run(conn); Assert.assertEquals(Arrays.asList(""), emptySplitSpace); List<String> emptySplitEmpty = r.expr("").split("").run(conn); assertEquals(Arrays.asList(), emptySplitEmpty); List<String> emptySplitNull5 = r.expr("").split(null, 5).run(conn); assertEquals(Arrays.asList(), emptySplitNull5); List<String> emptySplitSpace5 = r.expr("").split(" ", 5).run(conn); assertEquals(Arrays.asList(""), emptySplitSpace5); List<String> emptySplitEmpty5 = r.expr("").split("", 5).run(conn); assertEquals(Arrays.asList(), emptySplitEmpty5); } @Test public void testSplitWithNullOrWhitespace() { List<String> extraWhitespace = r.expr("aaaa bbbb cccc ").split().run(conn); assertEquals(Arrays.asList("aaaa", "bbbb", "cccc"), extraWhitespace); List<String> extraWhitespaceNull = r.expr("aaaa bbbb cccc ").split(null).run(conn); assertEquals(Arrays.asList("aaaa", "bbbb", "cccc"), extraWhitespaceNull); List<String> extraWhitespaceSpace = r.expr("aaaa bbbb cccc ").split(" ").run(conn); assertEquals(Arrays.asList("aaaa", "bbbb", "", "cccc", ""), extraWhitespaceSpace); List<String> extraWhitespaceEmpty = r.expr("aaaa bbbb cccc ").split("").run(conn); assertEquals(Arrays.asList("a", "a", "a", "a", " ", "b", "b", "b", "b", " ", " ", "c", "c", "c", "c", " "), extraWhitespaceEmpty); } @Test public void testSplitWithString() { List<String> b = r.expr("aaaa bbbb cccc ").split("b").run(conn); assertEquals(Arrays.asList("aaaa ", "", "", "", " cccc "), b); } @Test public void testTableInsert(){ MapObject foo = new MapObject() .with("hi", "There") .with("yes", 7) .with("no", null ); Map<String, Object> result = r.db(dbName).table(tableName).insert(foo).run(conn); assertEquals(result.get("inserted"), 1L); } @Test public void testDbGlobalArgInserted() { final String tblName = "test_global_optargs"; try { r.dbCreate("test").run(conn); } catch (Exception e) {} r.expr(r.array("optargs", "conn_default")).forEach(r::dbCreate).run(conn); r.expr(r.array("test", "optargs", "conn_default")).forEach(dbName -> r.db(dbName).tableCreate(tblName).do_((unused) -> r.db(dbName).table(tblName).insert(r.hashMap("dbName", dbName).with("id", 1)) ) ).run(conn); try { // no optarg set, no default db conn.use(null); Map x1 = r.table(tblName).get(1).run(conn); assertEquals("test", x1.get("dbName")); // no optarg set, default db set conn.use("conn_default"); Map x2 = r.table(tblName).get(1).run(conn); assertEquals("conn_default", x2.get("dbName")); // optarg set, no default db conn.use(null); Map x3 = r.table(tblName).get(1).run(conn, OptArgs.of("db", "optargs")); assertEquals("optargs", x3.get("dbName")); // optarg set, default db conn.use("conn_default"); Map x4 = r.table(tblName).get(1).run(conn, OptArgs.of("db", "optargs")); assertEquals("optargs", x4.get("dbName")); } finally { conn.use(null); r.expr(r.array("optargs", "conn_default")).forEach(r::dbDrop).run(conn); r.db("test").tableDrop(tblName).run(conn); } } @Test public void testTableSelectOfPojo() { TestPojo pojo = new TestPojo("foo", new TestPojoInner(42L, true)); Map<String, Object> pojoResult = r.db(dbName).table(tableName).insert(pojo).run(conn); assertEquals(1L, pojoResult.get("inserted")); String key = (String) ((List) pojoResult.get("generated_keys")).get(0); TestPojo result = r.db(dbName).table(tableName).get(key).run(conn, TestPojo.class); assertEquals("foo", result.getStringProperty()); assertTrue(42L == result.getPojoProperty().getLongProperty()); assertEquals(true, result.getPojoProperty().getBooleanProperty()); } @Test(expected = ClassCastException.class) public void testTableSelectOfPojo_withNoPojoClass_throwsException() { TestPojo pojo = new TestPojo("foo", new TestPojoInner(42L, true)); Map<String, Object> pojoResult = r.db(dbName).table(tableName).insert(pojo).run(conn); assertEquals(1L, pojoResult.get("inserted")); String key = (String) ((List) pojoResult.get("generated_keys")).get(0); TestPojo result = r.db(dbName).table(tableName).get(key).run(conn /* TestPojo.class is not specified */); } @Test public void testTableSelectOfPojoCursor() { TestPojo pojoOne = new TestPojo("foo", new TestPojoInner(42L, true)); TestPojo pojoTwo = new TestPojo("bar", new TestPojoInner(53L, false)); Map<String, Object> pojoOneResult = r.db(dbName).table(tableName).insert(pojoOne).run(conn); Map<String, Object> pojoTwoResult = r.db(dbName).table(tableName).insert(pojoTwo).run(conn); assertEquals(1L, pojoOneResult.get("inserted")); assertEquals(1L, pojoTwoResult.get("inserted")); Cursor<TestPojo> cursor = r.db(dbName).table(tableName).run(conn, TestPojo.class); List<TestPojo> result = cursor.toList(); assertEquals(2, result.size()); TestPojo pojoOneSelected = "foo".equals(result.get(0).getStringProperty()) ? result.get(0) : result.get(1); TestPojo pojoTwoSelected = "bar".equals(result.get(0).getStringProperty()) ? result.get(0) : result.get(1); assertEquals("foo", pojoOneSelected.getStringProperty()); assertTrue(42L == pojoOneSelected.getPojoProperty().getLongProperty()); assertEquals(true, pojoOneSelected.getPojoProperty().getBooleanProperty()); assertEquals("bar", pojoTwoSelected.getStringProperty()); assertTrue(53L == pojoTwoSelected.getPojoProperty().getLongProperty()); assertEquals(false, pojoTwoSelected.getPojoProperty().getBooleanProperty()); } @Test(expected = ClassCastException.class) public void testTableSelectOfPojoCursor_withNoPojoClass_throwsException() { TestPojo pojoOne = new TestPojo("foo", new TestPojoInner(42L, true)); TestPojo pojoTwo = new TestPojo("bar", new TestPojoInner(53L, false)); Map<String, Object> pojoOneResult = r.db(dbName).table(tableName).insert(pojoOne).run(conn); Map<String, Object> pojoTwoResult = r.db(dbName).table(tableName).insert(pojoTwo).run(conn); assertEquals(1L, pojoOneResult.get("inserted")); assertEquals(1L, pojoTwoResult.get("inserted")); Cursor<TestPojo> cursor = r.db(dbName).table(tableName).run(conn /* TestPojo.class is not specified */); List<TestPojo> result = cursor.toList(); TestPojo pojoSelected = result.get(0); } }
package models; import com.avaje.ebean.Ebean; import com.avaje.ebean.annotation.Where; import com.google.common.base.Predicate; import org.joda.time.DateMidnight; import play.db.ebean.Model; import javax.annotation.Nullable; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.xml.bind.annotation.XmlAttribute; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.avaje.ebean.Expr.eq; import static com.avaje.ebean.Expr.isNotNull; import static com.google.common.collect.Collections2.filter; @Entity public class Game extends BaseModel<Game> implements Comparable<Game> { public static Finder<Long, Game> finder = new Model.Finder(Long.class, Game.class); @XmlAttribute public String thread; @XmlAttribute public String cover; @XmlAttribute public String title; @OneToMany(mappedBy = "game") @Where(clause = "rank > 0") public List<Score> scores; @OneToMany(mappedBy = "game") public List<Score> allScores; @OneToMany(mappedBy = "game") @Where(clause = "rank > 0 AND onecc = 1") public List<Score> oneccs; @OrderBy("name") @OneToMany(mappedBy = "game") public List<Platform> platforms; @OrderBy("sortOrder") @OneToMany(mappedBy = "game") public List<Difficulty> difficulties; @OrderBy("sortOrder") @OneToMany(mappedBy = "game") public List<Mode> modes; @OrderBy("sortOrder") @OneToMany(mappedBy = "game") public List<Ship> ships; @OrderBy("sortOrder") @OneToMany(mappedBy = "game") public List<Stage> stages; private List<Ranking> initializedRankings; private boolean generalRanking; public Game(String title, String cover, String thread) { this.title = title; this.cover = cover; this.thread = thread; } public static List<Game> findAll() { return Ebean.find(Game.class).order("title").findList(); } public List<Ranking> rankings() { List<Ranking> rankings = new ArrayList<Ranking>(); if (generalRanking) { rankings.add(createGeneralRanking()); } if (modes.isEmpty()) { if (difficulties.isEmpty()) { rankings.add(createGeneralRanking()); } else { for (Difficulty difficulty : difficulties) { rankings.add(new Ranking(findBestScoresByVIPPlayers(difficulty, null), difficulty)); } } } else { for (Mode mode : modes) { if (difficulties.isEmpty()) { rankings.add(new Ranking(findBestScoresByVIPPlayers(null, mode), mode)); } else { for (Difficulty difficulty : difficulties) { rankings.add(new Ranking(findBestScoresByVIPPlayers(difficulty, mode), difficulty, mode)); } } } } return rankings; } private Ranking createGeneralRanking() { Ranking ranking = new Ranking(findBestScoresByVIPPlayers()); List<Score> scores = new ArrayList<Score>(); for (int rank = 0; rank < ranking.scores.size(); rank++) { Score score = ranking.scores.get(rank); scores.add(new Score(score.id, score.game, score.player, score.stage, score.ship, score.mode, score.difficulty, score.comment, score.platform, score.value, score.photo, score.replay, rank + 1)); } Ranking ranking1 = new Ranking(scores); ranking1.general = true; return ranking1; } public Collection<Score> findBestScoresByVIPPlayers(final Difficulty difficulty, final Mode mode) { if (scores == null) { return new ArrayList<Score>(); } List<Score> scores = Score.finder. fetch("mode"). fetch("difficulty"). fetch("player"). where().conjunction(). add(eq("game", this)). add(eq("difficulty", difficulty)). add(eq("mode", mode)). orderBy((mode == null || !mode.isTimerScore()) ? "value desc" : "value").findList(); return keepBestScoreByVIPPlayer(scores); } private Collection<Score> findBestScoresByVIPPlayers() { if (scores == null) { return new ArrayList<Score>(); } List<Score> scores = Score.finder. where().conjunction(). add(eq("game", this)). add(isNotNull("rank")). orderBy("value desc").findList(); return keepBestScoreByVIPPlayer(scores); } private Collection<Score> keepBestScoreByVIPPlayer(List<Score> scores) { final Set<Player> players = new HashSet<Player>(); return filter(scores, new Predicate<Score>() { @Override public boolean apply(@Nullable Score score) { if (players.contains(score.player)) { return false; } if (!score.player.isVip()) { return false; } players.add(score.player); return true; } }); } public String post() { return thread.replace("viewtopic.php?", "posting.php?mode=reply&f=20&"); } @Override public String toString() { return title; } public String getEscapedTitle() { String s = title.replaceAll("[^a-zA-Z0-9]", "_"); s = s.replaceAll("_(_)*", "_"); if (s.endsWith("_")) { s = s.substring(0, s.length() - 1); } return s; } public void recomputeRankings() { for (Score score : allScores) { score.updateRank(null); score.update(); } rankings(); } public String getCoverType() { if (cover.endsWith("jpg") || cover.endsWith("jpeg")) { return "image/jpeg"; } if (cover.endsWith("png")) { return "image/png"; } return "image/gif"; } public Integer getScoreCountLast30Days() { final Date _30DaysAgo = new DateMidnight().minusDays(30).toDate(); final Date gameCreatedAt = new DateMidnight(Game.this.getCreatedAt()).plusDays(1).toDate(); return filter(scores, new Predicate<Score>() { @Override public boolean apply(@Nullable Score score) { return score.getCreatedAt().after(_30DaysAgo) && score.getCreatedAt().after(gameCreatedAt); } }).size(); } public Collection<Player> getPlayers() { Set<Player> players = new HashSet<Player>(); for (Score score : scores) { players.add(score.player); } return players; } @Override public int compareTo(Game game) { return this.title.compareTo(game.title); } public boolean hasShip() { return ships != null && !ships.isEmpty(); } public int getOneCreditCount() { return oneccs.size(); } public boolean hasTimerScores() { if (this.modes == null || this.modes.isEmpty()) { return false; } for (Mode mode : modes) { if (mode.isTimerScore()) { return true; } } return false; } }
package models; import java.util.ArrayList; import java.util.List; import javax.persistence.*; import models.base.BaseNotifiable; import models.base.INotifiable; import play.data.validation.Constraints.Required; import play.db.jpa.JPA; import play.libs.F; @Entity public class Post extends BaseNotifiable implements INotifiable { public static final String GROUP = "group"; // post to group news stream public static final String PROFILE = "profile"; // post to own news stream public static final String STREAM = "stream"; // post to a foreign news stream public static final String COMMENT_PROFILE = "comment_profile"; // comment on a profile post public static final String COMMENT_GROUP = "comment_group"; // comment on a group post public static final String COMMENT_OWN_PROFILE = "comment_profile_own"; // comment on own news stream public static final String BROADCAST = "broadcast"; // broadcast post from admin control center public static final int PAGE = 1; @Required @Column(length=2000) public String content; @ManyToOne public Post parent; @ManyToOne public Group group; @ManyToOne public Account account; @ManyToOne public Account owner; @Column(name = "is_broadcast", nullable = false, columnDefinition = "boolean default false") public boolean isBroadcastMessage; @ManyToMany @JoinTable( name = "broadcast_account", joinColumns = { @JoinColumn(name = "post_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "account_id", referencedColumnName = "id") } ) public List<Account> broadcastPostRecipients; public void create() { JPA.em().persist(this); } @Override public void update() { updatedAt(); } @Override public void delete() { // delete all comments first List<Post> comments = getCommentsForPost(this.id, 0, 0); for (Post comment : comments) { comment.delete(); } Notification.deleteReferences(this); JPA.em().remove(this); } protected static Query limit(Query query, int limit, int offset) { if (limit > 0) { query.setMaxResults(limit); } if (offset >= 0) { query.setFirstResult(offset); } return query; } public static Post findById(Long id) { return JPA.em().find(Post.class, id); } @SuppressWarnings("unchecked") public static List<Post> getPostsForGroup(Group group, int limit, int page) { Query query = JPA.em() .createQuery("SELECT p FROM Post p WHERE p.group.id = ?1 ORDER BY p.createdAt DESC") .setParameter(1, group.id); int offset = (page * limit) - limit; query = limit(query, limit, offset); return query.getResultList(); } public static int countPostsForGroup(Group group) { return ((Number)JPA.em().createQuery("SELECT COUNT(p) FROM Post p WHERE p.group.id = ?1").setParameter(1, group.id).getSingleResult()).intValue(); } @SuppressWarnings("unchecked") public static List<Post> getCommentsForPost(Long id, int start, int max) { return (List<Post>) JPA.em() .createQuery("SELECT p FROM Post p WHERE p.parent.id = ?1 ORDER BY p.createdAt ASC") .setParameter(1, id) .setFirstResult(start) .setMaxResults(max) .getResultList(); } /** * Method getCommentsForPostTransactional() JPA transactional. * * @param id ID of parent post * @param start Comment start * @param max Max comments * @return List of Posts */ public static List<Post> getCommentsForPostTransactional(final Long id, final int start, final int max) { try { return JPA.withTransaction(new F.Function0<List<Post>>() { @Override public List<Post> apply() throws Throwable { return Post.getCommentsForPost(id, start, max); } }); } catch (Throwable throwable) { throwable.printStackTrace(); return null; } } @SuppressWarnings("unchecked") public static List<Post> findStreamForAccount(final Account account, final List<Group> groupList, final List<Account> friendList, final boolean isVisitor, final int limit, final int offset) { try { return JPA.withTransaction(new F.Function0<List>() { @Override public List apply() throws Throwable { Query query = streamForAccount("SELECT DISTINCT p ", account, groupList, friendList, isVisitor, " ORDER BY p.updatedAt DESC"); // set limit and offset query = limit(query, limit, offset); return query.getResultList(); } }); } catch (Throwable throwable) { throwable.printStackTrace(); return null; } } public static int countStreamForAccount(final Account account, final List<Group> groupList, final List<Account> friendList, final boolean isVisitor) { try { return JPA.withTransaction(new F.Function0<Integer>() { @Override public Integer apply() throws Throwable { final Query query = streamForAccount("SELECT DISTINCT COUNT(p)", account, groupList, friendList, isVisitor,""); return ((Number) query.getSingleResult()).intValue(); } }); } catch (Throwable throwable) { throwable.printStackTrace(); return 0; } } /** * @param account - Account (current user, profile or a friend) * @param groupList - a list containing all groups we want to search in * @param friendList - a list containing all friends we want to search in * @return List of Posts */ public static Query streamForAccount(String selectClause, Account account, List<Group> groupList, List<Account> friendList, boolean isVisitor, String orderByClause){ // since JPA is unable to handle empty lists (eg. groupList, friendList) we need to assemble our query. String myPostsClause; String groupListClause = ""; String friendListClause = ""; String visitorClause = ""; String broadcastJoin = ""; String broadcastClause = ""; /** * finds all stream-post for account. * e.g account = myself * 1. if i'm mentioned in post.account, somebody posted me. (yep, we want this => 'p.account = :account') * 2. if i'm post.owner, i posted somewhere (yep, we want this too => 'p.owner = :account') * BUT, if i'm the owner and post.parent is set, it's only a comment. so => 'p.parent = NULL' */ myPostsClause = " p.account = :account OR (p.owner = :account AND p.parent = NULL) "; // add additional clauses if not null or empty if (friendList != null && !friendList.isEmpty()) { /** * finds all own stream-posts of my friends. * e.g account = a friend of mine * 1. if my friend is mentioned in p.account, somebody posted him => 'p.account IN :friendList' * BUT, we only want his/her own posts. so he has to be the owner as well => 'p.account = p.owner' */ friendListClause = " OR p.account IN :friendList AND p.account = p.owner"; } if (groupList != null && !groupList.isEmpty()) { // finds all stream-post of groups groupListClause = " OR p.group IN :groupList "; } if (isVisitor) { /** * since 'myPostsClause' includes posts where the given account posted to someone ('OR (p.owner = :account AND p.parent = NULL)'). * we have to modify it for the friends-stream (cut it out). */ myPostsClause = " p.account = :account "; /** * groupListClause includes all posts where my friend is member/owner of. * but we only need those posts where he/she is owner of. */ if (groupList != null && !groupList.isEmpty()) { visitorClause = " AND p.owner = :account "; } } else { // its the origin user, show also broadcast messages broadcastJoin = " LEFT JOIN p.broadcastPostRecipients bc_recipients"; broadcastClause = " OR bc_recipients = :account "; } // create Query. String completeQuery = selectClause + " FROM Post p" + broadcastJoin + " WHERE " + myPostsClause + groupListClause + friendListClause + visitorClause + broadcastClause + orderByClause; Query query = JPA.em().createQuery(completeQuery); query.setParameter("account", account); // add parameter as needed if (groupList != null && !groupList.isEmpty()) { query.setParameter("groupList", groupList); } if (friendList != null && !friendList.isEmpty()) { query.setParameter("friendList", friendList); } return query; } public static int countCommentsForPost(final Long id) { try { return JPA.withTransaction(new F.Function0<Integer>() { @Override public Integer apply() throws Throwable { return ((Number)JPA.em().createQuery("SELECT COUNT(p.id) FROM Post p WHERE p.parent.id = ?1").setParameter(1, id).getSingleResult()).intValue(); } }); } catch (Throwable throwable) { throwable.printStackTrace(); return 0; } } public int getCountComments() { return Post.countCommentsForPost(this.id); } public boolean belongsToGroup() { return this.group != null; } public boolean belongsToAccount() { return this.account != null; } /** * @param account Account (current user) * @return List of Posts */ public static List<Post> getStream(Account account, int limit, int page) { // find friends and groups of given account List<Account> friendList = Friendship.findFriends(account); List<Group> groupList = GroupAccount.findEstablishedTransactional(account); int offset = (page * limit) - limit; return findStreamForAccount(account, groupList, friendList, false, limit, offset); } /** * @param account Account (current user) * @return Number of Posts */ public static int countStream(Account account){ // find friends and groups of given account List<Account> friendList = Friendship.findFriends(account); List<Group> groupList = GroupAccount.findEstablishedTransactional(account); return countStreamForAccount(account, groupList, friendList, false); } /** * @param friend - Account (a friends account) * @return List of Posts */ public static List<Post> getFriendStream(Account friend, int limit, int page) { // find open groups for given account List<Group> groupList = GroupAccount.findPublicEstablished(friend); int offset = (page * limit) - limit; return findStreamForAccount(friend, groupList, null, true, limit, offset); } /** * @param friend - Account (a friends account) * @return Number of Posts */ public static int countFriendStream(Account friend){ // find groups of given account List<Group> groupList = GroupAccount.findPublicEstablished(friend); return countStreamForAccount(friend, groupList, null, true); } @Override public Account getSender() { return this.owner; } @Override public List<Account> getRecipients() { if (this.type.equals(Post.BROADCAST)) { return this.broadcastPostRecipients; } // if this is a comment, return the parent information if (this.parent != null) { // if this is a comment on own news stream, send notification to the initial poster if (this.type.equals(Post.COMMENT_OWN_PROFILE)) { return this.parent.getAsAccountList(this.parent.owner); } return this.parent.belongsToAccount() ? this.parent.getAsAccountList(this.parent.account) : this.parent.getGroupAsAccountList(this.parent.group); } // return account if not null, otherwise group return this.belongsToAccount() ? this.getAsAccountList(this.account) : this.getGroupAsAccountList(this.group); } /** * Adds an account to the persistent recipient list. * * @param recipient One of the recipients */ public void addRecipient(Account recipient) { if (this.broadcastPostRecipients == null) { this.broadcastPostRecipients = new ArrayList<>(); } if (!this.broadcastPostRecipients.contains(recipient)) { this.broadcastPostRecipients.add(recipient); } } @Override public String getTargetUrl() { if (this.type.equals(Post.GROUP)) { return controllers.routes.GroupController.view(this.group.id, Post.PAGE).toString(); } if (this.type.equals(Post.PROFILE)) { return controllers.routes.ProfileController.stream(this.account.id, Post.PAGE).toString(); } if (this.type.equals(Post.COMMENT_PROFILE)) { return controllers.routes.ProfileController.stream(this.parent.account.id, Post.PAGE).toString(); } if (this.type.equals(Post.COMMENT_GROUP)) { return controllers.routes.GroupController.view(this.parent.group.id, Post.PAGE).toString(); } if (this.type.equals(Post.COMMENT_OWN_PROFILE)) { return controllers.routes.ProfileController.stream(this.parent.account.id, Post.PAGE).toString(); } if (this.type.equals(Post.BROADCAST)) { return controllers.routes.Application.stream(Post.PAGE).toString(); } return super.getTargetUrl(); } }
package models; import java.util.List; import javax.persistence.Entity; import javax.persistence.Id; import play.data.validation.Constraints.Required; import play.db.ebean.Model; @Entity @SuppressWarnings("serial") public class Post extends Model { @Id public Long key; @Required public String title; @Required public String content; public static Finder<Long, Post> find = new Finder<Long, Post>(Long.class, Post.class); public static List<Post> all() { return find.all(); } public static void create(Post post) { post.save(); } public static void delete(Long key) { find.ref(key).delete(); } public static Post get(long key) { return find.ref(key); } public static void update(long key, Post post) { post.update(key); } public Long getKey() { return key; } public void setKey(Long key) { this.key = key; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Post [key=").append(key).append(", title=") .append(title).append(", content=").append(content).append("]"); return builder.toString(); } }
package core; import java.sql.*; public class Database { private static Connection conn = null; public Database(){ try{ Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite:app_data/test.db"); createTables(); }catch(Exception ex){ ex.printStackTrace(); } } private void createTables(){ try{ Statement statement = conn.createStatement(); statement.setQueryTimeout(30); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "DiscordServer(" + "id INTEGER NOT NULL, " + "name VARCHAR(50) NOT NULL, " + "PRIMARY KEY (id)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "Player(" + "id INTEGER NOT NULL, " + "name VARCHAR(50) NOT NULL, " + "PRIMARY KEY (id)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "Queue(" + "name VARCHAR(50) NOT NULL, " + "serverId INTEGER NOT NULL, " + "PRIMARY KEY (name, serverId), " + "FOREIGN KEY (serverId) REFERENCES Server(id)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "Game(" + "timestamp INTEGER NOT NULL, " + "queueName VARCHAR(50) NOT NULL, " + "serverId INTEGER NOT NULL, " + "PRIMARY KEY (timestamp, queueName, serverId), " + "FOREIGN KEY (serverId) REFERENCES Queue(serverId)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "PlayerGame(" + "playerId INTEGER NOT NULL, " + "timestamp INTEGER NOT NULL, " + "serverId INTEGER NOT NULL, " + "pickOrder INTEGER, " + "captain INTEGER DEFAULT 0, " + "PRIMARY KEY (playerId, timestamp, serverId), " + "FOREIGN KEY (playerId) REFERENCES Player(id), " + "FOREIGN KEY (serverId) REFERENCES Game(serverId), " + "FOREIGN KEY (timestamp) REFERENCES Game(timestamp)" + ")"); }catch(Exception ex){ ex.printStackTrace(); } } public static void insertDiscordServer(Long id, String name){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO DiscordServer VALUES(?, ?)"); pStatement.setLong(1, id); pStatement.setString(2, name); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } public static void insertPlayer(Long id, String name){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO Player VALUES(?, ?)"); pStatement.setLong(1, id); pStatement.setString(2, name); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } public static void insertQueue(Long serverId, String Name){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO Queue VALUES(?, ?)"); pStatement.setString(1, Name); pStatement.setLong(2, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } public static void insertGame(Long timestamp, String queueName, Long serverId){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO Game VALUES(?, ?, ?)"); pStatement.setLong(1, timestamp); pStatement.setString(2, queueName); pStatement.setLong(3, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } public static void insertPlayerGame(Long playerId, Long timestamp, Long serverId){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO PlayerGame (playerId, timestamp, serverId) VALUES(?, ?, ?)"); pStatement.setLong(1, playerId); pStatement.setLong(2, timestamp); pStatement.setLong(3, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } public static void updatePlayerGamePickOrder(Long playerId, Long timestamp, Long serverId, Integer pickOrder){ try{ PreparedStatement pStatement = conn.prepareStatement("UPDATE PlayerGame SET pickOrder = ? " + "WHERE playerId = ? AND timestamp = ? AND serverId = ?"); pStatement.setInt(1, pickOrder); pStatement.setLong(2, playerId); pStatement.setLong(3, timestamp); pStatement.setLong(4, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } public static void updatePlayerGameCaptain(Long playerId, Long timestamp, Long serverId, boolean captain){ Integer captainInt = 0; if(captain){ captainInt = 1; } try{ PreparedStatement pStatement = conn.prepareStatement("UPDATE PlayerGame SET captain = ? " + "WHERE playerId = ? AND timestamp = ? AND serverId = ?"); pStatement.setInt(1, captainInt); pStatement.setLong(2, playerId); pStatement.setLong(3, timestamp); pStatement.setLong(4, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.core; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import net.opentsdb.uid.UniqueId; import org.hbase.async.Bytes; import org.hbase.async.KeyValue; import org.hbase.async.Scanner; import com.stumbleupon.async.Callback; public final class Internal { /** @see Const#FLAG_BITS */ public static final short FLAG_BITS = Const.FLAG_BITS; /** @see Const#LENGTH_MASK */ public static final short LENGTH_MASK = Const.LENGTH_MASK; /** @see Const#FLAGS_MASK */ public static final short FLAGS_MASK = Const.FLAGS_MASK; private Internal() { // Can't instantiate. } /** @see TsdbQuery#getScanner */ public static Scanner getScanner(final Query query) { return ((TsdbQuery) query).getScanner(); } /** @see RowKey#metricName */ public static String metricName(final TSDB tsdb, final byte[] id) { return RowKey.metricName(tsdb, id); } /** Extracts the timestamp from a row key. */ public static long baseTime(final TSDB tsdb, final byte[] row) { return Bytes.getUnsignedInt(row, tsdb.metrics.width()); } /** @return the time normalized to an hour boundary in epoch seconds */ public static long baseTime(final long timestamp) { if ((timestamp & Const.SECOND_MASK) != 0) { // drop the ms timestamp to seconds to calculate the base timestamp return ((timestamp / 1000) - ((timestamp / 1000) % Const.MAX_TIMESPAN)); } else { return (timestamp - (timestamp % Const.MAX_TIMESPAN)); } } /** @see Tags#getTags */ public static Map<String, String> getTags(final TSDB tsdb, final byte[] row) { return Tags.getTags(tsdb, row); } /** @see RowSeq#extractIntegerValue */ public static long extractIntegerValue(final byte[] values, final int value_idx, final byte flags) { return RowSeq.extractIntegerValue(values, value_idx, flags); } /** @see RowSeq#extractFloatingPointValue */ public static double extractFloatingPointValue(final byte[] values, final int value_idx, final byte flags) { return RowSeq.extractFloatingPointValue(values, value_idx, flags); } /** @see TSDB#metrics_width() */ public static short metricWidth(final TSDB tsdb) { return tsdb.metrics.width(); } public static Cell parseSingleValue(final KeyValue column) { if (column.qualifier().length == 2 || (column.qualifier().length == 4 && inMilliseconds(column.qualifier()))) { final ArrayList<KeyValue> row = new ArrayList<KeyValue>(1); row.add(column); final ArrayList<Cell> cells = extractDataPoints(row, 1); if (cells.isEmpty()) { return null; } return cells.get(0); } throw new IllegalDataException ( "Qualifier does not appear to be a single data point: " + column); } public static ArrayList<Cell> extractDataPoints(final KeyValue column) { final ArrayList<KeyValue> row = new ArrayList<KeyValue>(1); row.add(column); return extractDataPoints(row, column.qualifier().length / 2); } public static ArrayList<Cell> extractDataPoints(final ArrayList<KeyValue> row, final int estimated_nvalues) { final ArrayList<Cell> cells = new ArrayList<Cell>(estimated_nvalues); for (final KeyValue kv : row) { final byte[] qual = kv.qualifier(); final int len = qual.length; final byte[] val = kv.value(); if (len % 2 != 0) { // skip a non data point column continue; } else if (len == 2) { // Single-value cell. // Maybe we need to fix the flags in the qualifier. final byte[] actual_val = fixFloatingPointValue(qual[1], val); final byte q = fixQualifierFlags(qual[1], actual_val.length); final byte[] actual_qual; if (q != qual[1]) { // We need to fix the qualifier. actual_qual = new byte[] { qual[0], q }; // So make a copy. } else { actual_qual = qual; // Otherwise use the one we already have. } final Cell cell = new Cell(actual_qual, actual_val); cells.add(cell); continue; } else if (len == 4 && inMilliseconds(qual[0])) { // since ms support is new, there's nothing to fix final Cell cell = new Cell(qual, val); cells.add(cell); continue; } // Now break it down into Cells. int val_idx = 0; try { for (int i = 0; i < len; i += 2) { final byte[] q = extractQualifier(qual, i); final int vlen = getValueLengthFromQualifier(qual, i); if (inMilliseconds(qual[i])) { i += 2; } final byte[] v = new byte[vlen]; System.arraycopy(val, val_idx, v, 0, vlen); val_idx += vlen; final Cell cell = new Cell(q, v); cells.add(cell); } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalDataException("Corrupted value: couldn't break down" + " into individual values (consumed " + val_idx + " bytes, but was" + " expecting to consume " + (val.length - 1) + "): " + kv + ", cells so far: " + cells); } // Check we consumed all the bytes of the value. Remember the last byte // is metadata, so it's normal that we didn't consume it. if (val_idx != val.length - 1) { throw new IllegalDataException("Corrupted value: couldn't break down" + " into individual values (consumed " + val_idx + " bytes, but was" + " expecting to consume " + (val.length - 1) + "): " + kv + ", cells so far: " + cells); } } Collections.sort(cells); return cells; } /** * Represents a single data point in a row. Compacted columns may not be * stored in a cell. * <p> * This is simply a glorified pair of (qualifier, value) that's comparable. * Only the qualifier is used to make comparisons. * @since 2.0 */ public static final class Cell implements Comparable<Cell> { /** Tombstone used as a helper during the complex compaction. */ public static final Cell SKIP = new Cell(null, null); final byte[] qualifier; final byte[] value; /** * Constructor that sets the cell * @param qualifier Qualifier to store * @param value Value to store */ public Cell(final byte[] qualifier, final byte[] value) { this.qualifier = qualifier; this.value = value; } /** Compares the qualifiers of two cells */ public int compareTo(final Cell other) { return compareQualifiers(qualifier, 0, other.qualifier, 0); } /** Determines if the cells are equal based on their qualifier */ @Override public boolean equals(final Object o) { return o != null && o instanceof Cell && compareTo((Cell) o) == 0; } /** @return a hash code based on the qualifier bytes */ @Override public int hashCode() { return Arrays.hashCode(qualifier); } /** Prints the raw data of the qualifier and value */ @Override public String toString() { return "Cell(" + Arrays.toString(qualifier) + ", " + Arrays.toString(value) + ')'; } /** @return the qualifier byte array */ public byte[] qualifier() { return qualifier; } /** @return the value byte array */ public byte[] value() { return value; } public Number parseValue() { if (isInteger()) { return extractIntegerValue(value, 0, (byte)getFlagsFromQualifier(qualifier)); } else { return extractFloatingPointValue(value, 0, (byte)getFlagsFromQualifier(qualifier)); } } /** * Returns the Unix epoch timestamp in milliseconds * @param base_time Row key base time to add the offset to * @return Unix epoch timestamp in milliseconds */ public long timestamp(final long base_time) { return getTimestampFromQualifier(qualifier, base_time); } /** * Returns the timestamp as stored in HBase for the cell, i.e. in seconds * or milliseconds * @param base_time Row key base time to add the offset to * @return Unix epoch timestamp */ public long absoluteTimestamp(final long base_time) { final long timestamp = getTimestampFromQualifier(qualifier, base_time); if (inMilliseconds(qualifier)) { return timestamp; } else { return timestamp / 1000; } } /** @return Whether or not the value is an integer */ public boolean isInteger() { return (Internal.getFlagsFromQualifier(qualifier) & Const.FLAG_FLOAT) == 0x0; } } /** * Helper to sort a row with a mixture of millisecond and second data points. * In such a case, we convert all of the seconds into millisecond timestamps, * then perform the comparison. * <b>Note:</b> You must filter out all but the second, millisecond and * compacted rows * @since 2.0 */ public static final class KeyValueComparator implements Comparator<KeyValue> { /** * Compares the qualifiers from two key values * @param a The first kv * @param b The second kv * @return 0 if they have the same timestamp, -1 if a is less than b, 1 * otherwise. */ public int compare(final KeyValue a, final KeyValue b) { return compareQualifiers(a.qualifier(), 0, b.qualifier(), 0); } } /** * Callback used to fetch only the last data point from a row returned as the * result of a GetRequest. Non data points will be parsed out and the * resulting time and value stored in an IncomingDataPoint if found. If no * valid data was found, a null is returned. * @since 2.0 */ public static class GetLastDataPointCB implements Callback<IncomingDataPoint, ArrayList<KeyValue>> { final TSDB tsdb; public GetLastDataPointCB(final TSDB tsdb) { this.tsdb = tsdb; } /** * Returns the last data point from a data row in the TSDB table. * @param row The row from HBase * @return null if no data was found, a data point if one was */ public IncomingDataPoint call(final ArrayList<KeyValue> row) throws Exception { if (row == null || row.size() < 1) { return null; } // check to see if the cells array is empty as it will flush out all // non-data points. final ArrayList<Cell> cells = extractDataPoints(row, row.size()); if (cells.isEmpty()) { return null; } final Cell cell = cells.get(cells.size() - 1); final IncomingDataPoint dp = new IncomingDataPoint(); final long base_time = baseTime(tsdb, row.get(0).key()); dp.setTimestamp(getTimestampFromQualifier(cell.qualifier(), base_time)); dp.setValue(cell.parseValue().toString()); return dp; } } /** * Compares two data point byte arrays with offsets. * Can be used on: * <ul><li>Single data point columns</li> * <li>Compacted columns</li></ul> * <b>Warning:</b> Does not work on Annotation or other columns * @param a The first byte array to compare * @param offset_a An offset for a * @param b The second byte array * @param offset_b An offset for b * @return 0 if they have the same timestamp, -1 if a is less than b, 1 * otherwise. * @since 2.0 */ public static int compareQualifiers(final byte[] a, final int offset_a, final byte[] b, final int offset_b) { final long left = Internal.getOffsetFromQualifier(a, offset_a); final long right = Internal.getOffsetFromQualifier(b, offset_b); if (left == right) { return 0; } return (left < right) ? -1 : 1; } /** * Fix the flags inside the last byte of a qualifier. * <p> * OpenTSDB used to not rely on the size recorded in the flags being * correct, and so for a long time it was setting the wrong size for * floating point values (pretending they were encoded on 8 bytes when * in fact they were on 4). So overwrite these bits here to make sure * they're correct now, because once they're compacted it's going to * be quite hard to tell if the flags are right or wrong, and we need * them to be correct to easily decode the values. * @param flags The least significant byte of a qualifier. * @param val_len The number of bytes in the value of this qualifier. * @return The least significant byte of the qualifier with correct flags. */ public static byte fixQualifierFlags(byte flags, final int val_len) { // Explanation: // (1) Take the last byte of the qualifier. // (2) Zero out all the flag bits but one. // The one we keep is the type (floating point vs integer value). // (3) Set the length properly based on the value we have. return (byte) ((flags & ~(Const.FLAGS_MASK >>> 1)) | (val_len - 1)); // (1) (2) (3) } /** * Returns whether or not this is a floating value that needs to be fixed. * <p> * OpenTSDB used to encode all floating point values as `float' (4 bytes) * but actually store them on 8 bytes, with 4 leading 0 bytes, and flags * correctly stating the value was on 4 bytes. * (from CompactionQueue) * @param flags The least significant byte of a qualifier. * @param value The value that may need to be corrected. */ public static boolean floatingPointValueToFix(final byte flags, final byte[] value) { return (flags & Const.FLAG_FLOAT) != 0 // We need a floating point value. && (flags & Const.LENGTH_MASK) == 0x3 // That pretends to be on 4 bytes. && value.length == 8; // But is actually using 8 bytes. } public static byte[] fixFloatingPointValue(final byte flags, final byte[] value) { if (floatingPointValueToFix(flags, value)) { // The first 4 bytes should really be zeros. if (value[0] == 0 && value[1] == 0 && value[2] == 0 && value[3] == 0) { // Just keep the last 4 bytes. return new byte[] { value[4], value[5], value[6], value[7] }; } else { // Very unlikely. throw new IllegalDataException("Corrupted floating point value: " + Arrays.toString(value) + " flags=0x" + Integer.toHexString(flags) + " -- first 4 bytes are expected to be zeros."); } } return value; } /** * Determines if the qualifier is in milliseconds or not * @param qualifier The qualifier to parse * @param offset An offset from the start of the byte array * @return True if the qualifier is in milliseconds, false if not * @since 2.0 */ public static boolean inMilliseconds(final byte[] qualifier, final int offset) { return inMilliseconds(qualifier[offset]); } /** * Determines if the qualifier is in milliseconds or not * @param qualifier The qualifier to parse * @return True if the qualifier is in milliseconds, false if not * @since 2.0 */ public static boolean inMilliseconds(final byte[] qualifier) { return inMilliseconds(qualifier[0]); } /** * Determines if the qualifier is in milliseconds or not * @param qualifier The first byte of a qualifier * @return True if the qualifier is in milliseconds, false if not * @since 2.0 */ public static boolean inMilliseconds(final byte qualifier) { return (qualifier & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG; } public static int getOffsetFromQualifier(final byte[] qualifier) { return getOffsetFromQualifier(qualifier, 0); } public static int getOffsetFromQualifier(final byte[] qualifier, final int offset) { validateQualifier(qualifier, offset); if ((qualifier[offset] & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG) { return (int)(Bytes.getUnsignedInt(qualifier, offset) & 0x0FFFFFC0) Const.MS_FLAG_BITS; } else { final int seconds = (Bytes.getUnsignedShort(qualifier, offset) & 0xFFFF) Const.FLAG_BITS; return seconds * 1000; } } public static byte getValueLengthFromQualifier(final byte[] qualifier) { return getValueLengthFromQualifier(qualifier, 0); } public static byte getValueLengthFromQualifier(final byte[] qualifier, final int offset) { validateQualifier(qualifier, offset); short length; if ((qualifier[offset] & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG) { length = (short) (qualifier[offset + 3] & Internal.LENGTH_MASK); } else { length = (short) (qualifier[offset + 1] & Internal.LENGTH_MASK); } return (byte) (length + 1); } public static short getQualifierLength(final byte[] qualifier) { return getQualifierLength(qualifier, 0); } public static short getQualifierLength(final byte[] qualifier, final int offset) { validateQualifier(qualifier, offset); if ((qualifier[offset] & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG) { if ((offset + 4) > qualifier.length) { throw new IllegalArgumentException( "Detected a millisecond flag but qualifier length is too short"); } return 4; } else { if ((offset + 2) > qualifier.length) { throw new IllegalArgumentException("Qualifier length is too short"); } return 2; } } public static long getTimestampFromQualifier(final byte[] qualifier, final long base_time) { return (base_time * 1000) + getOffsetFromQualifier(qualifier); } public static long getTimestampFromQualifier(final byte[] qualifier, final long base_time, final int offset) { return (base_time * 1000) + getOffsetFromQualifier(qualifier, offset); } public static short getFlagsFromQualifier(final byte[] qualifier) { return getFlagsFromQualifier(qualifier, 0); } public static short getFlagsFromQualifier(final byte[] qualifier, final int offset) { validateQualifier(qualifier, offset); if ((qualifier[offset] & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG) { return (short) (qualifier[offset + 3] & Internal.FLAGS_MASK); } else { return (short) (qualifier[offset + 1] & Internal.FLAGS_MASK); } } public static boolean isFloat(final byte[] qualifier) { return isFloat(qualifier, 0); } public static boolean isFloat(final byte[] qualifier, final int offset) { validateQualifier(qualifier, offset); if ((qualifier[offset] & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG) { return (qualifier[offset + 3] & Const.FLAG_FLOAT) == Const.FLAG_FLOAT; } else { return (qualifier[offset + 1] & Const.FLAG_FLOAT) == Const.FLAG_FLOAT; } } public static byte[] extractQualifier(final byte[] qualifier, final int offset) { validateQualifier(qualifier, offset); if ((qualifier[offset] & Const.MS_BYTE_FLAG) == Const.MS_BYTE_FLAG) { return new byte[] { qualifier[offset], qualifier[offset + 1], qualifier[offset + 2], qualifier[offset + 3] }; } else { return new byte[] { qualifier[offset], qualifier[offset + 1] }; } } /** * Returns a 2 or 4 byte qualifier based on the timestamp and the flags. If * the timestamp is in seconds, this returns a 2 byte qualifier. If it's in * milliseconds, returns a 4 byte qualifier * @param timestamp A Unix epoch timestamp in seconds or milliseconds * @param flags Flags to set on the qualifier (length &| float) * @return A 2 or 4 byte qualifier for storage in column or compacted column * @since 2.0 */ public static byte[] buildQualifier(final long timestamp, final short flags) { final long base_time; if ((timestamp & Const.SECOND_MASK) != 0) { // drop the ms timestamp to seconds to calculate the base timestamp base_time = ((timestamp / 1000) - ((timestamp / 1000) % Const.MAX_TIMESPAN)); final int qual = (int) (((timestamp - (base_time * 1000) << (Const.MS_FLAG_BITS)) | flags) | Const.MS_FLAG); return Bytes.fromInt(qual); } else { base_time = (timestamp - (timestamp % Const.MAX_TIMESPAN)); final short qual = (short) ((timestamp - base_time) << Const.FLAG_BITS | flags); return Bytes.fromShort(qual); } } private static void validateQualifier(final byte[] qualifier, final int offset) { if (offset < 0 || offset >= qualifier.length - 1) { throw new IllegalDataException("Offset of [" + offset + "] is out of bounds for the qualifier length of [" + qualifier.length + "]"); } } /** * Sets the server-side regexp filter on the scanner. * This will compile a list of the tagk/v pairs for the TSUIDs to prevent * storage from returning irrelevant rows. * @param scanner The scanner on which to add the filter. * @param tsuids The list of TSUIDs to filter on * @since 2.1 */ public static void createAndSetTSUIDFilter(final Scanner scanner, final List<String> tsuids) { Collections.sort(tsuids); // first, convert the tags to byte arrays and count up the total length // so we can allocate the string builder final short metric_width = TSDB.metrics_width(); int tags_length = 0; final ArrayList<byte[]> uids = new ArrayList<byte[]>(tsuids.size()); for (final String tsuid : tsuids) { final String tags = tsuid.substring(metric_width * 2); final byte[] tag_bytes = UniqueId.stringToUid(tags); tags_length += tag_bytes.length; uids.add(tag_bytes); } // Generate a regexp for our tags based on any metric and timestamp (since // those are handled by the row start/stop) and the list of TSUID tagk/v // pairs. The generated regex will look like: ^.{7}(tags|tags|tags)$ // where each "tags" is similar to \\Q\000\000\001\000\000\002\\E final StringBuilder buf = new StringBuilder( 13 + (tsuids.size() * 11) // "\\Q" + "\\E|" + tags_length); // total # of bytes in tsuids tagk/v pairs // Alright, let's build this regexp. From the beginning... buf.append("(?s)" // Ensure we use the DOTALL flag. + "^.{") // ... start by skipping the metric ID and timestamp. .append(TSDB.metrics_width() + Const.TIMESTAMP_BYTES) .append("}("); for (final byte[] tags : uids) { // quote the bytes buf.append("\\Q"); UniqueId.addIdToRegexp(buf, tags); buf.append('|'); } // Replace the pipe of the last iteration, close and set buf.setCharAt(buf.length() - 1, ')'); buf.append("$"); scanner.setKeyRegexp(buf.toString(), Charset.forName("ISO-8859-1")); } }
package edu.mit.simile.butterfly; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.security.AccessControlException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.ExtendedProperties; import org.apache.log4j.PropertyConfigurator; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Script; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.mit.simile.butterfly.velocity.ButterflyResourceLoader; import edu.mit.simile.butterfly.velocity.Super; /** * This is the Butterfly servlet and the main entry point * for a Butterfly-powered web application. This servlet is * responsible for loading, configuring and wire together * the various modules that compose your webapp and then * manages the dispatching of requests to the modules that * are supposed to handle them. */ public class Butterfly extends HttpServlet { public static final String HOST_HEADER = "X-Forwarded-Host"; public static final String CONTEXT_HEADER = "X-Context-Path"; private static final long serialVersionUID = 1938797827088619577L; private static final long watcherDelay = 1000; public static final String NAME = "butterfly.name"; public static final String APPENGINE = "butterfly.appengine"; public static final String AUTORELOAD = "butterfly.autoreload"; public static final String HOME = "butterfly.home"; public static final String ZONE = "butterfly.zone"; public static final String BASE_URL = "butterfly.url"; public static final String DEFAULT_ZONE = "butterfly.default.zone"; public static final String MAIN_ZONE = "main"; public static final List<String> CONTROLLER; private static final ContextFactory contextFactory = new ButterflyContextFactory(); static { ContextFactory.initGlobal(contextFactory); CONTROLLER = new ArrayList<String>(); CONTROLLER.add("controller.js"); } static class ButterflyContextFactory extends ContextFactory { protected void onContextCreated(Context cx) { cx.setOptimizationLevel(9); super.onContextCreated(cx); } } public static String getTrueHost(HttpServletRequest request) { String host = request.getHeader(HOST_HEADER); if (host != null) { String[] hosts = host.split(","); host = hosts[hosts.length - 1]; } return host; } public static String getTrueContextPath(HttpServletRequest request, boolean absolute) { String context = request.getHeader(CONTEXT_HEADER); if (context != null) { if (context.charAt(context.length() - 1) == '/') context = context.substring(0, context.length() - 1); } else { context = request.getContextPath(); } if (absolute) { return getFullHost(request) + context; } else { return context; } } public static String getTrueRequestURI(HttpServletRequest request, boolean absolute) { return getTrueContextPath(request,absolute) + request.getPathInfo(); } public static String getFullHost(HttpServletRequest request) { StringBuffer prefix = new StringBuffer(); String protocol = request.getScheme(); prefix.append(protocol); prefix.append(": String proxy = getTrueHost(request); if (proxy != null) { prefix.append(proxy); } else { prefix.append(request.getServerName()); int port = request.getServerPort(); if (!((protocol.equals("http") && port == 80) || (protocol.equals("https") && port == 443))) { prefix.append(':'); prefix.append(port); } } return prefix.toString(); } public static boolean isGAE(ServletConfig config) { return (config.getServletContext().getServerInfo().indexOf("Google App Engine") != -1); } transient private Logger _logger; private boolean _autoreload; private boolean _appengine; private String _name; private int _routingCookieMaxAge; transient protected Timer _timer; transient protected ButterflyClassLoader _classLoader; transient protected ButterflyScriptWatcher _scriptWatcher; transient protected ServletContext _context; transient protected ButterflyMounter _mounter; protected ExtendedProperties _properties; protected File _contextDir; protected File _homeDir; protected File _webInfDir; protected Exception _configurationException; protected boolean _configured = false; @Override public void init(ServletConfig config) throws ServletException { super.init(config); _appengine = isGAE(config); _name = System.getProperty(NAME, "butterfly"); _context = config.getServletContext(); _context.setAttribute(NAME, _name); _context.setAttribute(APPENGINE, _appengine); _contextDir = new File(_context.getRealPath("/")); _webInfDir = new File(_contextDir, "WEB-INF"); _properties = new ExtendedProperties(); _mounter = new ButterflyMounter(); // Load the butterfly properties String props = System.getProperty("butterfly.properties"); File butterflyProperties = (props == null) ? new File(_webInfDir, "butterfly.properties") : new File(props); BufferedInputStream is = null; try { is = new BufferedInputStream(new FileInputStream(butterflyProperties)); _properties.load(is); } catch (FileNotFoundException e) { throw new ServletException("Could not find butterfly properties file",e); } catch (IOException e) { throw new ServletException("Could not read butterfly properties file",e); } finally { try { is.close(); } catch (Exception e) { // ignore } } // Overload with properties set from the command line // using the -Dkey=value parameters to the JVM Properties systemProperties = System.getProperties(); for (Iterator<Object> i = systemProperties.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); String value = systemProperties.getProperty(key); _properties.setProperty(key, value); } _autoreload = _properties.getBoolean(AUTORELOAD, false); if (!_appengine) { String log4j = System.getProperty("butterfly.log4j"); File logProperties = (log4j == null) ? new File(_webInfDir, "log4j.properties") : new File(log4j); if (logProperties.exists()) { if (_autoreload) { PropertyConfigurator.configureAndWatch(logProperties.getAbsolutePath(), watcherDelay); } else { PropertyConfigurator.configure(logProperties.getAbsolutePath()); } } } _logger = LoggerFactory.getLogger(_name); _logger.info("Starting {} ...", _name); _logger.info("Properties loaded from {}", butterflyProperties); if (_autoreload) _logger.info("Autoreloading is enabled"); if (_appengine) _logger.info("Running in Google App Engine"); _logger.debug("> init"); _logger.debug("> initialize classloader"); try { _classLoader = AccessController.doPrivileged ( new PrivilegedAction<ButterflyClassLoader>() { public ButterflyClassLoader run() { return new ButterflyClassLoader(Thread.currentThread().getContextClassLoader()); } } ); Thread.currentThread().setContextClassLoader(_classLoader); _classLoader.watch(butterflyProperties); // reload if the butterfly properties change contextFactory.initApplicationClassLoader(_classLoader); // tell rhino to use this classloader as well if (_autoreload && !_appengine) { _timer = new Timer(true); TimerTask classloaderWatcher = _classLoader.getClassLoaderWatcher(new Trigger(_contextDir)); _timer.schedule(classloaderWatcher, watcherDelay, watcherDelay); } } catch (Exception e) { throw new ServletException("Failed to load butterfly classloader", e); } _logger.debug("< initialize classloader"); if (_autoreload && !_appengine) { _logger.debug("> initialize script watcher"); _scriptWatcher = new ButterflyScriptWatcher(); _timer.schedule(_scriptWatcher, watcherDelay, watcherDelay); _logger.debug("< initialize script watcher"); } this.configure(); _logger.debug("< init"); } @Override public void destroy() { _logger.info("Stopping Butterfly..."); for (ButterflyModule m : _modulesByName.values()) { try { _logger.debug("> destroying {}", m); m.destroy(); _logger.debug("< destroying {}", m); } catch (Exception e) { _logger.error("Exception caught while destroying '" + m + "'", e); } } if (_timer != null) { _timer.cancel(); } _logger.info("done."); } @SuppressWarnings("unchecked") public void configure() { _logger.debug("> configure"); _logger.info("> process properties"); try { String homePath = _properties.getString(HOME); if (homePath == null) { _homeDir = _contextDir; } else { _homeDir = new File(homePath); } _logger.info("Butterfly home: {}", _homeDir); Iterator<String> i = _properties.getKeys(ZONE); while (i.hasNext()) { String zone = i.next(); String path = _properties.getString(zone); zone = zone.substring(ZONE.length() + 1); _logger.info("Zone path: [{}] -> {}", zone, path); _mounter.registerZone(zone, path); } String defaultZone = _properties.getString(DEFAULT_ZONE); if (defaultZone != null) { _logger.info("Default zone is: '{}'", defaultZone); _mounter.setDefaultZone(defaultZone); } else { String baseURL = _properties.getString(BASE_URL,"/"); _mounter.registerZone(MAIN_ZONE, baseURL); _mounter.setDefaultZone(MAIN_ZONE); } String language = _properties.getString("butterfly.locale.language"); String country = _properties.getString("butterfly.locale.country"); String variant = _properties.getString("butterfly.locale.variant"); if (language != null) { if (country != null) { if (variant != null) { Locale.setDefault(new Locale(language, country, variant)); } else { Locale.setDefault(new Locale(language, country)); } } else { Locale.setDefault(new Locale(language)); } } String timeZone = _properties.getString("butterfly.timeZone"); if (timeZone != null) { TimeZone.setDefault(TimeZone.getTimeZone(timeZone)); } _routingCookieMaxAge = _properties.getInt("butterfly.routing.cookie.maxage",-1); } catch (Exception e) { _configurationException = new Exception("Failed to load butterfly properties", e); } _logger.info("< process properties"); _logger.info("> load modules"); List<String> paths = _properties.getList("butterfly.modules.path"); for (String path : paths) { findModulesIn(absolutize(_homeDir, path)); } _logger.info("< load modules"); _logger.info("> create modules"); for (String name : _moduleProperties.keySet()) { createModule(name); } _logger.info("< create modules"); _logger.info("> load module wirings"); ExtendedProperties wirings = new ExtendedProperties(); try { // Load the wiring properties File moduleWirings = absolutize(_homeDir, _properties.getString("butterfly.modules.wirings","WEB-INF/modules.properties")); _logger.info("Loaded module wirings from: {}", moduleWirings); _classLoader.watch(moduleWirings); // reload if the module wirings change FileInputStream fis = new FileInputStream(moduleWirings); wirings.load(fis); fis.close(); } catch (Exception e) { _configurationException = new Exception("Failed to load module wirings", e); } _logger.info("< load module wirings"); _logger.info("> wire modules"); try { wireModules(wirings); } catch (Exception e) { _configurationException = new Exception("Failed to wire modules", e); } _logger.info("< wire modules"); _logger.info("> configure modules"); try { configureModules(); } catch (Exception e) { _configurationException = new Exception("Failed to configure modules", e); } _logger.info("< configure modules"); _logger.info("> initialize modules"); Set<String> initialized = new HashSet<String>(); Set<String> initializing = new HashSet<String>(); for (String name : _modulesByName.keySet()) { initializeModule(name, initialized, initializing); } _logger.info("< initialize modules"); _configured = true; _logger.debug("< configure"); } protected void initializeModule(String name, Set<String> initialized, Set<String> initializing) { ButterflyModule m = _modulesByName.get(name); if (m != null && !initialized.contains(name)) { _logger.debug("> initialize " + m.getName()); if (initializing.contains(name)) { _logger.warn("Circular dependencies detected involving module " + m); } else { initializing.add(name); for (String depends : m.getDependencies().keySet()) { initializeModule(depends, initialized, initializing); } initializing.remove(name); } try { m.init(getServletConfig()); } catch (Exception e) { _configurationException = new Exception("Failed to initialize module " + m, e); } _logger.debug("< initialize " + m.getName()); initialized.add(name); } } @Override @SuppressWarnings("unchecked") public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getMethod(); String path = request.getPathInfo(); String urlQuery = request.getQueryString(); if (_mounter != null) { Zone zone = _mounter.getZone(request); if (_logger.isDebugEnabled()) { _logger.debug("> " + method + " [" + zone.getName() + "] " + path + ((urlQuery != null) ? "?" + urlQuery : "")); Enumeration<String> en = request.getHeaderNames(); while (en.hasMoreElements()) { String header = en.nextElement(); _logger.trace("{}: {}", header, request.getHeader(header)); } } else if (_logger.isInfoEnabled()) { String zoneName = (zone != null) ? zone.getName() : ""; _logger.info("{} {} [{}]", new String[] { method,path,zoneName }); } setRoutingCookie(request, response); try { if (_configured) { if (_configurationException == null) { ButterflyModule module = _mounter.getModule(path,zone); _logger.debug("Module '{}' will handle the request", module.getName()); String localPath = module.getRelativePath(request); if (!module.process(localPath, request, response)) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } else { error(response, "Butterfly Error", "Butterfly incurred in the following errors while initializing:", _configurationException); } } else { delay(response, "Butterfly is still initializing..."); } } catch (FileNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (Exception e) { error(response, "Butterfly Error", "Butterfly caught the following error while processing the request:", e); } response.flushBuffer(); if (_logger.isDebugEnabled()) _logger.debug("< " + method + " [" + zone.getName() + "] " + path + ((urlQuery != null) ? "?" + urlQuery : "")); } else { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } final static private String dependencyPrefix = "requires"; final static private String implementsProperty = "implements"; final static private String extendsProperty = "extends"; protected Map<String,ButterflyModule> _modulesByName = new HashMap<String,ButterflyModule>(); protected Map<String,Map<String,ButterflyModule>> _modulesByInterface = new HashMap<String,Map<String,ButterflyModule>>(); protected Map<String,ExtendedProperties> _moduleProperties = new HashMap<String,ExtendedProperties>(); protected Map<String,Boolean> _created = new HashMap<String,Boolean>(); final static private String routingCookie = "host"; /* * This method adds a cookie to the response that will be used by mod_proxy_balancer * to know what server is supposed to be handling all the requests of this user agent. */ protected void setRoutingCookie(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (routingCookie.equals(cookie.getName())) { return; } } } Cookie cookie = new Cookie(routingCookie, "." + _name); // IMPORTANT: the initial dot is required by mod_proxy_balancer! cookie.setMaxAge(_routingCookieMaxAge); // delete at end of browser session cookie.setPath("/"); response.addCookie(cookie); } protected File absolutize(File base, String location) { if (location == null || location.length() == 0) { // we got an empty location return base; } else if (location.indexOf(':') > 0) { // we got an absolute windows location (ie c:\blah) return new File(location); } else if (location.charAt(0) == '/' || location.charAt(0) == '\\') { // we got an absolute location return new File(location); } else { // we got a relative location return new File(base, location); } } protected static final String PATH_PROP = "__path__"; protected void findModulesIn(File f) { _logger.debug("look for modules in {}", f); File modFile = new File(f,"MOD-INF"); if (modFile.exists()) { _logger.trace("> findModulesIn({})", f); try { String name = f.getName(); ExtendedProperties p = new ExtendedProperties(); File propFile = new File(modFile,"module.properties"); if (propFile.exists()) { _classLoader.watch(propFile); // reload if the the module properties change BufferedInputStream stream = new BufferedInputStream(new FileInputStream(propFile)); p.load(stream); stream.close(); } p.addProperty(PATH_PROP, f.getAbsolutePath()); if (p.containsKey("name")) { name = p.getString("name"); } _moduleProperties.put(name, p); } catch (Exception e) { _logger.error("Error finding module wirings", e); } _logger.trace("< findModulesIn({})", f); } else { File[] files = f.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; try { if (file.isDirectory()) { findModulesIn(file); } } catch (AccessControlException e) { // skip // NOTE: this is needed for Google App Engine that doesn't like us snooping around the internal file system } } } } } @SuppressWarnings("unchecked") protected ButterflyModule createModule(String name) { _logger.trace("> Creating module: {}", name); if (_modulesByName.containsKey(name)) { _logger.trace("< Module '{}' already exists", name); return _modulesByName.get(name); } ExtendedProperties p = _moduleProperties.get(name); File path = new File(p.getString(PATH_PROP)); _logger.debug("Module path: {}", path); File classes = new File(path,"MOD-INF/classes"); if (classes.exists()) { _classLoader.addRepository(classes); } File libs = new File(path,"MOD-INF/lib"); if (libs.exists()) { _classLoader.addRepository(libs); } ButterflyModule m = new ButterflyModuleImpl(); // process module's controller String manager = p.getString("module-impl"); if (manager != null && !manager.equals(m.getClass().getName())) { try { Class c = _classLoader.loadClass(manager); m = (ButterflyModule) c.newInstance(); } catch (Exception e) { _logger.error("Error loading special module manager", e); } } m.setName(name); m.setPath(path); m.setModules(_modulesByName); m.setMounter(_mounter); m.setClassLoader(_classLoader); m.setTimer(_timer); _modulesByName.put(name,m); // process inheritance ButterflyModule parentModule = null; String parentName = p.getString(extendsProperty); if (parentName != null) { if (_moduleProperties.containsKey(parentName)) { if (_modulesByName.containsKey(parentName)) { parentModule = _modulesByName.get(parentName); } else { parentModule = createModule(parentName); } } else { throw new RuntimeException("Cannot wire module '" + name + "' because the extended module '" + parentName + "' is not defined."); } } if (parentModule != null) { m.setExtended(parentModule); parentModule.addExtendedBy(m); } _logger.trace("< Creating module: {}", name); return m; } @SuppressWarnings("unchecked") protected void wireModules(ExtendedProperties wirings) { _logger.trace("> wireModules()"); _logger.info("mounting modules"); for (String name : _moduleProperties.keySet()) { _logger.trace("> Mounting module: {}", name); ButterflyModule m = _modulesByName.get(name); String mountPointStr = wirings.getString(m.getName()); if (mountPointStr == null) { _logger.info("No mount point defined for module '{}', it won't be exposed.", name); } else { MountPoint mountPoint = new MountPoint(mountPointStr); if (_mounter.isRegistered(mountPoint)) { throw new RuntimeException("Cannot have two different modules with the same mount point '" + mountPoint + "'."); } else { _mounter.register(mountPoint, m); } } _logger.trace("< Mounting module: {}", name); } for (String name : _moduleProperties.keySet()) { _logger.trace("> Expanding properties for module: {}", name); ButterflyModule m = _modulesByName.get(name); ExtendedProperties p = _moduleProperties.get(name); ButterflyModule extended = m.getExtendedModule(); while (extended != null) { _logger.trace("> Merging properties from extended module: {}", name); ExtendedProperties temp = p; p = _moduleProperties.get(extended.getName()); p.combine(temp); _logger.trace("< Merging properties from extended module: {} -> {}", name, p); extended = extended.getExtendedModule(); } _moduleProperties.put(name,p); List<String> implementations = p.getList(implementsProperty); if (implementations != null) { for (String i : implementations) { Map<String, ButterflyModule> map = _modulesByInterface.get(i); if (map == null) { map = new HashMap<String,ButterflyModule>(); _modulesByInterface.put(i, map); } map.put(name, m); m.setImplementation(i); } } _logger.trace("< Expanding properties for module: {}", name); } for (String name : _moduleProperties.keySet()) { _logger.trace("> Inject dependencies in module: {}", name); ExtendedProperties p = _moduleProperties.get(name); ButterflyModule m = _modulesByName.get(name); for (Object o : p.keySet()) { String s = (String) o; if (s.equals(dependencyPrefix)) { for (Object oo : p.getList(s)) { String dep = (String) oo; _logger.trace("> Processing dependency: {}", dep); dep = dep.trim(); Map<String,ButterflyModule> modules = _modulesByInterface.get(dep); if (modules != null) { if (modules.size() == 1) { // if there's only one module implementing that interface, wiring is automatic setDependency(m, dep, modules.values().iterator().next()); } else { ButterflyModule parent = m.getExtendedModule(); do { String wiredDependency = wirings.getString(name + "." + dep); if (wiredDependency != null) { setDependency(m, dep, _modulesByName.get(wiredDependency)); break; } else { if (parent != null) { name = parent.getName(); } } } while (parent != null); } } else { throw new RuntimeException("Cannot wire module '" + name + "' because no module implements the required interface '" + dep + "'"); } _logger.trace("< Processing dependency: {}", dep); } } } _logger.trace("< Inject dependencies in module: {}", name); } ButterflyModule rootModule = _mounter.getRootModule(); // in case nothing defined the root mount point use the default one if (rootModule == null) { rootModule = _modulesByName.get("main"); } // in case not even the 'main' module is available, give up if (rootModule == null) { throw new RuntimeException("Cannot initialize the modules because I can't guess which module to mount to '/'"); } _logger.trace("< wireModules()"); } @SuppressWarnings("unchecked") protected void configureModules() { _logger.trace("> configureModules()"); for (String name : _moduleProperties.keySet()) { _logger.trace("> Configuring module: {}", name); ExtendedProperties p = _moduleProperties.get(name); ButterflyModule m = _modulesByName.get(name); // make the system properties accessible to the modules m.setProperties(_properties); try { if (p.getBoolean("templating", Boolean.TRUE)) { _logger.trace("> enabling templating"); // load the default velocity properties Properties properties = new Properties(); File velocityProperties = new File(_webInfDir, "velocity.properties"); _classLoader.watch(velocityProperties); // reload if the velocity properties change FileInputStream fis = new FileInputStream(velocityProperties); properties.load(fis); fis.close(); // set properties for resource loading properties.setProperty("resource.loader", "butterfly"); properties.setProperty("butterfly.resource.loader.class", ButterflyResourceLoader.class.getName()); properties.setProperty("butterfly.resource.loader.cache", "true"); properties.setProperty("butterfly.resource.loader.modificationCheckInterval", "1"); properties.setProperty("butterfly.resource.loader.description", "Butterfly Resource Loader"); // set properties for macros properties.setProperty("velocimacro.library", p.getString("templating.macros", "")); // Set our special parent injection directive properties.setProperty("userdirective", Super.class.getName()); // Set logging properties if (_appengine) { properties.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.JdkLogChute"); } else { properties.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute"); properties.setProperty("runtime.log.logsystem.log4j.logger", "velocity"); } // create a module-specific velocity engine VelocityEngine velocity = new VelocityEngine(); velocity.setApplicationAttribute("module", m); // this is how we pass the module to the resource loader velocity.init(properties); // inject the template engine in the module m.setTemplateEngine(velocity); _logger.trace("< enabling templating"); } List<String> scriptables = p.getList("scriptables"); if (scriptables.size() > 0) { Context context = Context.enter(); BufferedReader initializerReader = null; for (String scriptable : scriptables) { if (!scriptable.equals("")) { try { _logger.trace("> adding scriptable object: {}", scriptable); Class c = _classLoader.loadClass(scriptable); ButterflyScriptableObject o = (ButterflyScriptableObject) c.newInstance(); setScriptable(m, o); URL initializer = c.getResource("init.js"); if (initializer != null) { initializerReader = new BufferedReader(new InputStreamReader(initializer.openStream())); setScript(m, initializer, context.compileReader(initializerReader, "init.js", 1, null)); _scriptWatcher.watch(initializer,m); _logger.trace("Parsed scriptable javascript initializer successfully"); } _logger.trace("< adding scriptable object: {}", scriptable); } catch (Exception e) { _logger.trace("Error initializing scriptable object '{}': {}", scriptable, e); } finally { if (initializerReader != null) initializerReader.close(); } } } Context.exit(); } List<String> controllers = p.getList("controller", CONTROLLER); Set<URL> controllerURLs = new HashSet<URL>(controllers.size()); for (String controller : controllers) { URL controllerURL = m.getResource("MOD-INF/" + controller); if (controllerURL != null) { controllerURLs.add(controllerURL); } } if (controllerURLs.size() > 0) { _logger.trace("> enabling javascript control"); Context context = Context.enter(); BufferedReader initializerReader = null; try { URL initializer = this.getClass().getClassLoader().getResource("edu/mit/simile/butterfly/Butterfly.js"); initializerReader = new BufferedReader(new InputStreamReader(initializer.openStream())); setScript(m, initializer, context.compileReader(initializerReader, "Butterfly.js", 1, null)); watch(initializer,m); _logger.trace("Parsed javascript initializer successfully"); } finally { if (initializerReader != null) initializerReader.close(); } BufferedReader controllerReader = null; for (URL controllerURL : controllerURLs) { try{ controllerReader = new BufferedReader(new InputStreamReader(controllerURL.openStream())); setScript(m, controllerURL, context.compileReader(controllerReader, controllerURL.toString(), 1, null)); watch(controllerURL,m); _logger.trace("Parsed javascript controller successfully: {}", controllerURL); } finally { if (controllerReader != null) controllerReader.close(); } } Context.exit(); _logger.trace("< enabling javascript control"); } } catch (Exception e) { _logger.error("Error enabling javascript control",e); } _logger.trace("< Configuring module: {}", name); } _logger.trace("< configureModules()"); } protected void setDependency(ButterflyModule subj, String dep, ButterflyModule obj) { subj.setDependency(dep, obj); ButterflyModule extended = subj.getExtendedModule(); if (extended != null) { setDependency(extended, dep, obj); } } protected void setScriptable(ButterflyModule mod, ButterflyScriptableObject scriptable) { mod.setScriptable(scriptable); ButterflyModule extended = mod.getExtendedModule(); if (extended != null) { setScriptable(extended, scriptable); } } protected void watch(URL script, ButterflyModule module) throws IOException { if (_scriptWatcher != null) { _scriptWatcher.watch(script, module); } } /* * NOTE(SM): I'm fully aware that these embedded HTML snippets are really ugly, but I don't * want to depend on velocity for error reporting as that would prevent us from reporting * errors about velocity's dependency itself. */ String header = "<html>" + " <head>" + " </head>" + " <body>"; String footer = "</body></html>"; protected void delay(HttpServletResponse response, String title) throws IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.println(header); writer.println("<h1>" + title + "</h1>"); writer.println("<script>setTimeout(function() { window.location = '.' }, 3000);</script>"); writer.println(footer); writer.close(); } protected void error(HttpServletResponse response, String title, String msg, Exception e) throws IOException { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); writer.println(title); writer.println(msg); if (e != null) { e.printStackTrace(writer); } writer.close(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, stringWriter.toString()); } static protected void setScript(ButterflyModule mod, URL location, Script script) { mod.setScript(location, script); ButterflyModule extended = mod.getExtendedModule(); if (extended != null) { setScript(extended, location, script); } } /* * This is the trigger invoked by the butterfly classloader if any of the observed classes or files * has changed. This trigger attempts to find the Butterfly.class on disk and changes its lastModified * time if found. This has no effect in some servlet containers, but in others (for example the Jetty * plugin for Maven) this triggers a context autoreload. * NOTE: this is only invoked when files that were found when the application started are modified * Adding new files to the classpath does not trigger a restart! */ private static class Trigger implements Runnable { final static private Logger _logger = LoggerFactory.getLogger("butterfly.trigger"); private File _context; Trigger(File context) { _context = context; } public void run() { _logger.debug("classloader changed trigger invoked"); List<File> tries = new ArrayList<File>(); tries.add(new File(_context, "WEB-INF/classes/edu/mit/simile/butterfly/Butterfly.class")); for (File f : tries) { _logger.debug(" trying: " + f.getAbsolutePath()); if (f.exists()) { f.setLastModified((new Date()).getTime()); _logger.debug(" touched!!"); return; } } _logger.debug(" but could not find any class to touch!!"); } } } class ButterflyScriptWatcher extends TimerTask { final static private Logger _logger = LoggerFactory.getLogger("butterfly.script_watcher"); private Map<URL,ButterflyModule> scripts = new HashMap<URL,ButterflyModule>(); private Map<URL,Long> lastModifieds = new HashMap<URL,Long>(); protected void watch(URL script, ButterflyModule module) throws IOException { _logger.debug("Watching {}", script); this.lastModifieds.put(script, script.openConnection().getLastModified()); this.scripts.put(script, module); } public void run() { for (URL url : this.scripts.keySet()) { try { URLConnection connection = url.openConnection(); long lastModified = connection.getLastModified(); if (lastModified > this.lastModifieds.get(url)) { _logger.debug("{} has changed, reparsing...", url); this.lastModifieds.put(url, lastModified); ButterflyModule module = this.scripts.get(url); BufferedReader reader = null; try { Context context = Context.enter(); reader = new BufferedReader(new InputStreamReader(url.openStream())); Butterfly.setScript(module, url, context.compileReader(reader, url.getFile(), 1, null)); _logger.info("{} reloaded", url); Context.exit(); } finally { if (reader != null) reader.close(); } } connection.getInputStream().close(); // NOTE(SM): this avoids leaking file descriptions in some JVMs } catch (Exception e) { _logger.error("", e); } } } }
package org.elasticsearch.xpack.prelert.integration; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterModule; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.xpack.prelert.PrelertPlugin; import org.elasticsearch.xpack.prelert.action.OpenJobAction; import org.elasticsearch.xpack.prelert.action.PutJobAction; import org.elasticsearch.xpack.prelert.action.ScheduledJobsIT; import org.elasticsearch.xpack.prelert.job.AnalysisConfig; import org.elasticsearch.xpack.prelert.job.DataDescription; import org.elasticsearch.xpack.prelert.job.Detector; import org.elasticsearch.xpack.prelert.job.Job; import org.elasticsearch.xpack.prelert.job.manager.AutodetectProcessManager; import org.elasticsearch.xpack.prelert.job.metadata.PrelertMetadata; import org.junit.After; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import static org.elasticsearch.test.XContentTestUtils.convertToMap; import static org.elasticsearch.test.XContentTestUtils.differenceBetweenMapsIgnoringArrayOrder; @ESIntegTestCase.ClusterScope(numDataNodes = 1) public class TooManyJobsIT extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(PrelertPlugin.class); } @Override protected Collection<Class<? extends Plugin>> transportClientPlugins() { return nodePlugins(); } @After public void clearPrelertMetadata() throws Exception { ScheduledJobsIT.clearPrelertMetadata(client()); } public void testCannotStartTooManyAnalyticalProcesses() throws Exception { int maxRunningJobsPerNode = AutodetectProcessManager.MAX_RUNNING_JOBS_PER_NODE.getDefault(Settings.EMPTY); logger.info("[{}] is [{}]", AutodetectProcessManager.MAX_RUNNING_JOBS_PER_NODE.getKey(), maxRunningJobsPerNode); for (int i = 1; i <= (maxRunningJobsPerNode + 1); i++) { Job.Builder job = createJob(Integer.toString(i)); PutJobAction.Request putJobRequest = new PutJobAction.Request(job.build(true)); PutJobAction.Response putJobResponse = client().execute(PutJobAction.INSTANCE, putJobRequest).get(); assertTrue(putJobResponse.isAcknowledged()); try { OpenJobAction.Request openJobRequest = new OpenJobAction.Request(job.getId()); openJobRequest.setOpenTimeout(TimeValue.timeValueSeconds(10)); OpenJobAction.Response openJobResponse = client().execute(OpenJobAction.INSTANCE, openJobRequest) .get(); assertTrue(openJobResponse.isAcknowledged()); logger.info("Opened {}th job", i); } catch (Exception e) { Throwable cause = ExceptionsHelper.unwrapCause(e.getCause()); if (ElasticsearchStatusException.class.equals(cause.getClass()) == false) { logger.warn("Unexpected cause", e); } assertEquals(ElasticsearchStatusException.class, cause.getClass()); assertEquals(RestStatus.CONFLICT, ((ElasticsearchStatusException) cause).status()); assertEquals("[" + (maxRunningJobsPerNode + 1) + "] expected job status [OPENED], but got [FAILED], reason " + "[failed to open, max running job capacity [" + maxRunningJobsPerNode + "] reached]", cause.getMessage()); logger.info("good news everybody --> reached maximum number of allowed opened jobs, after trying to open the {}th job", i); // now manually clean things up and see if we can succeed to run one new job clearPrelertMetadata(); putJobResponse = client().execute(PutJobAction.INSTANCE, putJobRequest).get(); assertTrue(putJobResponse.isAcknowledged()); OpenJobAction.Response openJobResponse = client().execute(OpenJobAction.INSTANCE, new OpenJobAction.Request(job.getId())) .get(); assertTrue(openJobResponse.isAcknowledged()); return; } } fail("shouldn't be able to add more than [" + maxRunningJobsPerNode + "] jobs"); } private Job.Builder createJob(String id) { DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setFormat(DataDescription.DataFormat.JSON); dataDescription.setTimeFormat(DataDescription.EPOCH_MS); Detector.Builder d = new Detector.Builder("count", null); AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Collections.singletonList(d.build())); Job.Builder builder = new Job.Builder(); builder.setId(id); builder.setAnalysisConfig(analysisConfig); builder.setDataDescription(dataDescription); return builder; } @Override protected void ensureClusterStateConsistency() throws IOException { ensureClusterStateConsistencyWorkAround(); } // TODO: Fix in ES. In ESIntegTestCase we should get all NamedWriteableRegistry.Entry entries from ESIntegTestCase#nodePlugins() public static void ensureClusterStateConsistencyWorkAround() throws IOException { if (cluster() != null && cluster().size() > 0) { List<NamedWriteableRegistry.Entry> namedWritables = new ArrayList<>(ClusterModule.getNamedWriteables()); namedWritables.add(new NamedWriteableRegistry.Entry(MetaData.Custom.class, "prelert", PrelertMetadata::new)); final NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(namedWritables); ClusterState masterClusterState = client().admin().cluster().prepareState().all().get().getState(); byte[] masterClusterStateBytes = ClusterState.Builder.toBytes(masterClusterState); // remove local node reference masterClusterState = ClusterState.Builder.fromBytes(masterClusterStateBytes, null, namedWriteableRegistry); Map<String, Object> masterStateMap = convertToMap(masterClusterState); int masterClusterStateSize = ClusterState.Builder.toBytes(masterClusterState).length; String masterId = masterClusterState.nodes().getMasterNodeId(); for (Client client : cluster().getClients()) { ClusterState localClusterState = client.admin().cluster().prepareState().all().setLocal(true).get().getState(); byte[] localClusterStateBytes = ClusterState.Builder.toBytes(localClusterState); // remove local node reference localClusterState = ClusterState.Builder.fromBytes(localClusterStateBytes, null, namedWriteableRegistry); final Map<String, Object> localStateMap = convertToMap(localClusterState); final int localClusterStateSize = ClusterState.Builder.toBytes(localClusterState).length; // Check that the non-master node has the same version of the cluster state as the master and // that the master node matches the master (otherwise there is no requirement for the cluster state to match) if (masterClusterState.version() == localClusterState.version() && masterId.equals(localClusterState.nodes().getMasterNodeId())) { try { assertEquals("clusterstate UUID does not match", masterClusterState.stateUUID(), localClusterState.stateUUID()); // We cannot compare serialization bytes since serialization order of maps is not guaranteed // but we can compare serialization sizes - they should be the same assertEquals("clusterstate size does not match", masterClusterStateSize, localClusterStateSize); // Compare JSON serialization assertNull("clusterstate JSON serialization does not match", differenceBetweenMapsIgnoringArrayOrder(masterStateMap, localStateMap)); } catch (AssertionError error) { fail("Cluster state from master:\n" + masterClusterState.toString() + "\nLocal cluster state:\n" + localClusterState.toString()); throw error; } } } } } }
package org.exist.xquery.modules.mail; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.dom.QName; import org.exist.util.MimeTable; import org.exist.xquery.*; import org.exist.xquery.functions.system.GetVersion; import org.exist.xquery.value.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import jakarta.activation.DataHandler; import jakarta.mail.*; import jakarta.mail.internet.*; import jakarta.mail.util.ByteArrayDataSource; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.util.*; //send-email specific imports /* TODO according to RFC 821, SMTP commands must end with <CR><LF>, Java uses platform native end-of-line characters for .println(...) functions and so this function may have issues on non-Windows platforms */ public class SendEmailFunction extends BasicFunction { protected static final Logger logger = LogManager.getLogger(SendEmailFunction.class); private final int MIME_BASE64_MAX_LINE_LENGTH = 76; //RFC 2045, page 24 private String charset; public final static FunctionSignature deprecated = new FunctionSignature( new QName("send-email", MailModule.NAMESPACE_URI, MailModule.PREFIX), "Sends an email through the SMTP Server.", new SequenceType[] { new FunctionParameterSequenceType("email", Type.ELEMENT, Cardinality.ONE_OR_MORE, "The email message in the following format: <mail> <from/> <reply-to/> <to/> <cc/> <bcc/> <subject/> <message> <text/> <xhtml/> </message> <attachment filename=\"\" mimetype=\"\">xs:base64Binary</attachment> </mail>."), new FunctionParameterSequenceType("server", Type.STRING, Cardinality.ZERO_OR_ONE, "The SMTP server. If empty, then it tries to use the local sendmail program."), new FunctionParameterSequenceType("charset", Type.STRING, Cardinality.ZERO_OR_ONE, "The charset value used in the \"Content-Type\" message header (Defaults to UTF-8)") }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.ONE_OR_MORE, "true if the email message was successfully sent") ); public final static FunctionSignature signatures[] = { new FunctionSignature( new QName("send-email", MailModule.NAMESPACE_URI, MailModule.PREFIX), "Sends an email using javax.mail messaging libraries.", new SequenceType[] { new FunctionParameterSequenceType( "mail-handle", Type.LONG, Cardinality.EXACTLY_ONE, "The JavaMail session handle retrieved from mail:get-mail-session()" ), new FunctionParameterSequenceType( "email", Type.ELEMENT, Cardinality.ONE_OR_MORE, "The email message in the following format: <mail> <from/> <reply-to/> <to/> <cc/> <bcc/> <subject/> <message> <text/> <xhtml/> </message> <attachment filename=\"\" mimetype=\"\">xs:base64Binary</attachment> </mail>.") }, new SequenceType( Type.ITEM, Cardinality.EMPTY_SEQUENCE ) ) }; public SendEmailFunction(XQueryContext context, FunctionSignature signature) { super( context, signature ); } @Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { if(args.length==3) { return deprecatedSendEmail(args, contextSequence); } else { return sendEmail(args, contextSequence); } } public Sequence sendEmail(Sequence[] args, Sequence contextSequence) throws XPathException { // was a session handle specified? if( args[0].isEmpty() ) { throw( new XPathException( this, "Session handle not specified" ) ); } // get the Session long sessionHandle = ((IntegerValue)args[0].itemAt(0)).getLong(); Session session = MailModule.retrieveSession( context, sessionHandle ); if( session == null ) { throw( new XPathException( this, "Invalid Session handle specified" ) ); } try { List<Message> messages = parseInputEmails(session,args[1]); String proto = session.getProperty("mail.transport.protocol"); if(proto==null) proto = "smtp"; try (Transport t = session.getTransport(proto)) { if (session.getProperty("mail." + proto + ".auth") != null) t.connect(session.getProperty("mail." + proto + ".user"), session.getProperty("mail." + proto + ".password")); for (Message msg : messages) { t.sendMessage(msg, msg.getAllRecipients()); } } return( Sequence.EMPTY_SEQUENCE ); } catch(TransformerException te) { throw new XPathException(this, "Could not Transform XHTML Message Body: " + te.getMessage(), te); } catch(MessagingException smtpe) { throw new XPathException(this, "Could not send message(s): " + smtpe.getMessage(), smtpe); } catch(IOException ioe) { throw new XPathException(this, "Attachment in some message could not be prepared: " + ioe.getMessage(), ioe); } catch(Throwable t) { throw new XPathException(this, "Unexpected error from JavaMail layer (Is your message well structured?): " + t.getMessage(), t); } } public Sequence deprecatedSendEmail(Sequence[] args, Sequence contextSequence) throws XPathException { try { //get the charset parameter, default to UTF-8 if (!args[2].isEmpty()) { charset = args[2].getStringValue(); } else { charset = "UTF-8"; } //Parse the XML <mail> into a mail Object List<Element> mailElements = new ArrayList<>(); if(args[0].getItemCount() > 1 && args[0] instanceof ValueSequence) { for(int i = 0; i < args[0].getItemCount(); i++) { mailElements.add((Element)args[0].itemAt(i)); } } else { mailElements.add((Element)args[0].itemAt(0)); } List<Mail> mails = parseMailElement(mailElements); ValueSequence results = new ValueSequence(); //Send email with Sendmail or SMTP? if(!args[1].isEmpty()) { //SMTP List<Boolean> mailResults = sendBySMTP(mails, args[1].getStringValue()); for(Boolean mailResult : mailResults) { results.add(BooleanValue.valueOf(mailResult)); } } else { for(Mail mail : mails) { boolean result = sendBySendmail(mail); results.add(BooleanValue.valueOf(result)); } } return results; } catch(TransformerException te) { throw new XPathException(this, "Could not Transform XHTML Message Body: " + te.getMessage(), te); } catch(SMTPException smtpe) { throw new XPathException(this, "Could not send message(s)" + smtpe.getMessage(), smtpe); } } private List<Message> parseInputEmails(Session session, Sequence arg) throws IOException, MessagingException, TransformerException { //Parse the XML <mail> into a mail Object List<Element> mailElements = new ArrayList<>(); if(arg.getItemCount() > 1 && arg instanceof ValueSequence) { for(int i = 0; i < arg.getItemCount(); i++) { mailElements.add((Element)arg.itemAt(i)); } } else { mailElements.add((Element)arg.itemAt(0)); } return parseMessageElement(session, mailElements); } /** * Sends an email using the Operating Systems sendmail application * * @param mail representation of the email to send * @return boolean value of true of false indicating success or failure to send email */ private boolean sendBySendmail(Mail mail) { PrintWriter out = null; try { //Create a list of all Recipients, should include to, cc and bcc recipient List<String> allrecipients = new ArrayList<>(); allrecipients.addAll(mail.getTo()); allrecipients.addAll(mail.getCC()); allrecipients.addAll(mail.getBCC()); //Get a string of all recipients email addresses final StringBuilder recipients = new StringBuilder(); for (String recipient : allrecipients) { recipients.append(" "); //Check format of to address does it include a name as well as the email address? if (recipient.contains("<")) { //yes, just add the email address recipients.append(recipient.substring(recipient.indexOf("<") + 1, recipient.indexOf(">"))); } else { //add the email address recipients.append(recipient); } } //Create a sendmail Process Process p = Runtime.getRuntime().exec("/usr/sbin/sendmail" + recipients.toString()); //Get a Buffered Print Writer to the Processes stdOut out = new PrintWriter(new OutputStreamWriter(p.getOutputStream(),charset)); //Send the Message writeMessage(out, mail); } catch(IOException e) { LOG.error(e.getMessage(), e); return false; } finally { //Close the stdOut if(out != null) out.close(); } //Message Sent Succesfully LOG.info("send-email() message sent using Sendmail {}", new Date()); return true; } private static class SMTPException extends Exception { private static final long serialVersionUID = 4859093648476395159L; public SMTPException(String message) { super(message); } public SMTPException(Throwable cause) { super(cause); } } /** * Sends an email using SMTP * * @param mails A list of mail object representing the email to send * @param smtpServerArg The SMTP Server to send the email through * @return boolean value of true of false indicating success or failure to send email * * @throws SMTPException if an I/O error occurs */ private List<Boolean> sendBySMTP(List<Mail> mails, final String smtpServerArg) throws SMTPException { String smtpHost = "localhost"; int smtpPort = 25; if (smtpServerArg != null && !smtpServerArg.isEmpty()) { final int idx = smtpServerArg.indexOf(':'); if (idx > -1) { smtpHost = smtpServerArg.substring(0, idx); smtpPort = Integer.parseInt(smtpServerArg.substring(idx + 1)); } else { smtpHost = smtpServerArg; } } String smtpResult = ""; //Holds the server Result code when an SMTP Command is executed List<Boolean> sendMailResults = new ArrayList<>(); try (//Create a Socket and connect to the SMTP Server Socket smtpSock = new Socket(smtpHost, smtpPort); //Create a Buffered Reader for the Socket InputStream smtpSockInputStream = smtpSock.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(smtpSockInputStream); BufferedReader smtpIn = new BufferedReader(inputStreamReader); //Create an Output Writer for the Socket OutputStream smtpSockOutputStream = smtpSock.getOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(smtpSockOutputStream, charset); PrintWriter smtpOut = new PrintWriter(outputStreamWriter)) { //First line sent to us from the SMTP server should be "220 blah blah", 220 indicates okay smtpResult = smtpIn.readLine(); if(!smtpResult.substring(0, 3).equals("220")) { String errMsg = "Error - SMTP Server not ready: '" + smtpResult + "'"; LOG.error(errMsg); throw new SMTPException(errMsg); } //Say "HELO" smtpOut.println("HELO " + InetAddress.getLocalHost().getHostName()); smtpOut.flush(); //get "HELLO" response, should be "250 blah blah" smtpResult = smtpIn.readLine(); if(smtpResult == null) { String errMsg = "Error - Unexpected null response to SMTP HELO"; LOG.error(errMsg); throw new SMTPException(errMsg); } if(!smtpResult.substring(0, 3).equals("250")) { String errMsg = "Error - SMTP HELO Failed: '" + smtpResult + "'"; LOG.error(errMsg); throw new SMTPException(errMsg); } //write SMTP message(s) for(Mail mail : mails) { boolean mailResult = writeSMTPMessage(mail, smtpOut, smtpIn); sendMailResults.add(mailResult); } } catch(IOException ioe) { LOG.error(ioe.getMessage(), ioe); throw new SMTPException(ioe); } //Message(s) Sent Succesfully LOG.info("send-email() message(s) sent using SMTP {}", new Date()); return sendMailResults; } private boolean writeSMTPMessage(Mail mail, PrintWriter smtpOut, BufferedReader smtpIn) { try { String smtpResult = ""; //Send "MAIL FROM:" //Check format of from address does it include a name as well as the email address? if(mail.getFrom().contains("<")) { //yes, just send the email address smtpOut.println("MAIL FROM:<" + mail.getFrom().substring(mail.getFrom().indexOf("<") + 1, mail.getFrom().indexOf(">")) + ">"); } else { //no, doesnt include a name so send the email address smtpOut.println("MAIL FROM:<" + mail.getFrom() + ">"); } smtpOut.flush(); //Get "MAIL FROM:" response smtpResult = smtpIn.readLine(); if(smtpResult == null) { LOG.error("Error - Unexpected null response to SMTP MAIL FROM"); return false; } if(!smtpResult.substring(0, 3).equals("250")) { LOG.error("Error - SMTP MAIL FROM failed: {}", smtpResult); return false; } //RCPT TO should be issued for each to, cc and bcc recipient List<String> allrecipients = new ArrayList<>(); allrecipients.addAll(mail.getTo()); allrecipients.addAll(mail.getCC()); allrecipients.addAll(mail.getBCC()); for (String recipient : allrecipients) { //Send "RCPT TO:" //Check format of to address does it include a name as well as the email address? if (recipient.contains("<")) { //yes, just send the email address smtpOut.println("RCPT TO:<" + recipient.substring(recipient.indexOf("<") + 1, recipient.indexOf(">")) + ">"); } else { smtpOut.println("RCPT TO:<" + recipient + ">"); } smtpOut.flush(); //Get "RCPT TO:" response smtpResult = smtpIn.readLine(); if(!smtpResult.substring(0, 3).equals("250")) { LOG.error("Error - SMTP RCPT TO failed: {}", smtpResult); } } //SEND "DATA" smtpOut.println("DATA"); smtpOut.flush(); //Get "DATA" response, should be "354 blah blah" smtpResult = smtpIn.readLine(); if(!smtpResult.substring(0, 3).equals("354")) { LOG.error("Error - SMTP DATA failed: {}", smtpResult); return false; } //Send the Message writeMessage(smtpOut, mail); //Get end message response, should be "250 blah blah" smtpResult = smtpIn.readLine(); if(!smtpResult.substring(0, 3).equals("250")) { LOG.error("Error - Message not accepted: {}", smtpResult); return false; } } catch(IOException ioe) { LOG.error(ioe.getMessage(), ioe); return false; } return true; } /** * Writes an email payload (Headers + Body) from a mail object * * @param out A PrintWriter to receive the email * @param aMail A mail object representing the email to write out * * @throws IOException if an I/O error occurs */ private void writeMessage(PrintWriter out, Mail aMail) throws IOException { String Version = eXistVersion(); //Version of eXist String MultipartBoundary = "eXist.multipart." + Version; //Multipart Boundary //write the message headers out.println("From: " + encode64Address(aMail.getFrom())); if(aMail.getReplyTo() != null) { out.println("Reply-To: " + encode64Address(aMail.getReplyTo())); } for(int x = 0; x < aMail.countTo(); x++) { out.println("To: " + encode64Address(aMail.getTo(x))); } for(int x = 0; x < aMail.countCC(); x++) { out.println("CC: " + encode64Address(aMail.getCC(x))); } for(int x = 0; x < aMail.countBCC(); x++) { out.println("BCC: " + encode64Address(aMail.getBCC(x))); } out.println("Date: " + getDateRFC822()); out.println("Subject: " + encode64(aMail.getSubject())); out.println("X-Mailer: eXist " + Version + " mail:send-email()"); out.println("MIME-Version: 1.0"); boolean multipartAlternative = false; String multipartBoundary = null; if(aMail.attachmentIterator().hasNext()) { // we have an attachment as well as text and/or html so we need a multipart/mixed message multipartBoundary = MultipartBoundary; } else if(!aMail.getText().isEmpty() && !aMail.getXHTML().isEmpty()) { // we have text and html so we need a multipart/alternative message and no attachment multipartAlternative = true; multipartBoundary = MultipartBoundary + "_alt"; } else { // we have either text or html and no attachment this message is not multipart } //content type if(multipartBoundary != null) { //multipart message out.println("Content-Type: " + (multipartAlternative ? "multipart/alternative" : "multipart/mixed") + "; boundary=\"" + multipartBoundary + "\";"); //Mime warning out.println(); out.println("Error your mail client is not MIME Compatible"); out.println("--" + multipartBoundary); } // TODO - need to put out a multipart/mixed boundary here when HTML, text and attachment present if(!aMail.getText().isEmpty() && !aMail.getXHTML().isEmpty() && aMail.attachmentIterator().hasNext()) { out.println("Content-Type: multipart/alternative; boundary=\"" + MultipartBoundary + "_alt\";"); out.println("--" + MultipartBoundary + "_alt"); } //text email if(!aMail.getText().isEmpty()) { out.println("Content-Type: text/plain; charset=" + charset); out.println("Content-Transfer-Encoding: 8bit"); //now send the txt message out.println(); out.println(aMail.getText()); if(multipartBoundary != null) { if(!aMail.getXHTML().isEmpty() || aMail.attachmentIterator().hasNext()) { if(!aMail.getText().isEmpty() && !aMail.getXHTML().isEmpty() && aMail.attachmentIterator().hasNext()) { out.println("--" + MultipartBoundary + "_alt"); } else { out.println("--" + multipartBoundary); } } else { if(!aMail.getText().isEmpty() && !aMail.getXHTML().isEmpty() && aMail.attachmentIterator().hasNext()) { out.println("--" + MultipartBoundary + "_alt--"); } else { out.println("--" + multipartBoundary + "--"); } } } } //HTML email if(!aMail.getXHTML().isEmpty()) { out.println("Content-Type: text/html; charset=" + charset); out.println("Content-Transfer-Encoding: 8bit"); //now send the html message out.println(); out.println("<!DOCTYPE html PUBLIC \"- out.println(aMail.getXHTML()); if(multipartBoundary != null) { if(aMail.attachmentIterator().hasNext()) { if(!aMail.getText().isEmpty() && !aMail.getXHTML().isEmpty() && aMail.attachmentIterator().hasNext()) { out.println("--" + MultipartBoundary + "_alt--"); out.println("--" + multipartBoundary); } else { out.println("--" + multipartBoundary); } } else { if(!aMail.getText().isEmpty() && !aMail.getXHTML().isEmpty() && aMail.attachmentIterator().hasNext()) { out.println("--" + MultipartBoundary + "_alt--"); } else { out.println("--" + multipartBoundary + "--"); } } } } //attachments if(aMail.attachmentIterator().hasNext()) { for(Iterator<MailAttachment> itAttachment = aMail.attachmentIterator(); itAttachment.hasNext(); ) { MailAttachment ma = itAttachment.next(); out.println("Content-Type: " + ma.getMimeType() + "; name=\"" + ma.getFilename() + "\""); out.println("Content-Transfer-Encoding: base64"); out.println("Content-Description: " + ma.getFilename()); out.println("Content-Disposition: attachment; filename=\"" + ma.getFilename() + "\""); out.println(); //write out the attachment encoded data in fixed width lines final char buf[] = new char[MIME_BASE64_MAX_LINE_LENGTH]; int read = -1; final Reader attachmentDataReader = new StringReader(ma.getData()); while((read = attachmentDataReader.read(buf, 0, MIME_BASE64_MAX_LINE_LENGTH)) > -1) { out.println(String.valueOf(buf, 0, read)); } if(itAttachment.hasNext()) { out.println("--" + multipartBoundary); } } //Emd multipart message out.println("--" + multipartBoundary + "--"); } //end the message, <cr><lf>.<cr><lf> out.println(); out.println("."); out.flush(); } /** * Get's the version of eXist we are running * The eXist version is used as part of the multipart separator * * @return The eXist Version * * @throws IOException if an I/O error occurs */ private String eXistVersion() throws IOException { Properties sysProperties = new Properties(); sysProperties.load(GetVersion.class.getClassLoader().getResourceAsStream("org/exist/system.properties")); return sysProperties.getProperty("product-version", "unknown version"); } /** * Constructs a mail Object from an XML representation of an email * * The XML email Representation is expected to look something like this * * <mail> * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text></text> * <xhtml></xhtml> * </message> * </mail> * * @param mailElements The XML mail Node * @return A mail Object representing the XML mail Node * * @throws TransformerException if a transformation error occurs */ private List<Mail> parseMailElement(List<Element> mailElements) throws TransformerException { List<Mail> mails = new ArrayList<>(); for(Element mailElement : mailElements) { //Make sure that message has a Mail node if(mailElement.getLocalName().equals("mail")) { //New mail Object Mail mail = new Mail(); //Get the First Child Node child = mailElement.getFirstChild(); while(child != null) { //Parse each of the child nodes if(child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": mail.setFrom(child.getFirstChild().getNodeValue()); break; case "reply-to": mail.setReplyTo(child.getFirstChild().getNodeValue()); break; case "to": mail.addTo(child.getFirstChild().getNodeValue()); break; case "cc": mail.addCC(child.getFirstChild().getNodeValue()); break; case "bcc": mail.addBCC(child.getFirstChild().getNodeValue()); break; case "subject": mail.setSubject(child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while(bodyPart != null) { if(bodyPart.getLocalName().equals("text")) { mail.setText(bodyPart.getFirstChild().getNodeValue()); } else if(bodyPart.getLocalName().equals("xhtml")) { //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); mail.setXHTML(strWriter.toString()); } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": Element attachment = (Element)child; MailAttachment ma = new MailAttachment(attachment.getAttribute("filename"), attachment.getAttribute("mimetype"), attachment.getFirstChild().getNodeValue()); mail.addAttachment(ma); break; } } //next node child = child.getNextSibling(); } mails.add(mail); } } return mails; } /** * Constructs a mail Object from an XML representation of an email * * The XML email Representation is expected to look something like this * * <mail> * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text charset="" encoding=""></text> * <xhtml charset="" encoding=""></xhtml> * <generic charset="" type="" encoding=""></generic> * </message> * <attachment mimetype="" filename=""></attachment> * </mail> * * @param mailElements The XML mail Node * @return A mail Object representing the XML mail Node * * @throws IOException if an I/O error occurs * @throws MessagingException if an email error occurs * @throws TransformerException if a transformation error occurs */ private List<Message> parseMessageElement(Session session, List<Element> mailElements) throws IOException, MessagingException, TransformerException { List<Message> mails = new ArrayList<>(); for (Element mailElement : mailElements) { //Make sure that message has a Mail node if (mailElement.getLocalName().equals("mail")) { //New message Object // create a message MimeMessage msg = new MimeMessage(session); ArrayList<InternetAddress> replyTo = new ArrayList<>(); boolean fromWasSet = false; MimeBodyPart body = null; Multipart multibody = null; ArrayList<MimeBodyPart> attachments = new ArrayList<>(); String firstContent = null; String firstContentType = null; String firstCharset = null; String firstEncoding = null; //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": // set the from and to address InternetAddress[] addressFrom = {new InternetAddress(child.getFirstChild().getNodeValue())}; msg.addFrom(addressFrom); fromWasSet = true; break; case "reply-to": // As we can only set the reply-to, not add them, let's keep // all of them in a list replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue())); msg.setReplyTo(replyTo.toArray(new InternetAddress[0])); break; case "to": msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "cc": msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "bcc": msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "subject": msg.setSubject(child.getFirstChild().getNodeValue()); break; case "header": // Optional : You can also set your custom headers in the Email if you Want msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if (bodyPart.getNodeType() != Node.ELEMENT_NODE) continue; Element elementBodyPart = (Element) bodyPart; String content = null; String contentType = null; switch (bodyPart.getLocalName()) { case "text": // Setting the Subject and Content Type content = bodyPart.getFirstChild().getNodeValue(); contentType = "plain"; break; case "xhtml": //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content = strWriter.toString(); contentType = "html"; break; case "generic": // Setting the Subject and Content Type content = elementBodyPart.getFirstChild().getNodeValue(); contentType = elementBodyPart.getAttribute("type"); break; } // Now, time to store it if (content != null && contentType != null && !contentType.isEmpty()) { String charset = elementBodyPart.getAttribute("charset"); String encoding = elementBodyPart.getAttribute("encoding"); if (body != null && multibody == null) { multibody = new MimeMultipart("alternative"); multibody.addBodyPart(body); } if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } if (StringUtils.isEmpty(encoding)) { encoding = "quoted-printable"; } if (body == null) { firstContent = content; firstCharset = charset; firstContentType = contentType; firstEncoding = encoding; } body = new MimeBodyPart(); body.setText(content, charset, contentType); if (encoding != null) { body.setHeader("Content-Transfer-Encoding", encoding); } if (multibody != null) multibody.addBodyPart(body); } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": Element attachment = (Element) child; MimeBodyPart part; // if mimetype indicates a binary resource, assume the content is base64 encoded if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) { part = new MimeBodyPart(); } else { part = new PreencodedMimeBodyPart("base64"); } StringBuilder content = new StringBuilder(); Node attachChild = attachment.getFirstChild(); while (attachChild != null) { if (attachChild.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(attachChild); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content.append(strWriter.toString()); } else { content.append(attachChild.getNodeValue()); } attachChild = attachChild.getNextSibling(); } part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype")))); part.setFileName(attachment.getAttribute("filename")); // part.setHeader("Content-Transfer-Encoding", "base64"); attachments.add(part); break; } } //next node child = child.getNextSibling(); } // Lost from if (!fromWasSet) msg.setFrom(); // Preparing content and attachments if (!attachments.isEmpty()) { if (multibody == null) { multibody = new MimeMultipart("mixed"); if (body != null) { multibody.addBodyPart(body); } } else { MimeMultipart container = new MimeMultipart("mixed"); MimeBodyPart containerBody = new MimeBodyPart(); containerBody.setContent(multibody); container.addBodyPart(containerBody); multibody = container; } for (MimeBodyPart part : attachments) { multibody.addBodyPart(part); } } // And now setting-up content if (multibody != null) { msg.setContent(multibody); } else if (body != null) { msg.setText(firstContent, firstCharset, firstContentType); if (firstEncoding != null) { msg.setHeader("Content-Transfer-Encoding", firstEncoding); } } msg.saveChanges(); mails.add(msg); } } return mails; } /** * Returns the current date and time in an RFC822 format, suitable for an email Date Header * * @return RFC822 formated date and time as a String */ private String getDateRFC822() { String dateString = ""; final Calendar rightNow = Calendar.getInstance(); //Day of the week switch(rightNow.get(Calendar.DAY_OF_WEEK)) { case Calendar.MONDAY: dateString = "Mon"; break; case Calendar.TUESDAY: dateString = "Tue"; break; case Calendar.WEDNESDAY: dateString = "Wed"; break; case Calendar.THURSDAY: dateString = "Thu"; break; case Calendar.FRIDAY: dateString = "Fri"; break; case Calendar.SATURDAY: dateString = "Sat"; break; case Calendar.SUNDAY: dateString = "Sun"; break; } dateString += ", "; //Date dateString += rightNow.get(Calendar.DAY_OF_MONTH); dateString += " "; //Month switch(rightNow.get(Calendar.MONTH)) { case Calendar.JANUARY: dateString += "Jan"; break; case Calendar.FEBRUARY: dateString += "Feb"; break; case Calendar.MARCH: dateString += "Mar"; break; case Calendar.APRIL: dateString += "Apr"; break; case Calendar.MAY: dateString += "May"; break; case Calendar.JUNE: dateString += "Jun"; break; case Calendar.JULY: dateString += "Jul"; break; case Calendar.AUGUST: dateString += "Aug"; break; case Calendar.SEPTEMBER: dateString += "Sep"; break; case Calendar.OCTOBER: dateString += "Oct"; break; case Calendar.NOVEMBER: dateString += "Nov"; break; case Calendar.DECEMBER: dateString += "Dec"; break; } dateString += " "; //Year dateString += rightNow.get(Calendar.YEAR); dateString += " "; //Time String tHour = Integer.toString(rightNow.get(Calendar.HOUR_OF_DAY)); if(tHour.length() == 1) { tHour = "0" + tHour; } String tMinute = Integer.toString(rightNow.get(Calendar.MINUTE)); if(tMinute.length() == 1) { tMinute = "0" + tMinute; } String tSecond = Integer.toString(rightNow.get(Calendar.SECOND)); if(tSecond.length() == 1) { tSecond = "0" + tSecond; } dateString += tHour + ":" + tMinute + ":" + tSecond + " "; //TimeZone Correction final String tzSign; String tzHours = ""; String tzMinutes = ""; final TimeZone thisTZ = rightNow.getTimeZone(); int tzOffset = thisTZ.getOffset(rightNow.getTime().getTime()); //get timezone offset in milliseconds tzOffset = (tzOffset / 1000); //convert to seconds tzOffset = (tzOffset / 60); //convert to minutes //Sign if(tzOffset > 1) { tzSign = "+"; } else { tzSign = "-"; tzOffset *= -1; } //Calc Hours and Minutes? if(tzOffset >= 60) { //Minutes and Hours tzHours += (tzOffset / 60); //hours // do we need to prepend a 0 if(tzHours.length() == 1) { tzHours = "0" + tzHours; } tzMinutes += (tzOffset % 60); //minutes // do we need to prepend a 0 if(tzMinutes.length() == 1) { tzMinutes = "0" + tzMinutes; } } else { //Just Minutes tzHours = "00"; tzMinutes += tzOffset; // do we need to prepend a 0 if(tzMinutes.length() == 1) { tzMinutes = "0" + tzMinutes; } } dateString += tzSign + tzHours + tzMinutes; return dateString; } /** * Base64 Encodes a string (used for message subject) * * @param str The String to encode * @return The encoded String * * @throws java.io.UnsupportedEncodingException if the encocding is unsupported */ private String encode64 (String str) throws java.io.UnsupportedEncodingException { String result = Base64.encodeBase64String(str.getBytes(charset)); result = result.replaceAll("\n","?=\n =?" + charset + "?B?"); result = "=?" + charset + "?B?" + result + "?="; return(result); } /** * Base64 Encodes an email address * * @param str The email address as a String to encode * @return The encoded email address String * * @throws java.io.UnsupportedEncodingException if the encocding is unsupported */ private String encode64Address (String str) throws java.io.UnsupportedEncodingException { String result; int idx = str.indexOf("<"); if(idx != -1) { result = encode64(str.substring(0,idx)) + " " + str.substring(idx); } else { result = str; } return(result); } /** * A simple data class to represent an email * attachment. Just has private * members and some get methods. * * @version 1.2 */ private static class MailAttachment { private String filename; private String mimeType; private String data; public MailAttachment(String filename, String mimeType, String data) { this.filename = filename; this.mimeType = mimeType; this.data = data; } public String getData() { return data; } public String getFilename() { return filename; } public String getMimeType() { return mimeType; } } /** * A simple data class to represent an email * doesnt do anything fancy just has private * members and get and set methods * * @version 1.2 */ private static class Mail { private String from = ""; //Who is the mail from private String replyTo = null; //Who should you reply to private final List<String> to = new ArrayList<>(); //Who is the mail going to private final List<String> cc = new ArrayList<>(); //Carbon Copy to private final List<String> bcc = new ArrayList<>(); //Blind Carbon Copy to private String subject = ""; //Subject of the mail private String text = ""; //Body text of the mail private String xhtml = ""; //Body XHTML of the mail private final List<MailAttachment> attachment = new ArrayList<>(); //Any attachments //From public void setFrom(String from) { this.from = from; } public String getFrom() { return(this.from); } //reply-to public void setReplyTo(String replyTo) { this.replyTo = replyTo; } public String getReplyTo() { return replyTo; } public void addTo(String to) { this.to.add(to); } public int countTo() { return(to.size()); } public String getTo(int index) { return to.get(index); } public List<String> getTo() { return(to); } public void addCC(String cc) { this.cc.add(cc); } public int countCC() { return(cc.size()); } public String getCC(int index) { return cc.get(index); } public List<String> getCC() { return(cc); } //BCC public void addBCC(String bcc) { this.bcc.add(bcc); } public int countBCC() { return bcc.size(); } public String getBCC(int index) { return bcc.get(index); } public List<String> getBCC() { return(bcc); } //Subject public void setSubject(String subject) { this.subject = subject; } public String getSubject() { return subject; } //text public void setText(String text) { this.text = text; } public String getText() { return text; } //xhtml public void setXHTML(String xhtml) { this.xhtml = xhtml; } public String getXHTML() { return xhtml; } public void addAttachment(MailAttachment ma) { attachment.add(ma); } public Iterator<MailAttachment> attachmentIterator() { return attachment.iterator(); } } }
package org.fao.fenix.commons.msd.dto.full; import com.fasterxml.jackson.annotation.JsonProperty; import org.fao.fenix.commons.annotations.Description; import org.fao.fenix.commons.annotations.Format; import org.fao.fenix.commons.annotations.Label; import org.fao.fenix.commons.annotations.Order; import org.fao.fenix.commons.msd.dto.JSONEntity; import javax.persistence.Embedded; import java.io.Serializable; public class MeAccessibility extends JSONEntity implements Serializable { @JsonProperty @Label(en="DATA DISSEMINATION",fr="DIFFUSION DE DONNÉES",es="DISTRIBUCIÓN DE DATOS") @Description(en= "This section reports the mode of distribution of the resource with a focus on how to access the resource, the supported formats.") @Order(1) @Format(Format.FORMAT.string) private SeDataDissemination seDataDissemination; @JsonProperty @Label(en="Clarity",fr="Clarté",es="Claridad") @Description(en= "This section gives information about the availability of additional information (documentation, further metadata. . . ) linked to the resource.") @Order(2) @Format(Format.FORMAT.string) private SeClarity seClarity; @JsonProperty @Label(en="Confidentiality",fr="Confidentialité",es="Confidencialidad") @Description(en= "This section information on the level of confidentiality and the applied policy for releasing the resource. This metadata sub-entity concerns legislation (or any other formal provision) related to statistical confidentiality applied to the resource as well as the actual confidentiality data treatment applied (also with regard to the aggregated data disseminated).") @Order(3) @Format(Format.FORMAT.string) private SeConfidentiality seConfidentiality; public SeDataDissemination getSeDataDissemination() { return seDataDissemination; } @Embedded public void setSeDataDissemination(SeDataDissemination seDataDissemination) { this.seDataDissemination = seDataDissemination; } public SeClarity getSeClarity() { return seClarity; } @Embedded public void setSeClarity(SeClarity seClarity) { this.seClarity = seClarity; } public SeConfidentiality getSeConfidentiality() { return seConfidentiality; } @Embedded public void setSeConfidentiality(SeConfidentiality seConfidentiality) { this.seConfidentiality = seConfidentiality; } }
package org.usip.osp.networking; import java.util.Hashtable; import java.lang.reflect.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.log4j.*; import org.usip.osp.baseobjects.USIP_OSP_Util; public class USIP_OSP_ContextListener implements ServletContextListener { /** Key to get hashtable with localized language strings. */ public static final String CACHEON_UI_LOCALIZED_LANGUAGE = "local_lang"; /** Name of the actors stored by schema and rs_id and actor_id */ public static final String CACHEON_ACTOR_NAMES = "actor_names"; //$NON-NLS-1$ /** * Name of the actor thumb nail images stored by schema and rs_id and * actor_id */ public static final String CACHEON_ACTOR_THUMBS = "actor_thumbs"; //$NON-NLS-1$ /** Simulation section Information is continually being accessed. */ public static final String CACHEON_SIM_SEC_INFO = "sim_section_info"; //$NON-NLS-1$ /** * Conversations are cached so that the database doesn't have to be * continually hit as players log on and off. */ public static final String CACHEON_BROADCAST_CONV = "broadcast_conversations"; //$NON-NLS-1$ /** * Conversations are cached so that the database doesn't have to be * continually hit as players log on and off. */ public static final String CACHEON_CONVERSATIONS = "conversation_cache"; //$NON-NLS-1$ /** * The actors available for conversation are cached to help load chat * pages quickly. */ public static final String CACHEON_CONV_ACTORS = "conversation_actors"; //$NON-NLS-1$ /** * Chart information can also be cached. */ public static final String CACHEON_CHARTS = "charts"; //$NON-NLS-1$ /** * When a change is made to the database, this value is updated for the * simulation. Highest change number This alerts the program to check * against the database for new values. */ public static final String CACHEON_ALERT_NUMBERS = "highestAlertNumber"; //$NON-NLS-1$ public static final String CACHEON_PHASE_IDS = "phaseIds"; //$NON-NLS-1$ public static final String CACHEON_L_S_PHASE_NAMES_BY_RS_ID = "phaseNames"; //$NON-NLS-1$ public static final String CACHEON_L_S_PHASE_NAMES_BY_ID = "phaseNamesById"; //$NON-NLS-1$ public static final String CACHEON_L_S_METAPHASE_NAMES_BY_ID = "metaPhaseNamesById"; //$NON-NLS-1$ /** The id of the running simulation is used to find the round name. */ public static final String CACHEON_L_S_ROUND_NAMES = "roundNames"; //$NON-NLS-1$ /** The id of the running simulation is keyed */ public static final String CACHEON_L_S_PHASE_CHANGE_ALARMS = "phaseChangeAlarm"; //$NON-NLS-1$ /** Tickets are used to keep track of who is currently logged in. */ public static final String CACHEON_ACTIVE_TICKETS = "activeTickets"; //$NON-NLS-1$ public static final String CACHEON_LOGGED_IN_PLAYERS = "loggedInPlayers"; //$NON-NLS-1$ public static final String CACHEON_LOGGED_IN_USERS = "loggedInUsers"; //$NON-NLS-1$ public static final String CACHEON_USER_ASSIGNMENTS = "user_assignments"; //$NON-NLS-1$ public static final String CACHEON_USER_NAMES = "user_names"; //$NON-NLS-1$ public static final String CACHEON_USER_IDS = "user_ids"; //$NON-NLS-1$ public static final String CACHEON_BPI_NAMES = "bpi_names"; //$NON-NLS-1$ public static final String CACHEON_AUTOCOMPLETE_USERNAMES = "acu_names"; //$NON-NLS-1$ public static final String CACHEON_AUTOCOMPLETE_PLAYER_USERNAMES = "acup_names"; //$NON-NLS-1$ public static final String CACHEON_SIM_NAMES_BY_ID = "simNamesById"; //$NON-NLS-1$ /** Used to keep track of which injects have been fired during a game. */ public static final String CACHEON_INJECTS_FIRED = "injects_fired"; //$NON-NLS-1$ public static final String CACHEON_GAMETIMER = "usip_osp_game_timer"; /** * Utility method that ultimately leads on to resetWebCache(ServletContext) * @param request */ public static void resetWebCache(HttpServletRequest request, String schema) { resetWebCache(request.getSession(), schema); } /** * Utility method that ultimately leads on to resetWebCache(ServletContext) * @param request */ public static void resetWebCache(HttpSession session, String schema) { resetWebCache(session.getServletContext(), schema); } /** * This loops over all of the public static final fields in this class itself and uses their names * to get the stored caches, which it then sets to new Hashtables. * * @param sce The context for which the cache should be reset. * @param schema The database schema in which the user is working. */ public static void resetWebCache(ServletContext context, String schema) { Field field[] = USIP_OSP_ContextListener.class.getFields(); for (int ii = 0; ii < field.length; ++ii) { String fieldName = field[ii].getName(); int mod = field[ii].getModifiers(); String modifiers = Modifier.toString(mod); if (modifiers.equalsIgnoreCase("public static final")) { //$NON-NLS-1$ try { String field_value = (String) field[ii].get(null); String completeHashKey = USIP_OSP_Cache .makeSchemaSpecificHashKey(schema, field_value); if (fieldName.contains("_L_S_")) { //$NON-NLS-1$ context.setAttribute(field_value, new Hashtable<Long, String>()); } else { context.setAttribute(field_value, new Hashtable()); } } catch (Exception e) { Logger.getRootLogger() .warn("Exception in USIP_OSP_ContextListener.resetWebCache"); //$NON-NLS-1$ Logger.getRootLogger().warn("Error was: " + e.getMessage()); //$NON-NLS-1$ Logger.getRootLogger().warn( "While trying to set field: " + fieldName); //$NON-NLS-1$ } } } } /** Used to keep track of sections that an author can add. */ public static final String CACHEON_CUSTOMIZED_SECTIONS = "custom_section_info"; //$NON-NLS-1$ /** Used to keep track of sections that an author can add. */ public static final String CACHEON_BASE_SECTIONS = "base_section_info"; //$NON-NLS-1$ public static final String CACHED_TABLE_LONG_HASHTABLE = "long_hashtable"; public static final String CACHED_TABLE_LONG_STRING = "long_string"; public static final String CACHED_TABLE_LONG_LONG = "long_long"; public static final String CACHED_TABLE_STRING_VECTOR = "string_vector"; public static final String CACHED_TABLE_LIST = "list"; public static final String CACHED_TABLE_LONG_LIST = "long_list"; public static final String CACHED_TABLE_LONG_GPCT = "long_gpct"; public void contextInitialized(ServletContextEvent sce) { // SC - 9/20/2011. // I don't think we need this, and moving to a 'schema based cache' // makes it more // difficult and error prone to enable. // ServletContext context = sce.getServletContext(); // USIP_OSP_ContextListener.resetWebCache(context); // Running into problem hitting the database before tomcat has restarted // completely // since the logout page leads automatically back to the login page. // This may need to change. // USIP_OSP_Util.completedStartup = true; } public void contextDestroyed(ServletContextEvent arg0) { } }
package com.cqvip.zlfassist.activity; import java.sql.SQLException; 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.Set; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request.Method; import com.android.volley.Response.Listener; import com.cqvip.zlfassist.R; import com.cqvip.zlfassist.base.BaseActionBarActivity; import com.cqvip.zlfassist.bean.GeneralResult; import com.cqvip.zlfassist.bean.ItemFollows; import com.cqvip.zlfassist.constant.C; import com.cqvip.zlfassist.db.DatabaseHelper; import com.cqvip.zlfassist.http.VolleyManager; import com.google.gson.Gson; import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.dao.Dao; public class DisplayFollowActivity extends BaseActionBarActivity implements OnRefreshListener, OnItemClickListener, OnItemLongClickListener, OnClickListener { private Context context; public boolean isedit = false; private Adapter adapter; private ViewGroup mSelectionMenuView; private Button cancel, delete; private SwipeRefreshLayout mSwipeRefreshWidget; private ListView mList; private Map<String, String> gparams; private Handler mHandler = new Handler(); private final Runnable mRefreshDone = new Runnable() { @Override public void run() { mSwipeRefreshWidget.setRefreshing(false); } }; private DatabaseHelper databaseHelper = null; private ArrayList<ItemFollows> allFollowItem = new ArrayList<>(); private ArrayList<ItemFollows> selectedFollowItem = new ArrayList<>(); @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.activity_display_follow); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mSelectionMenuView = (ViewGroup) findViewById(R.id.selection_menu); delete = (Button) findViewById(R.id.selection_delete); cancel = (Button) findViewById(R.id.deselect_all); delete.setOnClickListener(this); cancel.setOnClickListener(this); mSwipeRefreshWidget = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_widget); mSwipeRefreshWidget.setColorSchemeResources(R.color.color1, R.color.color2, R.color.color3, R.color.color4); mList = (ListView) findViewById(R.id.Lv_followcontent); //list = new ArrayList<String>(Arrays.asList(TITLES)); context = this; adapter = new Adapter(context, allFollowItem); mList.addFooterView(getLayoutInflater().inflate( R.layout.item_displayfollow_list_footer, null)); mList.setAdapter(adapter); mList.setOnItemClickListener(this); mList.setOnItemLongClickListener(this); mSwipeRefreshWidget.setOnRefreshListener(this); getdatafromdb(); } @Override public void onRefresh() { refresh(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.display_follow, menu); return true; } /** * Click handler for the menu item to force a refresh. */ @Override public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); switch (id) { case R.id.force_refresh: mSwipeRefreshWidget.setRefreshing(true); refresh(); return true; case R.id.follow_add: startActivity(new Intent(this, AddFollowActivity.class)); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); return true; } return false; } private void refresh() { mHandler.removeCallbacks(mRefreshDone); mHandler.postDelayed(mRefreshDone, 1000); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.selection_delete: // for (String str : mSelectedIds) { // list.remove(str); allFollowItem.removeAll(selectedFollowItem); deleteDB(selectedFollowItem); adapter.notifyDataSetChanged(); clearSelection(); break; case R.id.deselect_all: clearSelection(); isedit = false; break; default: break; } } private void clearSelection() { selectedFollowItem.clear(); showOrHideSelectionMenu(); mList.invalidateViews(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == allFollowItem.size()) { startActivityForResult(new Intent(this, AddFollowActivity.class),1); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } else if (isedit) { } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); getdatafromdb(); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { isedit = true; mList.invalidateViews(); // mList.invalidate(); return true; } class Adapter extends BaseAdapter { private Context context; private LayoutInflater inflater = null; private ArrayList<ItemFollows> list; public Adapter(Context context, ArrayList<ItemFollows> list) { this.context = context; this.list = list; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { // TODO Auto-generated method stub return list.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } public long getItemId(int position) { // TODO Auto-generated method stub return position; } public View getView(final int position, View convertView, ViewGroup parent) { final ViewHolder holder; // TODO Auto-generated method stub if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate( R.layout.item_displayfollow_list, null); holder.title = (TextView) convertView .findViewById(R.id.tv_name); holder.cb = (CheckBox) convertView.findViewById(R.id.check); // holder.cb // .setOnCheckedChangeListener(new OnCheckedChangeListener() { // @Override // public void onCheckedChanged( // CompoundButton buttonView, boolean isChecked) { // if(position>=mList.getFirstVisiblePosition()&&position<=mList.getLastVisiblePosition()){ // if (isChecked) { // mSelectedIds.add(list.get(position)); // Log.i("onCheckedChanged", list.get(position)); // } else { // mSelectedIds.remove(list.get(position)); // delete.setText("("+mSelectedIds.size()+")"); // showOrHideSelectionMenu(); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.title.setText(list.get(position).getName()); holder.cb.setChecked(false); if (isedit) { holder.cb.setVisibility(View.VISIBLE); } else { holder.cb.setVisibility(View.GONE); } if (isedit && selectedFollowItem.contains(list.get(position))) { holder.cb.setChecked(true); } holder.cb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { holder.cb.toggle(); Log.i("getView", "onClick--" + position); if (selectedFollowItem.contains(list.get(position))) { selectedFollowItem.remove(list.get(position)); } else { selectedFollowItem.add(list.get(position)); } showOrHideSelectionMenu(); } }); return convertView; } class ViewHolder { TextView title; CheckBox cb; } } private void showOrHideSelectionMenu() { mList.invalidateViews(); boolean shouldBeVisible = !selectedFollowItem.isEmpty(); boolean isVisible = mSelectionMenuView.getVisibility() == View.VISIBLE; if (shouldBeVisible) { if (!isVisible) { // show menu mSelectionMenuView.setVisibility(View.VISIBLE); mSelectionMenuView.startAnimation(AnimationUtils.loadAnimation( this, R.anim.footer_appear)); } } else if (!shouldBeVisible && isVisible) { // hide menu mSelectionMenuView.setVisibility(View.GONE); mSelectionMenuView.startAnimation(AnimationUtils.loadAnimation( this, R.anim.footer_disappear)); } } private DatabaseHelper getHelper() { if (databaseHelper == null) { databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class); } return databaseHelper; } @Override protected void onDestroy() { super.onDestroy(); if (databaseHelper != null) { OpenHelperManager.releaseHelper(); databaseHelper = null; } } private void getdatafromdb() { try { Dao<ItemFollows, Integer> itemFollowsDao = getHelper() .getItemFollowsDao(); allFollowItem.clear(); ArrayList<ItemFollows> temp = (ArrayList<ItemFollows>) itemFollowsDao.queryBuilder().orderBy("datetime", false).query(); Log.i("getdatafromdb", allFollowItem.size()+""); allFollowItem.addAll(temp); adapter.notifyDataSetChanged(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void deleteDB(ArrayList<ItemFollows> itemFollows) { try { Dao<ItemFollows, Integer> itemFollowsDao = getHelper() .getItemFollowsDao(); // ItemFollows itemFollows = new ItemFollows(); // store it in the database itemFollowsDao.delete(itemFollows); } catch (SQLException e) { e.printStackTrace(); } } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.coref; import java.io.IOException; import java.util.Arrays; import java.util.List; import opennlp.tools.coref.mention.Extent; import opennlp.tools.coref.mention.HeadFinder; import opennlp.tools.coref.mention.MentionContext; import opennlp.tools.coref.mention.MentionFinder; import opennlp.tools.coref.mention.Parse; import opennlp.tools.coref.resolver.AbstractResolver; /** * Provides a default implementation of many of the methods in <code>Linker</code> that * most implementations of <code>Linker</code> wil want to extend. */ public abstract class AbstractLinker implements Linker { /** The mention finder used to find mentions. */ protected MentionFinder mentionFinder; /** Specifies whether debug print is generated. */ protected boolean debug = true; /** The mode in which this linker is running. */ protected LinkerMode mode; /** Instance used for for returning the same linker for subsequent getInstance requests. */ protected static Linker linker; /** The resolvers used by this Linker. */ protected AbstractResolver[] resolvers; /** The names of the resolvers used by this Linker. */ protected String[] resolverNames; /** Array used to store the results of each call made to the linker. */ protected DiscourseEntity[] entities; /** The index of resolver which is used for singular pronouns. */ protected int SINGULAR_PRONOUN; /** The name of the project where the coreference models are stored. */ protected String corefProject; /** The head finder used in this linker. */ protected HeadFinder headFinder; /** Specifies whether coreferent mentions should be combined into a single entity. * Set this to true to combine them, false otherwise. */ protected boolean useDiscourseModel; /** * Creates a new linker using the models in the specified project directory and using the specified mode. * @param project The location of the models or other data needed by this linker. * @param mode The mode the linker should be run in: testing, training, or evaluation. */ public AbstractLinker(String project, LinkerMode mode) { this(project,mode,true); } /** * Creates a new linker using the models in the specified project directory, using the specified mode, * and combining coreferent entities based on the specified value. * @param project The location of the models or other data needed by this linker. * @param mode The mode the linker should be run in: testing, training, or evaluation. * @param useDiscourseModel Specifies whether coreferent mention should be combined or not. */ public AbstractLinker(String project, LinkerMode mode,boolean useDiscourseModel) { this.corefProject = project; this.mode = mode; SINGULAR_PRONOUN = -1; this.useDiscourseModel = useDiscourseModel; } /** * Removes the specified mention to an entity in the specified discourse model or creates a new entity for the mention. * @param mention The mention to resolve. * @param discourseModel The discource model of existing entities. */ protected void resolve(MentionContext mention, DiscourseModel discourseModel) { //System.err.println("AbstractLinker.resolve: "+mode+"("+econtext.id+") "+econtext.toText()); boolean validEntity = true; // true if we should add this entity to the dm boolean canResolve = false; for (int ri = 0; ri < resolvers.length; ri++) { if (resolvers[ri].canResolve(mention)) { if (mode == LinkerMode.TEST) { entities[ri] = resolvers[ri].resolve(mention, discourseModel); canResolve = true; } else if (mode == LinkerMode.TRAIN) { entities[ri] = resolvers[ri].retain(mention, discourseModel); if (ri+1 != resolvers.length) { canResolve = true; } } else if (mode == LinkerMode.EVAL) { entities[ri] = resolvers[ri].retain(mention, discourseModel); //DiscourseEntity rde = resolvers[ri].resolve(mention, discourseModel); //eval.update(rde == entities[ri], ri, entities[ri], rde); } else { System.err.println("AbstractLinker.Unknown mode: " + mode); } if (ri == SINGULAR_PRONOUN && entities[ri] == null) { validEntity = false; } } else { entities[ri] = null; } } if (!canResolve) { //System.err.println("No resolver for: "+econtext.toText()+ " head="+econtext.headTokenText+" "+econtext.headTokenTag); validEntity = false; } DiscourseEntity de = checkForMerges(discourseModel, entities); if (validEntity) { updateExtent(discourseModel, mention, de,useDiscourseModel); } } public HeadFinder getHeadFinder() { return headFinder; } /** * Updates the specified discourse model with the specified mention as coreferent with the specified entity. * @param dm The discourse model * @param mention The mention to be added to the specified entity. * @param entity The entity which is mentioned by the specified mention. * @param useDiscourseModel Whether the mentions should be kept as an entiy or simply co-indexed. */ protected void updateExtent(DiscourseModel dm, MentionContext mention, DiscourseEntity entity, boolean useDiscourseModel) { if (useDiscourseModel) { if (entity != null) { //System.err.println("AbstractLinker.updateExtent: addingExtent: // "+econtext.toText()); if (entity.getGenderProbability() < mention.getGenderProb()) { entity.setGender(mention.getGender()); entity.setGenderProbability(mention.getGenderProb()); } if (entity.getNumberProbability() < mention.getNumberProb()) { entity.setNumber(mention.getNumber()); entity.setNumberProbability(mention.getNumberProb()); } entity.addExtent(mention); dm.mentionEntity(entity); } else { //System.err.println("AbstractLinker.updateExtent: creatingExtent: // "+econtext.toText()+" "+econtext.gender+" "+econtext.number); entity = new DiscourseEntity(mention, mention.getGender(), mention.getGenderProb(), mention.getNumber(), mention.getNumberProb()); dm.addEntity(entity); } } else { if (entity != null) { DiscourseEntity newEntity = new DiscourseEntity(mention, mention.getGender(), mention.getGenderProb(), mention.getNumber(), mention.getNumberProb()); dm.addEntity(newEntity); newEntity.setId(entity.getId()); } else { DiscourseEntity newEntity = new DiscourseEntity(mention, mention.getGender(), mention.getGenderProb(), mention.getNumber(), mention.getNumberProb()); dm.addEntity(newEntity); } } //System.err.println(de1); } protected DiscourseEntity checkForMerges(DiscourseModel dm, DiscourseEntity[] des) { DiscourseEntity de1; //tempory variable DiscourseEntity de2; //tempory variable de1 = des[0]; for (int di = 1; di < des.length; di++) { de2 = des[di]; if (de2 != null) { if (de1 != null && de1 != de2) { dm.mergeEntities(de1, de2, 1); } else { de1 = de2; } } } return (de1); } public DiscourseEntity[] getEntities(Extent[] mentions) { MentionContext[] extentContexts = this.constructMentionContexts(mentions); DiscourseModel dm = new DiscourseModel(); for (int ei = 0; ei < extentContexts.length; ei++) { //System.err.println(ei+" "+extentContexts[ei].toText()); resolve(extentContexts[ei], dm); } return (dm.getEntities()); } public void setEntities(Extent[] mentions) { getEntities(mentions); } public void train() throws IOException { for (int ri = 0; ri < resolvers.length; ri++) { resolvers[ri].train(); } } public Extent[] getMentions(Parse sentence) { return (mentionFinder.getMentions(sentence)); } public MentionContext[] constructMentionContexts(Extent[] mentions) { int mentionInSentenceIndex=-1; int numMentionsInSentence=-1; MentionContext[] contexts = new MentionContext[mentions.length]; for (int mi=0,mn=mentions.length;mi<mn;mi++) { Parse mentionParse = mentions[mi].getParse(); //System.err.println("AbstractLinker.constructMentionContexts: mentionParse="+mentionParse); if (mentionParse == null) { System.err.println("no parse for "+mentions[mi]); } int sentenceIndex = mentionParse.getSentenceNumber(); contexts[mi]=new MentionContext(mentionParse, mentionInSentenceIndex, numMentionsInSentence, mi, sentenceIndex, mentions[mi].getNameType(),getHeadFinder()); //System.err.println("AbstractLinker.constructMentionContexts: mi="+mi+" sn="+mentionParse.getSentenceNumber()+" extent="+mentions[mi]+" parse="+mentionParse.getSpan()+" mc="+contexts[mi].toText()); contexts[mi].setId(mentions[mi].getId()); mentionInSentenceIndex++; } return (contexts); } }
package org.apache.velocity.test.misc; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.io.StringWriter; import java.util.ArrayList; import java.util.Hashtable; import java.util.HashMap; import java.util.Properties; import java.util.Stack; import java.util.Vector; import org.apache.velocity.VelocityContext; import org.apache.velocity.Template; import org.apache.velocity.app.FieldMethodizer; import org.apache.velocity.app.Velocity; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.test.provider.TestProvider; /** * This class the testbed for Velocity. It is used to * test all the directives support by Velocity. * * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @version $Id: Test.java,v 1.14 2001/02/11 21:41:23 geirm Exp $ */ public class Test { /** * Cache of writers */ private static Stack writerStack = new Stack(); public Test(String templateFile) { Writer writer = null; TestProvider provider = new TestProvider(); ArrayList al = provider.getCustomers(); Hashtable h = new Hashtable(); /* * put this in to test introspection $h.Bar or $h.get("Bar") etc */ h.put("Bar", "this is from a hashtable!"); /* * adding simple vector with strings for testing late introspection stuff */ Vector v = new Vector(); v.addElement( new String("hello") ); v.addElement( new String("hello2") ); try { /* * this is another way to do properties when initializing Runtime. * make a Properties */ Properties p = new Properties(); /* * now, if you want to, load it from a file (or whatever) */ try { FileInputStream fis = new FileInputStream( new File("velocity.properties" )); if( fis != null) p.load( fis ); } catch (Exception ex) { /* no worries. no file... */ } /* * add some individual properties if you wish */ p.setProperty(Runtime.RUNTIME_LOG_ERROR_STACKTRACE, "true"); p.setProperty(Runtime.RUNTIME_LOG_WARN_STACKTRACE, "true"); p.setProperty(Runtime.RUNTIME_LOG_INFO_STACKTRACE, "true"); /* * and now call init */ Runtime.init(p); /* * now, do what we want to do. First, get the Template */ if (templateFile == null) templateFile = "examples/example.vm"; Template template = Runtime.getTemplate(templateFile); /* * now, make a Context object and populate it. */ VelocityContext context = new VelocityContext(); context.put("provider", provider); context.put("name", "jason"); context.put("providers", provider.getCustomers2()); context.put("list", al); context.put("hashtable", h); context.put("search", provider.getSearch()); context.put("relatedSearches", provider.getRelSearches()); context.put("searchResults", provider.getRelSearches()); context.put("menu", provider.getMenu()); context.put("stringarray", provider.getArray()); context.put("vector", v); context.put("mystring", new String()); context.put("hashmap", new HashMap() ); context.put("runtime", new FieldMethodizer( "org.apache.velocity.runtime.Runtime" )); context.put("fmprov", new FieldMethodizer( provider )); context.put("Floog", "floogie woogie"); String stest = " My name is $name -> $Floog"; StringWriter w = new StringWriter(); Velocity.evaluate( context, w, "evaltest",stest ); //System.out.println("Eval = " + w ); w = new StringWriter(); Velocity.mergeTemplate( "mergethis.vm", context, w ); //System.out.println("Merge = " + w ); w = new StringWriter(); Velocity.invokeVelocimacro( "floog", "test", new String[2], context, w ); //System.out.println("Invoke = " + w ); /* * make a writer, and merge the template 'against' the context */ writer = new BufferedWriter(new OutputStreamWriter(System.out)); template.merge( context , writer); writer.flush(); writer.close(); } catch( Exception e ) { Runtime.error(e); } } public static void main(String[] args) { Test t; t = new Test(args[0]); } }
package alien4cloud.dao; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import lombok.SneakyThrows; import org.apache.commons.collections4.map.HashedMap; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.count.CountRequestBuilder; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.elasticsearch.mapping.ElasticSearchClient; import org.elasticsearch.mapping.FilterValuesStrategy; import org.elasticsearch.mapping.MappingBuilder; import org.elasticsearch.mapping.QueryBuilderAdapter; import org.elasticsearch.mapping.QueryHelper; import org.elasticsearch.mapping.QueryHelper.SearchQueryHelperBuilder; import org.elasticsearch.mapping.SourceFetchContext; import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; import org.elasticsearch.search.aggregations.bucket.global.Global; import org.elasticsearch.search.aggregations.bucket.terms.InternalTerms; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import alien4cloud.dao.model.FacetedSearchFacet; import alien4cloud.dao.model.FacetedSearchResult; import alien4cloud.dao.model.GetMultipleDataResult; import alien4cloud.rest.utils.JsonUtil; import alien4cloud.utils.ElasticSearchUtil; import alien4cloud.utils.MapUtil; import com.google.common.collect.Lists; /** * Elastic search dao that manages search operations. * * @author luc boutier */ public abstract class ESGenericSearchDAO extends ESGenericIdDAO implements IGenericSearchDAO { // private static final String SCORE_SCRIPT = "_score * ((doc.containsKey('alienScore') && !doc['alienScore'].empty) ? doc['alienScore'].value : 1)"; @Resource private ElasticSearchClient esClient; @Resource private QueryHelper queryHelper; @Override public <T> long count(Class<T> clazz, QueryBuilder query) { String indexName = getIndexForType(clazz); String typeName = MappingBuilder.indexTypeFromClass(clazz); CountRequestBuilder countRequestBuilder = getClient().prepareCount(indexName).setTypes(typeName); if (query != null) { countRequestBuilder.setQuery(query); } return countRequestBuilder.execute().actionGet().getCount(); } @Override public <T> long count(Class<T> clazz, String searchText, Map<String, String[]> filters) { String[] searchIndexes = clazz == null ? getAllIndexes() : new String[]{getIndexForType(clazz)}; Class<?>[] requestedTypes = getRequestedTypes(clazz); return this.queryHelper.buildCountQuery(searchIndexes, searchText).types(requestedTypes).filters(filters).count().getCount(); } @Override public void delete(Class<?> clazz, QueryBuilder query) { String indexName = getIndexForType(clazz); String typeName = MappingBuilder.indexTypeFromClass(clazz); // get all elements and then use a bulk delete to remove data. SearchRequestBuilder searchRequestBuilder = getClient().prepareSearch(indexName).setTypes(getTypesFromClass(clazz)).setQuery(query).setNoFields().setFetchSource(false); searchRequestBuilder.setFrom(0).setSize(1000); SearchResponse response = searchRequestBuilder.execute().actionGet(); while (somethingFound(response)) { BulkRequestBuilder bulkRequestBuilder = getClient().prepareBulk().setRefresh(true); for (int i = 0; i < response.getHits().hits().length; i++) { String id = response.getHits().hits()[i].getId(); bulkRequestBuilder.add(getClient().prepareDelete(indexName, typeName, id)); } bulkRequestBuilder.execute().actionGet(); if (response.getHits().totalHits() == response.getHits().hits().length) { response = null; } else { response = searchRequestBuilder.execute().actionGet(); } } } @SneakyThrows({IOException.class}) private <T> List<T> doCustomFind(Class<T> clazz, QueryBuilder query, SortBuilder sortBuilder, int size) { String indexName = getIndexForType(clazz); SearchRequestBuilder searchRequestBuilder = getClient().prepareSearch(indexName).setTypes(getTypesFromClass(clazz)).setSize(size); if (query != null) { searchRequestBuilder.setQuery(query); } if (sortBuilder != null) { searchRequestBuilder.addSort(sortBuilder); } SearchResponse response = searchRequestBuilder.execute().actionGet(); if (!somethingFound(response)) { return null; } else { List<T> hits = Lists.newArrayList(); for (int i = 0; i < response.getHits().getHits().length; i++) { String hit = response.getHits().getAt(i).sourceAsString(); hits.add((T) getJsonMapper().readValue(hit, getClassFromType(response.getHits().getAt(i).getType()))); } return hits; } } @Override public <T> T customFind(Class<T> clazz, QueryBuilder query) { return customFind(clazz, query, null); } @Override public <T> T customFind(Class<T> clazz, QueryBuilder query, SortBuilder sortBuilder) { List<T> results = doCustomFind(clazz, query, sortBuilder, 1); if (results == null || results.isEmpty()) { return null; } else { return results.iterator().next(); } } @Override public <T> List<T> customFindAll(Class<T> clazz, QueryBuilder query) { return customFindAll(clazz, query, null); } @Override public <T> List<T> customFindAll(Class<T> clazz, QueryBuilder query, SortBuilder sortBuilder) { return doCustomFind(clazz, query, sortBuilder, Integer.MAX_VALUE); } @Override public <T> GetMultipleDataResult<T> find(Class<T> clazz, Map<String, String[]> filters, int maxElements) { return find(clazz, filters, 0, maxElements); } @Override public <T> GetMultipleDataResult<T> find(Class<T> clazz, Map<String, String[]> filters, int from, int maxElements) { return search(clazz, null, filters, from, maxElements); } @Override public GetMultipleDataResult<Object> search(SearchQueryHelperBuilder queryHelperBuilder, int from, int maxElements) { return toGetMultipleDataResult(Object.class, queryHelperBuilder.search(from, maxElements), from); } @Override public <T> GetMultipleDataResult<T> search(Class<T> clazz, String searchText, Map<String, String[]> filters, int maxElements) { return search(clazz, searchText, filters, 0, maxElements); } @Override public <T> GetMultipleDataResult<T> search(Class<T> clazz, String searchText, Map<String, String[]> filters, int from, int maxElements) { return search(clazz, searchText, filters, null, from, maxElements); } @Override public <T> GetMultipleDataResult<T> search(Class<T> clazz, String searchText, Map<String, String[]> filters, String fetchContext, int from, int maxElements) { return search(clazz, searchText, filters, null, fetchContext, from, maxElements); } @Override public <T> GetMultipleDataResult<T> search(Class<T> clazz, String searchText, Map<String, String[]> filters, FilterBuilder customFilter, String fetchContext, int from, int maxElements) { return search(clazz, searchText, filters, customFilter, fetchContext, from, maxElements, null, false); } @Override public <T> GetMultipleDataResult<T> search(Class<T> clazz, String searchText, Map<String, String[]> filters, FilterBuilder customFilter, String fetchContext, int from, int maxElements, String fieldSort, boolean sortOrder) { SearchResponse searchResponse = doSearch(clazz, searchText, filters, customFilter, fetchContext, from, maxElements, false, fieldSort, sortOrder); return toGetMultipleDataResult(clazz, searchResponse, from); } @Override public GetMultipleDataResult<Object> search(String[] searchIndices, Class<?>[] classes, String searchText, Map<String, String[]> filters, String fetchContext, int from, int maxElements) { return search(searchIndices, classes, searchText, filters, null, fetchContext, from, maxElements); } @Override public GetMultipleDataResult<Object> search(String[] searchIndices, Class<?>[] classes, String searchText, Map<String, String[]> filters, FilterBuilder customFilter, String fetchContext, int from, int maxElements) { SearchResponse searchResponse = queryHelper.buildSearchQuery(searchIndices, searchText).fetchContext(fetchContext).filters(filters) .customFilter(customFilter).types(classes).search(from, maxElements); return toGetMultipleDataResult(Object.class, searchResponse, from); } @Override public <T> FacetedSearchResult facetedSearch(Class<T> clazz, String searchText, Map<String, String[]> filters, int maxElements) { return facetedSearch(clazz, searchText, filters, null, 0, maxElements); } @Override public <T> FacetedSearchResult facetedSearch(Class<T> clazz, String searchText, Map<String, String[]> filters, String fetchContext, int from, int maxElements) { return facetedSearch(clazz, searchText, filters, null, fetchContext, from, maxElements); } @Override public <T> FacetedSearchResult facetedSearch(Class<T> clazz, String searchText, Map<String, String[]> filters, FilterBuilder customFilter, String fetchContext, int from, int maxElements) { return facetedSearch(clazz, searchText, filters, customFilter, fetchContext, from, maxElements, null, false); } @SuppressWarnings("unchecked") @Override @SneakyThrows({IOException.class}) public <T> FacetedSearchResult facetedSearch(Class<T> clazz, String searchText, Map<String, String[]> filters, FilterBuilder customFilter, String fetchContext, int from, int maxElements, String fieldSort, boolean sortOrder) { SearchResponse searchResponse = doSearch(clazz, searchText, filters, customFilter, fetchContext, from, maxElements, true, fieldSort, sortOrder); // check something found // return an empty object if nothing found if (!somethingFound(searchResponse)) { T[] resultData = (T[]) Array.newInstance(clazz, 0); FacetedSearchResult toReturn = new FacetedSearchResult(from, 0, 0, 0, new String[0], resultData, new HashMap<String, FacetedSearchFacet[]>()); if (searchResponse != null) { toReturn.setQueryDuration(searchResponse.getTookInMillis()); } return toReturn; } FacetedSearchResult finalResponse = new FacetedSearchResult(); fillMultipleDataResult(clazz, searchResponse, finalResponse, from, true); finalResponse.setFacets(parseAggregationCounts(searchResponse)); return finalResponse; } @Override public GetMultipleDataResult<Object> suggestSearch(String[] searchIndices, Class<?>[] requestedTypes, String suggestFieldPath, String searchPrefix, String fetchContext, int from, int maxElements) { SearchResponse searchResponse = queryHelper.buildSearchSuggestQuery(searchIndices, searchPrefix, suggestFieldPath).types(requestedTypes) .fetchContext(fetchContext).search(from, maxElements); return toGetMultipleDataResult(Object.class, searchResponse, from); } @Override public <T> GetMultipleDataResult<T> search(Class<T> clazz, String searchText, Map<String, String[]> filters, Map<String, FilterValuesStrategy> filterStrategies, int maxElements) { String[] searchIndices = clazz == null ? getAllIndexes() : new String[]{getIndexForType(clazz)}; Class<?>[] requestedTypes = getRequestedTypes(clazz); SearchResponse searchResponse = queryHelper.buildSearchQuery(searchIndices).types(requestedTypes).filters(filters).filterStrategies(filterStrategies) .search(0, maxElements); return toGetMultipleDataResult(clazz, searchResponse, 0); } /** * Convert a SearchResponse into a {@link GetMultipleDataResult} including json deserialization. * * @param searchResponse The actual search response from elastic-search. * @param from The start index of the search request. * @return A {@link GetMultipleDataResult} instance that contains de-serialized data. */ @SuppressWarnings("unchecked") @SneakyThrows({IOException.class}) public <T> GetMultipleDataResult<T> toGetMultipleDataResult(Class<T> clazz, SearchResponse searchResponse, int from) { // return an empty object if no data has been found in elastic search. if (!somethingFound(searchResponse)) { return new GetMultipleDataResult<T>(new String[0], (T[]) Array.newInstance(clazz, 0)); } GetMultipleDataResult<T> finalResponse = new GetMultipleDataResult<T>(); fillMultipleDataResult(clazz, searchResponse, finalResponse, from, true); return finalResponse; } /** * Convert a SearchResponse into a list of objects (json deserialization.) * * @param searchResponse The actual search response from elastic-search. * @param clazz The type of objects to de-serialize. * @return A list of instances that contains de-serialized data. */ @SneakyThrows({IOException.class}) public <T> List<T> toGetListOfData(SearchResponse searchResponse, Class<T> clazz) { // return null if no data has been found in elastic search. if (!somethingFound(searchResponse)) { return null; } List<T> result = new ArrayList<>(); for (int i = 0; i < searchResponse.getHits().getHits().length; i++) { result.add(getJsonMapper().readValue(searchResponse.getHits().getAt(i).getSourceAsString(), clazz)); } return result; } private <T> void fillMultipleDataResult(Class<T> clazz, SearchResponse searchResponse, GetMultipleDataResult<T> finalResponse, int from, boolean managePagination) throws IOException { if (managePagination) { int to = from + searchResponse.getHits().getHits().length - 1; finalResponse.setFrom(from); finalResponse.setTo(to); finalResponse.setTotalResults(searchResponse.getHits().getTotalHits()); finalResponse.setQueryDuration(searchResponse.getTookInMillis()); } String[] resultTypes = new String[searchResponse.getHits().getHits().length]; T[] resultData = (T[]) Array.newInstance(clazz, resultTypes.length); for (int i = 0; i < resultTypes.length; i++) { resultTypes[i] = searchResponse.getHits().getAt(i).getType(); resultData[i] = (T) getJsonMapper().readValue(searchResponse.getHits().getAt(i).getSourceAsString(), getClassFromType(resultTypes[i])); } finalResponse.setData(resultData); finalResponse.setTypes(resultTypes); } private <T> SearchResponse doSearch(Class<T> clazz, String searchText, Map<String, String[]> filters, FilterBuilder customFilter, String fetchContext, int from, int maxElements, boolean enableFacets, String fieldSort, boolean sortOrder) { String[] searchIndexes = clazz == null ? getAllIndexes() : new String[]{getIndexForType(clazz)}; Class<?>[] requestedTypes = getRequestedTypes(clazz); String[] esTypes = getTypesStrings(requestedTypes); SearchQueryHelperBuilder query = this.queryHelper.buildSearchQuery(searchIndexes, searchText).types(requestedTypes).fetchContext(fetchContext) .filters(filters).customFilter(customFilter).facets(enableFacets); if (fieldSort != null) { query.fieldSort(fieldSort, sortOrder); } SearchRequestBuilder searchRequestBuilder = query.generate(from, maxElements, new QueryBuilderAdapter() { @Override public QueryBuilder adapt(QueryBuilder queryBuilder) { return QueryBuilders.functionScoreQuery(queryBuilder).scoreMode("multiply").boostMode(CombineFunction.MULT) .add(ScoreFunctionBuilders.fieldValueFactorFunction("alienScore").missing(1)); } }); searchRequestBuilder.setTypes(esTypes); return searchRequestBuilder.execute().actionGet(); } private boolean somethingFound(final SearchResponse searchResponse) { if (searchResponse == null || searchResponse.getHits() == null || searchResponse.getHits().getHits() == null || searchResponse.getHits().getHits().length == 0) { return false; } return true; } @Override public <T> List<T> findByIdsWithContext(Class<T> clazz, String fetchContext, String... ids) { // get the fetch context for the given type and apply it to the search List<String> includes = new ArrayList<String>(); List<String> excludes = new ArrayList<String>(); SourceFetchContext sourceFetchContext = getMappingBuilder().getFetchSource(clazz.getName(), fetchContext); if (sourceFetchContext != null) { includes.addAll(sourceFetchContext.getIncludes()); excludes.addAll(sourceFetchContext.getExcludes()); } else { getLog().warn("Unable to find fetch context <" + fetchContext + "> for class <" + clazz.getName() + ">. It will be ignored."); } String[] inc = includes.isEmpty() ? null : includes.toArray(new String[includes.size()]); String[] exc = excludes.isEmpty() ? null : excludes.toArray(new String[excludes.size()]); // TODO: correctly manage "from" and "size" SearchRequestBuilder searchRequestBuilder = getClient().prepareSearch(getIndexForType(clazz)) .setQuery(QueryBuilders.idsQuery(MappingBuilder.indexTypeFromClass(clazz)).ids(ids)).setFetchSource(inc, exc).setSize(20); SearchResponse searchResponse = searchRequestBuilder.execute().actionGet(); return toGetListOfData(searchResponse, clazz); } @Override public String[] selectPath(String index, Class<?>[] types, QueryBuilder queryBuilder, SortOrder sortOrder, String path, int from, int size) { String[] esTypes = new String[types.length]; for (int i = 0; i < types.length; i++) { esTypes[i] = MappingBuilder.indexTypeFromClass(types[i]); } return doSelectPath(index, esTypes, queryBuilder, sortOrder, path, from, size); } @Override public String[] selectPath(String index, String[] types, QueryBuilder queryBuilder, SortOrder sortOrder, String path, int from, int size) { return doSelectPath(index, types, queryBuilder, sortOrder, path, from, size); } @SneakyThrows({IOException.class}) private String[] doSelectPath(String index, String[] types, QueryBuilder queryBuilder, SortOrder sortOrder, String path, int from, int size) { SearchRequestBuilder searchRequestBuilder = esClient.getClient().prepareSearch(index); searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH).setQuery(queryBuilder).setSize(size).setFrom(from); searchRequestBuilder.setFetchSource(path, null); searchRequestBuilder.setTypes(types); if (sortOrder != null) { searchRequestBuilder.addSort(SortBuilders.fieldSort(path).order(sortOrder)); } SearchResponse searchResponse = searchRequestBuilder.execute().actionGet(); if (ElasticSearchUtil.isResponseEmpty(searchResponse)) { return new String[0]; } else { String[] results = new String[searchResponse.getHits().getHits().length]; for (int i = 0; i < results.length; i++) { Map<String, Object> result = JsonUtil.toMap(searchResponse.getHits().getAt(i).getSourceAsString()); results[i] = String.valueOf(MapUtil.get(result, path)); } return results; } } @Override public QueryHelper getQueryHelper() { return this.queryHelper; } // Parse aggregation and extract their results into an array of FacetedSearchFacets private Map<String, FacetedSearchFacet[]> parseAggregationCounts(SearchResponse searchResponse) { List<Aggregation> internalAggregationsList = null; if ( searchResponse.getAggregations() == null) return null; if( searchResponse.getAggregations().get("filter_aggregation") != null ) { MultiBucketsAggregation aggregation = searchResponse.getAggregations().get("filter_aggregation"); Aggregations internalAggregations = aggregation.getBuckets().iterator().next().getAggregations(); internalAggregationsList = internalAggregations.asList(); } if( searchResponse.getAggregations().get("global_aggregation") != null) { Global globalAggregation = searchResponse.getAggregations().get("global_aggregation"); Aggregations aggregations = globalAggregation.getAggregations(); internalAggregationsList = aggregations.asList(); } if ( internalAggregationsList != null && internalAggregationsList.size() > 0) { Map<String, FacetedSearchFacet[]> finalResults = new HashedMap(); for (Aggregation termsAgg : internalAggregationsList) { InternalTerms internalTerms = (InternalTerms) termsAgg; List<FacetedSearchFacet> facetedSearchFacets = new ArrayList<>(); for (Terms.Bucket entry : internalTerms.getBuckets()) { facetedSearchFacets.add(new FacetedSearchFacet(entry.getKey(), entry.getDocCount())); } finalResults.put(internalTerms.getName(), facetedSearchFacets.toArray(new FacetedSearchFacet[facetedSearchFacets.size()])); } return finalResults; } return null; } }
package org.formic.wizard.step; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.SwingConstants; import foxtrot.Worker; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.Project; import org.apache.tools.ant.Target; import org.apache.tools.ant.Task; import org.apache.tools.ant.UnknownElement; import org.apache.tools.ant.taskdefs.Ant; import org.apache.tools.ant.taskdefs.CallTarget; import org.formic.InstallContext; import org.formic.Installer; import org.formic.ant.util.AntUtils; import org.formic.dialog.console.ConsoleDialogs; import org.formic.dialog.gui.GuiDialogs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Step that runs the background install process and displays the progress for * the user. * * @author Eric Van Dewoestine (ervandew@yahoo.com) * @version $Revision$ */ public class InstallStep extends AbstractStep implements BuildListener { private static final String ICON = "/images/32x32/install.png"; private static final String INSTALL_TARGET = "install"; private JProgressBar guiOverallProgress; private JProgressBar guiTaskProgress; private JLabel guiOverallLabel; private JLabel guiTaskLabel; private JButton guiShowErrorButton; private charvax.swing.JProgressBar consoleOverallProgress; private charvax.swing.JProgressBar consoleTaskProgress; private charvax.swing.JLabel consoleOverallLabel; private charvax.swing.JLabel consoleTaskLabel; private charvax.swing.JButton consoleShowErrorButton; private List tasks = new ArrayList(); private String targetName = INSTALL_TARGET; private Throwable error; /** * Constructs this step. */ public InstallStep (String name) { super(name); } /** * {@inheritDoc} * @see AbstractStep#getIconPath() */ protected String getIconPath () { String path = super.getIconPath(); return path != null ? path : ICON; } /** * {@inheritDoc} * @see org.formic.wizard.WizardStep#initGui() */ public JComponent initGui () { guiOverallLabel = new JLabel(Installer.getString("install.initialize")); guiOverallLabel.setAlignmentX(0.0f); guiOverallProgress = new JProgressBar(); guiOverallProgress.setAlignmentX(0.0f); guiOverallProgress.setStringPainted(true); guiTaskLabel = new JLabel(); guiTaskLabel.setAlignmentX(0.0f); guiTaskProgress = new JProgressBar(); guiTaskProgress.setAlignmentX(0.0f); guiTaskProgress.setStringPainted(true); guiTaskProgress.setIndeterminate(true); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setBorder(BorderFactory.createEmptyBorder(50, 125, 10, 125)); panel.add(guiOverallProgress); panel.add(Box.createRigidArea(new Dimension(0, 5))); panel.add(guiOverallLabel); panel.add(Box.createRigidArea(new Dimension(0, 20))); panel.add(guiTaskProgress); panel.add(Box.createRigidArea(new Dimension(0, 5))); panel.add(guiTaskLabel); panel.add(Box.createRigidArea(new Dimension(0, 25))); JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); buttons.setAlignmentX(0.0f); guiShowErrorButton = new JButton(new ShowErrorAction()); guiShowErrorButton.setVisible(false); buttons.add(guiShowErrorButton); panel.add(buttons); return panel; } /** * {@inheritDoc} * @see org.formic.wizard.WizardStep#initConsole() */ public charva.awt.Component initConsole () { consoleOverallLabel = new charvax.swing.JLabel( Installer.getString("install.initialize")); consoleOverallProgress = new charvax.swing.JProgressBar(); consoleOverallProgress.setStringPainted(true); charvax.swing.JPanel overallProgressPanel = new charvax.swing.JPanel(new charva.awt.BorderLayout()); overallProgressPanel.setBorder( new charvax.swing.border.TitledBorder("Overall Progress")); overallProgressPanel.add(consoleOverallProgress, charva.awt.BorderLayout.CENTER); consoleTaskLabel = new charvax.swing.JLabel(); consoleTaskProgress = new charvax.swing.JProgressBar(); consoleTaskProgress.setStringPainted(true); consoleTaskProgress.setIndeterminate(true); charvax.swing.JPanel taskProgressPanel = new charvax.swing.JPanel(new charva.awt.BorderLayout()); taskProgressPanel.setBorder( new charvax.swing.border.TitledBorder("Task Progress")); taskProgressPanel.add(consoleTaskProgress, charva.awt.BorderLayout.CENTER); charvax.swing.JPanel panel = new charvax.swing.JPanel(); panel.setLayout( new charvax.swing.BoxLayout(panel, charvax.swing.BoxLayout.Y_AXIS)); //panel.setBorder(BorderFactory.createEmptyBorder(50, 125, 10, 125)); panel.add(new charvax.swing.JLabel()); panel.add(consoleOverallLabel); panel.add(new charvax.swing.JLabel()); panel.add(overallProgressPanel); panel.add(new charvax.swing.JLabel()); panel.add(consoleTaskLabel); panel.add(new charvax.swing.JLabel()); panel.add(taskProgressPanel); panel.add(new charvax.swing.JLabel()); charvax.swing.JPanel buttons = new charvax.swing.JPanel( new charva.awt.FlowLayout(FlowLayout.RIGHT, 0, 0)); consoleShowErrorButton = new charvax.swing.JButton(); //consoleShowErrorButton.addActionListener(...); consoleShowErrorButton.setVisible(false); buttons.add(consoleShowErrorButton); panel.add(buttons); return panel; } /** * {@inheritDoc} * @see org.formic.wizard.WizardStep#isBusyAnimated() */ public boolean isBusyAnimated () { return false; } /** * {@inheritDoc} * @see org.formic.wizard.WizardStep#isPreviousEnabled() */ public boolean isPreviousEnabled () { return false; } /** * {@inheritDoc} * @see org.formic.wizard.WizardStep#displayed() */ public void displayed () { // push context values into ant properties InstallContext context = Installer.getContext(); for (Iterator ii = context.keys(); ii.hasNext();){ Object key = ii.next(); Object value = context.getValue(key); if(key != null && value != null){ AntUtils.property(Installer.getProject(), key.toString(), value.toString()); } } if(Installer.isConsoleMode()){ displayedConsole(); }else{ displayedGui(); } } /** * Invoked when this step is displayed in the gui. */ protected void displayedGui () { setBusy(true); try{ Worker.post(new foxtrot.Task(){ public Object run () throws Exception { Target target = (Target) Installer.getProject().getTargets().get(INSTALL_TARGET); registerListener(target); execute(target); guiOverallProgress.setValue(guiOverallProgress.getMaximum()); guiOverallLabel.setText(Installer.getString("install.done")); guiTaskProgress.setValue(guiTaskProgress.getMaximum()); guiTaskLabel.setText(Installer.getString("install.done")); setCancelEnabled(false); return null; } }); }catch(Exception e){ error = e; error.printStackTrace(); GuiDialogs.showError(error); guiOverallLabel.setText( INSTALL_TARGET + ": " + Installer.getString("error.dialog.text")); guiShowErrorButton.setVisible(true); }finally{ setBusy(false); guiTaskProgress.setIndeterminate(false); } } /** * Invoked when this step is displayed in the console. */ protected void displayedConsole () { setBusy(true); new Thread(){ public void run () { try{ Target target = (Target) Installer.getProject().getTargets().get(INSTALL_TARGET); registerListener(target); execute(target); consoleOverallProgress.setValue(consoleOverallProgress.getMaximum()); consoleOverallLabel.setText(Installer.getString("install.done")); consoleTaskProgress.setValue(consoleTaskProgress.getMaximum()); consoleTaskLabel.setText(Installer.getString("install.done")); setCancelEnabled(false); }catch(Exception e){ error = e; error.printStackTrace(); ConsoleDialogs.showError(error); consoleOverallLabel.setText( INSTALL_TARGET + ": " + Installer.getString("error.dialog.text")); consoleShowErrorButton.setVisible(true); }finally{ consoleTaskProgress.setIndeterminate(false); setBusy(false); } } }.start(); } /** * Registers the listener to monitor build progress. * * @param target The install target. */ private void registerListener (Target target) { registerTasks(target.getTasks()); if(Installer.isConsoleMode()){ consoleOverallProgress.setMaximum(this.tasks.size()); consoleOverallProgress.setValue(0); }else{ guiOverallProgress.setMaximum(this.tasks.size()); guiOverallProgress.setValue(0); } Installer.getProject().addBuildListener(this); } /** * Register the supplied array of tasks. * * @param tasks The tasks to register. */ private void registerTasks (Task[] tasks) { for (int ii = 0; ii < tasks.length; ii++){ Task task = tasks[ii]; if(task instanceof UnknownElement){ UnknownElement ue = (UnknownElement)task; ue.maybeConfigure(); task = ((UnknownElement)task).getTask(); } this.tasks.add(task); if (task instanceof Ant || task instanceof CallTarget) { Project project = null; String[] targets = null; if(task instanceof Ant){ project = ((Ant)task).getTargetProject(); targets = ((Ant)task).getTargetNames(); }else{ project = ((CallTarget)task).getTargetProject(); targets = ((CallTarget)task).getTargetNames(); } project.addBuildListener(this); for (int jj = 0; jj < targets.length; jj++){ Target target = (Target)project.getTargets().get(targets[jj]); registerTasks(target.getTasks()); } } // TODO: For AntCallBack, AntFetch, and RunTarget, recursively determine // task list. } } /** * Executes the install target. * * @param target The install target. */ private void execute (Target target) throws BuildException { if(target == null){ throw new IllegalArgumentException( Installer.getString("install.target.not.found")); } target.execute(); tasks.clear(); } /** * {@inheritDoc} * @see BuildListener#buildStarted(BuildEvent) */ public void buildStarted (BuildEvent e) { } /** * {@inheritDoc} * @see BuildListener#buildFinished(BuildEvent) */ public void buildFinished (BuildEvent e) { } /** * {@inheritDoc} * @see BuildListener#targetStarted(BuildEvent) */ public void targetStarted (BuildEvent e) { targetName = e.getTarget().getName(); } /** * {@inheritDoc} * @see BuildListener#targetFinished(BuildEvent) */ public void targetFinished (BuildEvent e) { } /** * {@inheritDoc} * @see BuildListener#taskStarted(BuildEvent) */ public void taskStarted (BuildEvent e) { if(Installer.isConsoleMode()){ consoleOverallLabel.setText( targetName + " - " + e.getTask().getTaskName()); }else{ guiOverallLabel.setText(targetName + " - " + e.getTask().getTaskName()); } } /** * {@inheritDoc} * @see BuildListener#taskFinished(BuildEvent) */ public void taskFinished (BuildEvent e) { int index = tasks.indexOf(e.getTask()); if(index > 0){ if(Installer.isConsoleMode()){ consoleOverallProgress.setValue(index + 1); }else{ guiOverallProgress.setValue(index + 1); } } } /** * {@inheritDoc} * @see BuildListener#messageLogged(BuildEvent) */ public void messageLogged (BuildEvent e) { if(Installer.isConsoleMode()){ consoleTaskLabel.setText(e.getMessage()); }else{ guiTaskLabel.setText(e.getMessage()); } } private class ShowErrorAction extends AbstractAction { public ShowErrorAction () { super( Installer.getString("install.error.view"), new ImageIcon(Installer.getImage("/images/16x16/error.png"))); } public void actionPerformed (ActionEvent e){ GuiDialogs.showError(error); } } }
package nl.basjes.parse.useragent; import nl.basjes.parse.useragent.debug.UserAgentAnalyzerTester; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestPerformance { private static final Logger LOG = LoggerFactory.getLogger(TestPerformance.class); @Ignore @Test public void validateAllPredefinedBrowsersPerformance() { UserAgentAnalyzerTester uaa = new UserAgentAnalyzerTester(); Assert.assertTrue(uaa.runTests(false, false, true)); } }
package ti.modules.titanium.media; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollPropertyChange; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollProxyListener; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiRHelper; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.webkit.URLUtil; public class TiSound implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, KrollProxyListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnInfoListener, MediaPlayer.OnPreparedListener { private static final String TAG = "TiSound"; public static final int STATE_BUFFERING = 0; // current playback is in the buffering from the network state public static final int STATE_INITIALIZED = 1; // current playback is in the initialization state public static final int STATE_PAUSED = 2; // current playback is in the paused state public static final int STATE_PLAYING = 3; // current playback is in the playing state public static final int STATE_STARTING = 4; // current playback is in the starting playback state public static final int STATE_STOPPED = 5; // current playback is in the stopped state public static final int STATE_STOPPING = 6; // current playback is in the stopping state public static final int STATE_WAITING_FOR_DATA = 7; // current playback is in the waiting for audio data from the network state public static final int STATE_WAITING_FOR_QUEUE = 8; // current playback is in the waiting for audio data to fill the queue state public static final String STATE_BUFFERING_DESC = "buffering"; // current playback is in the buffering from the network state public static final String STATE_INITIALIZED_DESC = "initialized"; // current playback is in the initialization state public static final String STATE_PAUSED_DESC = "paused"; // current playback is in the paused state public static final String STATE_PLAYING_DESC = "playing"; // current playback is in the playing state public static final String STATE_STARTING_DESC = "starting"; // current playback is in the starting playback state public static final String STATE_STOPPED_DESC = "stopped"; // current playback is in the stopped state public static final String STATE_STOPPING_DESC = "stopping"; // current playback is in the stopping state public static final String STATE_WAITING_FOR_DATA_DESC = "waiting for data"; // current playback is in the waiting for audio data from the network state public static final String STATE_WAITING_FOR_QUEUE_DESC = "waiting for queue"; // current playback is in the waiting for audio data to fill the queue state public static final String EVENT_COMPLETE = "complete"; public static final String EVENT_ERROR = "error"; public static final String EVENT_CHANGE = "change"; public static final String EVENT_PROGRESS = "progress"; public static final String EVENT_COMPLETE_JSON = "{ type : '" + EVENT_COMPLETE + "' }"; private boolean paused = false; private boolean looping = false; protected KrollProxy proxy; protected MediaPlayer mp; protected float volume; protected boolean playOnResume; protected boolean remote; protected Timer progressTimer; private boolean pausePending = false; private boolean stopPending = false; private boolean playPending = false; private boolean prepareRequired = false; public TiSound(KrollProxy proxy) { this.proxy = proxy; this.playOnResume = false; this.remote = false; } protected void initializeAndPlay() throws IOException { try { mp = new MediaPlayer(); String url = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_URL)); boolean isAsset = URLUtil.isAssetUrl(url); if (isAsset || url.startsWith("android.resource")) { Context context = TiApplication.getInstance(); AssetFileDescriptor afd = null; try { if (isAsset) { String path = url.substring(TiConvert.ASSET_URL.length()); afd = context.getAssets().openFd(path); } else { Uri uri = Uri.parse(url); afd = context.getResources().openRawResourceFd(TiRHelper.getResource("raw." + uri.getLastPathSegment())); } // Why mp.setDataSource(afd) doesn't work is a problem for another day. mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); } catch (IOException e) { Log.e(TAG, "Error setting file descriptor: ", e); } finally { if (afd != null) { afd.close(); } } } else { Uri uri = Uri.parse(url); if (uri.getScheme().equals(TiC.PROPERTY_FILE)) { if (Build.VERSION.SDK_INT >= TiC.API_LEVEL_ICE_CREAM_SANDWICH) { mp.setDataSource(uri.getPath()); } else { // For 2.2 and below, MediaPlayer uses the native player which requires // files to have worldreadable access, workaround is to open an input // stream to the file and give that to the player. FileInputStream fis = null; try { fis = new FileInputStream(uri.getPath()); mp.setDataSource(fis.getFD()); } catch (IOException e) { Log.e(TAG, "Error setting file descriptor: ", e); } finally { if (fis != null) { fis.close(); } } } } else { remote = true; mp.setDataSource(url); } } String loop = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_LOOPING)); if (loop != null) { looping = Boolean.parseBoolean(loop); mp.setLooping(looping); } mp.setOnCompletionListener(this); mp.setOnErrorListener(this); mp.setOnInfoListener(this); mp.setOnBufferingUpdateListener(this); if (remote) { // try async mp.setOnPreparedListener(this); mp.prepareAsync(); playPending = true; } else { mp.prepare(); setState(STATE_INITIALIZED); setVolume(volume); if (proxy.hasProperty(TiC.PROPERTY_TIME)) { setTime(TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_TIME))); } startPlaying(); } } catch (Throwable t) { Log.w(TAG, "Issue while initializing : " , t); release(); setState(STATE_STOPPED); } } public boolean isLooping() { return looping; } public boolean isPaused() { return paused; } public boolean isPlaying() { boolean result = false; if (mp != null) { result = mp.isPlaying(); } return result; } public void pause() { try { if (mp != null) { if (mp.isPlaying()) { Log.d(TAG, "audio is playing, pause", Log.DEBUG_MODE); stopProgressTimer(); mp.pause(); paused = true; setState(STATE_PAUSED); } else if (playPending) { pausePending = true; } } } catch (Throwable t) { Log.w(TAG, "Issue while pausing : " , t); } } public void play() { try { if (mp == null) { setState(STATE_STARTING); initializeAndPlay(); } else { if (prepareRequired) { prepareAndPlay(); } else { startPlaying(); } } } catch (Throwable t) { Log.w(TAG, "Issue while playing : " , t); reset(); } } private void prepareAndPlay() throws IllegalStateException, IOException { prepareRequired = false; if (remote) { playPending = true; mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.setOnPreparedListener(null); mp.seekTo(0); if (!stopPending && !pausePending) { startPlaying(); } playPending = false; pausePending = false; stopPending = false; } }); mp.prepareAsync(); } else { mp.prepare(); mp.seekTo(0); startPlaying(); } } public void reset() { try { if (mp != null) { stopProgressTimer(); setState(STATE_STOPPING); mp.seekTo(0); looping = false; paused = false; setState(STATE_STOPPED); } } catch (Throwable t) { Log.w(TAG, "Issue while resetting : ", t); } } public void release() { try { if (mp != null) { mp.setOnCompletionListener(null); mp.setOnErrorListener(null); mp.setOnBufferingUpdateListener(null); mp.setOnInfoListener(null); mp.release(); mp = null; Log.d(TAG, "Native resources released.", Log.DEBUG_MODE); remote = false; } } catch (Throwable t) { Log.w(TAG, "Issue while releasing : " , t); } } public void setLooping(boolean loop) { try { if(loop != looping) { if (mp != null) { mp.setLooping(loop); } looping = loop; } } catch (Throwable t) { Log.w(TAG, "Issue while configuring looping : " , t); } } public void setVolume(float volume) { try { if (volume < 0.0f) { this.volume = 0.0f; Log.w(TAG, "Attempt to set volume less than 0.0. Volume set to 0.0"); } else if (volume > 1.0) { this.volume = 1.0f; proxy.setProperty(TiC.PROPERTY_VOLUME, volume); Log.w(TAG, "Attempt to set volume greater than 1.0. Volume set to 1.0"); } else { this.volume = volume; // Store in 0.0 to 1.0, scale when setting hw } if (mp != null) { float scaledVolume = this.volume; mp.setVolume(scaledVolume, scaledVolume); } } catch (Throwable t) { Log.w(TAG, "Issue while setting volume : " , t); } } public int getDuration() { int duration = 0; if (mp != null) { duration = mp.getDuration(); } return duration; } public int getTime() { int time = 0; if (mp != null) { time = mp.getCurrentPosition(); } else { time = TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_TIME)); } return time; } public void setTime(int position) { if (position < 0) { position = 0; } if (mp != null) { int duration = mp.getDuration(); if (position > duration) { position = duration; } try { mp.seekTo(position); } catch (IllegalStateException e) { Log.w(TAG, "Error calling seekTo() in an incorrect state. Ignoring."); } } proxy.setProperty(TiC.PROPERTY_TIME, position); } private void setState(int state) { proxy.setProperty("state", state); String stateDescription = ""; switch(state) { case STATE_BUFFERING : stateDescription = STATE_BUFFERING_DESC; break; case STATE_INITIALIZED : stateDescription = STATE_INITIALIZED_DESC; break; case STATE_PAUSED : stateDescription = STATE_PAUSED_DESC; break; case STATE_PLAYING : stateDescription = STATE_PLAYING_DESC; break; case STATE_STARTING : stateDescription = STATE_STARTING_DESC; break; case STATE_STOPPED : stateDescription = STATE_STOPPED_DESC; break; case STATE_STOPPING : stateDescription = STATE_STOPPING_DESC; break; case STATE_WAITING_FOR_DATA : stateDescription = STATE_WAITING_FOR_DATA_DESC; break; case STATE_WAITING_FOR_QUEUE : stateDescription = STATE_WAITING_FOR_QUEUE_DESC; break; } proxy.setProperty("stateDescription", stateDescription); Log.d(TAG, "Audio state changed: " + stateDescription, Log.DEBUG_MODE); KrollDict data = new KrollDict(); data.put("state", state); data.put("description", stateDescription); proxy.fireEvent(EVENT_CHANGE, data); } public void stop() { try { if (mp != null) { if (mp.isPlaying() || isPaused()) { Log.d(TAG, "audio is playing, stop()", Log.DEBUG_MODE); setState(STATE_STOPPING); mp.stop(); setState(STATE_STOPPED); stopProgressTimer(); prepareRequired = true; } else if (playPending) { stopPending = true; } if (isPaused()) { paused = false; } } } catch (Throwable t) { Log.e(TAG, "Error : ", t); } } public void onCompletion(MediaPlayer mp) { KrollDict data = new KrollDict(); data.putCodeAndMessage(TiC.ERROR_CODE_NO_ERROR, null); proxy.fireEvent(EVENT_COMPLETE, data); stop(); } @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { String msg = "Unknown media issue."; switch(what) { case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING : msg = "Stream not interleaved or interleaved improperly."; break; case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE : msg = "Stream does not support seeking"; break; case MediaPlayer.MEDIA_INFO_UNKNOWN : msg = "Unknown media issue"; break; case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING : msg = "Video is too complex for decoder, video lagging."; // shouldn't occur, but covering bases. break; } KrollDict data = new KrollDict(); data.putCodeAndMessage(TiC.ERROR_CODE_UNKNOWN, msg); proxy.fireEvent(EVENT_ERROR, data); return true; } @Override public boolean onError(MediaPlayer mp, int what, int extra) { int code = what; if(what == 0) { code = -1; } String msg = "Unknown media error."; if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) { msg = "Media server died"; } release(); KrollDict data = new KrollDict(); data.putCodeAndMessage(code, msg); data.put(TiC.PROPERTY_MESSAGE, msg); proxy.fireEvent(EVENT_ERROR, data); return true; } @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { Log.d(TAG, "Buffering: " + percent + "%", Log.DEBUG_MODE); } private void startProgressTimer() { if (progressTimer == null) { progressTimer = new Timer(true); } else { progressTimer.cancel(); progressTimer = new Timer(true); } progressTimer.schedule(new TimerTask() { @Override public void run() { if (mp != null && mp.isPlaying()) { int position = mp.getCurrentPosition(); KrollDict event = new KrollDict(); event.put("progress", position); proxy.fireEvent(EVENT_PROGRESS, event); } } }, 1000, 1000); } private void stopProgressTimer() { if (progressTimer != null) { progressTimer.cancel(); progressTimer = null; } } public void onDestroy() { if (mp != null) { mp.release(); mp = null; } // TitaniumMedia clears out the references after onDestroy. } public void onPause() { if (mp != null) { if (isPlaying()) { pause(); playOnResume = true; } } } public void onResume() { if (mp != null) { if (playOnResume) { play(); playOnResume = false; } } } @Override public void listenerAdded(String type, int count, KrollProxy proxy) { } @Override public void listenerRemoved(String type, int count, KrollProxy proxy) { } @Override public void processProperties(KrollDict d) { if (d.containsKey(TiC.PROPERTY_VOLUME)) { setVolume(TiConvert.toFloat(d, TiC.PROPERTY_VOLUME, 1.0f)); } } @Override public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (TiC.PROPERTY_VOLUME.equals(key)) { setVolume(TiConvert.toFloat(newValue, 1.0f)); } else if (TiC.PROPERTY_TIME.equals(key)) { setTime(TiConvert.toInt(newValue)); } } @Override public void propertiesChanged(List<KrollPropertyChange> changes, KrollProxy proxy) { for (KrollPropertyChange change : changes) { propertyChanged(change.getName(), change.getOldValue(), change.getNewValue(), proxy); } } private void startPlaying() { if (mp != null) { if (!isPlaying()) { Log.d(TAG, "audio is not playing, starting.", Log.DEBUG_MODE); Log.d(TAG, "Play: Volume set to " + volume, Log.DEBUG_MODE); mp.start(); paused = false; startProgressTimer(); } setState(STATE_PLAYING); } } @Override public void onPrepared(MediaPlayer mp) { mp.setOnPreparedListener(null); setState(STATE_INITIALIZED); setVolume(volume); if (proxy.hasProperty(TiC.PROPERTY_TIME)) { setTime(TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_TIME))); } if (!pausePending && !stopPending) { try { startPlaying(); } catch (Throwable t) { Log.w(TAG, "Issue while playing : ", t); reset(); } } playPending = false; pausePending = false; stopPending = false; } }
package jmetest.input; import java.util.HashMap; import javax.swing.ImageIcon; import jmetest.terrain.TestTerrain; import com.jme.app.SimpleGame; import com.jme.bounding.BoundingBox; import com.jme.image.Texture; import com.jme.input.ChaseCamera; import com.jme.input.ThirdPersonHandler; import com.jme.light.DirectionalLight; import com.jme.math.FastMath; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.Node; import com.jme.scene.shape.Box; import com.jme.scene.state.CullState; import com.jme.scene.state.FogState; import com.jme.scene.state.TextureState; import com.jme.util.LoggingSystem; import com.jme.util.TextureManager; import com.jmex.terrain.TerrainPage; import com.jmex.terrain.util.FaultFractalHeightMap; import com.jmex.terrain.util.ProceduralTextureGenerator; /** * <code>TestThirdPersonController</code> * * @author Joshua Slack * @version $Revision: 1.14 $ */ public class TestThirdPersonController extends SimpleGame { private Node m_character; private ChaseCamera chaser; private TerrainPage page; /** * Entry point for the test, * * @param args */ public static void main(String[] args) { LoggingSystem.getLogger().setLevel(java.util.logging.Level.OFF); TestThirdPersonController app = new TestThirdPersonController(); app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG); app.start(); } /** * builds the scene. * * @see com.jme.app.SimpleGame#initGame() */ protected void simpleInitGame() { display.setTitle("jME - 3rd person controller test"); setupCharacter(); setupTerrain(); setupChaseCamera(); setupInput(); } protected void simpleUpdate() { chaser.update(tpf); float camMinHeight = page.getHeight(cam.getLocation()) + 2f; if (!Float.isInfinite(camMinHeight) && !Float.isNaN(camMinHeight) && cam.getLocation().y <= camMinHeight) { cam.getLocation().y = camMinHeight; cam.update(); } float characterMinHeight = page.getHeight(m_character .getLocalTranslation())+((BoundingBox)m_character.getWorldBound()).yExtent; if (!Float.isInfinite(characterMinHeight) && !Float.isNaN(characterMinHeight)) { m_character.getLocalTranslation().y = characterMinHeight; } } private void setupCharacter() { Box b = new Box("box", new Vector3f(), 5,5,5); b.setModelBound(new BoundingBox()); b.updateModelBound(); m_character = new Node("char node"); rootNode.attachChild(m_character); m_character.attachChild(b); m_character.updateWorldBound(); // We do this to allow the camera setup access to the world bound in our setup code. TextureState ts = display.getRenderer().createTextureState(); ts.setEnabled(true); ts.setTexture( TextureManager.loadTexture( TestThirdPersonController.class.getClassLoader().getResource( "jmetest/data/images/Monkey.tga"), Texture.MM_LINEAR, Texture.FM_LINEAR)); m_character.setRenderState(ts); } private void setupTerrain() { rootNode.setRenderQueueMode(Renderer.QUEUE_OPAQUE); fpsNode.setRenderQueueMode(Renderer.QUEUE_ORTHO); display.getRenderer().setBackgroundColor( new ColorRGBA(0.5f, 0.5f, 0.5f, 1)); DirectionalLight dr = new DirectionalLight(); dr.setEnabled(true); dr.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f)); dr.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); dr.setDirection(new Vector3f(0.5f, -0.5f, 0)); CullState cs = display.getRenderer().createCullState(); cs.setCullMode(CullState.CS_BACK); cs.setEnabled(true); rootNode.setRenderState(cs); lightState.detachAll(); lightState.attach(dr); FaultFractalHeightMap heightMap = new FaultFractalHeightMap(257, 32, 0, 255, 0.75f); Vector3f terrainScale = new Vector3f(10, 1, 10); heightMap.setHeightScale(0.001f); page = new TerrainPage("Terrain", 33, heightMap.getSize(), terrainScale, heightMap.getHeightMap(), false); page.setDetailTexture(1, 16); rootNode.attachChild(page); ProceduralTextureGenerator pt = new ProceduralTextureGenerator( heightMap); pt.addTexture(new ImageIcon(TestTerrain.class.getClassLoader() .getResource("jmetest/data/texture/grassb.png")), -128, 0, 128); pt.addTexture(new ImageIcon(TestTerrain.class.getClassLoader() .getResource("jmetest/data/texture/dirt.jpg")), 0, 128, 255); pt.addTexture(new ImageIcon(TestTerrain.class.getClassLoader() .getResource("jmetest/data/texture/highest.jpg")), 128, 255, 384); pt.createTexture(512); TextureState ts = display.getRenderer().createTextureState(); ts.setEnabled(true); Texture t1 = TextureManager.loadTexture(pt.getImageIcon().getImage(), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, true); ts.setTexture(t1, 0); Texture t2 = TextureManager.loadTexture(TestThirdPersonController.class .getClassLoader() .getResource("jmetest/data/texture/Detail.jpg"), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR); ts.setTexture(t2, 1); t2.setWrap(Texture.WM_WRAP_S_WRAP_T); t1.setApply(Texture.AM_COMBINE); t1.setCombineFuncRGB(Texture.ACF_MODULATE); t1.setCombineSrc0RGB(Texture.ACS_TEXTURE); t1.setCombineOp0RGB(Texture.ACO_SRC_COLOR); t1.setCombineSrc1RGB(Texture.ACS_PRIMARY_COLOR); t1.setCombineOp1RGB(Texture.ACO_SRC_COLOR); t1.setCombineScaleRGB(1.0f); t2.setApply(Texture.AM_COMBINE); t2.setCombineFuncRGB(Texture.ACF_ADD_SIGNED); t2.setCombineSrc0RGB(Texture.ACS_TEXTURE); t2.setCombineOp0RGB(Texture.ACO_SRC_COLOR); t2.setCombineSrc1RGB(Texture.ACS_PREVIOUS); t2.setCombineOp1RGB(Texture.ACO_SRC_COLOR); t2.setCombineScaleRGB(1.0f); rootNode.setRenderState(ts); FogState fs = display.getRenderer().createFogState(); fs.setDensity(0.5f); fs.setEnabled(true); fs.setColor(new ColorRGBA(0.5f, 0.5f, 0.5f, 0.5f)); fs.setEnd(1000); fs.setStart(500); fs.setDensityFunction(FogState.DF_LINEAR); fs.setApplyFunction(FogState.AF_PER_VERTEX); rootNode.setRenderState(fs); } private void setupChaseCamera() { Vector3f targetOffset = new Vector3f(); targetOffset.y = ((BoundingBox) m_character.getWorldBound()).yExtent * 1.5f; chaser = new ChaseCamera(cam, m_character); chaser.setTargetOffset(targetOffset); } private void setupInput() { HashMap handlerProps = new HashMap(); handlerProps.put(ThirdPersonHandler.PROP_DOGRADUAL, "true"); handlerProps.put(ThirdPersonHandler.PROP_TURNSPEED, ""+(1.0f * FastMath.PI)); handlerProps.put(ThirdPersonHandler.PROP_LOCKBACKWARDS, "false"); handlerProps.put(ThirdPersonHandler.PROP_CAMERAALIGNEDMOVE, "true"); input = new ThirdPersonHandler(m_character, cam, handlerProps); input.setActionSpeed(100f); } }
package jp.ac.ynu.pl2017.gg.reversi.gui; import javax.swing.*; import javax.swing.border.EmptyBorder; import jp.ac.ynu.pl2017.gg.reversi.ai.BaseAI; import jp.ac.ynu.pl2017.gg.reversi.ai.Evaluation; import jp.ac.ynu.pl2017.gg.reversi.ai.OnlineDummyAI; import jp.ac.ynu.pl2017.gg.reversi.util.BoardHelper; import jp.ac.ynu.pl2017.gg.reversi.util.Item; import jp.ac.ynu.pl2017.gg.reversi.util.Stone; import jp.ac.ynu.pl2017.gg.reversi.util.Direction; import jp.ac.ynu.pl2017.gg.reversi.util.FinishListenedThread; import jp.ac.ynu.pl2017.gg.reversi.util.FinishListenedThread.ThreadFinishListener; import jp.ac.ynu.pl2017.gg.reversi.util.Point; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Random; public class Othello extends JPanel implements ActionListener, ThreadFinishListener { public static final int BOARD_SIZE = 8; public static final int IMAGE_ICON_SIZE = 40; public static final int ITEM_COUNT = 3; public static final ImageIcon emptyIcon = new ImageIcon("image/board/Empty.png"); public static final ImageIcon blackIcon = new ImageIcon("image/board/black.png"); public static final ImageIcon whiteIcon = new ImageIcon("image/board/white.png"); public static final ImageIcon tripleBlackIcon = new ImageIcon("image/board/tripleB.png"); public static final ImageIcon tripleWhiteIcon = new ImageIcon("image/board/tripleW.png"); public static final ImageIcon rolloverIcon = new ImageIcon("image/board/Rollover.png"); public static final ImageIcon canPutIcon = new ImageIcon("image/board/CanPut.png"); public static final ImageIcon grayIcon = new ImageIcon("image/board/graypanel.png"); public static final ImageIcon cannotPutIcon = new ImageIcon("image/board/bannedpanel.png"); public static final ImageIcon turn1Icon = new ImageIcon("image/board/45degree.png"); public static final ImageIcon turn2Icon = new ImageIcon("image/board/90degree.png"); public static final ImageIcon turn3Icon = new ImageIcon("image/board/135degree.png"); public static final ImageIcon dropB1Icon = new ImageIcon("image/board/dropB1.png"); public static final ImageIcon dropB2Icon = new ImageIcon("image/board/dropB2.png"); public static final ImageIcon dropB3Icon = new ImageIcon("image/board/dropB3.png"); public static final ImageIcon dropW1Icon = new ImageIcon("image/board/dropW1.png"); public static final ImageIcon dropW2Icon = new ImageIcon("image/board/dropW2.png"); public static final ImageIcon dropW3Icon = new ImageIcon("image/board/dropW3.png"); public static final ImageIcon dropK1Icon = new ImageIcon("image/board/dropback1.png"); public static final ImageIcon[] turnBtoW = {turn1Icon, turn2Icon, turn3Icon, whiteIcon}; public static final ImageIcon[] turnWtoB = {turn3Icon, turn2Icon, turn1Icon, blackIcon}; public static final ImageIcon[] turnWtoE = {dropW1Icon, dropW2Icon, dropW3Icon, dropK1Icon, emptyIcon}; public static final ImageIcon[] turnBtoE = {dropB1Icon, dropB2Icon, dropB3Icon, dropK1Icon, emptyIcon}; public static final ImageIcon itemIcon = new ImageIcon("image/board/item.png"); public static final ImageIcon itemCanPutIcon = new ImageIcon("image/board/itemCanPut.png"); public static final ImageIcon itemRollOver = new ImageIcon("image/board/itemRollover.png"); private JButton[][] buttonBoard = new JButton[BOARD_SIZE][BOARD_SIZE]; private Stone[][] board = new Stone[BOARD_SIZE][BOARD_SIZE]; private List<Point> itemPoints = new ArrayList<>(); private Stone myStone; // actionEvent private boolean myTurn; private boolean passFlag = false; private boolean dropFlag = false; private int grayTurn = 0; private int grayTurnCPU = 0; private boolean tripleFlag = false; private List<Point> triplePoints = new ArrayList<>(); private Class<BaseAI> selectedAI; private int selectedDifficulty; private boolean isCPU = false; // CPU private boolean CPUItemFlag = false; private PlayCallback callback; public Othello(PlayCallback pCallback, Class<BaseAI> pAi, int pDifficulty) { Dimension lDimension = new Dimension(BOARD_SIZE * IMAGE_ICON_SIZE, BOARD_SIZE * IMAGE_ICON_SIZE); setSize(lDimension); setPreferredSize(lDimension); // setResizable() -> pack() // setResizable(false); // pack(); Random random = new Random(); selectItemPoints(); myStone = random.nextBoolean() ? Stone.Black : Stone.White; myTurn = random.nextBoolean(); callback = pCallback; selectedAI = pAi; selectedDifficulty = pDifficulty; isCPU = !pAi.equals(OnlineDummyAI.class); initBoard(); // setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setVisible(true); new FinishListenedThread(this) { @Override public void doRun() { try { Thread.sleep(1500); } catch (InterruptedException e) { } } }.start(); } @Override public void actionPerformed( ActionEvent e) { String[] position = e.getActionCommand().split(","); int r = Integer.parseInt(position[0]); int c = Integer.parseInt(position[1]); if (dropFlag) { drop(r, c); return; } // if (r == BOARD_SIZE - 1 && c == BOARD_SIZE -1) { // useDrop(); // removeAllListener(); putStone(r, c, myStone); } public List<Point> makeHint( Stone stone) { List<Point> hint = new ArrayList<>(); for (int i = 0; i < BOARD_SIZE; i++) for (int j = 0; j < BOARD_SIZE; j++) if (!selectDirections(i, j, stone).isEmpty()) hint.add(new Point(i, j)); return hint; } private void putStone( int r, int c, Stone stone) { EnumSet<Direction> directions = selectDirections(r, c, stone); if (directions.isEmpty()) return; removeAllListener(); hideHint(); if (tripleFlag) { buttonBoard[r][c].setIcon(stone.getTripleImageIcon()); triplePoints.add(new Point(r, c)); tripleFlag = false; } else { buttonBoard[r][c].setIcon(stone.getImageIcon()); } buttonBoard[r][c].setRolloverIcon(null); board[r][c] = stone; Point point = new Point(r, c); if (itemPoints.contains(point)) { gainItem(point); } reverseStone(r, c, stone, directions); // printBoard(); new FinishListenedThread(this) { @Override public void doRun() { try { Thread.sleep(1000); } catch (InterruptedException e) { } } }.start(); } @Override public void onThreadFinish() { nextTurn(); } private EnumSet<Direction> selectDirections( int r, int c, Stone stone) { EnumSet<Direction> directions = EnumSet.noneOf(Direction.class); if (board[r][c] != Stone.Empty) return directions; EnumSet.allOf(Direction.class).stream().filter(d -> checkLine(r, c, stone, d)).forEach(directions::add); return directions; } private boolean checkLine( int r, int c, Stone stone, Direction direction) { int dr = direction.getDR(); int dc = direction.getDC(); int i = r + dr; int j = c + dc; while (0 <= i && i < BOARD_SIZE && 0 <= j && j < BOARD_SIZE) { if (board[i][j] == Stone.Empty || board[i][j] == Stone.Ban) break; else if (board[i][j] == stone) { if (Math.abs(r - i) > 1 || Math.abs(c - j) > 1) return true; else break; } i += dr; j += dc; } return false; } private void nextTurn() { myTurn = !myTurn; myStone = myStone.getReverse(); Stone playersStone = myTurn ? myStone : myStone.getReverse(); callback.onTurnChange(myTurn, new int[]{countStone(playersStone), countStone(playersStone.getReverse())}); if (grayTurn < 0) undoGray(); hideHint(); List<Point> hint = makeHint(myStone); if (hint.isEmpty()) { if (passFlag) { gameOver(); } else { passFlag = true; nextTurn(); } } else { passFlag = false; if (myTurn) { displayHint(hint); addAllListener(); grayTurn } else { // CPUItemFlag = true; if (CPUItemFlag) { useItemCPU(); callback.onOpponentUseItem(); hint = makeHint(myStone); CPUItemFlag = false; if (hint.isEmpty()) { nextTurn(); return; } } // removeAllListener(); // OmegaAI ai = new OmegaAI(hint, myStone, board, selectedDifficulty); // ai.think(); // putStone(ai.getRow(), ai.getColumn(), myStone); // Create AI Instance try { Constructor<BaseAI> tConstructor = selectedAI.getConstructor(List.class, Stone.class, Stone[][].class, int.class); Object[] tArgs = {hint, myStone, board, selectedDifficulty}; BaseAI ai = (BaseAI) tConstructor.newInstance(tArgs); if (isCPU && grayTurnCPU > 0) { ai.setGray(); grayTurnCPU } ai.think(); putStone(ai.getRow(), ai.getColumn(), myStone); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } // addAllListener(); } } } private void removeAllListener() { for (JButton[] buttons : buttonBoard) for (JButton button : buttons) button.removeActionListener(this); callback.disableItem(); } private void addAllListener() { for (JButton[] buttons : buttonBoard) for (JButton button : buttons) button.addActionListener(this); callback.enableItem(); } private void reverseStone( int r, int c, Stone stone, EnumSet<Direction> directions) { directions.forEach(d -> reverseLine(r, c, stone, d)); } private void reverseLine( int r, int c, Stone stone, Direction direction) { int dr = direction.getDR(); int dc = direction.getDC(); int i = r + dr; int j = c + dc; Stone reverse = stone.getReverse(); while (0 <= i && i < BOARD_SIZE && 0 <= j && j < BOARD_SIZE) { if (board[i][j] == reverse) { board[i][j] = stone; showAnimation(buttonBoard[i][j], stone, false); // buttonBoard[i][j].setIcon(stone.getImageIcon()); } else { break; } i += dr; j += dc; } } private void showAnimation(final JButton pTargetButton, final Stone pStone, boolean pIsDrop) { new Thread(){ @Override public void run() { ImageIcon[] targetIcons = null; if (pIsDrop) { targetIcons = pStone.equals(Stone.Black) ? turnBtoE : turnWtoE; } else { if (pStone.equals(Stone.White)) { targetIcons = turnBtoW; } else if (pStone.equals(Stone.Black)) { targetIcons = turnWtoB; } } for (int i = 0; i < targetIcons.length; i++) { pTargetButton.setIcon(targetIcons[i]); try { Thread.sleep(120); } catch (InterruptedException e) { pTargetButton.setIcon(targetIcons[3]); break; } } String[] position = pTargetButton.getActionCommand().split(","); int r = Integer.parseInt(position[0]); int c = Integer.parseInt(position[1]); if (triplePoints.contains(new Point(r, c))) pTargetButton.setIcon(pStone.getTripleImageIcon()); } }.start(); } private void displayHint( List<Point> hint) { hint.forEach(p -> { if (itemPoints.contains(p)) buttonBoard[p.getRow()][p.getColumn()].setIcon(itemCanPutIcon); else buttonBoard[p.getRow()][p.getColumn()].setIcon(canPutIcon); }); } private void hideHint() { for (JButton[] buttons : buttonBoard) for (JButton button : buttons) if (button.getIcon().equals(canPutIcon)) button.setIcon(emptyIcon); else if (button.getIcon().equals(itemCanPutIcon)) button.setIcon(itemIcon); } private void gameOver() { String result = String.format("%d %d", countStone(Stone.Black), countStone(Stone.White)); JOptionPane.showMessageDialog(this, new JLabel(result), "", JOptionPane.INFORMATION_MESSAGE); undoGray(); // ImageIcon for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { buttonBoard[i][j].setDisabledIcon(board[i][j].getImageIcon()); buttonBoard[i][j].setEnabled(false); } } // PlayPanel callback.onGameOver(); } private int countStone( Stone stone) { int count = (int) Arrays.stream(board).mapToLong(ss -> Arrays.stream(ss).filter(s -> s == stone).count()).sum(); for (Point p : triplePoints) { if (board[p.getRow()][p.getColumn()] == stone) count += 2; } return count; } private void initBoard() { setLayout(new GridLayout(BOARD_SIZE, BOARD_SIZE)); for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { JButton button = new JButton(emptyIcon); button.setRolloverIcon(rolloverIcon); button.setBorder(new EmptyBorder(0, 0, 0, 0)); button.setActionCommand(i + "," + j); button.addActionListener(this); add(button); buttonBoard[i][j] = button; board[i][j] = Stone.Empty; } } board[3][3] = Stone.Black; board[3][4] = Stone.White; board[4][3] = Stone.White; board[4][4] = Stone.Black; buttonBoard[3][3].setIcon(blackIcon); buttonBoard[3][4].setIcon(whiteIcon); buttonBoard[4][3].setIcon(whiteIcon); buttonBoard[4][4].setIcon(blackIcon); buttonBoard[3][3].setRolloverIcon(null); buttonBoard[3][4].setRolloverIcon(null); buttonBoard[4][3].setRolloverIcon(null); buttonBoard[4][4].setRolloverIcon(null); buttonBoard[itemPoints.get(0).getRow()][itemPoints.get(0).getColumn()].setIcon(itemIcon); buttonBoard[itemPoints.get(1).getRow()][itemPoints.get(1).getColumn()].setIcon(itemIcon); buttonBoard[itemPoints.get(2).getRow()][itemPoints.get(2).getColumn()].setIcon(itemIcon); buttonBoard[itemPoints.get(0).getRow()][itemPoints.get(0).getColumn()].setRolloverIcon(itemRollOver); buttonBoard[itemPoints.get(1).getRow()][itemPoints.get(1).getColumn()].setRolloverIcon(itemRollOver); buttonBoard[itemPoints.get(2).getRow()][itemPoints.get(2).getColumn()].setRolloverIcon(itemRollOver); } private void selectItemPoints() { Random random = new Random(); while (itemPoints.size() < ITEM_COUNT) { int r = random.nextInt(8); int c = random.nextInt(8); if (2 <= r && r <= 5 && 2 <= c && c <= 5) continue; Point point = new Point(r, c); if (!itemPoints.contains(point)) { itemPoints.add(point); Evaluation.updateSquare(point); } } } private void gainItem(Point point) { itemPoints.remove(point); callback.onGainItem(myTurn); if (isCPU) { CPUItemFlag = true; } } public void useItem(Item item) { switch (item) { case BAN: useBan(); break; case DROP: useDrop(); break; case GRAY: if (isCPU) { grayTurnCPU = 3; } break; case TRIPLE: useTriple(); break; case CONTROLER: break; } } private void useBan() { hideHint(); List<Point> banPoints = new ArrayList<>(); // TODO: banPoints reflectBan(makeBanPoints()); List<Point> hint = makeHint(myStone); if (hint.isEmpty()) nextTurn(); else displayHint(hint); } private List<Point> makeBanPoints() { Random random = new Random(); List<Point> emptyPoints = BoardHelper.getPoints(Stone.Empty, board); int count = Math.min(3, emptyPoints.size()); List<Point> banPoints = new ArrayList<>(); for (int i = 0; i < count; i++) { banPoints.add(emptyPoints.get(random.nextInt(emptyPoints.size()))); } return banPoints; } private void useDrop() { dropFlag = true; hideHint(); removeAllListener(); for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { if (board[i][j] == myStone.getReverse()) { buttonBoard[i][j].addActionListener(this); } } } } private void drop(int r, int c) { removeAllListener(); Stone lbkStone = board[r][c]; board[r][c] = Stone.Empty; triplePoints.remove(new Point(r, c)); dropFlag = false; showAnimation(buttonBoard[r][c], lbkStone, true); // TODO: new FinishListenedThread(new ThreadFinishListener() { @Override public void onThreadFinish() { addAllListener(); List<Point> hint = makeHint(myStone); displayHint(hint); } }) { @Override public void doRun() { // TODO Auto-generated method stub try { Thread.sleep(1000); } catch (InterruptedException e) { } } }.start(); /* new Thread(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } addAllListener(); List<Point> hint = makeHint(myStone); displayHint(hint); }).start(); */ } private void useGray() { grayTurn = 1; for (JButton[] buttons : buttonBoard) for (JButton button : buttons) if (button.getIcon() == blackIcon || button.getIcon() == whiteIcon) button.setIcon(grayIcon); } private void undoGray() { for (int i = 0; i < BOARD_SIZE; i++) for (int j = 0; j < BOARD_SIZE; j++) if (buttonBoard[i][j].getIcon() == grayIcon) buttonBoard[i][j].setIcon(board[i][j].getImageIcon()); } private void useTriple() { tripleFlag = true; } private void useItemCPU() { // control4 int select = new Random().nextInt(4); // System.out.print("use item:"); switch (select) { case 0: // System.out.println("ban"); reflectBan(makeBanPoints()); break; case 1: // System.out.println("drop"); reflectDrop(Evaluation.getMaxEvaluatedPoint(BoardHelper.getPoints(myStone.getReverse(), board))); break; case 2: // System.out.println("gray"); reflectGray(); break; case 3: // System.out.println("triple"); reflectTriple(); break; } } /** * * @param banPoints */ public void reflectBan(List<Point> banPoints) { banPoints.forEach(p -> { board[p.getRow()][p.getColumn()] = Stone.Ban; buttonBoard[p.getRow()][p.getColumn()].setIcon(cannotPutIcon); buttonBoard[p.getRow()][p.getColumn()].setRolloverIcon(null); }); } public void reflectDrop(Point point) { drop(point.getRow(), point.getColumn()); } public void reflectGray() { useGray(); } public void reflectTriple() { tripleFlag = true; } }
package jp.tkji.yapcasiaviewer; import java.text.ParseException; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class TalkListFragment extends YAVListFragment implements LoaderCallbacks<VenueList> { private static final String STATE_ACTIVATED_POSITION = "activated_position"; private static final String STATE_NAVIGATION_POSITION = "navigation_position"; public static final String BUNDLE_DATE = "date"; private Callbacks mCallbacks = sDummyCallbacks; private int mActivatedPosition = ListView.INVALID_POSITION; private OnNavigationListener mNavigationListener = new OnNavigationListener() { @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { if (mNavigationPosition != itemPosition) { mVenue = mVenuList.get(itemPosition); setTalkList(mVenue.talkList); } mNavigationPosition = itemPosition; return true; } }; private ArrayAdapter<Venue> mVenuAdapter; private TalkListAdapter mTalkAdapter; private VenueList mVenuList; private String mDateString; private int loaderId; public interface Callbacks { public void onItemSelected(String id); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onItemSelected(String id) { } }; Venue mVenue; int mNavigationPosition = -1; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (savedInstanceState != null) { setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION)); mNavigationPosition = savedInstanceState.getInt(STATE_NAVIGATION_POSITION); } } protected void setTalkList(TalkList talkList) { if (talkList == null) { talkList = new TalkList(); } mTalkAdapter = new TalkListAdapter(activity(), talkList); setListAdapter(mTalkAdapter); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new IllegalStateException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle args = getArguments(); int pos = 0; if (args != null) { pos = args.getInt(BUNDLE_DATE, 0); } loaderId = pos; mDateString = getResources().getStringArray(R.array.dates)[pos]; try { getActivity().setTitle(DateUtil.convertToDisplayDayString(mDateString)); } catch (ParseException e) { e.printStackTrace(); } if (mVenuList == null) { getLoaderManager().initLoader(loaderId, null, this); } } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mActivatedPosition != ListView.INVALID_POSITION) { outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } outState.putInt(STATE_NAVIGATION_POSITION, mNavigationPosition); } public void setActivateOnItemClick(boolean activateOnItemClick) { getListView().setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE); } public void setActivatedPosition(int position) { if (position == ListView.INVALID_POSITION) { getListView().setItemChecked(mActivatedPosition, false); } else { getListView().setItemChecked(position, true); } mActivatedPosition = position; } private void setListNavigation() { ActionBar ab = activity().getSupportActionBar(); if (mVenuList != null) { mVenuAdapter = new ArrayAdapter<Venue>(ab.getThemedContext(), android.R.layout.simple_list_item_1, mVenuList); } else { mVenuAdapter = null; } ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); ab.setListNavigationCallbacks(mVenuAdapter, mNavigationListener); } @Override public Loader<VenueList> onCreateLoader(int id, Bundle args) { ActionBar ab = activity().getSupportActionBar(); ab.setListNavigationCallbacks(null, null); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); return new TimeTableLoader(app(), mDateString); } @Override public void onLoadFinished(Loader<VenueList> loader, VenueList data) { if (data == null) { app().showErrorToast(); } else if(mVenuList == null) { mVenuList = data; setListNavigation(); } } @Override public void onLoaderReset(Loader<VenueList> loader) {} public String getDateString() { return mDateString; } }
package com.tanguyantoine.react; import android.app.NotificationManager; import android.app.NotificationChannel; import android.content.ComponentCallbacks2; import android.content.Intent; import android.content.IntentFilter; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.os.SystemClock; import android.os.Build; import androidx.annotation.RequiresApi; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.RatingCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import androidx.core.app.NotificationCompat; import androidx.media.app.NotificationCompat.MediaStyle; import android.util.Log; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Locale; import java.util.Map; public class MusicControlModule extends ReactContextBaseJavaModule implements ComponentCallbacks2 { private static final String TAG = MusicControlModule.class.getSimpleName(); static MusicControlModule INSTANCE; private boolean init = false; protected MediaSessionCompat session; private MediaMetadataCompat.Builder md; private PlaybackStateCompat.Builder pb; public NotificationCompat.Builder nb; private PlaybackStateCompat state; public MusicControlNotification notification; private MusicControlVolumeListener volume; private MusicControlReceiver receiver; private MusicControlEventEmitter emitter; private MusicControlAudioFocusListener afListener; private Thread artworkThread; public ReactApplicationContext context; private boolean remoteVolume = false; private boolean isPlaying = false; private long controls = 0; protected int ratingType = RatingCompat.RATING_PERCENTAGE; public NotificationClose notificationClose = NotificationClose.PAUSED; public static final String CHANNEL_ID = "react-native-music-control"; public static final int NOTIFICATION_ID = 100; public MusicControlModule(ReactApplicationContext context) { super(context); } @Override public String getName() { return "MusicControlManager"; } @Override public Map<String, Object> getConstants() { Map<String, Object> map = new HashMap<>(); map.put("STATE_ERROR", PlaybackStateCompat.STATE_ERROR); map.put("STATE_STOPPED", PlaybackStateCompat.STATE_STOPPED); map.put("STATE_PLAYING", PlaybackStateCompat.STATE_PLAYING); map.put("STATE_PAUSED", PlaybackStateCompat.STATE_PAUSED); map.put("STATE_BUFFERING", PlaybackStateCompat.STATE_BUFFERING); map.put("RATING_HEART", RatingCompat.RATING_HEART); map.put("RATING_THUMBS_UP_DOWN", RatingCompat.RATING_THUMB_UP_DOWN); map.put("RATING_3_STARS", RatingCompat.RATING_3_STARS); map.put("RATING_4_STARS", RatingCompat.RATING_4_STARS); map.put("RATING_5_STARS", RatingCompat.RATING_5_STARS); map.put("RATING_PERCENTAGE", RatingCompat.RATING_PERCENTAGE); return map; } @RequiresApi(Build.VERSION_CODES.O) private void createChannel(ReactApplicationContext context) { NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "Media playback", NotificationManager.IMPORTANCE_LOW); mChannel.setDescription("Media playback controls"); mChannel.setShowBadge(false); mChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC); mNotificationManager.createNotificationChannel(mChannel); } private boolean hasControl(long control) { if((controls & control) == control) { return true; } return false; } private void updateNotificationMediaStyle() { if (!Build.MANUFACTURER.toLowerCase(Locale.getDefault()).contains("huawei") && Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { MediaStyle style = new MediaStyle(); style.setMediaSession(session.getSessionToken()); int controlCount = 0; if(hasControl(PlaybackStateCompat.ACTION_PLAY) || hasControl(PlaybackStateCompat.ACTION_PAUSE) || hasControl(PlaybackStateCompat.ACTION_PLAY_PAUSE)) { controlCount += 1; } if(hasControl(PlaybackStateCompat.ACTION_SKIP_TO_NEXT)) { controlCount += 1; } if(hasControl(PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)) { controlCount += 1; } if(hasControl(PlaybackStateCompat.ACTION_FAST_FORWARD)) { controlCount += 1; } if(hasControl(PlaybackStateCompat.ACTION_REWIND)) { controlCount += 1; } int[] actions = new int[controlCount]; for(int i=0; i<actions.length; i++) { actions[i] = i; } style.setShowActionsInCompactView(actions); nb.setStyle(style); } } public void init() { if (init) return; INSTANCE = this; context = getReactApplicationContext(); emitter = new MusicControlEventEmitter(context); session = new MediaSessionCompat(context, "MusicControl"); session.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); session.setCallback(new MediaSessionCallback(emitter)); volume = new MusicControlVolumeListener(context, emitter, true, 100, 100); if(remoteVolume) { session.setPlaybackToRemote(volume); } else { session.setPlaybackToLocal(AudioManager.STREAM_MUSIC); } md = new MediaMetadataCompat.Builder(); pb = new PlaybackStateCompat.Builder(); pb.setActions(controls); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createChannel(context); } nb = new NotificationCompat.Builder(context, CHANNEL_ID); nb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); nb.setPriority(NotificationCompat.PRIORITY_HIGH); updateNotificationMediaStyle(); state = pb.build(); notification = new MusicControlNotification(this, context); notification.updateActions(controls, null); IntentFilter filter = new IntentFilter(); filter.addAction(MusicControlNotification.REMOVE_NOTIFICATION); filter.addAction(MusicControlNotification.MEDIA_BUTTON); filter.addAction(Intent.ACTION_MEDIA_BUTTON); filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); receiver = new MusicControlReceiver(this, context); context.registerReceiver(receiver, filter); Intent myIntent = new Intent(context, MusicControlNotification.NotificationService.class); afListener = new MusicControlAudioFocusListener(context, emitter, volume); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ context.startForegroundService(myIntent); } else context.startService(myIntent); context.registerComponentCallbacks(this); isPlaying = false; init = true; } @ReactMethod public synchronized void stopControl() { if (!init) return; if (notification != null) notification.hide(); session.release(); ReactApplicationContext context = getReactApplicationContext(); context.unregisterReceiver(receiver); context.unregisterComponentCallbacks(this); if (artworkThread != null && artworkThread.isAlive()) artworkThread.interrupt(); artworkThread = null; session = null; notification = null; volume = null; receiver = null; state = null; md = null; pb = null; nb = null; init = false; } synchronized public void destroy() { stopControl(); } @ReactMethod public void enableBackgroundMode(boolean enable) { // Nothing? } @ReactMethod public void observeAudioInterruptions(boolean enable) { if (enable) { afListener.requestAudioFocus(); } else { afListener.abandonAudioFocus(); } } @ReactMethod synchronized public void setNowPlaying(ReadableMap metadata) { init(); if(artworkThread != null && artworkThread.isAlive()) artworkThread.interrupt(); String title = metadata.hasKey("title") ? metadata.getString("title") : null; String artist = metadata.hasKey("artist") ? metadata.getString("artist") : null; String album = metadata.hasKey("album") ? metadata.getString("album") : null; String genre = metadata.hasKey("genre") ? metadata.getString("genre") : null; String description = metadata.hasKey("description") ? metadata.getString("description") : null; String date = metadata.hasKey("date") ? metadata.getString("date") : null; long duration = metadata.hasKey("duration") ? (long)(metadata.getDouble("duration") * 1000) : 0; int notificationColor = metadata.hasKey("color") ? metadata.getInt("color") : NotificationCompat.COLOR_DEFAULT; String notificationIcon = metadata.hasKey("notificationIcon") ? metadata.getString("notificationIcon") : null; // If a color is supplied, we need to clear the MediaStyle set during init(). // Otherwise, the color will not be used for the notification's background. boolean removeFade = metadata.hasKey("color"); if(removeFade) { nb.setStyle(new MediaStyle()); } RatingCompat rating; if(metadata.hasKey("rating")) { if(ratingType == RatingCompat.RATING_PERCENTAGE) { rating = RatingCompat.newPercentageRating((float)metadata.getDouble("rating")); } else if(ratingType == RatingCompat.RATING_HEART) { rating = RatingCompat.newHeartRating(metadata.getBoolean("rating")); } else if(ratingType == RatingCompat.RATING_THUMB_UP_DOWN) { rating = RatingCompat.newThumbRating(metadata.getBoolean("rating")); } else { rating = RatingCompat.newStarRating(ratingType, (float)metadata.getDouble("rating")); } } else { rating = RatingCompat.newUnratedRating(ratingType); } md.putText(MediaMetadataCompat.METADATA_KEY_TITLE, title); md.putText(MediaMetadataCompat.METADATA_KEY_ARTIST, artist); md.putText(MediaMetadataCompat.METADATA_KEY_ALBUM, album); md.putText(MediaMetadataCompat.METADATA_KEY_GENRE, genre); md.putText(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, description); md.putText(MediaMetadataCompat.METADATA_KEY_DATE, date); md.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration); if (android.os.Build.VERSION.SDK_INT > 19) { md.putRating(MediaMetadataCompat.METADATA_KEY_RATING, rating); } nb.setContentTitle(title); nb.setContentText(artist); nb.setContentInfo(album); nb.setColor(notificationColor); notification.setCustomNotificationIcon(notificationIcon); if(metadata.hasKey("artwork")) { String artwork = null; boolean localArtwork = false; if(metadata.getType("artwork") == ReadableType.Map) { artwork = metadata.getMap("artwork").getString("uri"); localArtwork = true; } else { artwork = metadata.getString("artwork"); } final String artworkUrl = artwork; final boolean artworkLocal = localArtwork; artworkThread = new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = loadArtwork(artworkUrl, artworkLocal); if(md != null) { md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, bitmap); session.setMetadata(md.build()); } if(nb != null) { nb.setLargeIcon(bitmap); notification.show(nb, isPlaying); } artworkThread = null; } }); artworkThread.start(); } else { md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, null); nb.setLargeIcon(null); } session.setMetadata(md.build()); session.setActive(true); notification.show(nb, isPlaying); } @ReactMethod synchronized public void updatePlayback(ReadableMap info) { init(); long updateTime; long elapsedTime; long bufferedTime = info.hasKey("bufferedTime") ? (long)(info.getDouble("bufferedTime") * 1000) : state.getBufferedPosition(); float speed = info.hasKey("speed") ? (float)info.getDouble("speed") : state.getPlaybackSpeed(); int pbState = info.hasKey("state") ? info.getInt("state") : state.getState(); int maxVol = info.hasKey("maxVolume") ? info.getInt("maxVolume") : volume.getMaxVolume(); int vol = info.hasKey("volume") ? info.getInt("volume") : volume.getCurrentVolume(); ratingType = info.hasKey("rating") ? info.getInt("rating") : ratingType; if(info.hasKey("elapsedTime")) { elapsedTime = (long)(info.getDouble("elapsedTime") * 1000); updateTime = SystemClock.elapsedRealtime(); } else { elapsedTime = state.getPosition(); updateTime = state.getLastPositionUpdateTime(); } pb.setState(pbState, elapsedTime, speed, updateTime); pb.setBufferedPosition(bufferedTime); pb.setActions(controls); isPlaying = pbState == PlaybackStateCompat.STATE_PLAYING || pbState == PlaybackStateCompat.STATE_BUFFERING; if(session.isActive()) notification.show(nb, isPlaying); state = pb.build(); session.setPlaybackState(state); session.setRatingType(ratingType); if(remoteVolume) { session.setPlaybackToRemote(volume.create(null, maxVol, vol)); } else { session.setPlaybackToLocal(AudioManager.STREAM_MUSIC); } } @ReactMethod synchronized public void resetNowPlaying() { if(!init) return; if(artworkThread != null && artworkThread.isAlive()) artworkThread.interrupt(); artworkThread = null; md = new MediaMetadataCompat.Builder(); if (notification != null) notification.hide(); session.setActive(false); } @ReactMethod synchronized public void enableControl(String control, boolean enable, ReadableMap options) { init(); Map<String, Integer> skipOptions = new HashMap<String, Integer>(); long controlValue; switch(control) { case "skipForward": if (options.hasKey("interval")) skipOptions.put("skipForward", options.getInt("interval")); controlValue = PlaybackStateCompat.ACTION_FAST_FORWARD; break; case "skipBackward": if (options.hasKey("interval")) skipOptions.put("skipBackward", options.getInt("interval")); controlValue = PlaybackStateCompat.ACTION_REWIND; break; case "nextTrack": controlValue = PlaybackStateCompat.ACTION_SKIP_TO_NEXT; break; case "previousTrack": controlValue = PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; break; case "play": controlValue = PlaybackStateCompat.ACTION_PLAY; break; case "pause": controlValue = PlaybackStateCompat.ACTION_PAUSE; break; case "togglePlayPause": controlValue = PlaybackStateCompat.ACTION_PLAY_PAUSE; break; case "stop": controlValue = PlaybackStateCompat.ACTION_STOP; break; case "seek": controlValue = PlaybackStateCompat.ACTION_SEEK_TO; break; case "setRating": controlValue = PlaybackStateCompat.ACTION_SET_RATING; break; case "volume": volume = volume.create(enable, null, null); if(remoteVolume) session.setPlaybackToRemote(volume); return; case "remoteVolume": remoteVolume = enable; if(enable) { session.setPlaybackToRemote(volume); } else { session.setPlaybackToLocal(AudioManager.STREAM_MUSIC); } return; case "closeNotification": if(enable) { if (options.hasKey("when")) { if ("always".equals(options.getString("when"))) { this.notificationClose = notificationClose.ALWAYS; }else if ("paused".equals(options.getString("when"))) { this.notificationClose = notificationClose.PAUSED; }else { this.notificationClose = notificationClose.NEVER; } } return; } default: // Unknown control type, let's just ignore it return; } if(enable) { controls |= controlValue; } else { controls &= ~controlValue; } notification.updateActions(controls, skipOptions); pb.setActions(controls); state = pb.build(); session.setPlaybackState(state); updateNotificationMediaStyle(); if(session.isActive()) { notification.show(nb, isPlaying); } } private Bitmap loadArtwork(String url, boolean local) { Bitmap bitmap = null; try { // If we are running the app in debug mode, the "local" image will be served from htt://localhost:8080, so we need to check for this case and load those images from URL if(local && !url.startsWith("http")) { // Gets the drawable from the RN's helper for local resources ResourceDrawableIdHelper helper = ResourceDrawableIdHelper.getInstance(); Drawable image = helper.getResourceDrawable(getReactApplicationContext(), url); if(image instanceof BitmapDrawable) { bitmap = ((BitmapDrawable)image).getBitmap(); } else { bitmap = BitmapFactory.decodeFile(url); } } else { // Open connection to the URL and decodes the image URLConnection con = new URL(url).openConnection(); con.connect(); InputStream input = con.getInputStream(); bitmap = BitmapFactory.decodeStream(input); input.close(); } } catch(IOException ex) { Log.w(TAG, "Could not load the artwork", ex); } return bitmap; } @Override public void onTrimMemory(int level) { switch(level) { // Trims memory when it reaches a moderate level and the session is inactive case ComponentCallbacks2.TRIM_MEMORY_MODERATE: case ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE: if(session.isActive()) break; // Trims memory when it reaches a critical level case ComponentCallbacks2.TRIM_MEMORY_COMPLETE: case ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL: Log.w(TAG, "Control resources are being removed due to system's low memory (Level: " + level + ")"); destroy(); break; } } @Override public void onConfigurationChanged(Configuration newConfig) { } @Override public void onLowMemory() { Log.w(TAG, "Control resources are being removed due to system's low memory (Level: MEMORY_COMPLETE)"); destroy(); } public enum NotificationClose { ALWAYS, PAUSED, NEVER } public boolean isPlaying() { return isPlaying; } }
package com.algolia.search.saas; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; public class Query { public enum QueryType { /// all query words are interpreted as prefixes. PREFIX_ALL, /// only the last word is interpreted as a prefix (default behavior). PREFIX_LAST, /// no query word is interpreted as a prefix. This option is not recommended. PREFIX_NONE } public enum RemoveWordsType { // when a query does not return any result, the final word will be removed until there is results. This option is particulary useful on e-commerce websites REMOVE_LAST_WORDS, // when a query does not return any result, the first word will be removed until there is results. This option is useful on adress search. REMOVE_FIRST_WORDS, // No specific processing is done when a query does not return any result. REMOVE_NONE, /// When a query does not return any result, a second trial will be made with all words as optional (which is equivalent to transforming the AND operand between query terms in a OR operand) REMOVE_ALLOPTIONAL } public enum TypoTolerance { /// the typotolerance is enabled and all typos are retrieved. (Default behavior) TYPO_TRUE, /// the typotolerance is disabled. TYPO_FALSE, /// only keep results with the minimum number of typos. TYPO_MIN, /// the typotolerance with a distance=2 is disabled if the results contain hits without typo. TYPO_STRICT } protected List<String> attributes; protected List<String> attributesToHighlight; protected List<String> attributesToSnippet; protected int minWordSizeForApprox1; protected int minWordSizeForApprox2; protected boolean getRankingInfo; protected boolean ignorePlural; protected boolean distinct; protected boolean advancedSyntax; protected int page; protected int minProximity; protected String highlightPreTag; protected String highlightPostTag; protected int hitsPerPage; protected String restrictSearchableAttributes; protected String tags; protected String numerics; protected String insideBoundingBox; protected String aroundLatLong; protected boolean aroundLatLongViaIP; protected String query; protected QueryType queryType; protected String optionalWords; protected String facets; protected String facetFilters; protected int maxNumberOfFacets; protected boolean analytics; protected boolean synonyms; protected boolean replaceSynonyms; protected boolean allowTyposOnNumericTokens; protected RemoveWordsType removeWordsIfNoResult; protected TypoTolerance typoTolerance; protected String analyticsTags; public Query(String query) { minProximity = 1; minWordSizeForApprox1 = 3; minWordSizeForApprox2 = 7; getRankingInfo = false; ignorePlural = false; distinct = false; page = 0; minProximity = 1; hitsPerPage = 20; this.query = query; queryType = QueryType.PREFIX_LAST; maxNumberOfFacets = -1; advancedSyntax = false; analytics = synonyms = replaceSynonyms = allowTyposOnNumericTokens = true; analyticsTags = null; typoTolerance = TypoTolerance.TYPO_TRUE; removeWordsIfNoResult = RemoveWordsType.REMOVE_NONE; } public Query() { minProximity = 1; minWordSizeForApprox1 = 3; minWordSizeForApprox2 = 7; getRankingInfo = false; ignorePlural = false; distinct = false; page = 0; minProximity = 1; hitsPerPage = 20; queryType = QueryType.PREFIX_ALL; maxNumberOfFacets = -1; advancedSyntax = false; analytics = synonyms = replaceSynonyms = allowTyposOnNumericTokens = true; analyticsTags = null; typoTolerance = TypoTolerance.TYPO_TRUE; removeWordsIfNoResult = RemoveWordsType.REMOVE_NONE; } public Query(Query other) { if (other.attributesToHighlight != null) { attributesToHighlight = new ArrayList<String>(other.attributesToHighlight); } if (other.attributes != null) { attributes = new ArrayList<String>(other.attributes); } if (other.attributesToSnippet != null) { attributesToSnippet = new ArrayList<String>(other.attributesToSnippet); } minProximity = other.minProximity; highlightPreTag = other.highlightPreTag; highlightPostTag = other.highlightPostTag; minWordSizeForApprox1 = other.minWordSizeForApprox1; minWordSizeForApprox2 = other.minWordSizeForApprox2; getRankingInfo = other.getRankingInfo; ignorePlural = other.ignorePlural; distinct = other.distinct; advancedSyntax = other.advancedSyntax; page = other.page; hitsPerPage = other.hitsPerPage; restrictSearchableAttributes = other.restrictSearchableAttributes; tags = other.tags; numerics = other.numerics; insideBoundingBox = other.insideBoundingBox; aroundLatLong = other.aroundLatLong; aroundLatLongViaIP = other.aroundLatLongViaIP; query = other.query; queryType = other.queryType; optionalWords = other.optionalWords; facets = other.facets; facetFilters = other.facetFilters; maxNumberOfFacets = other.maxNumberOfFacets; analytics = other.analytics; analyticsTags = other.analyticsTags; synonyms = other.synonyms; replaceSynonyms = other.replaceSynonyms; typoTolerance = other.typoTolerance; allowTyposOnNumericTokens = other.allowTyposOnNumericTokens; removeWordsIfNoResult = other.removeWordsIfNoResult; } /** * Select the strategy to adopt when a query does not return any result. */ public Query removeWordsIfNoResult(RemoveWordsType type) { this.removeWordsIfNoResult = type; return this; } /** * List of attributes you want to use for textual search (must be a subset of the attributesToIndex * index setting). Attributes are separated with a comma (for example @"name,address"). * You can also use a JSON string array encoding (for example encodeURIComponent("[\"name\",\"address\"]")). * By default, all attributes specified in attributesToIndex settings are used to search. */ public Query restrictSearchableAttributes(String attributes) { this.restrictSearchableAttributes = attributes; return this; } /** * Select how the query words are interpreted: */ public Query setQueryType(QueryType type) { this.queryType = type; return this; } /** * Set the full text query */ public Query setQueryString(String query) { this.query = query; return this; } /** * Specify the list of attribute names to retrieve. * By default all attributes are retrieved. */ public Query setAttributesToRetrieve(List<String> attributes) { this.attributes = attributes; return this; } /** * Specify the list of attribute names to highlight. * By default indexed attributes are highlighted. */ public Query setAttributesToHighlight(List<String> attributes) { this.attributesToHighlight = attributes; return this; } /** * Specify the list of attribute names to Snippet alongside the number of words to return (syntax is 'attributeName:nbWords'). * By default no snippet is computed. */ public Query setAttributesToSnippet(List<String> attributes) { this.attributesToSnippet = attributes; return this; } /** * * @param If set to true, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best * one is kept and others are removed. */ public Query enableDistinct(boolean distinct) { this.distinct = distinct; return this; } /** * @param If set to false, this query will not be taken into account in analytics feature. Default to true. */ public Query enableAnalytics(boolean enabled) { this.analytics = enabled; return this; } /** * @param Set the analytics tags identifying the query */ public Query setAnalyticsTags(String analyticsTags) { this.analyticsTags = analyticsTags; return this; } /** * @param If set to false, this query will not use synonyms defined in configuration. Default to true. */ public Query enableSynonyms(boolean enabled) { this.synonyms = enabled; return this; } /** * @param If set to false, words matched via synonyms expansion will not be replaced by the matched synonym in highlight result. Default to true. */ public Query enableReplaceSynonymsInHighlight(boolean enabled) { this.replaceSynonyms = enabled; return this; } /** * @param If set to false, disable typo-tolerance. Default to true. */ public Query enableTypoTolerance(boolean enabled) { if (enabled) { this.typoTolerance = TypoTolerance.TYPO_TRUE; } else { this.typoTolerance = TypoTolerance.TYPO_FALSE; } return this; } /** * @param This option allow to control the number of typo in the results set. */ public Query setTypoTolerance(TypoTolerance typoTolerance) { this.typoTolerance = typoTolerance; return this; } /** * Specify the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. */ public Query setMinWordSizeToAllowOneTypo(int nbChars) { minWordSizeForApprox1 = nbChars; return this; } /** * Specify the minimum number of characters in a query word to accept two typos in this word. * Defaults to 7. */ public Query setMinWordSizeToAllowTwoTypos(int nbChars) { minWordSizeForApprox2 = nbChars; return this; } /** * @param If set to false, disable typo-tolerance on numeric tokens. Default to true. */ public Query enableTyposOnNumericTokens(boolean enabled) { this.allowTyposOnNumericTokens = enabled; return this; } /** * if set, the result hits will contain ranking information in _rankingInfo attribute. */ public Query getRankingInfo(boolean enabled) { this.getRankingInfo = enabled; return this; } /** * If set to true, plural won't be considered as a typo (for example car/cars will be considered as equals). Default to false. */ public Query ignorePlural(boolean enabled) { this.ignorePlural = enabled; return this; } /** * Set the page to retrieve (zero base). Defaults to 0. */ public Query setPage(int page) { this.page = page; return this; } /** * Set the number of hits per page. Defaults to 10. */ public Query setHitsPerPage(int nbHitsPerPage) { this.hitsPerPage = nbHitsPerPage; return this; } /** * Set the number of hits per page. Defaults to 10. * @deprecated Use {@code setHitsPerPage} */ @Deprecated public Query setNbHitsPerPage(int nbHitsPerPage) { return setHitsPerPage(nbHitsPerPage); } /* * Configure the precision of the proximity ranking criterion. * By default, the minimum (and best) proximity value distance between 2 matching words is 1. Setting it to 2 (or 3) would allow 1 (or 2) words to be found between the matching words without degrading the proximity ranking value. * * Considering the query "javascript framework", if you set minProximity=2 the records "JavaScript framework" and "JavaScript charting framework" will get the same proximity score, even if the second one contains a word between the 2 matching words. Default to 1. */ public Query setMinProximity(int value) { this.minProximity = value; return this; } /* * Specify the string that is inserted before/after the highlighted parts in the query result (default to "<em>" / "</em>"). */ public Query setHighlightingTags(String preTag, String postTag) { this.highlightPreTag = preTag; this.highlightPostTag = postTag; return this; } /** * Search for entries around a given latitude/longitude. * @param radius set the maximum distance in meters. * Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}}) */ public Query aroundLatitudeLongitude(float latitude, float longitude, int radius) { aroundLatLong = "aroundLatLng=" + latitude + "," + longitude + "&aroundRadius=" + radius; return this; } /** * Search for entries around a given latitude/longitude. * @param radius set the maximum distance in meters. * @param precision set the precision for ranking (for example if you set precision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). * Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}}) */ public Query aroundLatitudeLongitude(float latitude, float longitude, int radius, int precision) { aroundLatLong = "aroundLatLng=" + latitude + "," + longitude + "&aroundRadius=" + radius + "&aroundPrecision=" + precision; return this; } /** * Search for entries around the latitude/longitude of user (using IP geolocation) * @param radius set the maximum distance in meters. * Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}}) */ public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius) { aroundLatLong = "aroundRadius=" + radius; aroundLatLongViaIP = enabled; return this; } /** * Search for entries around the latitude/longitude of user (using IP geolocation) * @param radius set the maximum distance in meters. * @param precision set the precision for ranking (for example if you set precision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). * Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}}) */ public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius, int precision) { aroundLatLong = "aroundRadius=" + radius + "&aroundPrecision=" + precision; aroundLatLongViaIP = enabled; return this; } /** * Search for entries inside a given area defined by the two extreme points of a rectangle. * At indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}}) */ public Query insideBoundingBox(float latitudeP1, float longitudeP1, float latitudeP2, float longitudeP2) { insideBoundingBox = "insideBoundingBox=" + latitudeP1 + "," + longitudeP1 + "," + latitudeP2 + "," + longitudeP2; return this; } /** * Set the list of words that should be considered as optional when found in the query. * @param words The list of optional words, comma separated. */ public Query setOptionalWords(String words) { this.optionalWords = words; return this; } /** * Set the list of words that should be considered as optional when found in the query. * @param words The list of optional words. */ public Query setOptionalWords(List<String> words) { StringBuilder builder = new StringBuilder(); for (String word : words) { builder.append(word); builder.append(","); } this.optionalWords = builder.toString(); return this; } /** * Filter the query by a list of facets. Each filter is encoded as `attributeName:value`. */ public Query setFacetFilters(List<String> facets) { JSONArray obj = new JSONArray(); for (String facet : facets) { obj.put(facet); } this.facetFilters = obj.toString(); return this; } public Query setFacetFilters(String facetsFilter) { this.facetFilters = facetsFilter; return this; } /** * List of object attributes that you want to use for faceting. <br/> * Only attributes that have been added in **attributesForFaceting** index setting can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. */ public Query setFacets(List<String> facets) { JSONArray obj = new JSONArray(); for (String facet : facets) { obj.put(facet); } this.facets = obj.toString(); return this; } /** * Limit the number of facet values returned for each facet. */ public Query setMaxNumberOfFacets(int n) { this.maxNumberOfFacets = n; return this; } /** * Filter the query by a set of tags. You can AND tags by separating them by commas. To OR tags, you must add parentheses. For example tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags attribute of objects (for example {"_tags":["tag1","tag2"]} ) */ public Query setTagFilters(String tags) { this.tags = tags; return this; } /** * Add a list of numeric filters separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value. Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example `numerics=price>100,price<1000`. */ public Query setNumericFilters(String numerics) { this.numerics = numerics; return this; } /** * Add a list of numeric filters separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value. Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example `numerics=price>100,price<1000`. */ public Query setNumericFilters(List<String> numerics) { StringBuilder builder = new StringBuilder(); boolean first = true; for (String n : numerics) { if (!first) builder.append(","); builder.append(n); first = false; } this.numerics = builder.toString(); return this; } /** * Enable the advanced query syntax. Defaults to false. * - Phrase query: a phrase query defines a particular sequence of terms. * A phrase query is build by Algolia's query parser for words surrounded by ". * For example, "search engine" will retrieve records having search next to engine only. * Typo-tolerance is disabled on phrase queries. * - Prohibit operator: The prohibit operator excludes records that contain the term after the - symbol. * For example search -engine will retrieve records containing search but not engine. */ public Query enableAvancedSyntax(boolean advancedSyntax) { this.advancedSyntax = advancedSyntax; return this; } protected String getQueryString() { StringBuilder stringBuilder = new StringBuilder(); try { if (attributes != null) { stringBuilder.append("attributes="); boolean first = true; for (String attr : this.attributes) { if (!first) stringBuilder.append(","); stringBuilder.append(URLEncoder.encode(attr, "UTF-8")); first = false; } } if (attributesToHighlight != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("attributesToHighlight="); boolean first = true; for (String attr : this.attributesToHighlight) { if (!first) stringBuilder.append(','); stringBuilder.append(URLEncoder.encode(attr, "UTF-8")); first = false; } } if (attributesToSnippet != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("attributesToSnippet="); boolean first = true; for (String attr : this.attributesToSnippet) { if (!first) stringBuilder.append(','); stringBuilder.append(URLEncoder.encode(attr, "UTF-8")); first = false; } } if (typoTolerance != TypoTolerance.TYPO_TRUE) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("typoTolerance="); switch (typoTolerance) { case TYPO_FALSE: stringBuilder.append("false"); break; case TYPO_MIN: stringBuilder.append("min"); break; case TYPO_STRICT: stringBuilder.append("strict"); break; case TYPO_TRUE: stringBuilder.append("true"); break; } } if (minProximity > 1) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("minProximity="); stringBuilder.append(minProximity); } if (highlightPreTag != null && highlightPostTag != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("highlightPreTag="); stringBuilder.append(highlightPreTag); stringBuilder.append("&highlightPostTag="); stringBuilder.append(highlightPostTag); } if (!allowTyposOnNumericTokens) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("allowTyposOnNumericTokens=false"); } if (minWordSizeForApprox1 != 3) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("minWordSizefor1Typo="); stringBuilder.append(minWordSizeForApprox1); } if (minWordSizeForApprox2 != 7) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("minWordSizefor2Typos="); stringBuilder.append(minWordSizeForApprox2); } if (getRankingInfo) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("getRankingInfo=1"); } if (ignorePlural) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("ignorePlural=true"); } if (!analytics) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("analytics=0"); } if (analyticsTags != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("analyticsTags=" + analyticsTags); } if (!synonyms) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("synonyms=0"); } if (!replaceSynonyms) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("replaceSynonymsInHighlight=0"); } if (distinct) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("distinct=1"); } if (advancedSyntax) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("advancedSyntax=1"); } if (page > 0) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("page="); stringBuilder.append(page); } if (hitsPerPage != 20 && hitsPerPage > 0) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("hitsPerPage="); stringBuilder.append(hitsPerPage); } if (tags != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("tagFilters="); stringBuilder.append(URLEncoder.encode(tags, "UTF-8")); } if (numerics != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("numericFilters="); stringBuilder.append(URLEncoder.encode(numerics, "UTF-8")); } if (insideBoundingBox != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append(insideBoundingBox); } else if (aroundLatLong != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append(aroundLatLong); } if (aroundLatLongViaIP) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("aroundLatLngViaIP=true"); } if (query != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("query="); stringBuilder.append(URLEncoder.encode(query, "UTF-8")); } if (facets != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("facets="); stringBuilder.append(URLEncoder.encode(facets, "UTF-8")); } if (facetFilters != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("facetFilters="); stringBuilder.append(URLEncoder.encode(facetFilters, "UTF-8")); } if (maxNumberOfFacets > 0) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("maxNumberOfFacets="); stringBuilder.append(maxNumberOfFacets); } if (optionalWords != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("optionalWords="); stringBuilder.append(URLEncoder.encode(optionalWords, "UTF-8")); } if (restrictSearchableAttributes != null) { if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("restrictSearchableAttributes="); stringBuilder.append(URLEncoder.encode(restrictSearchableAttributes, "UTF-8")); } switch (removeWordsIfNoResult) { case REMOVE_LAST_WORDS: if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("removeWordsIfNoResult=LastWords"); break; case REMOVE_FIRST_WORDS: if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("removeWordsIfNoResult=FirstWords"); break; case REMOVE_ALLOPTIONAL: if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("removeWordsIfNoResult=allOptional"); break; case REMOVE_NONE: break; } switch (queryType) { case PREFIX_ALL: if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("queryType=prefixAll"); break; case PREFIX_LAST: break; case PREFIX_NONE: if (stringBuilder.length() > 0) stringBuilder.append('&'); stringBuilder.append("queryType=prefixNone"); break; } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return stringBuilder.toString(); } /** * @return the attributes */ public List<String> getAttributes() { return attributes; } /** * @return the attributesToHighlight */ public List<String> getAttributesToHighlight() { return attributesToHighlight; } /** * @return the attributesToSnippet */ public List<String> getAttributesToSnippet() { return attributesToSnippet; } /** * @return the minWordSizeForApprox1 */ public int getMinWordSizeForApprox1() { return minWordSizeForApprox1; } /** * @return the minWordSizeForApprox2 */ public int getMinWordSizeForApprox2() { return minWordSizeForApprox2; } /** * @return the getRankingInfo */ public boolean isGetRankingInfo() { return getRankingInfo; } /** * @return the ignorePlural */ public boolean isIgnorePlural() { return ignorePlural; } /** * @return the distinct */ public boolean isDistinct() { return distinct; } /** * @return the advancedSyntax */ public boolean isAdvancedSyntax() { return advancedSyntax; } /** * @return the page */ public int getPage() { return page; } /** * @return the hitsPerPage */ public int getHitsPerPage() { return hitsPerPage; } /** * @return the restrictSearchableAttributes */ public String getRestrictSearchableAttributes() { return restrictSearchableAttributes; } /** * @return the tags */ public String getTags() { return tags; } /** * @return the numerics */ public String getNumerics() { return numerics; } /** * @return the insideBoundingBox */ public String getInsideBoundingBox() { return insideBoundingBox; } /** * @return the aroundLatLong */ public String getAroundLatLong() { return aroundLatLong; } /** * @return the aroundLatLongViaIP */ public boolean isAroundLatLongViaIP() { return aroundLatLongViaIP; } /** * @return the query */ public String getQuery() { return query; } /** * @return the queryType */ public QueryType getQueryType() { return queryType; } /** * @return the optionalWords */ public String getOptionalWords() { return optionalWords; } /** * @return the facets */ public String getFacets() { return facets; } /** * @return the facetFilters */ public String getFacetFilters() { return facetFilters; } /** * @return the maxNumberOfFacets */ public int getMaxNumberOfFacets() { return maxNumberOfFacets; } /** * @return the analytics */ public boolean isAnalytics() { return analytics; } /** * @return the analytics tags */ public String getAnalyticsTags() { return analyticsTags; } /** * @return the synonyms */ public boolean isSynonyms() { return synonyms; } /** * @return the replaceSynonyms */ public boolean isReplaceSynonyms() { return replaceSynonyms; } /** * @return the allowTyposOnNumericTokens */ public boolean isAllowTyposOnNumericTokens() { return allowTyposOnNumericTokens; } /** * @return the removeWordsIfNoResult */ public RemoveWordsType getRemoveWordsIfNoResult() { return removeWordsIfNoResult; } /** * @return the typoTolerance */ public TypoTolerance getTypoTolerance() { return typoTolerance; } }
package com.bandcamp.squeaky; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import com.bandcamp.squeaky.util.Logger; /** * Database is the central class in Squeaky. Instances of {@link Database} are responsible for * managing SQLite tables assigned to them as instances of {@link Table} using * {@link Database#addTable(Table)}.<br/><br/> * * Once all required Tables have been added to the database, a call to {@link Database#prepare()} * will trigger any necessary migrations and will place the Database instance in to a state where * it is ready to accept queries. */ public class Database { private static final String DEFAULT_VERSIONS_TABLE_NAME = "versions"; private final Class<? extends DatabaseHelper> mHelperClass; private static final int SQLITE_DB_VERSION = 1; private HashMap<String, Table> mTables = new HashMap<>(); private final VersionsTable mVersionsTable; private final String mName; private final Context mContext; private DatabaseHelper mHelper; private SQLiteDatabase mWritableDB; private SQLiteDatabase mReadableDB; private boolean mPrepared; /** * Creates a new instance of {@link Database} using the default {@link DatabaseHelper} class. * @param context Android context. * @param name Name of the database. */ public Database(Context context, String name) { this(context, name, DatabaseHelper.class); } /** * Creates a new instance of {@link Database}, allowing for a customized {@link DatabaseHelper} * class to be provided. * @param context Android context. * @param name Name of the database. * @param helper Helper used to listen to requests from Android's SQLiteDatabase system for * creation/migration and passes those requests on to {@link Database} */ public Database(Context context, String name, Class<? extends DatabaseHelper> helper) { this(context, name, DEFAULT_VERSIONS_TABLE_NAME, DatabaseHelper.class); } /** * Creates a new instance of {@link Database}, allowing for a customized name of the table used * to track {@link Table} versions. * @param context Android context. * @param name Name of the database. * @param versionsTableName Name of the versions table. */ public Database(Context context, String name, String versionsTableName) { this(context, name, versionsTableName, DatabaseHelper.class); } /** * Creates a new instance of {@link Database}, allowing for a customized {@link DatabaseHelper} * class and a custom version table to be provided. * @param context Android context. * @param name Name of the database. * @param versionsTableName Name of the versions table. * @param helper Helper used to listen to requests from Android's SQLiteDatabase system for * creation/migration and passes those requests on to {@link Database} */ public Database(Context context, String name, String versionsTableName, Class<? extends DatabaseHelper> helper) { mHelperClass = helper; mName = name; mContext = context; mVersionsTable = new VersionsTable(this, versionsTableName); } /** * Get the name of the database. * @return Name of the database. */ public String getName() { return mName; } /** * Add a {@link Table} to the Database definition. * @param t Table to add. */ public void addTable(Table t) { if (!mTables.containsKey(t.getName())) { mTables.put(t.getName(), t); } } /** * Prepare the database by instantiating a {@link DatabaseHelper} and establishing connections * to the database. Calling {@link #prepare()} again after the Database is already prepared * will throw a {@link DatabaseException}. If you need to re-prepare a database (to add or * migrate a {@link Table} definition), call {@link #close()} first, add your tables, then * re-call {@link #prepare()}. * @see #isPrepared() */ public void prepare() { if (mPrepared) { throw new DatabaseException("Cannot re-prepare a prepared database!"); } try { Constructor<? extends DatabaseHelper> c = mHelperClass.getDeclaredConstructor(Context.class, String.class, int.class); mHelper = c.newInstance(mContext, mName, SQLITE_DB_VERSION); mWritableDB = mHelper.getWritableDatabase(); mReadableDB = mHelper.getReadableDatabase(); doMigrations(mWritableDB); mPrepared = true; } catch (NoSuchMethodException e) { throw new DatabaseException("Provided database helper class does not expose a constructor of the form (Context, String, int)", e); } catch (InvocationTargetException e) { throw new DatabaseException("Error instantiating database helper.", e); } catch (InstantiationException e) { throw new DatabaseException("Error instantiating database helper.", e); } catch (IllegalAccessException e) { throw new DatabaseException("Error instantiating database helper.", e); } } /** * Close the helper and database connections. */ public void close() { mHelper.close(); mWritableDB.close(); mReadableDB.close(); mPrepared = false; } /** * Returns whether or not the {@link Database} instance is prepared. * @return Whether or not the Database is prepared. */ public boolean isPrepared() { return mPrepared; } /** * Query the database. * @param stmt SQL Query * @param bindArgs Parameters mapping to '?'s in the stmt. * @return An instance of {@link android.database.Cursor} giving you access to the results of * the query. */ public synchronized Cursor query(String stmt, Object... bindArgs) { if (!mPrepared) { throw new DatabaseException("Database "+getName()+" not prepared yet."); } String[] args = null; if (bindArgs != null) { args = new String[bindArgs.length]; for (int i = 0; i < bindArgs.length; i++) { Object arg = bindArgs[i]; if (arg instanceof String) { args[i] = arg.toString(); } else { args[i] = arg.toString(); } } } Cursor result = getReadableDB().rawQuery(stmt, args); Logger.i(stmt+";", args); return result; } // Used before mReadableDB is available. private Cursor querySimple(SQLiteDatabase db, String stmt, Object... bindArgs) { String[] args = null; if (bindArgs != null) { args = new String[bindArgs.length]; for (int i = 0; i < bindArgs.length; i++) { Object arg = bindArgs[i]; if (arg instanceof String) { args[i] = DatabaseUtils.sqlEscapeString((String) arg); } else { args[i] = arg.toString(); } } } Cursor result = db.rawQuery(stmt, args); Logger.i(stmt+";", args); return result; } /** * Insert a record in to the database and receive its <code>rowid</code> or <code>_id</code> * value as a result. * @param stmt Insert query. (not enforced, but encouraged) * @param bindArgs Arguments to bind to '?'s in the query. * @return Value of the new record's <code>rowid</code>/<code>_id</code> column. */ public synchronized long insert(String stmt, Object... bindArgs) { SQLiteStatement statement = getWritableDB().compileStatement(stmt); bindArgs(statement, bindArgs); Logger.i(stmt+";", bindArgs); return statement.executeInsert(); } /** * Run an update/delete query on the database * @param stmt Query to execute. * @param bindArgs Arguments to bind to '?'s in the query. * @return Number of affected rows. */ public synchronized int update(String stmt, Object... bindArgs) { if (bindArgs == null) { return updateBatch(new String[] {stmt}, null, false); } return updateBatch(new String[] {stmt}, new Object[][] {bindArgs}, false); } /** * Run a bunch of updates/deletes/inserts on the database at once, optionally within a * transaction. * @param stmts Array of statements to execute. * @param bindArgs Arguments to bind to '?'s in the queries. (Optional, if not needed, pass * null) Condition: bindArgs.length == stmts.length if not null. * @param withTransaction Whether or not to execute the updates within a transaction. * @return Number of updated records. */ public synchronized int updateBatch(String[] stmts, Object[][] bindArgs, boolean withTransaction) { boolean hasArgs = bindArgs != null; if (hasArgs && bindArgs.length != stmts.length) { throw new DatabaseException("bindArgs.length != stmts.length"); } if (withTransaction) { getWritableDB().beginTransaction(); } int rows = 0; for (int i = 0; i < stmts.length; i++) { SQLiteStatement statement = getWritableDB().compileStatement(stmts[i]); if (hasArgs) { bindArgs(statement, bindArgs[i]); } try { rows += statement.executeUpdateDelete(); } finally { statement.close(); } Logger.i(stmts[i]+";", bindArgs[i]); } if (withTransaction) { getWritableDB().endTransaction(); } return rows; } private void updateSimple(SQLiteDatabase db, String stmt, Object... bindArgs) { if (bindArgs != null) { updateBatchSimple(db, new String[]{stmt}, new Object[][]{bindArgs}); } else { updateBatchSimple(db, new String[]{stmt}, null); } } private void updateBatchSimple(SQLiteDatabase db, String[] stmts, Object[][] bindArgs) { boolean hasArgs = bindArgs != null; if (hasArgs && bindArgs.length != stmts.length) { throw new DatabaseException("bindArgs.length != stmts.length"); } for (int i = 0; i < stmts.length; i++) { if (!stmts[i].endsWith(";")) { stmts[i] += ";"; } if (hasArgs && bindArgs[i] != null) { Logger.i(stmts[i], bindArgs[i]); db.execSQL(stmts[i], bindArgs[i]); } else { Logger.i(stmts[i]); db.execSQL(stmts[i]); } } } private void bindArgs(SQLiteStatement statement, Object[] args) { if (args == null) { return; } for (int i = 0; i < args.length; i++) { Object o = args[i]; if (o instanceof String) { statement.bindString(i + 1, (String) o); } else if (o instanceof byte[]) { statement.bindBlob(i + 1, (byte[]) o); } else if (o instanceof Integer) { statement.bindLong(i+1, (Integer) o); } else if (o instanceof Long) { statement.bindLong(i + 1, (Long) o); } else if (o instanceof Double || o instanceof Float) { statement.bindDouble(i+1, (Double) o); } else if (o == null) { statement.bindNull(i+1); } else if (o instanceof BlobValue) { statement.bindBlob(i+1, ((BlobValue) o).getBytes()); } else { statement.bindString(i+1, o.toString()); } } } private void doMigrations(SQLiteDatabase db) { Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null); boolean needVersionsTable = true; while ( c.moveToNext() ) { if (c.getString(0).equals(mVersionsTable.getName())) { needVersionsTable = false; break; } } c.close(); if (needVersionsTable) { updateBatchSimple(db, mVersionsTable.getCreateTable(), null); } Map<String, Integer> versions = mVersionsTable.getTableVersions(db); for (Table t : mTables.values()) { if (versions.containsKey(t.getName())) { // have a version, need to upgrade? boolean changed = false; for (int currentVersion = versions.get(t.getName()); currentVersion < t.getVersion(); currentVersion++) { changed = true; Logger.d("Upgrading", t.getName(), "from", "v"+currentVersion, "to", "v"+(currentVersion+1)); String[] migrateStmts = t.getMigration(currentVersion+1); updateBatchSimple(db, migrateStmts, null); } if (changed) { updateSimple(db, "UPDATE "+mVersionsTable.getName()+" SET version = ? WHERE table_name = ?", t.getVersion(), t.getName()); } } else { // need to create. Logger.d("Creating new table:", t.getName(), "at version", t.getVersion()); String[] createStmts = t.getCreateTable(); updateBatchSimple(db, createStmts, null); updateSimple(db, "INSERT INTO "+mVersionsTable.getName()+" (table_name, version) VALUES (?, ?)", t.getName(), t.getVersion()); } } } /** * Get the {@link android.content.Context} associated with the Database. * @return {@link android.content.Context} associated with the Database. */ public Context getContext() { return mContext; } /** * Get the instance of {@link Database.VersionsTable} used by this Database. * @return The {@link Database.VersionsTable} used by the Database. */ public Table getVersionsTable() { return mVersionsTable; } /** * Get the {@link Table} instances associated with this Database. * @return {@link Table} instances associated with the Database. */ public Collection<Table> getTables() { return mTables.values(); } /** * Get a raw SQLiteDatabase connection for writing. * @return Raw SQLite Database connection. */ public SQLiteDatabase getWritableDB() { if (mWritableDB == null) { mWritableDB = mHelper.getWritableDatabase(); } return mWritableDB; } /** * Get a raw SQLiteDatabase connection for reading. * @return Raw SQLite Database connection. */ public SQLiteDatabase getReadableDB() { if (mReadableDB == null) { mReadableDB = mHelper.getReadableDatabase(); } return mReadableDB; } /** * {@link Table} definition used to define the SQLite table which tracks the current versions of * all other {@link Table}s in the database. */ public static final class VersionsTable extends Table { private final Database mDb; private final String mName; public VersionsTable(Database db, String name) { mDb = db; mName = name; } @Override public String getName() { return mName; } @Override public int getVersion() { return 1; } @Override public String[] getCreateTable() { return new String[] { "CREATE TABLE "+getName()+" (\n" + " `table_name` TEXT NOT NULL,\n"+ " `version` INTEGER NOT NULL\n"+ ")" }; } @Override public String[] getMigration(int nextVersion) { return new String[0]; } /** * Get the current version of a particular table in the {@link Database}. * @param sqldb SQLiteDatabase connection. * @param tableName Name of the table for which to retrieve the version. * @return Version of the table with name {@param tableName} */ public int getTableVersion(SQLiteDatabase sqldb, String tableName) { Cursor c = mDb.querySimple(sqldb, "SELECT version FROM "+getName()+" WHERE table_name = ?", tableName); int version = -1; while (c.moveToNext()) { version = c.getInt(0); } c.close(); return version; } /** * Get all current versions of tables in the {@link Database} * @param sqldb SQLiteDatabase connection. * @return Mapping from {@link Table#getName()} to its current version * in the database. */ public Map<String, Integer> getTableVersions(SQLiteDatabase sqldb) { Cursor c = mDb.querySimple(sqldb, "SELECT table_name, version FROM "+getName()); HashMap<String, Integer> result = new HashMap<>(); int modelIndex = c.getColumnIndex("table_name"); int versionIndex = c.getColumnIndex("version"); while (c.moveToNext()) { result.put(c.getString(modelIndex), c.getInt(versionIndex)); } c.close(); return result; } } }
package com.crowdin.cli.client; import com.crowdin.cli.commands.functionality.PropertiesBeanUtils; import com.crowdin.cli.utils.Utils; import com.crowdin.client.core.http.impl.json.JacksonJsonTransformer; import com.crowdin.client.core.model.ClientConfig; import com.crowdin.client.core.model.Credentials; import com.crowdin.client.core.model.PatchRequest; import com.crowdin.client.glossaries.model.AddGlossaryRequest; import com.crowdin.client.glossaries.model.ExportGlossaryRequest; import com.crowdin.client.glossaries.model.Glossary; import com.crowdin.client.glossaries.model.GlossaryExportStatus; import com.crowdin.client.glossaries.model.GlossaryImportStatus; import com.crowdin.client.glossaries.model.ImportGlossaryRequest; import com.crowdin.client.glossaries.model.Term; import com.crowdin.client.sourcefiles.model.AddBranchRequest; import com.crowdin.client.sourcefiles.model.AddDirectoryRequest; import com.crowdin.client.sourcefiles.model.AddFileRequest; import com.crowdin.client.sourcefiles.model.Branch; import com.crowdin.client.sourcefiles.model.Directory; import com.crowdin.client.sourcefiles.model.UpdateFileRequest; import com.crowdin.client.sourcestrings.model.AddSourceStringRequest; import com.crowdin.client.sourcestrings.model.SourceString; import com.crowdin.client.translationmemory.model.AddTranslationMemoryRequest; import com.crowdin.client.translationmemory.model.TranslationMemory; import com.crowdin.client.translationmemory.model.TranslationMemoryExportRequest; import com.crowdin.client.translationmemory.model.TranslationMemoryExportStatus; import com.crowdin.client.translationmemory.model.TranslationMemoryImportRequest; import com.crowdin.client.translationmemory.model.TranslationMemoryImportStatus; import com.crowdin.client.translations.model.BuildProjectTranslationRequest; import com.crowdin.client.translations.model.ProjectBuild; import com.crowdin.client.translations.model.UploadTranslationsRequest; import com.crowdin.client.translationstatus.model.LanguageProgress; import java.io.InputStream; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.URL; import java.util.List; import java.util.Optional; public interface Client { CrowdinProjectFull downloadFullProject(); CrowdinProject downloadProjectWithLanguages(); CrowdinProjectInfo downloadProjectInfo(); Branch addBranch(AddBranchRequest request); Long uploadStorage(String fileName, InputStream content); Directory addDirectory(AddDirectoryRequest request) throws ResponseException; void updateSource(Long sourceId, UpdateFileRequest request); void addSource(AddFileRequest request); void uploadTranslations(String languageId, UploadTranslationsRequest request); ProjectBuild startBuildingTranslation(BuildProjectTranslationRequest request); ProjectBuild checkBuildingTranslation(Long buildId); URL downloadBuild(Long buildId); List<LanguageProgress> getProjectProgress(String languageId); SourceString addSourceString(AddSourceStringRequest request); List<SourceString> listSourceString(Long fileId, String filter); void deleteSourceString(Long id); SourceString editSourceString(Long sourceId, List<PatchRequest> requests); List<Glossary> listGlossaries(); Optional<Glossary> getGlossary(Long glossaryId); Glossary addGlossary(AddGlossaryRequest request); GlossaryImportStatus importGlossary(Long glossaryId, ImportGlossaryRequest request); List<Term> listTerms(Long glossaryId); GlossaryExportStatus startExportingGlossary(Long glossaryId, ExportGlossaryRequest request); GlossaryExportStatus checkExportingGlossary(Long glossaryId, String exportId); URL downloadGlossary(Long glossaryId, String exportId); List<TranslationMemory> listTms(); Optional<TranslationMemory> getTm(Long tmId); TranslationMemory addTm(AddTranslationMemoryRequest request); TranslationMemoryImportStatus importTm(Long tmId, TranslationMemoryImportRequest request); TranslationMemoryExportStatus startExportingTm(Long tmId, TranslationMemoryExportRequest request); TranslationMemoryExportStatus checkExportingTm(Long tmId, String exportId); URL downloadTm(Long tmId, String exportId); static Client getDefault(String apiToken, String baseUrl, long projectId) { boolean isTesting = PropertiesBeanUtils.isUrlForTesting(baseUrl); String organization = PropertiesBeanUtils.getOrganization(baseUrl); Credentials credentials = (isTesting) ? new Credentials(apiToken, organization, baseUrl) : new Credentials(apiToken, organization); ClientConfig clientConfig = ClientConfig.builder() .jsonTransformer(new JacksonJsonTransformer()) .userAgent(Utils.buildUserAgent()) .build(); Utils.proxyHost() .map(pair -> new ClientConfig.Host(pair.getKey(), pair.getValue())) .ifPresent(proxy -> { clientConfig.setProxy(proxy); System.setProperty("https.proxyHost", proxy.getHost()); System.setProperty("https.proxyPort", String.valueOf(proxy.getPort())); }); Utils.proxyCredentials() .map(pair -> new ClientConfig.UsernamePasswordCredentials(pair.getKey(), pair.getValue())) .ifPresent(proxyCreds -> { clientConfig.setProxyCreds(proxyCreds); if (proxyCreds.getUsername() != null && proxyCreds.getPassword() != null) { Authenticator.setDefault( new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { return new PasswordAuthentication(proxyCreds.getUsername(), proxyCreds.getPassword().toCharArray()); } else { return null; } } } ); System.setProperty("jdk.http.auth.tunneling.disabledSchemes", ""); } }); com.crowdin.client.Client client = new com.crowdin.client.Client(credentials, clientConfig); return new CrowdinClient(client, projectId); } }
package com.dbpm.build; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import com.dbpm.Module; import com.dbpm.logger.Logger; import com.dbpm.utils.ManifestReader; import com.dbpm.utils.files.AllowedFiles; import com.dbpm.utils.files.AllowedFolders; import com.dbpm.utils.files.IllegalFileException; import com.dbpm.utils.files.IllegalFolderException; import com.dbpm.repository.Package; /** * This class handles the creation of dbpm packages. * @author gvenzl */ public class PackageBuilder implements Module { private static int BYTES = 8192; private File workDir; private Package dbpmPackage; /** * Creates a new PackageBuilder instance. */ public PackageBuilder() { workDir = new File (System.getProperty("user.dir")); } @Override public void run() { Logger.log("Building package..."); Logger.verbose("Current directory: " + workDir); File manifestFile = new File (workDir + "/manifest.pm"); if (!manifestFile.exists()) { Logger.error("Manifest not found!"); } else { Logger.verbose("Found manifest, reading..."); try { String manifest = new String( Files.readAllBytes( Paths.get(manifestFile.getAbsolutePath()))); dbpmPackage = new ManifestReader(manifest).getPackage(); Logger.verbose("Package name: " + dbpmPackage.getName()); Logger.verbose("Building for platform: " + dbpmPackage.getPlatform()); String dbpgFileName = dbpmPackage.getFullName(); File dbpgFile = new File(dbpgFileName); if (dbpgFile.exists()) { Logger.verbose("Package file already exists, overwriting..."); dbpgFile.delete(); } createPackage(dbpgFileName); } catch (IOException e) { Logger.error("Can't read manifest file!"); Logger.error(e.getMessage()); } } } private void createPackage(String packageName) { byte[] buffer = new byte[BYTES]; int len; try { // Get all files in working directory ArrayList<File> files = getDirectoryStructure(workDir.getAbsoluteFile()); // Create zip file ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(packageName)); zip.setMethod(ZipOutputStream.DEFLATED); zip.setLevel(9); for (File entry : files) { Logger.verbose("Adding " + entry.getName()); String fileName = entry.getAbsolutePath().replace(workDir.getAbsolutePath() + "/", ""); zip.putNextEntry(new ZipEntry(fileName)); FileInputStream in = new FileInputStream(entry); // Read content into zip file while ((len = in.read(buffer)) > 0) { zip.write(buffer, 0, len); } // Close zip entry in.close(); } // Close zip file zip.close(); } catch (Exception e) { Logger.error("Cannot create package archive!"); Logger.error(e.getMessage()); } } private ArrayList<File> getDirectoryStructure(File dir) throws IllegalFolderException, IllegalFileException { ArrayList<File> filesCollection = new ArrayList<File>(); File[] files = dir.listFiles(); for (int i=0; i<files.length; i++) { // Recursive tree build if (files[i].isDirectory()) { // Throw exception if folder is not allowed! if (!isAllowedDirectory(files[i])) { throw new IllegalFolderException("Folder " + files[i].getName() + " is invalid!"); } filesCollection.addAll(getDirectoryStructure(files[i])); } else { if (!isAllowedFile(files[i])) { throw new IllegalFileException("File " + files[i].getName() + " has not a valid extension!"); } filesCollection.add(files[i]); } } return filesCollection; } private boolean isAllowedFile(File file) { for (AllowedFiles fileExt : AllowedFiles.values()) { if (file.getName().toUpperCase().endsWith(fileExt.name().toUpperCase())) { return true; } } return false; } private boolean isAllowedDirectory(File file) { for (AllowedFolders folderName : AllowedFolders.values()) { if (folderName.name().equals(file.getName())) { return true; } } return false; } }
//@author A0111875E package com.epictodo.engine; import com.epictodo.controller.nlp.GrammaticalParser; import com.epictodo.controller.nlp.SentenceAnalysis; import com.epictodo.controller.nlp.SentenceStructure; import com.epictodo.model.Delta; import com.epictodo.model.Response; import com.epictodo.model.Search; import com.epictodo.util.DateValidator; import com.epictodo.util.TimeValidator; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.trees.TypedDependency; import java.io.OutputStream; import java.io.PrintStream; import java.text.ParseException; import java.util.*; public class NLPEngine { protected static StanfordCoreNLP _pipeline; private static NLPEngine instance = null; private NLPLoadEngine load_engine = NLPLoadEngine.getInstance(); private TimeValidator time_validator = TimeValidator.getInstance(); private DateValidator date_validator = DateValidator.getInstance(); private SentenceAnalysis sentence_analysis = new SentenceAnalysis(); private SentenceStructure sentence_struct = new SentenceStructure(); private GrammaticalParser grammartical_parser = new GrammaticalParser(); private Response _response = new Response(); private Delta _delta = new Delta(); private Search _search = new Search(); private PrintStream _err = System.err; private int CAPACITY = 1000; public NLPEngine() { _pipeline = load_engine._pipeline; } /** * This method ensures that there will only be one running instance * * @return */ public static NLPEngine getInstance() { if (instance == null) { instance = new NLPEngine(); } return instance; } /** * This method mutes NLP API Error Messages temporarily * This works for all console messages * <p/> * Usage: * <p/> * mute(); */ public void mute() { System.setErr(new PrintStream(new OutputStream() { public void write(int b) { } })); } /** * This method restores NLP API Error Messages to be displayed * This method works for all console messages. * <p/> * Usage: * <p/> * restore(); */ public void restore() { System.setErr(_err); } public Response flexiAdd(String _sentence) throws ParseException { boolean is_date_set = false; boolean is_time_set = false; boolean is_priority_set = false; boolean to_check = false; String tomorrow_date; String date_value; String time_value; String _priority; String start_time; String end_time; double _duration; int num_days; List<String> analyzed_results = new ArrayList<>(); List<String> task_name = new ArrayList<>(); List<String> task_desc = new ArrayList<>(); List<String> task_date = new ArrayList<>(); List<String> task_time = new ArrayList<>(); // Initialize Sentence Structure & Sentence Analysis to Map Map<String, String> sentence_struct_map = sentence_struct.sentenceDependencies(_sentence); Map<String, String> date_time_map = sentence_analysis.dateTimeAnalyzer(_sentence); Map<String, String> sentence_token_map = sentence_analysis.sentenceAnalyzer(_sentence); LinkedHashMap<String, LinkedHashSet<String>> entities_map = sentence_analysis.nerEntitiesExtractor(_sentence); List<TypedDependency> grammar_struct_map = grammartical_parser.grammarAnalyzer(_sentence); /** * Name Entity Recognition (NER) map * For loop to traverse key:value of NER map to retrieve keywords to be processed * * Example: root, nn, dobj, nsubj, aux, xcomp, prep, num, etc. * */ for (Map.Entry<String, LinkedHashSet<String>> map_result : entities_map.entrySet()) { String _key = map_result.getKey(); LinkedHashSet<String> _value = map_result.getValue(); } /** * Sentence analyzer to analyze the text for keywords * For loop to traverse the following: * * 1. (TIME) - stores TIME's (value) key to check if it's a single or multiple TIME value * 1.1. Checks if key is valid time before storing. * 1.2. "at" maybe classified as a valid TIME but we do not want to register this * * 2. (PERSON) - stores PERSON name to be processed in Task Description * 2.1. PERSON does not accept 'Prof' as an actual person, rather an entity * * 3. (LOCATION) - stores LOCATION name if it exists. * 3.1. TOKYO, SINGAPORE are actual LOCATION * 3.2. COM1, LT15, SR1 are not an actual LOCATION stored in our model (can be implemented using Classifier in future) * */ for (Map.Entry<String, String> map_result : sentence_token_map.entrySet()) { String _key = map_result.getKey(); String _value = map_result.getValue(); if (_value.equalsIgnoreCase("TIME")) { if (time_validator.validate(_key)) { task_time.add(_key); } } if (_value.equalsIgnoreCase("NUMBER")) { if (date_validator.validateDateExpression(_key)) { date_value = date_validator.fixShortDate(_key); task_date.add(date_value); num_days = date_validator.compareDate(date_value); // Checks if date distance is >= 0 or <= 1 of 1 day if (num_days >= 0 && num_days <= 1) { _priority = date_validator.determinePriority(date_value); date_value = date_validator.genericDateFormat(date_value); if (_response.getTaskDate() == null) { _response.setTaskDate(date_value); } _response.setPriority(Integer.parseInt(_priority)); is_priority_set = true; } else { // Check if TaskDate has been set previously, prevent override _priority = date_validator.determinePriority(date_value); date_value = date_validator.genericDateFormat(date_value); if (_response.getTaskDate() == null) { _response.setTaskDate(date_value); } _response.setPriority(Integer.parseInt(_priority)); is_priority_set = true; } is_date_set = true; } } if (_value.equalsIgnoreCase("PERSON")) { if (!_key.equalsIgnoreCase("Prof")) { task_desc.add(_key); analyzed_results.add(_key); } else { task_desc.add(_key); analyzed_results.add(_key); } } else if (_value.equalsIgnoreCase("LOCATION")) { task_desc.add(_key); analyzed_results.add(_key); } else if (_value.equalsIgnoreCase("ORGANIZATION")) { task_desc.add(_key); analyzed_results.add(_key); } } /** * This algorithm checks if the time values stored are more than or equals to 2 * There can be instances where users input 3 or more time variables, but the first 2 will be registered * * This algorithm will getTimeDuration before storing start_time, end_time & _duration to _response */ if (task_time.size() != 0 && task_time.size() >= 2) { start_time = task_time.get(0); end_time = task_time.get(1); _duration = time_validator.getTimeDuration(start_time, end_time); _response.setStartTime(start_time); _response.setEndTime(end_time); _response.setTaskDuration(_duration); is_time_set = true; } else if (task_time.size() != 0 && task_time.size() < 2) { _response.setTaskTime(task_time.get(0)); is_time_set = true; } /** * Date time analyzer map to analyze date time values to be stored * This algorithm will check for TOMORROW date & time distance. * * If that case happens, the result will be parsed to getDateInFormat & getTimeInFormat to handle such cases * Otherwise, the result will be parsed to validateDate & validateTime to handle the more generic cases */ for (Map.Entry<String, String> map_result : date_time_map.entrySet()) { String _key = map_result.getKey(); String _value = map_result.getValue(); if (!is_date_set) { tomorrow_date = date_validator.convertDateFormat(_value); num_days = date_validator.compareDate(tomorrow_date); // Checks if date distance is >= 0 or <= 1 of 1 day if (num_days >= 0 && num_days <= 1) { _priority = date_validator.determinePriority(tomorrow_date); date_value = date_validator.genericDateFormat(tomorrow_date); time_value = date_validator.getTimeInFormat(_value); if (!is_date_set) { // Check if TaskDate has been set previously, prevent override _response.setTaskDate(date_value); is_date_set = true; } if (!is_time_set) { _response.setTaskTime(time_value); is_time_set = true; } if (!is_priority_set) { _response.setPriority(Integer.parseInt(_priority)); is_priority_set = true; } // _response.setTaskDate(date_value); // _response.setTaskTime(time_value); // _response.setPriority(Integer.parseInt(_priority)); task_desc.add(_key); analyzed_results.add(_key); analyzed_results.add(date_value); analyzed_results.add(time_value); analyzed_results.add(_priority); } else { // Check if TaskDate has been set previously, prevent override _priority = date_validator.determinePriority(_value); date_value = date_validator.genericDateFormat(tomorrow_date); time_value = date_validator.validateTime(_value); if (!is_date_set) { _response.setTaskDate(date_value); is_date_set = true; } if (!is_time_set) { _response.setTaskTime(time_value); is_time_set = true; } if (!is_priority_set) { _response.setPriority(Integer.parseInt(_priority)); is_priority_set = true; } // _response.setTaskDate(date_value); // _response.setTaskTime(time_value); // _response.setPriority(Integer.parseInt(_priority)); task_desc.add(_key); analyzed_results.add(_key); analyzed_results.add(date_value); analyzed_results.add(time_value); analyzed_results.add(_priority); } } } /** * Sentence Dependencies map to analyze and return the dependencies of the sentence structure * This algorithm checks the dependencies relationship in the tree structure, and returns the results */ for (Map.Entry<String, String> map_result : sentence_struct_map.entrySet()) { String _key = map_result.getKey(); String _value = map_result.getValue(); if ((_key.equalsIgnoreCase("root") || _key.equalsIgnoreCase("dep") || _key.equalsIgnoreCase("dobj") || _key.equalsIgnoreCase("prep_on") || _key.equalsIgnoreCase("prep_for") || _key.equalsIgnoreCase("nn") || _key.equalsIgnoreCase("xcomp")) && (_value.equalsIgnoreCase("aux"))) { task_name.add(_value); analyzed_results.add(_value); } } /** * Grammartical Struct map analyzes and return the relationship and dependencies of the grammartical structure * This algorithm checks for * * 1. root: the grammatical relation that points to the root of the sentence * 1.1. Remove words like 'be' * 1.2. Remove words that are already added into the list * 2. nn: noun compound modifier is any noun that serves to modify the head noun * 2.1. Remove words that is stored already in Task Description * 3. nsubj: nominal subject is a noun phrase which is the syntactic subject of a clause * aux: auxiliary is a non-main verb of the clause * xcomp: open clausal complement is a clausal complement without * its own subject, whose reference is determined by an external subject * dobj: direct object is the noun phrase which is the (accusative) object of the verb * 3.1. Add words that does not already exist in Task Name * 4. amod: adjectival modifier is any adjectival phrase that serves to modify the meaning of the NP * 4.1. Remove words like 'next' * 5. prep: prepositional modifier of a verb, adjective, or noun is any prepositional phrase that serves to * modify the meaning of the verb, adjective, noun, or even another prepositon * 5.1. Check Task Time size is more than 1 or less than 2 * 5.2. Remove Task Time accordingly * 6. dep: dependent is when the system is unable to determine a more precise * dependency relation between two words * 6.1. Remove words like 'regarding' * 7. aux: is a non-main verb of the clause, e.g., a modal auxiliary, or a form of * "be", "do" or "have" in a periphrastic tense * 7.1. Remove words like 'to' * * This algorithm ensures that NLP maintains a certain integrity to making sense while parsing the sentence * */ for (TypedDependency type_dependency : grammar_struct_map) { String reln_key = type_dependency.reln().getShortName(); String dep_value = type_dependency.dep().nodeString(); if (reln_key.equalsIgnoreCase("root")) { if (task_name.contains("Be") || task_name.contains("be")) { task_name.remove(dep_value); } else if (task_name.contains(dep_value)) { task_name.remove(dep_value); } else { task_name.add(dep_value); } } if (reln_key.equalsIgnoreCase("nn")) { if (!task_name.contains(dep_value)) { task_name.add(dep_value); } if (task_desc.contains(dep_value)) { task_name.remove(dep_value); } } if (reln_key.equalsIgnoreCase("nsubj") || reln_key.equalsIgnoreCase("aux") || reln_key.equalsIgnoreCase("xcomp") || reln_key.equalsIgnoreCase("dobj")) { if (!task_name.contains(dep_value)) { task_name.add(dep_value); } } if (reln_key.equalsIgnoreCase("amod") && !dep_value.equalsIgnoreCase("next")) { if (!task_name.contains(dep_value)) { task_name.add(dep_value); } } if (reln_key.equalsIgnoreCase("prep")) { if (!task_name.contains(dep_value)) { task_name.add(dep_value); } if (task_time.size() < 2) { if (dep_value.contains(task_time.get(0))) { task_name.remove(dep_value); } } else if (task_time.size() >= 2 && task_time.size() < 3) { if (dep_value.contains(task_time.get(0)) || dep_value.contains(task_time.get(1))) { task_name.remove(dep_value); } } } if (reln_key.equalsIgnoreCase("dep") && dep_value.equalsIgnoreCase("regarding")) { if (task_name.contains(dep_value)) { task_name.remove(dep_value); } } if (reln_key.equalsIgnoreCase("aux") && dep_value.equalsIgnoreCase("to")) { if (task_name.contains(dep_value)) { task_name.remove(dep_value); } } } _response.setTaskName(task_name); _response.setTaskDesc(task_desc); return _response; } public Delta flexiEdit(String _sentence) throws ParseException { boolean is_first = true; int _index = 0; List<String> sentence_list = new ArrayList<>(); List<String> delta_list = new ArrayList<>(); StringBuilder string_builder = new StringBuilder(CAPACITY); Scanner _scanner = new Scanner(_sentence); while (_scanner.hasNext()) { sentence_list.add(_scanner.next()); } _scanner.close(); /** * This algorithm removes words like 'edit' or 'change' which suggests editing of Task * The algorithm gets the index of 'to' and stores that index in order to identify ORIGINAL_TASK & DELTA * */ for (int i = 0; i < sentence_list.size(); i++) { if (sentence_list.get(i).equalsIgnoreCase("edit") || sentence_list.get(i).equalsIgnoreCase("change")) { sentence_list.remove(i); } if (sentence_list.get(i).equalsIgnoreCase("to")) { _index = i; sentence_list.remove(i); i = sentence_list.size(); } } /** * Removes ORIGINAL_TASK & adds to delta_list * */ for (int i = 0; i < _index; i++) { delta_list.add(sentence_list.get(0)); sentence_list.remove(0); } /** * Concatenate sentence List into a String before storing DELTA * */ for (String word : sentence_list) { if (is_first) { is_first = false; } else { string_builder.append(' '); } string_builder.append(word); } _delta.setTaskName(delta_list); _delta.setDeltaChange(flexiAdd(string_builder.toString())); return _delta; } /** * This method analyzes the sentence structure into SUTIME Annotation. * The algorithm facilitates natural language for searching by date. * * For instance, "search today" > retrieves today task * * Usage: * 1. flexiSearch("search today"); * * @param _sentence * @throws ParseException */ public Search flexiSearch(String _sentence) throws ParseException { String date_value; String parse_date = date_validator.nlpShortDate(_sentence); // Initialize Date Analysis to Map Map<String, String> date_map = sentence_analysis.dateTimeAnalyzer(_sentence); if (_sentence.isEmpty() || _sentence.equalsIgnoreCase(null) || _sentence.equals("")) { _search.setSearchDate(null); } if (_sentence.equalsIgnoreCase(parse_date)) { _search.setSearchDate(parse_date); } else { /** * Date analyzer analyzes the sentence in order to map the analyze date values to be searched * This algorithm will check for TOMORROW date & time distance. * */ for (Map.Entry<String, String> map_result : date_map.entrySet()) { String _value = map_result.getValue(); date_value = date_validator.convertDateFormat(_value); date_value = date_validator.genericDateFormat(date_value); _search.setSearchDate(date_value); } } return _search; } }
package com.github.pcmnac.prilaku; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import org.reflections.ReflectionUtils; import org.reflections.Reflections; import com.github.pcmnac.prilaku.annotation.Behavior; import com.github.pcmnac.prilaku.annotation.BehaviorOf; import com.github.pcmnac.prilaku.annotation.Domain; import com.github.pcmnac.prilaku.provider.DefaultInstanceProvider; import com.github.pcmnac.prilaku.provider.InstanceProvider; import com.google.common.base.Predicate; /** * @author pcmnac@gmail.com * */ @SuppressWarnings("unchecked") public class Pku { public static class Enhanced { private Object domainObject; public Enhanced(Object domainObject) { this.domainObject = domainObject; } public <T> T get(Class<? extends T> behaviorInterfaceType) { return Pku.get(domainObject, behaviorInterfaceType); } } public static Enhanced $(Object domainObject) { return new Enhanced(domainObject); } private static class Pair { Class<?> behavior; Class<?> domainClass; /** * @param behavior * @param domainClass */ public Pair(Class<?> behavior, Class<?> domainClass) { super(); this.behavior = behavior; this.domainClass = domainClass; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((behavior == null) ? 0 : behavior.hashCode()); result = prime * result + ((domainClass == null) ? 0 : domainClass.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (behavior == null) { if (other.behavior != null) return false; } else if (!behavior.equals(other.behavior)) return false; if (domainClass == null) { if (other.domainClass != null) return false; } else if (!domainClass.equals(other.domainClass)) return false; return true; } } private static Map<Class<?>, Map<Class<?>, Class<?>>> map = new HashMap<Class<?>, Map<Class<?>, Class<?>>>(); private static Map<Pair, Object> cache = new HashMap<Pair, Object>(); private static InstanceProvider provider; private static final Predicate<Field> DOMAIN_FIELD_PREDICATE = new Predicate<Field>() { @Override public boolean apply(Field input) { return input.isAnnotationPresent(Domain.class); } }; private static final Predicate<Class<?>> BEHAVIOR_PREDICATE = new Predicate<Class<?>>() { @Override public boolean apply(Class<?> type) { return type.isAnnotationPresent(Behavior.class); } }; public static <T> T get(Object domainObject, Class<? extends T> behaviorInterfaceType) { // Gets appropriate behavior implementation from local cache... Object behaviorImpl = cache.get(new Pair(behaviorInterfaceType, domainObject.getClass())); Class<?> domainType = domainObject.getClass(); // If theres no entry for required behavior on cache... if (behaviorImpl == null) { // Looks for the behavior implementation... try { Map<Class<?>, Class<?>> implementations = map.get(behaviorInterfaceType); if (implementations == null) { throw new RuntimeException( String.format("No implementations found for behavior: %s", behaviorInterfaceType)); } // Scans domain class and its super classes looking for an behavior implementation of required // interface. Class<?> treeDomainClass = domainType; do { Class<?> behaviorClass = implementations.get(treeDomainClass); // if is there a valid behavior implementation... if (behaviorClass != null) { // Gets the behavior implementation by using a instance provider. // if there is no provider set... if (provider == null) { // Loads custom provider... ServiceLoader<InstanceProvider> providers = ServiceLoader.load(InstanceProvider.class); // if there is a custom instance provider... if (providers.iterator().hasNext()) { // uses it. provider = providers.iterator().next(); } // otherwise... else { // uses the default one. provider = new DefaultInstanceProvider(); } } // gets the instance. behaviorImpl = provider.get(behaviorClass); // Injects the domain object on annotated field(s). Set<Field> fields = ReflectionUtils.getAllFields(behaviorClass, DOMAIN_FIELD_PREDICATE); for (Field field : fields) { field.setAccessible(true); field.set(behaviorImpl, domainObject); } } // if is there no valid behavior implementation... else { // Looks at its super class... treeDomainClass = treeDomainClass.getSuperclass(); } } // repeats the process until find a valid behavior implementation or reaches Object class on the // hierarchy. while (!treeDomainClass.equals(Object.class) && behaviorImpl == null); // If there's no behavior implementation for requested domain object and interface... if (behaviorImpl == null) { // Throws an exception. throw new RuntimeException(String.format("No implementation found for domain: %s and behavior: %s", domainType, behaviorInterfaceType)); } } catch (Exception e) { throw new RuntimeException("Error creating behavior instance", e); } } return (T) behaviorImpl; } public static void register(Class<?> domainClass, Class<?> behaviorInterfaceType, Class<?> behaviorImplementationType) { Map<Class<?>, Class<?>> implementations = map.get(behaviorInterfaceType); System.out.println(String.format("Registering behavior implementation (%s) for domain (%s) and behavior (%s).", behaviorImplementationType, domainClass, behaviorInterfaceType)); if (implementations == null) { implementations = new HashMap<Class<?>, Class<?>>(); map.put(behaviorInterfaceType, implementations); } implementations.put(domainClass, behaviorImplementationType); } public static void registerAnnotated(String packageName) { Reflections reflections = new Reflections(packageName); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(BehaviorOf.class); for (Class<?> behaviorImplType : annotated) { BehaviorOf domain = behaviorImplType.getAnnotation(BehaviorOf.class); Set<Class<?>> behaviors = ReflectionUtils.getAllSuperTypes(behaviorImplType, BEHAVIOR_PREDICATE); for (Class<?> behaviorType : behaviors) { System.out.println( String.format("Behavior implementation detected: (%s) for domain (%s) and behavior (%s).", behaviorImplType, domain.value(), behaviorType)); register(domain.value(), behaviorType, behaviorImplType); } } } }
package cmput301f17t01.bronzify; import android.drm.DrmStore; import android.support.test.espresso.Espresso; import android.support.test.espresso.contrib.DrawerActions; import android.support.test.espresso.contrib.NavigationViewActions; import android.support.test.espresso.contrib.PickerActions; import android.support.test.filters.LargeTest; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.widget.DatePicker; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import cmput301f17t01.bronzify.activities.LoginActivity; import cmput301f17t01.bronzify.activities.MyHomeActivity; import static android.support.test.espresso.Espresso.onData; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withClassName; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.core.StringStartsWith.startsWith; @RunWith(AndroidJUnit4.class) @LargeTest public class EspressoTesting { @Rule public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule(LoginActivity.class); @Test public void CreateNewHabitEvent() { onView(withId(R.id.enter_id)).perform(typeText("test_user_001")); onView(withId(R.id.enter_id)).check(matches(withText("test_user_001"))); onView(withId(R.id.login_button)).perform(closeSoftKeyboard()); onView(withId(R.id.login_button)).perform(click()); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyHabits)); onView(withId(R.id.createNewHabit)).perform(click()); onView(withId(R.id.textHabitName)).perform(typeText("Running")); onView(withId(R.id.textHabitName)).check(matches(withText("Running"))); onView(withId(R.id.textHabitReason)).perform(typeText("Get fit")); onView(withId(R.id.textHabitReason)).check(matches(withText("Get fit"))); onView(withId(R.id.buttonSelectDate)).perform(click()); onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(2017, 12, 5)); onView(withText("OK")).perform(click()); onView(withId(R.id.buttonMonday)).perform(click()); onView(withId(R.id.buttonWednesday)).perform(click()); onView(withId(R.id.buttonFriday)).perform(click()); onView(withId(R.id.buttonCreate)).perform(closeSoftKeyboard()); onView(withId(R.id.buttonCreate)).perform(click()); } @Test public void EditHabitType() { onView(withId(R.id.enter_id)).perform(typeText("test_user_001")); onView(withId(R.id.login_button)).perform(closeSoftKeyboard()); onView(withId(R.id.login_button)).perform(click()); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.MyHabits)); onView(withId(R.id.habitTypeRow)).check(matches(withText(containsString("Running")))); onView(withId(R.id.habitTypeRow)).perform(click()); onView(withId(R.id.buttonEdit)).perform(click()); onView(withId(R.id.textHabitName)).check(matches(withText("Running"))); onView(withId(R.id.textHabitName)).perform(typeText("Skating")); onView(withId(R.id.textHabitName)).check(matches(withText("Skating"))); onView(withId(R.id.buttonWednesday)).perform(click()); onView(withId(R.id.buttonEdit)).perform(click()); } }
package com.expidev.gcmapp.db; import android.content.Context; import android.test.InstrumentationTestCase; import android.test.RenamingDelegatingContext; import android.util.Log; import com.expidev.gcmapp.model.Assignment; import com.expidev.gcmapp.model.Ministry; import java.util.ArrayList; import java.util.List; public class MinistriesDaoTest extends InstrumentationTestCase { private final String TAG = getClass().getSimpleName(); private MinistriesDao ministriesDao; @Override public void setUp() throws Exception { super.setUp(); Context context = new RenamingDelegatingContext(getInstrumentation().getTargetContext().getApplicationContext(), "test_"); ministriesDao = MinistriesDao.getInstance(context); } private void cleanupDatabase() { Log.i(TAG, "Cleaning up database"); ministriesDao.deleteAllData(); } private ArrayList<Assignment> getTestAssignments() { ArrayList<Assignment> assignments = new ArrayList<Assignment>(); Assignment assignemnt1 = new Assignment(); assignemnt1.setId("A1"); assignemnt1.setMinistry(mockMinistry()); assignemnt1.setMinistryId(assignemnt1.getMinistry().getMinistryId()); assignemnt1.setRole(Assignment.Role.SELF_ASSIGNED); assignments.add(assignemnt1); return assignments; } /** * Mock Ministry * - Sub Ministry 1 * - Sub Ministry 2 * - Sub Ministry 3 * - Sub Ministry 4 * - Sub Ministry 5 */ private Ministry mockMinistry() { Ministry mockMinistry = new Ministry(); Ministry subMinistry1 = new Ministry(); Ministry subMinistry2 = new Ministry(); Ministry subMinistry3 = new Ministry(); Ministry subMinistry4 = new Ministry(); Ministry subMinistry5 = new Ministry(); mockMinistry.setName("Mock Ministry"); subMinistry1.setName("Sub Ministry 1"); subMinistry2.setName("Sub Ministry 2"); subMinistry3.setName("Sub Ministry 3"); subMinistry4.setName("Sub Ministry 4"); subMinistry5.setName("Sub Ministry 5"); mockMinistry.setMinistryId("M0"); subMinistry1.setMinistryId("M1"); subMinistry2.setMinistryId("M2"); subMinistry3.setMinistryId("M3"); subMinistry4.setMinistryId("M4"); subMinistry5.setMinistryId("M5"); mockMinistry.setMinistryCode("MOCK"); subMinistry1.setMinistryCode("MIN_1"); subMinistry2.setMinistryCode("MIN_2"); subMinistry3.setMinistryCode("MIN_3"); subMinistry4.setMinistryCode("MIN_4"); subMinistry5.setMinistryCode("MIN_5"); List<Ministry> subMinistryList1 = new ArrayList<>(); List<Ministry> subMinistryList2 = new ArrayList<>(); List<Ministry> subMinistryList3 = new ArrayList<>(); List<Ministry> subMinistryList4 = new ArrayList<>(); subMinistryList1.add(subMinistry1); subMinistryList2.add(subMinistry2); subMinistryList3.add(subMinistry3); subMinistryList2.add(subMinistry4); subMinistryList4.add(subMinistry5); return mockMinistry; } }
package com.jajja.jorm; import java.io.Closeable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class RecordIterator implements Closeable { private Symbol[] symbols; private Set<Symbol> symbolSet = new HashSet<Symbol>(); private PreparedStatement preparedStatement; private ResultSet resultSet; private boolean autoClose = true; public RecordIterator(PreparedStatement preparedStatement) throws SQLException { this.preparedStatement = preparedStatement; this.resultSet = preparedStatement.executeQuery(); init(); } public RecordIterator(ResultSet resultSet) throws SQLException { this.resultSet = resultSet; init(); } private void init() throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); symbols = new Symbol[metaData.getColumnCount()]; symbolSet = new HashSet<Symbol>(symbols.length + 1, 1.0f); // + 1 to prevent resize? for (int i = 0; i < symbols.length; i++) { symbols[i] = Symbol.get(metaData.getColumnLabel(i + 1)); symbolSet.add(symbols[i]); } } private void populate(Record record, ResultSet resultSet) throws SQLException { for (int i = 0; i < symbols.length; i++) { record.isStale = false; try { record.put(symbols[i], resultSet.getObject(i + 1)); } catch (SQLException sqlException) { record.open().getDialect().rethrow(sqlException); } finally { record.isStale = true; // lol exception } record.isStale = false; } Iterator<Symbol> i = record.fields.keySet().iterator(); while (i.hasNext()) { Symbol symbol = i.next(); if (!symbolSet.contains(symbol)) { record.unset(symbol); } } record.purify(); } public boolean next() throws SQLException { return resultSet.next(); } public <T extends Record> T record(Class<T> clazz) throws SQLException { T record = Record.construct(clazz); populate(record, resultSet); return record; } public void record(Record record) throws SQLException { populate(record, resultSet); } @Override public void close() { if (!autoClose) { return; } Exception ex = null; if (resultSet != null) { try { resultSet.close(); } catch (Exception e) { ex = e; } resultSet = null; } if (preparedStatement != null) { try { preparedStatement.close(); } catch (Exception e) { ex = e; } preparedStatement = null; } if (ex != null) { throw new RuntimeException(ex); } } public void setAutoClose(boolean autoClose) { this.autoClose = autoClose; } }
package com.jcabi.github.mock; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.github.Coordinates; import com.jcabi.github.Github; import com.jcabi.github.Repo; import com.jcabi.github.Repos; import com.jcabi.log.Logger; import java.io.IOException; import javax.json.JsonObject; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; import org.xembly.Directives; /** * Github repos. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 0.5 * @checkstyle MultipleStringLiterals (500 lines) */ @Immutable @Loggable(Loggable.DEBUG) @ToString @EqualsAndHashCode(of = { "storage", "self" }) final class MkRepos implements Repos { /** * Storage. */ private final transient MkStorage storage; /** * Login of the user logged in. */ private final transient String self; /** * Public ctor. * @param stg Storage * @param login User to login * @throws IOException If there is any I/O problem */ MkRepos( @NotNull(message = "stg can't be NULL") final MkStorage stg, @NotNull(message = "login can't be NULL") final String login ) throws IOException { this.storage = stg; this.self = login; this.storage.apply(new Directives().xpath("/github").addIf("repos")); } @Override @NotNull(message = "github can't be NULL") public Github github() { return new MkGithub(this.storage, this.self); } @Override @NotNull(message = "repo is never NULL") public Repo create( @NotNull(message = "json can't be NULL") final JsonObject json ) throws IOException { final String name = json.getString("name"); final Coordinates coords = new Coordinates.Simple(this.self, name); this.storage.apply( new Directives().xpath(this.xpath()).add("repo") .attr("coords", coords.toString()) .add("name").set(name) ); final Repo repo = this.get(coords); repo.patch(json); Logger.info( this, "repository %s created by %s", coords, this.self ); return repo; } @Override @NotNull(message = "Repo is never NULL") public Repo get( @NotNull(message = "coords can't be NULL") final Coordinates coords ) { try { final String xpath = String.format( "%s/repo[@coords='%s']", this.xpath(), coords ); if (this.storage.xml().nodes(xpath).isEmpty()) { throw new IllegalArgumentException( String.format("repository %s doesn't exist", coords) ); } } catch (final IOException ex) { throw new IllegalStateException(ex); } return new MkRepo(this.storage, this.self, coords); } @Override public void remove( @NotNull(message = "coordinates can't be NULL") final Coordinates coords) { try { this.storage.apply( new Directives().xpath( String.format("%s/repo[@coords='%s']", this.xpath(), coords) ).remove() ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } @Override public Iterable<Repo> iterate( @NotNull(message = "identifier can't be NULL") final String identifier) { throw new UnsupportedOperationException("MkRepos#iterate"); } /** * XPath of this element in XML tree. * @return XPath */ @NotNull(message = "Xpath is never NULL") private String xpath() { return "/github/repos"; } }
package com.amandafarrell.www.scorekeeper; import android.app.LoaderManager; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.amandafarrell.www.scorekeeper.data.PlayerContract; public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { public static final int PLAYER_LOADER = 0; private ActionMode mActionMode; public ListView mPlayerListView; //used for tracking the number of players in the list private int mPlayerNumber = 0; //The adapter that knows how to create list item views given a cursor private PlayerCursorAdapter mCursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Setup FAB to open EditScoreActivity FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String[] projection = {PlayerContract.PlayerEntry._ID}; Cursor cursor = getContentResolver().query( PlayerContract.PlayerEntry.CONTENT_URI, projection, null, null, null); //create player name string try { if (cursor.moveToFirst()) { mPlayerNumber = cursor.getCount() + 1; } else { mPlayerNumber = 1; } } catch (NullPointerException e) { Log.e("MainActivity", "moveToFirst: ", e); } String defaultName = getString(R.string.main_default_name); defaultName += " " + mPlayerNumber; // Create a new map of values, where column names are the keys, // and player attributes from the editor are the values ContentValues values = new ContentValues(); values.put(PlayerContract.PlayerEntry.COLUMN_PLAYER_NAME, defaultName); values.put(PlayerContract.PlayerEntry.COLUMN_PLAYER_SCORE, 0); // Insert the new row using PlayerProvider Uri newUri = getContentResolver().insert(PlayerContract.PlayerEntry.CONTENT_URI, values); //Finish contextual action bar when an item has been selected if (mActionMode != null) { mActionMode.finish(); } mPlayerListView.setSelection(mPlayerListView.getCount() - 1); mPlayerListView.requestFocus(); //Calls onCreateOptionsMenu() invalidateOptionsMenu(); try { cursor.close(); } catch (NullPointerException e) { Log.e("MainActivity", "cursor.close(): ", e); } } }); //Find the ListView which will be populated with the player data mPlayerListView = (ListView) findViewById(R.id.list_view_player); //Find and set empty view on the ListView so that it only shows when the list has 0 items. View emptyView = findViewById(R.id.empty_view); mPlayerListView.setEmptyView(emptyView); //set the choice mode for the contextual action bar mPlayerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); //Set up an Adapter to create a list item for each row of pet data in the Cursor //There is no pet data yet (until the loader finishes) so pass in null for the Cursor mCursorAdapter = new PlayerCursorAdapter(this, null); mPlayerListView.setAdapter(mCursorAdapter); //set an empty footer view at the end of the list to avoid the fab covering information TextView empty = new TextView(this); empty.setHeight(150); //The footer view cannot be selected mPlayerListView.addFooterView(empty, 0, false); //set click listeners on each list item mPlayerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, EditScoreActivity.class); //Append the id of the current pet to the content URI Uri currentPlayerUri = ContentUris.withAppendedId(PlayerContract.PlayerEntry.CONTENT_URI, id); //Set the URI on the data field of the intent intent.setData(currentPlayerUri); startActivity(intent); //Finish contextual action bar when an item has been selected if (mActionMode != null) { mActionMode.finish(); } //remove highlight from the selected player mPlayerListView.setItemChecked(position, false); } }); //Contextual action mode creates contextual action bar for list items selected with //a long press mPlayerListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (mActionMode != null) { return false; } // Start the CAB using the ActionMode.Callback defined above mActionMode = MainActivity.this.startActionMode(mActionModeCallback); if (mActionMode != null) { mActionMode.setTag(id); } //highlight the selected player by setting as checked mPlayerListView.setItemChecked(position, true); return true; } }); //Initialize Loader getLoaderManager(). initLoader(PLAYER_LOADER, null, this); } private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() { // Called when the action mode is created; startActionMode() was called @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { // Inflate a menu resource providing context menu items MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); return true; } // Called each time the action mode is shown. Always called after onCreateActionMode, but // may be called multiple times if the mode is invalidated. @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; // Return false if nothing is done } // Called when the user selects a contextual menu item @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { //get the id from the action mode tag long id = (long) mode.getTag(); //Append the id of the current pet to the content URI Uri currentPlayerUri = ContentUris.withAppendedId(PlayerContract.PlayerEntry.CONTENT_URI, id); switch (item.getItemId()) { case R.id.cab_edit: Intent intent = new Intent(MainActivity.this, EditNameActivity.class); //Set the URI on the data field of the intent intent.setData(currentPlayerUri); startActivity(intent); // Action picked, so close the CAB mode.finish(); return true; case R.id.cab_delete: // Call the ContentResolver to delete the player at the given content URI. // Pass in null for the selection and selection args because the mCurrentPlayerUri // content URI already identifies the player that we want. int rowsDeleted = getContentResolver().delete(currentPlayerUri, null, null); // Action picked, so close the CAB mode.finish(); return true; default: mode.finish(); return false; } } // Called when the user exits the action mode @Override public void onDestroyActionMode(ActionMode mode) { //Un-check all items to remove highlight color mPlayerListView.clearChoices(); for (int i = 0; i < mPlayerListView.getCount(); i++) { mPlayerListView.setItemChecked(i, false); } mActionMode = null; } }; @Override protected void onPause() { //Finish contextual action bar when an item has been selected if (mActionMode != null) { mActionMode.finish(); } super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_delete_all_entries: deleteAllPlayers(); invalidateOptionsMenu(); return true; case R.id.action_reset_scores: resetAllScores(); return true; case R.id.action_donate: Intent intent = new Intent(MainActivity.this, DonateActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } public void deleteAllPlayers() { // Call the ContentResolver to delete the player at the given content URI. // Pass in null for the selection and selection args because the mCurrentPlayerUri // content URI already identifies the player that we want. int rowsDeleted = getContentResolver().delete(PlayerContract.PlayerEntry.CONTENT_URI, null, null); } public void resetAllScores() { // Create a new map of values, where column name is the key, // and the reset score is the value ContentValues values = new ContentValues(); int scoreReset = 0; values.put(PlayerContract.PlayerEntry.COLUMN_PLAYER_SCORE, scoreReset); //Pass the content resolver the updated player information int rowsAffected = getContentResolver().update(PlayerContract.PlayerEntry.CONTENT_URI, values, null, null); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { //Define a projection that specifies the columns from the table we care about String[] projection = new String[]{ PlayerContract.PlayerEntry._ID, PlayerContract.PlayerEntry.COLUMN_PLAYER_NAME, PlayerContract.PlayerEntry.COLUMN_PLAYER_SCORE }; //This loader will execute the ContentProvider's query method on a background thread return new CursorLoader(this, PlayerContract.PlayerEntry.CONTENT_URI, projection, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mCursorAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mCursorAdapter.swapCursor(null); } }
package com.jcabi.manifests; import com.jcabi.log.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Enumeration; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.Manifest; import javax.servlet.ServletContext; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.SerializationUtils; @SuppressWarnings("PMD.UseConcurrentHashMap") public final class Manifests { /** * Injected attributes. * @see #inject(String,String) */ private static final Map<String, String> INJECTED = new ConcurrentHashMap<String, String>(); /** * Attributes retrieved from all existing {@code MANIFEST.MF} files. * @see #load() */ private static Map<String, String> attributes = Manifests.load(); /** * Failures registered during loading. * @see #load() */ private static Map<URI, String> failures; /** * It's a utility class, can't be instantiated. */ private Manifests() { // intentionally empty } public static String read( @NotNull(message = "attribute name can't be NULL") @Pattern(regexp = ".+", message = "attribute name can't be empty") final String name) { if (Manifests.attributes == null) { throw new IllegalArgumentException( "Manifests haven't been loaded yet by request from XsltFilter" ); } if (!Manifests.exists(name)) { final StringBuilder bldr = new StringBuilder( Logger.format( // @checkstyle LineLength (1 line) "Atribute '%s' not found in MANIFEST.MF file(s) among %d other attribute(s) %[list]s and %d injection(s)", name, Manifests.attributes.size(), new TreeSet<String>(Manifests.attributes.keySet()), Manifests.INJECTED.size() ) ); if (!Manifests.failures.isEmpty()) { bldr.append("; failures: ").append( Logger.format("%[list]s", Manifests.failures.keySet()) ); } throw new IllegalArgumentException(bldr.toString()); } String result; if (Manifests.INJECTED.containsKey(name)) { result = Manifests.INJECTED.get(name); } else { result = Manifests.attributes.get(name); } return result; } /** * Inject new attribute. * * <p>An attribute can be injected in runtime, mostly for the sake of * unit and integration testing. Once injected an attribute becomes * available with {@link #read(String)}. * * @param name Name of the attribute * @param value The value of the attribute being injected */ public static void inject( @NotNull(message = "injected name can't be NULL") @Pattern(regexp = ".+", message = "name of attribute can't be empty") final String name, @NotNull(message = "inected value can't be NULL") final String value) { if (Manifests.INJECTED.containsKey(name)) { Logger.info( Manifests.class, "#inject(%s, '%s'): replaced previous injection '%s'", name, value, Manifests.INJECTED.get(name) ); } else { Logger.info( Manifests.class, "#inject(%s, '%s'): injected", name, value ); } Manifests.INJECTED.put(name, value); } /** * Check whether attribute exists in any of {@code MANIFEST.MF} files. * * <p>Use this method before {@link #read(String)} to check whether an * attribute exists, in order to avoid a runtime exception. * * @param name Name of the attribute to check * @return Returns {@code TRUE} if it exists, {@code FALSE} otherwise */ public static boolean exists( @NotNull(message = "name of attribute can't be NULL") @Pattern(regexp = ".+", message = "name of attribute can't be empty") final String name) { return Manifests.attributes.containsKey(name) || Manifests.INJECTED.containsKey(name); } /** * Make a snapshot of current attributes and their values. * @return The snapshot, to be used later with {@link #revert(byte[])} */ public static byte[] snapshot() { byte[] snapshot; synchronized (Manifests.INJECTED) { snapshot = SerializationUtils.serialize( (Serializable) Manifests.INJECTED ); } Logger.debug( Manifests.class, "#snapshot(): created (%d bytes)", snapshot.length ); return snapshot; } /** * Revert to the state that was recorded by {@link #snapshot()}. * @param snapshot The snapshot taken by {@link #snapshot()} */ @SuppressWarnings("unchecked") public static void revert(@NotNull final byte[] snapshot) { synchronized (Manifests.INJECTED) { Manifests.INJECTED.clear(); Manifests.INJECTED.putAll( (Map<String, String>) SerializationUtils.deserialize(snapshot) ); } Logger.debug( Manifests.class, "#revert(%d bytes): reverted", snapshot.length ); } /** * Append attributes from the web application {@code MANIFEST.MF}, called * from {@link XsltFilter#init(FilterConfig)}. * * <p>You can call this method in your own * {@link javax.servlet.Filter} or * {@link javax.servlet.ServletContextListener}, * in order to inject {@code MANIFEST.MF} attributes to the class. * * @param ctx Servlet context * @see #Manifests() * @throws IOException If some I/O problem inside */ public static void append(@NotNull final ServletContext ctx) throws IOException { final long start = System.currentTimeMillis(); URL main; try { main = ctx.getResource("/META-INF/MANIFEST.MF"); } catch (java.net.MalformedURLException ex) { throw new IOException(ex); } if (main == null) { Logger.warn( Manifests.class, "#append(%s): MANIFEST.MF not found in WAR package", ctx.getClass().getName() ); } else { final Map<String, String> attrs = Manifests.loadOneFile(main); Manifests.attributes.putAll(attrs); Logger.info( Manifests.class, // @checkstyle LineLength (1 line) "#append(%s): %d attribs loaded from %s in %[ms]s (%d total): %[list]s", ctx.getClass().getName(), attrs.size(), main, System.currentTimeMillis() - start, Manifests.attributes.size(), new TreeSet<String>(attrs.keySet()) ); } } /** * Append attributes from the file. * @param file The file to load attributes from * @throws IOException If some I/O problem inside */ public static void append(@NotNull final File file) throws IOException { final long start = System.currentTimeMillis(); Map<String, String> attrs; try { attrs = Manifests.loadOneFile(file.toURI().toURL()); } catch (java.net.MalformedURLException ex) { throw new IOException(ex); } Manifests.attributes.putAll(attrs); Logger.info( Manifests.class, // @checkstyle LineLength (1 line) "#append('%s'): %d attributes loaded in %[ms]s (%d total): %[list]s", file, attrs.size(), System.currentTimeMillis() - start, Manifests.attributes.size(), new TreeSet<String>(attrs.keySet()) ); } /** * Load attributes from classpath. * * <p>This method doesn't throw any checked exceptions because it is called * from a static context above. It's just more convenient to catch all * exceptions here than above in a static call block. * * @return All found attributes */ private static Map<String, String> load() { final long start = System.currentTimeMillis(); Manifests.failures = new ConcurrentHashMap<URI, String>(); final Map<String, String> attrs = new ConcurrentHashMap<String, String>(); int count = 0; for (URI uri : Manifests.uris()) { try { attrs.putAll(Manifests.loadOneFile(uri.toURL())); } catch (IOException ex) { Manifests.failures.put(uri, ex.getMessage()); Logger.error( Manifests.class, "#load(): '%s' failed %[exception]s", uri, ex ); } ++count; } Logger.info( Manifests.class, "#load(): %d attribs loaded from %d URL(s) in %[ms]s: %[list]s", attrs.size(), count, System.currentTimeMillis() - start, new TreeSet<String>(attrs.keySet()) ); return attrs; } /** * Find all URLs. * * <p>This method doesn't throw any checked exceptions just for convenience * of calling of it (above in {@linke #load}), although it is clear that * {@link IOException} is a good candidate for being thrown out of it. * * @return The list of URLs * @see #load() */ private static Set<URI> uris() { Enumeration<URL> resources; try { resources = Thread.currentThread().getContextClassLoader() .getResources("META-INF/MANIFEST.MF"); } catch (IOException ex) { throw new IllegalStateException(ex); } final Set<URI> uris = new HashSet<URI>(); while (resources.hasMoreElements()) { try { uris.add(resources.nextElement().toURI()); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); } } return uris; } /** * Load attributes from one file. * * <p>Inside the method we catch {@code RuntimeException} (which may look * suspicious) in order to protect our execution flow from expected (!) * exceptions from {@link Manifest#getMainAttributes()}. For some reason, * this JDK method doesn't throw checked exceptions if {@code MANIFEST.MF} * file format is broken. Instead, it throws a runtime exception (an * unchecked one), which we should catch in such an inconvenient way. * * @param url The URL of it * @return The attributes loaded * @see #load() * @see tickets #193 and #323 * @throws IOException If some problem happens */ @SuppressWarnings("PMD.AvoidCatchingGenericException") private static Map<String, String> loadOneFile(final URL url) throws IOException { final Map<String, String> props = new ConcurrentHashMap<String, String>(); final InputStream stream = url.openStream(); try { final Manifest manifest = new Manifest(stream); final Attributes attrs = manifest.getMainAttributes(); for (Object key : attrs.keySet()) { final String value = attrs.getValue((Name) key); props.put(key.toString(), value); } Logger.debug( Manifests.class, "#loadOneFile('%s'): %d attributes loaded (%[list]s)", url, props.size(), new TreeSet<String>(props.keySet()) ); } catch (RuntimeException ex) { Logger.error( Manifests.class, "#getMainAttributes(): '%s' failed %[exception]s", url, ex ); } finally { IOUtils.closeQuietly(stream); } return props; } }
package com.belatrixsf.connect.ui.about; import com.belatrixsf.connect.R; import com.belatrixsf.connect.entities.Collaborator; import com.belatrixsf.connect.ui.common.BelatrixConnectPresenter; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; public class AboutPresenter extends BelatrixConnectPresenter<AboutView> { private List<Collaborator> collaboratorsList = new ArrayList<>(); @Inject public AboutPresenter(AboutView view) { super(view); } public void getContacts() { view.resetList(); prepareCollaborators(); view.addContacts(collaboratorsList); } private void prepareCollaborators() { collaboratorsList = new ArrayList<>(); collaboratorsList.add(new Collaborator("Antonella", "Manna", R.drawable.amanna)); collaboratorsList.add(new Collaborator("Carlos", "Piñan", R.drawable.cpinan)); collaboratorsList.add(new Collaborator("Diego", "Velásquez", R.drawable.dvelasquez)); collaboratorsList.add(new Collaborator("Eduardo", "Chuquilin", R.drawable.echuquilin)); collaboratorsList.add(new Collaborator("Flavio", "Franco", R.drawable.ffranco)); collaboratorsList.add(new Collaborator("Gianfranco", "Yosida", R.drawable.gyosida)); collaboratorsList.add(new Collaborator("Gladys", "Cuzcano", R.drawable.gcuzcano)); collaboratorsList.add(new Collaborator("Ivan", "Cerrate", R.drawable.icerrate)); collaboratorsList.add(new Collaborator("Javier", "Valdivia", R.drawable.jvaldivia)); collaboratorsList.add(new Collaborator("Jo", "Yep", R.drawable.jyep)); collaboratorsList.add(new Collaborator("Jorge", "Boneu", R.drawable.jboneu)); collaboratorsList.add(new Collaborator("Karla", "Cerron", R.drawable.kcerron)); collaboratorsList.add(new Collaborator("Lucia", "Castro", R.drawable.lcastro)); collaboratorsList.add(new Collaborator("Luis", "Barzola", R.drawable.lbarzola)); collaboratorsList.add(new Collaborator("Pedro", "Carrillo", R.drawable.pcarrillo)); collaboratorsList.add(new Collaborator("Rodrigo", "Gonzalez", R.drawable.rgonzalez)); collaboratorsList.add(new Collaborator("Sergio", "Infante", R.drawable.sinfante)); } @Override public void cancelRequests() { } public List<Collaborator> getCollaboratorsSync() { return collaboratorsList; } // saving state stuff public void loadPresenterState(List<Collaborator> collaboratorsList) { this.collaboratorsList = collaboratorsList; } }
package com.laxture.lib.util; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.support.v4.app.Fragment; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.laxture.lib.RuntimeContext; import java.io.File; import java.lang.reflect.Method; public final class ViewUtil { private ViewUtil() {} // Hide Constructor. public static final ViewGroup.LayoutParams DEFAULT_LAYOUT_PARAM = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ); public static final ViewGroup.LayoutParams FILL_LAYOUT_PARAM = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); public static final RadioGroup.OnCheckedChangeListener TOGGLE_LISTENER = new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(final RadioGroup radioGroup, final int i) { for (int j = 0; j < radioGroup.getChildCount(); j++) { final CompoundButton view = (CompoundButton) radioGroup.getChildAt(j); view.setChecked(view.getId() == i); } } }; public static boolean isFragmentDead(Fragment fragment) { return fragment.isDetached() || fragment.isRemoving() || !fragment.isAdded(); } public static void removeViewFromParent(View view) { if (view == null) return; ViewGroup parentView = (ViewGroup) view.getParent(); if (parentView == null) return; parentView.removeView(view); } /** * Convenient method to retrieve value from TextView. * * @param viewId the assigned view must be inherited from TextView * @param rootView accept any Object has <code>findViewById()</code> method. * @return */ public static String getViewText(int viewId, Object rootView) { try { TextView view = resolveTextView(viewId, rootView); return view.getText().toString(); } catch (Exception e) { return ""; } } /** * Convenient method to retrieve value from TextView. * * @param viewId the assigned view must be inherited from TextView * @param rootView accept any Object has <code>findViewById()</code> method. * @param color actual color that will be set. For color from Resource, use * Context.getResources().getColor() to get the real color */ public static void setViewTextColor(int viewId, Object rootView, int color) { TextView view = resolveTextView(viewId, rootView); if (view != null) view.setTextColor(color); } /** * Convenient method to set Text value for TextView. * * @param viewId the assigned view must be inherited from TextView * @param rootView accept any Object has <code>findViewById()</code> method. */ public static void setViewText(int viewId, Object rootView, CharSequence text) { TextView view = resolveTextView(viewId, rootView); if (view != null) view.setText(text); } /** * Convenient method to set Text value for TextView. * * @param viewId the assigned view must be inherited from TextView * @param rootView accept any Object has <code>findViewById()</code> method. */ public static void setViewText(int viewId, Object rootView, int textResId) { TextView view = resolveTextView(viewId, rootView); if (view != null) view.setText(textResId); } public static void setImageSource(int viewId, Object rootView, int resId) { ImageView view = resolveImageView(viewId, rootView); if (view != null) view.setImageResource(resId); } public static void setImageSource(int viewId, Object rootView, Bitmap bitmap) { ImageView view = resolveImageView(viewId, rootView); if (view != null) view.setImageBitmap(bitmap); } public static void setImageSource(int viewId, Object rootView, Drawable drawable) { ImageView view = resolveImageView(viewId, rootView); if (view != null) view.setImageDrawable(drawable); } public static void setImageSource(int viewId, Object rootView, File file) { ImageView view = resolveImageView(viewId, rootView); if (view != null) view.setImageURI(Uri.fromFile(file)); } private static TextView resolveTextView(int viewId, Object rootView) { Method method; TextView view = null; try { method = rootView.getClass().getMethod("findViewById", int.class); view = (TextView) method.invoke(rootView, viewId); } catch (Exception e) { LLog.w("Cannot find view "+viewId); } return view; } private static ImageView resolveImageView(int viewId, Object rootView) { Method method; ImageView view = null; try { method = rootView.getClass().getMethod("findViewById", int.class); view = (ImageView) method.invoke(rootView, viewId); } catch (Exception e) { LLog.w("Cannot find view "+viewId); } return view; } public static boolean isMultilineInputType(int inputType) { return (inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); } public static void showKeyboard(Context context) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } public static void hideKeyboard(Activity activity) { hideKeyboard(activity, activity.getWindow()); } public static void hideKeyboard(Activity activity, Window window) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); View focusView = (window != null) ? window.getDecorView() : activity.getWindow().getCurrentFocus(); if (focusView != null) imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0); } public static boolean checkIfTouchOutsideOfView(View view, MotionEvent event) { return event.getAction() == MotionEvent.ACTION_DOWN && checkIfMotionOutsideOfView(view, event); } public static boolean checkIfMotionOutsideOfView(View view, MotionEvent event) { if (view == null) return false; int scrcoords[] = new int[2]; view.getLocationOnScreen(scrcoords); float x = event.getRawX() + view.getLeft() - scrcoords[0]; float y = event.getRawY() + view.getTop() - scrcoords[1]; return x < view.getLeft() || x >= view.getRight() || y < view.getTop() || y > view.getBottom(); } public static void showToast(final Activity activity, final String message) { if (activity == null) return; activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, message, Toast.LENGTH_SHORT).show(); } }); } public static void showToast(final Activity activity, final int resId) { showToast(activity, activity.getString(resId)); } public static int getDisplaySize(int pixelSize) { return Math.round(pixelSize * RuntimeContext.getResources().getDisplayMetrics().density); } /** * dp px() */ public static int dip2px(float dpValue) { final float scale = RuntimeContext.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } public static View findViewById(Fragment fragment, int id) { return fragment.getActivity().findViewById(id); } /** EditText */ public static void setErrorHint(TextView textView, String errMsg) { ForegroundColorSpan span = new ForegroundColorSpan( RuntimeContext.getResources().getColor(android.R.color.white)); SpannableStringBuilder sb = new SpannableStringBuilder(errMsg); sb.setSpan(span, 0, errMsg.length(), 0); textView.setError(sb); } public static void setErrorHint(Spinner spinner, String errMsg) { View view = spinner.getSelectedView(); if (view != null) { if (view instanceof TextView) { setErrorHint((TextView) view, errMsg); } else if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for (int i=0; i<viewGroup.getChildCount(); i++) { if (viewGroup.getChildAt(i) instanceof TextView) { setErrorHint((TextView) viewGroup.getChildAt(i), errMsg); } } } } } public static void clearErrorHint(TextView textView) { textView.setError(null); } public static void clearErrorHint(Spinner spinner) { View view = spinner.getSelectedView(); if (view != null) { if (view instanceof TextView) { clearErrorHint((TextView) view); } else if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for (int i=0; i<viewGroup.getChildCount(); i++) { if (viewGroup.getChildAt(i) instanceof TextView) { clearErrorHint((TextView) viewGroup.getChildAt(i)); } } } } } }
package com.nilhcem.fakesmtp; import java.awt.EventQueue; import java.awt.Toolkit; import java.net.URL; import javax.swing.UIManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.apple.eawt.Application; import com.nilhcem.fakesmtp.core.Configuration; import com.nilhcem.fakesmtp.core.exception.UncaughtExceptionHandler; import com.nilhcem.fakesmtp.gui.MainFrame; /** * Entry point of the application. * * @author Nilhcem * @since 1.0 */ public final class FakeSMTP { private static final Logger LOGGER = LoggerFactory.getLogger(FakeSMTP.class); private FakeSMTP() { throw new UnsupportedOperationException(); } /** * Sets some specific properties, and runs the main window. * <p> * Before opening the main window, this method will: * <ul> * <li>set a default uncaught exception handler to intercept every uncaught exception;</li> * <li>use a custom icon in the Mac Dock;</li> * <li>set a property for Mac OS X to take the menu bar off the JFrame;</li> * <li>set a property for Mac OS X to set the name of the application menu item;</li> * <li>turn off the bold font in all components for swing default theme;</li> * <li>use the platform look and feel.</li> * </ul> * </p> * * @param args a list of parameters. */ public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler()); EventQueue.invokeLater(new Runnable() { @Override public void run() { try { URL envelopeImage = getClass().getResource(Configuration.INSTANCE.get("application.icon.path")); if (envelopeImage != null) { Application.getApplication().setDockIconImage(Toolkit.getDefaultToolkit().getImage(envelopeImage)); } } catch (RuntimeException e) { // Do nothing, this is probably because we run on a non-Mac platform and these components are not implemented. } catch (Exception e) { LOGGER.error("", e); } System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", Configuration.INSTANCE.get("application.name")); UIManager.put("swing.boldMetal", Boolean.FALSE); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { LOGGER.error("", e); } new MainFrame(); } }); } }
package com.example.android.sendmoods; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import java.util.ArrayList; import java.util.Date; import static com.example.android.sendmoods.Constants.*; public class MoodListActivity extends AppCompatActivity{ private ListView moodListView; private ArrayList<MoodEvent> moodEventList = new ArrayList<>(); private MoodListAdapter adapter; Location location = new Location("defaultlocation"); //private MoodEvent testMoodEvent = new MoodEvent("default", "default", "default", "default", location, "default", "default", 0, "default"); private MoodEvent testMoodEvent = new MoodEvent("February 02, 2017", "11:11", "Harder Better Faster", "Mohamad", "123 Fakestreet, WA", HAPPY_WORD, HAPPY_POPUP_BOX, HAPPY_COLOR); private MoodEvent newMoodEvent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mood_list); moodListView = (ListView) findViewById(R.id.mood_list); adapter = new MoodListAdapter(this, moodEventList); moodListView.setAdapter(adapter); /*testMoodEvent.setUsername("Mohamad"); testMoodEvent.setEmotion(HAPPY_WORD); testMoodEvent.setDate("February 02, 2017"); testMoodEvent.setTime("11:11"); testMoodEvent.setReason("Harder Better Faster"); testMoodEvent.setAddress("123 Fakestreet, WA"); testMoodEvent.setColor(HAPPY_COLOR); testMoodEvent.setPopupShape(HAPPY_POPUP_BOX);*/ moodEventList.add(testMoodEvent); adapter.notifyDataSetChanged(); moodListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> a, View v, int position, long id) { MoodEvent moodEvent = (MoodEvent) moodListView.getItemAtPosition(position); Intent myIntent = new Intent(MoodListActivity.this, MoodPopupActivity.class); myIntent.putExtra("MoodEvent", moodEvent); startActivityForResult(myIntent, 0); } }); } public void editMood(View view) { Intent intent = new Intent(this, EditMoodActivity.class); startActivityForResult(intent, Constants.INTENT_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Constants.INTENT_REQUEST_CODE){ //Intent intent = getIntent(); /*might not be necessary*/ Bundle extras = data.getExtras(); String date = extras.getString("EXTRA_DATE"); String time = extras.getString("EXTRA_TIME"); String reason = extras.getString("EXTRA_REASON"); String username = extras.getString("EXTRA_USER"); String address = extras.getString("EXTRA_ADDRESS"); String emotion = extras.getString("EXTRA_EMOTION"); int popupshape = extras.getInt("EXTRA_POPUP"); String color = extras.getString("EXTRA_COLOR"); newMoodEvent = new MoodEvent(date, time, reason, username, address, emotion, popupshape, color); moodEventList.add(newMoodEvent); adapter.notifyDataSetChanged(); } } public void addMood(MoodEvent moodevent){ } }
package com.opentok; import com.opentok.exception.InvalidArgumentException; import org.apache.commons.validator.routines.InetAddressValidator; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * Defines values for the <code>properties</code> parameter of the * {@link OpenTok#createSession(SessionProperties)} method. * * @see OpenTok#createSession(com.opentok.SessionProperties properties) */ public class SessionProperties { private String location = null; private MediaMode mediaMode; private ArchiveMode archiveMode; private SessionProperties(Builder builder) { this.location = builder.location; this.mediaMode = builder.mediaMode; this.archiveMode = builder.archiveMode; } /** * Use this class to create a SessionProperties object. * * @see SessionProperties */ public static class Builder { private String location = null; private MediaMode mediaMode = MediaMode.RELAYED; private ArchiveMode archiveMode = ArchiveMode.MANUAL; /** * Call this method to set an IP address that the OpenTok servers will use to * situate the session in its global network. If you do not set a location hint, * the OpenTok servers will be based on the first client connecting to the session. * * @param location The IP address to serve as the locaion hint. * * @return The SessionProperties.Builder object with the location hint setting. */ public Builder location(String location) throws InvalidArgumentException { if (!InetAddressValidator.getInstance().isValidInet4Address(location)) { throw new InvalidArgumentException("Location must be a valid IPv4 address. location = " + location); } this.location = location; return this; } public Builder mediaMode(MediaMode mediaMode) { this.mediaMode = mediaMode; return this; } /** * Call this method to determine whether the session will be automatically archived (<code>ArchiveMode.ALWAYS</code>) * or not (<code>ArchiveMode.MANUAL</code>). * * Using an always archived session also requires the routed media mode (<code>MediaMode.ROUTED</code>). * * @param archiveMode * * @return The SessionProperties.Builder object with the archive mode setting. */ public Builder archiveMode(ArchiveMode archiveMode) { this.archiveMode = archiveMode; return this; } /** * Builds the SessionProperties object. * * @return The SessionProperties object. */ public SessionProperties build() { // Would throw in this case, but would introduce a backwards incompatible change. //if (this.archiveMode == ArchiveMode.ALWAYS && this.mediaMode != MediaMode.ROUTED) { // throw new InvalidArgumentException("A session with always archive mode must also have the routed media mode."); return new SessionProperties(this); } } /** * The location hint IP address. See {@link SessionProperties.Builder#location(String location)}. */ public String getLocation() { return location; } /** * Defines whether the session will transmit streams using the OpenTok Media Server or attempt * to transmit streams directly between clients. See * {@link SessionProperties.Builder#mediaMode(MediaMode mediaMode)}. */ public MediaMode mediaMode() { return mediaMode; } /** * Defines whether the session will be automatically archived (<code>ArchiveMode.ALWAYS</code>) * or not (<code>ArchiveMode.MANUAL</code>). See * {@link com.opentok.SessionProperties.Builder#archiveMode(ArchiveMode archiveMode)} */ public ArchiveMode archiveMode() { return archiveMode; } /** * Returns the session properties as a Map. */ public Map<String, Collection<String>> toMap() { Map<String, Collection<String>> params = new HashMap<String, Collection<String>>(); if (null != location) { ArrayList<String> valueList = new ArrayList<String>(); valueList.add(location); params.put("location", valueList); } ArrayList<String> mediaModeValueList = new ArrayList<String>(); mediaModeValueList.add(mediaMode.toString()); params.put("p2p.preference", mediaModeValueList); ArrayList<String> archiveModeValueList = new ArrayList<String>(); archiveModeValueList.add(archiveMode.toString()); params.put("archiveMode", archiveModeValueList); return params; } };
package com.example.bsd_16.studentlist3; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "employee_directory"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { /* * Create the employee table and populate it with sample data. * In step 6, we will move these hardcoded statements to an XML document. */ String sql = "CREATE TABLE IF NOT EXISTS employee (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "firstName TEXT, " + "lastName TEXT, " + "title TEXT, " + "officePhone TEXT, " + "cellPhone TEXT, " + "email TEXT, " + "managerId INTEGER)"; db.execSQL(sql); ContentValues values = new ContentValues(); values.put("firstName", "John"); values.put("lastName", "Smith"); values.put("title", "CEO"); values.put("officePhone", "617-219-2001"); values.put("cellPhone", "617-456-7890"); values.put("email", "jsmith@email.com"); db.insert("employee", "lastName", values); values.put("firstName", "Robert"); values.put("lastName", "Jackson"); values.put("title", "VP Engineering"); values.put("officePhone", "617-219-3333"); values.put("cellPhone", "781-444-2222"); values.put("email", "rjackson@email.com"); values.put("managerId", "1"); db.insert("employee", "lastName", values); values.put("firstName", "Marie"); values.put("lastName", "Potter"); values.put("title", "VP Sales"); values.put("officePhone", "617-219-2002"); values.put("cellPhone", "987-654-3210"); values.put("email", "mpotter@email.com"); values.put("managerId", "1"); db.insert("employee", "lastName", values); values.put("firstName", "Lisa"); values.put("lastName", "Jordan"); values.put("title", "VP Marketing"); values.put("officePhone", "617-219-2003"); values.put("cellPhone", "987-654-7777"); values.put("email", "ljordan@email.com"); values.put("managerId", "2"); db.insert("employee", "lastName", values); values.put("firstName", "Christophe"); values.put("lastName", "Coenraets"); values.put("title", "Evangelist"); values.put("officePhone", "617-219-0000"); values.put("cellPhone", "617-666-7777"); values.put("email", "ccoenrae@adobe.com"); values.put("managerId", "2"); db.insert("employee", "lastName", values); values.put("firstName", "Paula"); values.put("lastName", "Brown"); values.put("title", "Director Engineering"); values.put("officePhone", "617-612-0987"); values.put("cellPhone", "617-123-9876"); values.put("email", "pbrown@email.com"); values.put("managerId", "2"); db.insert("employee", "lastName", values); values.put("firstName", "Mark"); values.put("lastName", "Taylor"); values.put("title", "Lead Architect"); values.put("officePhone", "617-444-1122"); values.put("cellPhone", "617-555-3344"); values.put("email", "mtaylor@email.com"); values.put("managerId", "2"); db.insert("employee", "lastName", values); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS employees"); onCreate(db); } }
package com.oreilly.rdf.tenuki; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.configuration.HierarchicalINIConfiguration; import org.apache.commons.dbcp.BasicDataSource; import com.hp.hpl.jena.sdb.StoreDesc; public class Tenuki { /** * @param args * @throws Exception */ @SuppressWarnings("static-access") public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "show this message"); options.addOption(OptionBuilder.withLongOpt("port").withDescription( "use PORT for server").hasArg().withArgName("PORT") .create("p")); options.addOption(OptionBuilder.withLongOpt("password") .withDescription("SQL database password").hasArg().withArgName( "PASSWORD").create()); try { CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("tenuki-server", options); return; } System.err.println("Starting Tenuki..."); Integer port = 7070; String driver = "org.postgresql.Driver"; String url = "jdbc:postgresql:sdb"; String username = "sdb"; String password = null; if (line.getArgList().size() > 0) { String configFilePath = line.getArgs()[0]; HierarchicalINIConfiguration config = new HierarchicalINIConfiguration( configFilePath); port = config.getInt("server.port", 7070); password = config.getString("datasource.password", password); driver = config.getString("datasource.driver", driver); username = config.getString("datasource.username", username); url = config.getString("datasource.url", url); } port = Integer.parseInt(line .getOptionValue("port", port.toString())); password = line.getOptionValue("password", password); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); if (password != null) { dataSource.setPassword(password); } StoreDesc storeDesc = new StoreDesc("layout2/index", "postgresql"); System.err.println("... configuration complete ..."); TenukiSever server = new TenukiSever(); server.setDatasource(dataSource); server.setStoreDesc(storeDesc); server.setPort(port); server.start(); } catch (ParseException e) { System.out.println("Unexpected exception:" + e.getMessage()); } } }
package com.example.jianming.Tasks; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import com.example.jianming.myapplication.PicListAcivity; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; public class DownloadWebpageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { try { return downloadUrl(urls[0]); } catch (IOException e) { e.printStackTrace(); return ""; } } private String downloadUrl(String myurl) throws IOException { InputStream is = null; int len = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); Log.d("network", "The response is: " + response); is = conn.getInputStream(); return readIt(is, len); } finally { if (is != null) { is.close(); } } } private String readIt(InputStream is, int len) throws IOException { Reader reader = null; reader = new InputStreamReader(is, "UTF-8"); char[] buffer = new char[len]; String content = ""; int readLen; do { readLen = reader.read(buffer); content += new String(buffer).substring(0, readLen); } while (readLen == len); return content; } }
package com.sixtyfour.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import com.sixtyfour.Loader; /** * A simple compressor that can compress and uncompress byte[]-arrays based on a * simple and most likely inefficient sliding window algorithm that I came with * while being half asleep. * * Not used for anything ATM, but it might get some use later... * * @author EgonOlsen * */ public class Compressor { public static void main(String[] args) throws Exception { testCompressor("C:\\Users\\EgonOlsen\\Desktop\\test.txt"); testCompressor("C:\\Users\\EgonOlsen\\Desktop\\++affine.prg"); testCompressor("C:\\Users\\EgonOlsen\\Desktop\\affine.bas"); testCompressor("C:\\Users\\EgonOlsen\\Desktop\\++corona.prg"); } private static void testCompressor(String fileName) { log("Compressing " + fileName); byte[] bytes = Loader.loadBlob(fileName); byte[] compressedBytes = compress(bytes); byte[] uncompressedBytes = uncompress(compressedBytes); log("Uncompressed size: " + uncompressedBytes.length); log("Equals: " + Arrays.equals(bytes, uncompressedBytes)); } public static byte[] compress(byte[] dump) { long time = System.currentTimeMillis(); int windowSize = 128; int minSize = 12; int len = dump.length; int windowPos = 0; byte[] window = new byte[windowSize]; fillWindow(dump, window, windowPos); List<Part> parts = findMatches(dump, windowSize, minSize, len, windowPos, window); byte[] bos = compress(parts, dump); if (bos.length >= len) { log("No further compression possible!"); return null; } log("Binary compressed from " + len + " to " + bos.length + " bytes in " + (System.currentTimeMillis() - time) + "ms"); DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH); DecimalFormat decFor = new DecimalFormat("###.##", symbols); log("Compression ratio: 1:" + decFor.format(((float) len / bos.length))); return bos; } public static byte[] uncompress(byte[] bytes) { int clen = bytes.length; int data = readLowHigh(bytes, 0); int dataPos = data; byte[] res = new byte[65536]; int pos = 0; for (int i = 2; i < data;) { int start = readLowHigh(bytes, i); int target = 0; i += 2; do { int len = bytes[i] & 0xFF; i++; target = 0; if (len != 0) { target = readLowHigh(bytes, i); int copyLen = target - pos; if (copyLen > 0) { System.arraycopy(bytes, dataPos, res, pos, copyLen); dataPos += copyLen; pos = target; } System.arraycopy(res, start, res, target, len); pos += len; i += 2; } else { i++; } } while (target > 0); } if (dataPos < clen) { System.arraycopy(bytes, dataPos, res, pos, clen - dataPos); pos += (bytes.length - dataPos); } return Arrays.copyOf(res, pos); } private static byte[] compress(List<Part> parts, byte[] dump) { ByteArrayOutputStream header = new ByteArrayOutputStream(); ByteArrayOutputStream data = new ByteArrayOutputStream(); int pos = 0; int lastStart = -1; for (Part part : parts) { int start = part.sourceAddress; int target = part.targetAddress; if (target > pos) { data.write(dump, pos, target - pos); pos = target; } pos += part.size; if (start != lastStart) { if (lastStart != -1) { writeEndFlag(header); } writeLowHigh(header, start); } lastStart = start; header.write(part.size); writeLowHigh(header, part.targetAddress); } data.write(dump, pos, dump.length - pos); writeEndFlag(header); ByteArrayOutputStream res = new ByteArrayOutputStream(); writeLowHigh(res, header.size() + 2); try { res.write(header.toByteArray()); res.write(data.toByteArray()); } catch (IOException e) { } return res.toByteArray(); } private static void writeEndFlag(ByteArrayOutputStream header) { header.write(0); header.write(0); } private static int readLowHigh(byte[] bytes, int pos) { return (bytes[pos] & 0xFF) + ((bytes[pos + 1] & 0xFF) << 8); } private static void writeLowHigh(ByteArrayOutputStream header, int start) { header.write((start & 0xFF)); header.write((start >> 8)); } private static List<Part> findMatches(byte[] dump, int windowSize, int minSize, int len, int windowPos, byte[] window) { int curSize = windowSize; int largest = 0; List<Part> parts = new ArrayList<>(); byte[] covered = new byte[len]; do { for (int i = windowPos + curSize; i < len - curSize; i++) { boolean match = true; for (int p = 0; p < curSize; p++) { if (covered[i + p] != 0) { match = false; break; } if (dump[i + p] != window[p]) { match = false; if (p > largest) { largest = p; } break; } } if (match) { boolean cov = false; for (int h = i; h < i + curSize && !cov; h++) { covered[h] = 1; } Part part = new Part(windowPos, i, curSize); parts.add(part); i += curSize; // log("Found: " + part); } } if (largest >= minSize) { curSize = largest; largest = 0; } else { curSize = windowSize; windowPos++; largest = 0; fillWindow(dump, window, windowPos); } } while (windowPos + curSize < len); Collections.sort(parts, new Comparator<Part>() { @Override public int compare(Part p1, Part p2) { return p1.targetAddress - p2.targetAddress; } }); // parts.forEach(p -> System.out.println(p)); return parts; } private static void fillWindow(byte[] dump, byte[] window, int pos) { System.arraycopy(dump, pos, window, 0, window.length); } private static void log(String txt) { System.out.println(txt); } private static class Part { Part(int source, int target, int size) { this.sourceAddress = source; this.targetAddress = target; this.size = size; } int sourceAddress; int targetAddress; int size; @Override public String toString() { return "block@ " + sourceAddress + "/" + targetAddress + "/" + size; } } }
package com.speedment.util; import java.util.Collection; import java.util.Optional; import java.util.stream.Stream; /** * * @author Duncan */ public class StreamUtil { public static <T> Stream<T> mandatory(Optional<? extends T> element) { return element.isPresent() ? Stream.of(element.get()) : Stream.empty(); } public static <T> Stream<T> of(Collection<Optional<? extends T>> collection) { return collection.stream().filter(Optional::isPresent).map((o) -> o.get()); } public static <T> Stream.Builder<T> streamBuilder(Collection<? extends T>... collections) { return streamBuilder(Stream.builder(), collections); } public static <T> Stream.Builder<T> streamBuilder(Stream.Builder<T> originalBuilder, Collection<? extends T>... collections) { Stream.of(collections).flatMap(Collection::stream).forEach(originalBuilder::add); return originalBuilder; } }
package com.karambit.bookie.helper; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.karambit.bookie.R; import com.karambit.bookie.model.Book; public class BookTimelineAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public static final String TAG = BookTimelineAdapter.class.getSimpleName(); private static final int TYPE_HEADER = 0; private static final int TYPE_BOOK_PROCESS = 1; private static final int TYPE_SUBTITLE = 2; private static final int TYPE_FOOTER = 3; private Context mContext; private Book.Details mBookDetails; private boolean mProgressBarActive; public BookTimelineAdapter(Context context, Book.Details bookDetails) { mContext = context; mBookDetails = bookDetails; mProgressBarActive = false; } private static class HeaderViewHolder extends RecyclerView.ViewHolder { private CircleImageView mBookPicture; private TextView mBookName; private TextView mAuthor; private TextView mGenre; private CircleImageView mOwnerPicture; private TextView mOwnerName; private TextView mBookState; private Button mRequest; private HeaderViewHolder(View headerView) { super(headerView); mBookPicture = (CircleImageView) headerView.findViewById(R.id.bookPictureHeaderCircleImageView); mBookName = (TextView) headerView.findViewById(R.id.bookNameHeaderTextView); mAuthor = (TextView) headerView.findViewById(R.id.authorHeaderTextView); mGenre = (TextView) headerView.findViewById(R.id.genreHeaderTextView); mOwnerPicture = (CircleImageView) headerView.findViewById(R.id.ownerPictureHeaderCircleImageView); mOwnerName = (TextView) headerView.findViewById(R.id.ownerNameHeaderTextView); mBookState = (TextView) headerView.findViewById(R.id.bookStateHeaderTextView); mRequest = (Button) headerView.findViewById(R.id.requestHeaderButton); } } private static class BookProcessViewHolder extends RecyclerView.ViewHolder { private ImageView mProcessImage; private TextView mProcessChange; private View mTopLine; private View mBottomLine; private BookProcessViewHolder(View itemView) { super(itemView); mProcessImage = (ImageView) itemView.findViewById(R.id.bookProcessImageView); mProcessChange = (TextView) itemView.findViewById(R.id.bookProcessChangeTextView); mTopLine = itemView.findViewById(R.id.topLineView); mBottomLine = itemView.findViewById(R.id.bottomLineView); } } private static class SubtitleViewHolder extends RecyclerView.ViewHolder { private TextView mSubtitle; private SubtitleViewHolder(View subtitleView) { super(subtitleView); mSubtitle = (TextView) subtitleView.findViewById(R.id.subtitleTextView); } } private static class FooterViewHolder extends RecyclerView.ViewHolder { private ProgressBar mProgressBar; private TextView mTextView; private FooterViewHolder(View footerView) { super(footerView); mProgressBar = (ProgressBar) footerView.findViewById(R.id.footerProgressBar); mTextView = (TextView) footerView.findViewById(R.id.footerTextView); } } @Override public int getItemCount() { return mBookDetails.getBookProcesses().size() + 3; // + Header + Subtitle + Footer } /* HEADER SUBTITLE BOOK PROCESSES FOOTER */ @Override public int getItemViewType(int position) { if (position == 0) { return TYPE_HEADER; } else if (position == 1) { return TYPE_SUBTITLE; } else if (position < mBookDetails.getBookProcesses().size() + 2) { // + Header + Subtitle return TYPE_BOOK_PROCESS; } else if (position == getItemCount() - 1) { return TYPE_FOOTER; } else { throw new IllegalArgumentException("Invalid view type at position " + position); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //View inflating for view types and creating ViewHolders switch (viewType) { case TYPE_HEADER: View headerView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_header_book_timeline, parent, false); return new HeaderViewHolder(headerView); case TYPE_BOOK_PROCESS: View bookProcessView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_process_book_timeline, parent, false); return new BookProcessViewHolder(bookProcessView); case TYPE_SUBTITLE: View subtitleView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_subtitle, parent, false); return new SubtitleViewHolder(subtitleView); case TYPE_FOOTER: View footerView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer, parent, false); return new FooterViewHolder(footerView); default: throw new IllegalArgumentException("Invalid view type variable: viewType=" + viewType); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { switch (getItemViewType(position)) { case TYPE_HEADER: { HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder; // TODO Listener setup Glide.with(mContext) .load(mBookDetails.getBook().getThumbnailURL()) .asBitmap() .placeholder(R.drawable.placeholder_book) .centerCrop() .into(headerViewHolder.mBookPicture); headerViewHolder.mBookName.setText(mBookDetails.getBook().getName()); headerViewHolder.mAuthor.setText(mBookDetails.getBook().getAuthor()); //TODO Genre headerViewHolder.mGenre.setText("Genre"); Glide.with(mContext) .load(mBookDetails.getBook().getOwner().getThumbnailUrl()) .asBitmap() .placeholder(R.drawable.placeholder_book) .centerCrop() .into(headerViewHolder.mOwnerPicture); headerViewHolder.mOwnerName.setText(mBookDetails.getBook().getOwner().getName()); Book.State state = mBookDetails.getBook().getState(); headerViewHolder.mBookState.setText(bookStateToString(state)); // Enable or disable book request button if (state == Book.State.OPENED_TO_SHARE) { headerViewHolder.mRequest.setEnabled(true); } else { headerViewHolder.mRequest.setEnabled(false); } break; } case TYPE_SUBTITLE: { SubtitleViewHolder subtitleHolder = (SubtitleViewHolder) holder; subtitleHolder.mSubtitle.setText(mContext.getString(R.string.pass_through)); break; } case TYPE_BOOK_PROCESS: { final BookProcessViewHolder itemHolder = (BookProcessViewHolder) holder; // TopLine BottomLine setup if (mBookDetails.getBookProcesses().size() == 1) { itemHolder.mTopLine.setVisibility(View.INVISIBLE); itemHolder.mBottomLine.setVisibility(View.INVISIBLE); } else { if (position == 2) { itemHolder.mTopLine.setVisibility(View.INVISIBLE); itemHolder.mBottomLine.setVisibility(View.VISIBLE); } else if (position == getItemCount() - 2) { itemHolder.mTopLine.setVisibility(View.VISIBLE); itemHolder.mBottomLine.setVisibility(View.INVISIBLE); } else { itemHolder.mTopLine.setVisibility(View.VISIBLE); itemHolder.mBottomLine.setVisibility(View.VISIBLE); } } final Book.BookProcess item = mBookDetails.getBookProcesses().get(position - 2); // - Header - Subtitle /** * Decide which Book process. Visitor pattern takes care this. */ item.accept(new Book.TimelineDisplayableVisitor() { // Visitor interface @Override public void visit(Book.Interaction interaction) { // If BookProcess is a Book.Interaction object itemHolder.mProcessImage.setVisibility(View.VISIBLE); switch (interaction.getInteractionType()) { case ADD: // itemHolder.mProcessImage.setImageResource(R.drawable.reading_24dp); itemHolder.mProcessChange.setText( mContext.getString(R.string.x_added_this_book, interaction.getUser().getName())); break; case READ_START: // itemHolder.mProcessImage.setImageResource(R.drawable.reading_24dp); itemHolder.mProcessChange.setText(mContext.getString(R.string.x_started_to_read_this_book, interaction.getUser().getName())); break; case READ_STOP: // itemHolder.mProcessImage.setImageResource(R.drawable.reading_24dp); itemHolder.mProcessChange.setText(mContext.getString(R.string.x_finished_to_read_this_book, interaction.getUser().getName())); break; case CLOSE_TO_SHARE: // itemHolder.mProcessImage.setImageResource(R.drawable.close_to_share_24dp); itemHolder.mProcessChange.setText(mContext.getString(R.string.x_closed_sharing_for_this_book, interaction.getUser().getName())); break; case OPEN_TO_SHARE: // itemHolder.mProcessImage.setImageResource(R.drawable.open_to_share_24dp); itemHolder.mProcessChange.setText(mContext.getString(R.string.x_opened_sharing_for_this_book, interaction.getUser().getName())); break; default: throw new IllegalArgumentException("Invalid interaction type:" + interaction.getInteractionType().name()); } } @Override public void visit(Book.Transaction transaction) { // If BookProcess is a Book.Transaction object itemHolder.mProcessImage.setVisibility(View.VISIBLE); switch (transaction.getTransactionType()) { case COME_TO_HAND: // itemHolder.mProcessImage.setImageResource(R.drawable.on_road_24dp); itemHolder.mProcessChange.setText(mContext.getString(R.string.x_took_the_book, transaction.getToUser().getName())); break; case DISPACTH: // itemHolder.mProcessImage.setImageResource(R.drawable.on_road_24dp); itemHolder.mProcessChange.setText(mContext.getString(R.string.x_sent_the_book_to_y, transaction.getFromUser().getName(), transaction.getToUser().getName())); break; case LOST: // itemHolder.mProcessImage.setImageResource(R.drawable.lost_24dp); itemHolder.mProcessChange.setText(mContext.getString(R.string.book_sent_from_x_to_y_and_its_lost, transaction.getFromUser().getName(), transaction.getToUser().getName())); break; default: throw new IllegalArgumentException("Invalid transaction type:" + transaction.getTransactionType().name()); } } @Override public void visit(Book.Request request) { // If BookProcess is a Book.Request object itemHolder.mProcessImage.setVisibility(View.GONE); switch (request.getRequestType()) { case SEND: itemHolder.mProcessChange.setText(mContext.getString(R.string.x_sent_request_to_y, request.getFromUser().getName(), request.getToUser().getName())); break; case ACCEPT: itemHolder.mProcessChange.setText(mContext.getString(R.string.x_accepted_ys_request, request.getFromUser().getName(), request.getToUser().getName())); break; case REJECT: itemHolder.mProcessChange.setText(mContext.getString(R.string.x_rejected_ys_request, request.getFromUser().getName(), request.getToUser().getName())); break; default: throw new IllegalArgumentException("Invalid request type:" + request.getRequestType().name()); } } }); break; } case TYPE_FOOTER: { FooterViewHolder footerHolder = (FooterViewHolder) holder; if (mProgressBarActive) { footerHolder.mProgressBar.setVisibility(View.VISIBLE); } else { footerHolder.mProgressBar.setVisibility(View.GONE); } break; } } } private String bookStateToString(Book.State state) { switch (state) { case READING: return mContext.getString(R.string.reading); case OPENED_TO_SHARE: return mContext.getString(R.string.opened_to_share); case CLOSED_TO_SHARE: return mContext.getString(R.string.closed_to_share); case ON_ROAD: return mContext.getString(R.string.on_road); case LOST: return mContext.getString(R.string.lost); default: return null; } } // public interface HeaderClickListeners { // void onRequestButtonClick(Book.Details details); // void onOwnerClick(User owner); // void onBookPictureClick(Book.Details details); }
package com.sun.akuma; import com.sun.jna.StringArray; import com.sun.jna.Memory; import com.sun.jna.Native; import static com.sun.jna.Pointer.NULL; import com.sun.jna.ptr.IntByReference; import java.util.*; import static java.util.logging.Level.FINEST; import java.util.logging.Logger; import java.util.logging.Level; import java.util.logging.ConsoleHandler; import java.io.IOException; import java.io.FileInputStream; import java.io.File; import java.io.ByteArrayOutputStream; import java.io.RandomAccessFile; import java.io.DataInputStream; import static com.sun.akuma.CLibrary.LIBC; import com.sun.akuma.CLibrary.FILE; /** * List of arguments for Java VM and application. * * @author Kohsuke Kawaguchi */ public class JavaVMArguments extends ArrayList<String> { private static final long serialVersionUID = 1; public JavaVMArguments() { } public JavaVMArguments(Collection<? extends String> c) { super(c); } public void removeSystemProperty(String name) { name = "-D"+name; String nameeq = name+'='; for (Iterator<String> itr = this.iterator(); itr.hasNext();) { String s = itr.next(); if(s.equals(name) || s.startsWith(nameeq)) itr.remove(); } } public void setSystemProperty(String name, String value) { removeSystemProperty(name); // index 0 is the executable name add(1,"-D"+name+"="+value); } /** * Removes the n items from the end. * Useful for removing all the Java arguments to rebuild them. */ public void removeTail(int n) { removeAll(subList(size()-n,size())); } /*package*/ StringArray toStringArray() { return new StringArray(toArray(new String[size()])); } /** * Gets the process argument list of the current process. */ public static JavaVMArguments current() throws IOException { return of(-1); } /** * Gets the process argument list of the specified process ID. * * @param pid * -1 to indicate the current process. */ public static JavaVMArguments of(int pid) throws IOException { String os = System.getProperty("os.name"); if("Linux".equals(os)) return ofLinux(pid); if("SunOS".equals(os)) return ofSolaris(pid); if("Mac OS X".equals(os)) return ofMac(pid); if("FreeBSD".equals(os)) return ofFreeBSD(pid); throw new UnsupportedOperationException("Unsupported Operating System "+os); } private static JavaVMArguments ofLinux(int pid) throws IOException { pid = resolvePID(pid); String cmdline = readFile(new File("/proc/" + pid + "/cmdline")); JavaVMArguments args = new JavaVMArguments(Arrays.asList(cmdline.split("\0"))); // we don't want them inherited args.removeSystemProperty(Daemon.class.getName()); return args; } private static int resolvePID(int pid) { if(pid==-1) pid=LIBC.getpid(); return pid; } private static JavaVMArguments ofSolaris(int pid) throws IOException { // /proc shows different contents based on the caller's memory model, so we need to know if we are 32 or 64. // 32 JVMs are the norm, so err on the 32bit side. boolean areWe64 = "64".equals(System.getProperty("sun.arch.data.model")); pid = resolvePID(pid); RandomAccessFile psinfo = new RandomAccessFile(new File("/proc/"+pid+"/psinfo"),"r"); try { //typedef struct psinfo { // int pr_flag; /* process flags */ // int pr_nlwp; /* number of lwps in the process */ // pid_t pr_pid; /* process id */ // pid_t pr_ppid; /* process id of parent */ // pid_t pr_pgid; /* process id of process group leader */ // pid_t pr_sid; /* session id */ // uid_t pr_uid; /* real user id */ // uid_t pr_euid; /* effective user id */ // gid_t pr_gid; /* real group id */ // gid_t pr_egid; /* effective group id */ // uintptr_t pr_addr; /* address of process */ // size_t pr_size; /* size of process image in Kbytes */ // size_t pr_rssize; /* resident set size in Kbytes */ // dev_t pr_ttydev; /* controlling tty device (or PRNODEV) */ // ushort_t pr_pctcpu; /* % of recent cpu time used by all lwps */ // ushort_t pr_pctmem; /* % of system memory used by process */ // timestruc_t pr_start; /* process start time, from the epoch */ // timestruc_t pr_time; /* cpu time for this process */ // timestruc_t pr_ctime; /* cpu time for reaped children */ // char pr_fname[PRFNSZ]; /* name of exec'ed file */ // char pr_psargs[PRARGSZ]; /* initial characters of arg list */ // int pr_wstat; /* if zombie, the wait() status */ // int pr_argc; /* initial argument count */ // uintptr_t pr_argv; /* address of initial argument vector */ // uintptr_t pr_envp; /* address of initial environment vector */ // char pr_dmodel; /* data model of the process */ // lwpsinfo_t pr_lwp; /* information for representative lwp */ //} psinfo_t; // for the size of the various datatype. // for how to read this information psinfo.seek(8); if(adjust(psinfo.readInt())!=pid) throw new IOException("psinfo PID mismatch"); // sanity check /* The following program computes the offset: #include <stdio.h> #include <sys/procfs.h> int main() { printf("psinfo_t = %d\n", sizeof(psinfo_t)); psinfo_t *x; x = 0; printf("%x\n", &(x->pr_argc)); } */ psinfo.seek(areWe64?0xEC:0xBC); // now jump to pr_argc int argc = adjust(psinfo.readInt()); long argp = areWe64?adjust(psinfo.readLong()):to64(adjust(psinfo.readInt())); if(LOGGER.isLoggable(FINEST)) LOGGER.finest(String.format("argc=%d,argp=%X",argc,argp)); File asFile = new File("/proc/" + pid + "/as"); if (areWe64) { // 32bit and 64bit basically does the same thing, but because the stream position // is computed with signed long, doing 64bit seek to a position bigger than Long.MAX_VALUE // requres some real hacking. Hence two different code path. // (RandomAccessFile uses Java long for offset, so it just can't get to anywhere beyond Long.MAX_VALUE) FILE fp = LIBC.fopen(asFile.getPath(),"r"); try { JavaVMArguments args = new JavaVMArguments(); Memory m = new Memory(8); for( int n=0; n<argc; n++ ) { // read a pointer to one entry seek64(fp,argp+n*8); if(LOGGER.isLoggable(FINEST)) LOGGER.finest(String.format("Seeked to %X",LIBC.ftell(fp))); m.setLong(0,0); // just to make sure failed read won't result in bogus value LIBC.fread(m,1,8,fp); long p = m.getLong(0); args.add(readLine(fp, p, "argv["+ n +"]")); } return args; } finally { LIBC.fclose(fp); } } else { RandomAccessFile as = new RandomAccessFile(asFile,"r"); try { JavaVMArguments args = new JavaVMArguments(); for( int n=0; n<argc; n++ ) { // read a pointer to one entry as.seek(argp+n*4); int p = adjust(as.readInt()); args.add(readLine(as, p, "argv["+ n +"]")); } return args; } finally { as.close(); } } } finally { psinfo.close(); } } /** * Seek to the specified position. This method handles offset bigger than {@link Long#MAX_VALUE} correctly. * * @param upos * This value is interpreted as unsigned 64bit integer (even though it's typed 'long') */ private static void seek64(FILE fp, long upos) { LIBC.fseek(fp,0,0); // start at the beginning while(upos<0) { long chunk = Long.MAX_VALUE; upos -= chunk; LIBC.fseek(fp,chunk,1); } LIBC.fseek(fp,upos,1); } /** * {@link DataInputStream} reads a value in big-endian, so * convert it to the correct value on little-endian systems. */ private static int adjust(int i) { if(IS_LITTLE_ENDIAN) return (i<<24) |((i<<8) & 0x00FF0000) | ((i>>8) & 0x0000FF00) | (i>>>24); else return i; } private static long adjust(long i) { if(IS_LITTLE_ENDIAN) return (i<<56) | ((i<<40) & 0x00FF000000000000L) | ((i<<24) & 0x0000FF0000000000L) | ((i<< 8) & 0x000000FF00000000L) | ((i>> 8) & 0x00000000FF000000L) | ((i>>24) & 0x0000000000FF0000L) | ((i>>40) & 0x000000000000FF00L) | (i>>56); else return i; } /** * int to long conversion with zero-padding. */ private static long to64(int i) { return i&0xFFFFFFFFL; } private static String readLine(RandomAccessFile as, int p, String prefix) throws IOException { if(LOGGER.isLoggable(FINEST)) LOGGER.finest(String.format("Reading %s at %X",prefix,p)); as.seek(to64(p)); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int ch,i=0; while((ch=as.read())>0) { if((++i)%100==0 && LOGGER.isLoggable(FINEST)) LOGGER.finest(prefix +" is so far "+buf.toString()); buf.write(ch); } String line = buf.toString(); if(LOGGER.isLoggable(FINEST)) LOGGER.finest(prefix+" was "+line); return line; } private static String readLine(FILE as, long p, String prefix) throws IOException { if(LOGGER.isLoggable(FINEST)) LOGGER.finest(String.format("Reading %s at %X",prefix,p)); seek64(as,p); Memory m = new Memory(1); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int i=0; while(true) { if(LIBC.fread(m,1,1,as)==0) break; byte b = m.getByte(0); if(b==0) break; if((++i)%100==0 && LOGGER.isLoggable(FINEST)) LOGGER.finest(prefix +" is so far "+buf.toString()); buf.write(b); } String line = buf.toString(); if(LOGGER.isLoggable(FINEST)) LOGGER.finest(prefix+" was "+line); return line; } /** * Reads the entire file. */ private static String readFile(File f) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileInputStream fin = new FileInputStream(f); try { int sz; byte[] buf = new byte[1024]; while((sz=fin.read(buf))>=0) { baos.write(buf,0,sz); } return baos.toString(); } finally { fin.close(); } } private static JavaVMArguments ofMac(int pid) { // local constants final int CTL_KERN = 1; final int KERN_ARGMAX = 8; final int KERN_PROCARGS2 = 49; final int sizeOfInt = Native.getNativeSize(int.class); IntByReference ibr = new IntByReference(); IntByReference argmaxRef = new IntByReference(0); IntByReference size = new IntByReference(sizeOfInt); // for some reason, I was never able to get sysctlbyname work. // if(LIBC.sysctlbyname("kern.argmax", argmaxRef.getPointer(), size, NULL, ibr)!=0) if(LIBC.sysctl(new int[]{CTL_KERN,KERN_ARGMAX},2, argmaxRef.getPointer(), size, NULL, ibr)!=0) throw new UnsupportedOperationException("Failed to get kernl.argmax: "+LIBC.strerror(Native.getLastError())); int argmax = argmaxRef.getValue(); LOGGER.fine("argmax="+argmax); class StringArrayMemory extends Memory { private long offset=0; StringArrayMemory(long l) { super(l); } int readInt() { int r = getInt(offset); offset+=sizeOfInt; return r; } byte peek() { return getByte(offset); } String readString() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte ch; while((ch = getByte(offset++))!='\0') baos.write(ch); return baos.toString(); } void skip0() { // skip trailing '\0's while(getByte(offset)=='\0') offset++; } } StringArrayMemory m = new StringArrayMemory(argmax); size.setValue(argmax); if(LIBC.sysctl(new int[]{CTL_KERN,KERN_PROCARGS2,resolvePID(pid)},3, m, size, NULL, ibr)!=0) throw new UnsupportedOperationException("Failed to obtain ken.procargs2: "+LIBC.strerror(Native.getLastError())); JavaVMArguments args = new JavaVMArguments(); int nargs = m.readInt(); m.readString(); // exec path for( int i=0; i<nargs; i++) { m.skip0(); args.add(m.readString()); } // this is how you can read environment variables // List<String> lst = new ArrayList<String>(); // while(m.peek()!=0) // lst.add(m.readString()); return args; } private static JavaVMArguments ofFreeBSD(int pid) { // taken from sys/sysctl.h final int CTL_KERN = 1; final int KERN_ARGMAX = 8; final int KERN_PROC = 14; final int KERN_PROC_ARGS = 7; IntByReference ibr = new IntByReference(); IntByReference sysctlArgMax = new IntByReference(); IntByReference size = new IntByReference(); size.setValue(4); if( LIBC.sysctl(new int[]{CTL_KERN, KERN_ARGMAX}, 2, sysctlArgMax.getPointer(), size, NULL, ibr) != 0) throw new UnsupportedOperationException("Failed to sysctl kern.argmax"); int argmax = sysctlArgMax.getValue(); Memory m = new Memory(argmax); size.setValue(argmax); if( LIBC.sysctl(new int[]{CTL_KERN,KERN_PROC, KERN_PROC_ARGS, resolvePID(pid)}, 4, m, size, NULL, ibr) != 0) throw new UnsupportedOperationException(""); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ArrayList<String> lArgs = new ArrayList<String>(); byte ch; int offset = 0; while(offset < size.getValue()){ while((ch = m.getByte(offset++))!='\0') baos.write(ch); lArgs.add(baos.toString()); baos.reset(); } return new JavaVMArguments(lArgs); } private static final boolean IS_LITTLE_ENDIAN = "little".equals(System.getProperty("sun.cpu.endian")); private static final Logger LOGGER = Logger.getLogger(JavaVMArguments.class.getName()); public static void main(String[] args) throws IOException { // dump the process model of the caller System.out.println("sun.arch.data.model="+System.getProperty("sun.arch.data.model")); System.out.println("sun.cpu.endian="+System.getProperty("sun.cpu.endian")); LOGGER.setLevel(Level.ALL); ConsoleHandler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); LOGGER.addHandler(handler); if (args.length==0) System.out.println(current()); else { for (String arg : args) { System.out.println(of(Integer.valueOf(arg))); } } } }
package com.martin.kantidroid.ui.widget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.support.v4.content.FileProvider; import android.webkit.MimeTypeMap; import android.widget.RemoteViews; import com.martin.kantidroid.R; import com.martin.kantidroid.logic.PromoCheck; import com.martin.kantidroid.logic.PromoRes; import com.martin.kantidroid.logic.Util; import com.martin.kantidroid.ui.main.MainActivity; import java.io.File; public class WidgetProvider extends AppWidgetProvider { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final int N = appWidgetIds.length; // Perform this loop procedure for each App Widget that belongs to this provider for (int i = 0; i < N; i++) { int appWidgetId = appWidgetIds[i]; // Create an Intent to launch MainActivity Intent intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); Intent settingIntent = new Intent(context, SemesterSelector.class); PendingIntent pendingSettings = PendingIntent.getActivity(context, 0, settingIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Get the layout for the App Widget and attach on-click listeners RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); views.setOnClickPendingIntent(R.id.widget_pp, pendingIntent); views.setOnClickPendingIntent(R.id.widget_kont, pendingIntent); views.setOnClickPendingIntent(R.id.widget_title, pendingIntent); views.setOnClickPendingIntent(R.id.widget_semester, pendingSettings); SharedPreferences prefs = context.getSharedPreferences("Kantidroid", Context.MODE_PRIVATE); File f = new File(prefs.getString("last_timetable", "nope")); if (f.exists()) { String className = f.getName().replace(".pdf", ""); views.setTextViewText(R.id.widget_timetable, className); MimeTypeMap myMime = MimeTypeMap.getSingleton(); Intent newIntent = new Intent(Intent.ACTION_VIEW); String mimeType = myMime.getMimeTypeFromExtension(Util.fileExt(f).substring(1)); newIntent.setDataAndType(FileProvider.getUriForFile(context, "com.martin.fileprovider", f), mimeType); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION); PendingIntent pdfIntent = PendingIntent.getActivity(context, 0, newIntent, 0); views.setOnClickPendingIntent(R.id.widget_timetable, pdfIntent); } else { views.setTextViewText(R.id.widget_timetable, "-"); views.setOnClickPendingIntent(R.id.widget_timetable, null); } if (prefs.getInt("widget_semester", 1) == 1) { views.setTextViewText(R.id.widget_semester, context.getString(R.string.first_semester) + " " + context.getString(R.string.down_arrow)); } else { views.setTextViewText(R.id.widget_semester, context.getString(R.string.second_semester) + " " + context.getString(R.string.down_arrow)); } final PromoRes promo = new PromoCheck(context).getPromo(prefs.getInt("widget_semester", 1)); views.setTextViewText(R.id.widget_pp, promo.sPP); views.setTextViewText(R.id.widget_kont, promo.sKont); // Tell the AppWidgetManager to perform an update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, views); } } }
package com.untamedears.humbug; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; 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 java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.EnderPearl; import org.bukkit.entity.Enderman; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.entity.ThrownPotion; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Skeleton.SkeletonType; import org.bukkit.entity.minecart.HopperMinecart; import org.bukkit.entity.minecart.StorageMinecart; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Damageable; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.enchantment.PrepareItemEnchantEvent; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityCreatePortalEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.entity.ExpBottleEvent; import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.entity.SheepDyeWoolEvent; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.PortalCreateEvent; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.Server; import com.untamedears.humbug.annotations.BahHumbug; import com.untamedears.humbug.annotations.BahHumbugs; import com.untamedears.humbug.annotations.ConfigOption; import com.untamedears.humbug.annotations.OptType; public class Humbug extends JavaPlugin implements Listener { public static void severe(String message) { log_.severe("[Humbug] " + message); } public static void warning(String message) { log_.warning("[Humbug] " + message); } public static void info(String message) { log_.info("[Humbug] " + message); } public static void debug(String message) { if (config_.getDebug()) { log_.info("[Humbug] " + message); } } public static Humbug getPlugin() { return global_instance_; } private static final Logger log_ = Logger.getLogger("Humbug"); private static Humbug global_instance_ = null; private static Config config_ = null; private static int max_golden_apple_stack_ = 1; static { max_golden_apple_stack_ = Material.GOLDEN_APPLE.getMaxStackSize(); if (max_golden_apple_stack_ > 64) { max_golden_apple_stack_ = 64; } } private Random prng_ = new Random(); public Humbug() {} // Reduce registered PlayerInteractEvent count. onPlayerInteractAll handles // cancelled events. @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPlayerInteract(PlayerInteractEvent event) { onAnvilOrEnderChestUse(event); if (!event.isCancelled()) { onCauldronInteract(event); } if (!event.isCancelled()) { onRecordInJukebox(event); } } @EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false public void onPlayerInteractAll(PlayerInteractEvent event) { onPlayerEatGoldenApple(event); onPlayerPearlTeleport(event); } // Stops people from dying sheep @BahHumbug(opt="allow_dye_sheep", def="true") @EventHandler public void onDyeWool(SheepDyeWoolEvent event) { if (!config_.get("allow_dye_sheep").getBool()) { event.setCancelled(true); } } // Fixes Teleporting through walls and doors // ** and ** // Ender Pearl Teleportation disabling @BahHumbugs({ @BahHumbug(opt="ender_pearl_teleportation", def="true"), @BahHumbug(opt="ender_pearl_teleportation_throttled", def="true"), @BahHumbug(opt="fix_teleport_glitch", def="true") }) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { TeleportCause cause = event.getCause(); if (cause != TeleportCause.ENDER_PEARL) { return; } else if (!config_.get("ender_pearl_teleportation").getBool()) { event.setCancelled(true); return; } if (!config_.get("fix_teleport_glitch").getBool()) { return; } Location to = event.getTo(); World world = to.getWorld(); // From and To are feet positions. Check and make sure we can teleport to a location with air // above the To location. Block toBlock = world.getBlockAt(to); Block aboveBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()+1, to.getBlockZ()); Block belowBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()-1, to.getBlockZ()); boolean lowerBlockBypass = false; double height = 0.0; switch( toBlock.getType() ) { case CHEST: // Probably never will get hit directly case ENDER_CHEST: // Probably never will get hit directly height = 0.875; break; case STEP: lowerBlockBypass = true; height = 0.5; break; case WATER_LILY: height = 0.016; break; case ENCHANTMENT_TABLE: lowerBlockBypass = true; height = 0.75; break; case BED: case BED_BLOCK: // This one is tricky, since even with a height offset of 2.5, it still glitches. //lowerBlockBypass = true; //height = 0.563; // Disabling teleporting on top of beds for now by leaving lowerBlockBypass false. break; case FLOWER_POT: case FLOWER_POT_ITEM: height = 0.375; break; case SKULL: // Probably never will get hit directly height = 0.5; break; default: break; } // Check if the below block is difficult // This is added because if you face downward directly on a gate, it will // teleport your feet INTO the gate, thus bypassing the gate until you leave that block. switch( belowBlock.getType() ) { case FENCE: case FENCE_GATE: case NETHER_FENCE: case COBBLE_WALL: height = 0.5; break; default: break; } boolean upperBlockBypass = false; if( height >= 0.5 ) { Block aboveHeadBlock = world.getBlockAt(aboveBlock.getX(), aboveBlock.getY()+1, aboveBlock.getZ()); if( false == aboveHeadBlock.getType().isSolid() ) { height = 0.5; } else { upperBlockBypass = true; // Cancel this event. What's happening is the user is going to get stuck due to the height. } } // Normalize teleport to the center of the block. Feet ON the ground, plz. // Leave Yaw and Pitch alone to.setX(Math.floor(to.getX()) + 0.5000); to.setY(Math.floor(to.getY()) + height); to.setZ(Math.floor(to.getZ()) + 0.5000); if(aboveBlock.getType().isSolid() || (toBlock.getType().isSolid() && !lowerBlockBypass) || upperBlockBypass ) { // One last check because I care about Top Nether. (someone build me a shrine up there) boolean bypass = false; if ((world.getEnvironment() == Environment.NETHER) && (to.getBlockY() > 124) && (to.getBlockY() < 129)) { bypass = true; } if (!bypass) { event.setCancelled(true); } } } // Villager Trading @BahHumbug(opt="villager_trades") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { if (config_.get("villager_trades").getBool()) { return; } Entity npc = event.getRightClicked(); if (npc == null) { return; } if (npc.getType() == EntityType.VILLAGER) { event.setCancelled(true); } } // Anvil and Ender Chest usage // EventHandler registered in onPlayerInteract @BahHumbugs({ @BahHumbug(opt="anvil"), @BahHumbug(opt="ender_chest") }) public void onAnvilOrEnderChestUse(PlayerInteractEvent event) { if (config_.get("anvil").getBool() && config_.get("ender_chest").getBool()) { return; } Action action = event.getAction(); Material material = event.getClickedBlock().getType(); boolean anvil = !config_.get("anvil").getBool() && action == Action.RIGHT_CLICK_BLOCK && material.equals(Material.ANVIL); boolean ender_chest = !config_.get("ender_chest").getBool() && action == Action.RIGHT_CLICK_BLOCK && material.equals(Material.ENDER_CHEST); if (anvil || ender_chest) { event.setCancelled(true); } } @BahHumbug(opt="ender_chests_placeable", def="true") @EventHandler(ignoreCancelled=true) public void onEnderChestPlace(BlockPlaceEvent e) { Material material = e.getBlock().getType(); if (!config_.get("ender_chests_placeable").getBool() && material == Material.ENDER_CHEST) { e.setCancelled(true); } } public void EmptyEnderChest(HumanEntity human) { if (config_.get("ender_backpacks").getBool()) { dropInventory(human.getLocation(), human.getEnderChest()); } } public void dropInventory(Location loc, Inventory inv) { final World world = loc.getWorld(); final int end = inv.getSize(); for (int i = 0; i < end; ++i) { try { final ItemStack item = inv.getItem(i); if (item != null) { world.dropItemNaturally(loc, item); inv.clear(i); } } catch (Exception ex) {} } } // Unlimited Cauldron water // EventHandler registered in onPlayerInteract @BahHumbug(opt="unlimitedcauldron") public void onCauldronInteract(PlayerInteractEvent e) { if (!config_.get("unlimitedcauldron").getBool()) { return; } // block water going down on cauldrons if(e.getClickedBlock().getType() == Material.CAULDRON && e.getMaterial() == Material.GLASS_BOTTLE && e.getAction() == Action.RIGHT_CLICK_BLOCK) { Block block = e.getClickedBlock(); if(block.getData() > 0) { block.setData((byte)(block.getData()+1)); } } } // Quartz from Gravel @BahHumbug(opt="quartz_gravel_percentage", type=OptType.Int) @EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST) public void onGravelBreak(BlockBreakEvent e) { if(e.getBlock().getType() != Material.GRAVEL || config_.get("quartz_gravel_percentage").getInt() <= 0) { return; } if(prng_.nextInt(100) < config_.get("quartz_gravel_percentage").getInt()) { e.setCancelled(true); e.getBlock().setType(Material.AIR); e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation(), new ItemStack(Material.QUARTZ, 1)); } } // Portals @BahHumbug(opt="portalcreate", def="true") @EventHandler(ignoreCancelled=true) public void onPortalCreate(PortalCreateEvent e) { if (!config_.get("portalcreate").getBool()) { e.setCancelled(true); } } @EventHandler(ignoreCancelled=true) public void onEntityPortalCreate(EntityCreatePortalEvent e) { if (!config_.get("portalcreate").getBool()) { e.setCancelled(true); } } // EnderDragon @BahHumbug(opt="enderdragon", def="true") @EventHandler(ignoreCancelled=true) public void onDragonSpawn(CreatureSpawnEvent e) { if (e.getEntityType() == EntityType.ENDER_DRAGON && !config_.get("enderdragon").getBool()) { e.setCancelled(true); } } // Join/Quit/Kick messages @BahHumbug(opt="joinquitkick", def="true") @EventHandler(priority=EventPriority.HIGHEST) public void onJoin(PlayerJoinEvent e) { if (!config_.get("joinquitkick").getBool()) { e.setJoinMessage(null); } } @EventHandler(priority=EventPriority.HIGHEST) public void onQuit(PlayerQuitEvent e) { EmptyEnderChest(e.getPlayer()); if (!config_.get("joinquitkick").getBool()) { e.setQuitMessage(null); } } @EventHandler(priority=EventPriority.HIGHEST) public void onKick(PlayerKickEvent e) { EmptyEnderChest(e.getPlayer()); if (!config_.get("joinquitkick").getBool()) { e.setLeaveMessage(null); } } // Death Messages @BahHumbugs({ @BahHumbug(opt="deathannounce", def="true"), @BahHumbug(opt="deathlog"), @BahHumbug(opt="deathpersonal"), @BahHumbug(opt="deathred"), @BahHumbug(opt="ender_backpacks") }) @EventHandler(priority=EventPriority.HIGHEST) public void onDeath(PlayerDeathEvent e) { final boolean logMsg = config_.get("deathlog").getBool(); final boolean sendPersonal = config_.get("deathpersonal").getBool(); final Player player = (Player)e.getEntity(); EmptyEnderChest(player); if (logMsg || sendPersonal) { Location location = player.getLocation(); String msg = String.format( "%s ([%s] %d, %d, %d)", e.getDeathMessage(), location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (logMsg) { info(msg); } if (sendPersonal) { e.getEntity().sendMessage(ChatColor.RED + msg); } } if (!config_.get("deathannounce").getBool()) { e.setDeathMessage(null); } else if (config_.get("deathred").getBool()) { e.setDeathMessage(ChatColor.RED + e.getDeathMessage()); } } // Endermen Griefing @BahHumbug(opt="endergrief", def="true") @EventHandler(ignoreCancelled=true) public void onEndermanGrief(EntityChangeBlockEvent e) { if (!config_.get("endergrief").getBool() && e.getEntity() instanceof Enderman) { e.setCancelled(true); } } // Wither Insta-breaking and Explosions @BahHumbug(opt="wither_insta_break") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityChangeBlock(EntityChangeBlockEvent event) { if (config_.get("wither_insta_break").getBool()) { return; } Entity npc = event.getEntity(); if (npc == null) { return; } EntityType npc_type = npc.getType(); if (npc_type.equals(EntityType.WITHER)) { event.setCancelled(true); } } @BahHumbug(opt="wither_explosions") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityExplode(EntityExplodeEvent event) { if (config_.get("wither_explosions").getBool()) { return; } Entity npc = event.getEntity(); if (npc == null) { return; } EntityType npc_type = npc.getType(); if ((npc_type.equals(EntityType.WITHER) || npc_type.equals(EntityType.WITHER_SKULL))) { event.blockList().clear(); } } @BahHumbug(opt="wither", def="true") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onWitherSpawn(CreatureSpawnEvent event) { if (config_.get("wither").getBool()) { return; } if (!event.getEntityType().equals(EntityType.WITHER)) { return; } event.setCancelled(true); } // Prevent specified items from dropping off mobs public void removeItemDrops(EntityDeathEvent event) { if (!config_.doRemoveItemDrops()) { return; } if (event.getEntity() instanceof Player) { return; } Set<Integer> remove_ids = config_.getRemoveItemDrops(); List<ItemStack> drops = event.getDrops(); ItemStack item; int i = drops.size() - 1; while (i >= 0) { item = drops.get(i); if (remove_ids.contains(item.getTypeId())) { drops.remove(i); } --i; } } // Spawn more Wither Skeletons and Ghasts @BahHumbugs ({ @BahHumbug(opt="extra_ghast_spawn_rate", type=OptType.Int), @BahHumbug(opt="extra_wither_skele_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_extra_ghast_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_extra_wither_skele_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_pig_spawn_multiplier", type=OptType.Int) }) @EventHandler(ignoreCancelled=true) public void spawnMoreHellMonsters(CreatureSpawnEvent e) { final Location loc = e.getLocation(); final World world = loc.getWorld(); boolean portalSpawn = false; final int blockType = world.getBlockTypeIdAt(loc); if (blockType == 90 || blockType == 49) { // >= because we are preventing instead of spawning if(prng_.nextInt(1000000) >= config_.get("portal_pig_spawn_multiplier").getInt()) { e.setCancelled(true); return; } portalSpawn = true; } if (config_.get("extra_wither_skele_spawn_rate").getInt() <= 0 && config_.get("extra_ghast_spawn_rate").getInt() <= 0) { return; } if (e.getEntityType() == EntityType.PIG_ZOMBIE) { int adjustedwither; int adjustedghast; if (portalSpawn) { adjustedwither = config_.get("portal_extra_wither_skele_spawn_rate").getInt(); adjustedghast = config_.get("portal_extra_ghast_spawn_rate").getInt(); } else { adjustedwither = config_.get("extra_wither_skele_spawn_rate").getInt(); adjustedghast = config_.get("extra_ghast_spawn_rate").getInt(); } if(prng_.nextInt(1000000) < adjustedwither) { e.setCancelled(true); world.spawnEntity(loc, EntityType.SKELETON); } else if(prng_.nextInt(1000000) < adjustedghast) { e.setCancelled(true); int x = loc.getBlockX(); int z = loc.getBlockZ(); List<Integer> heights = new ArrayList<Integer>(16); int lastBlockHeight = 2; int emptyCount = 0; int maxHeight = world.getMaxHeight(); for (int y = 2; y < maxHeight; ++y) { Block block = world.getBlockAt(x, y, z); if (block.isEmpty()) { ++emptyCount; if (emptyCount == 11) { heights.add(lastBlockHeight + 2); } } else { lastBlockHeight = y; emptyCount = 0; } } if (heights.size() <= 0) { return; } loc.setY(heights.get(prng_.nextInt(heights.size()))); world.spawnEntity(loc, EntityType.GHAST); } } else if (e.getEntityType() == EntityType.SKELETON && e.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) { Entity entity = e.getEntity(); if (entity instanceof Skeleton) { Skeleton skele = (Skeleton)entity; skele.setSkeletonType(SkeletonType.WITHER); EntityEquipment entity_equip = skele.getEquipment(); entity_equip.setItemInHand(new ItemStack(Material.STONE_SWORD)); entity_equip.setItemInHandDropChance(0.0F); } } } // Wither Skull drop rate public static final int skull_id_ = Material.SKULL_ITEM.getId(); public static final byte wither_skull_data_ = 1; @BahHumbug(opt="wither_skull_drop_rate", type=OptType.Int) public void adjustWitherSkulls(EntityDeathEvent event) { Entity entity = event.getEntity(); if (!(entity instanceof Skeleton)) { return; } int rate = config_.get("wither_skull_drop_rate").getInt(); if (rate < 0 || rate > 1000000) { return; } Skeleton skele = (Skeleton)entity; if (skele.getSkeletonType() != SkeletonType.WITHER) { return; } List<ItemStack> drops = event.getDrops(); ItemStack item; int i = drops.size() - 1; while (i >= 0) { item = drops.get(i); if (item.getTypeId() == skull_id_ && item.getData().getData() == wither_skull_data_) { drops.remove(i); } --i; } if (rate - prng_.nextInt(1000000) <= 0) { return; } item = new ItemStack(Material.SKULL_ITEM); item.setAmount(1); item.setDurability((short)wither_skull_data_); drops.add(item); } // Generic mob drop rate adjustment public void adjustMobItemDrops(EntityDeathEvent event){ Entity mob = event.getEntity(); if (mob instanceof Player){ return; } if (mob.getWorld() == Bukkit.getWorld("world_the_end")) { return; } // Try specific multiplier, if that doesn't exist use generic EntityType mob_type = mob.getType(); int multiplier = config_.getLootMultiplier(mob_type.toString()); if (multiplier == 1) { multiplier = config_.getLootMultiplier("generic"); } for (ItemStack item : event.getDrops()) { int amount = item.getAmount() * multiplier; item.setAmount(amount); } } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityDeathEvent(EntityDeathEvent event) { removeItemDrops(event); adjustWitherSkulls(event); adjustMobItemDrops(event); } // Enchanted Golden Apple public boolean isEnchantedGoldenApple(ItemStack item) { // Golden Apples are GOLDEN_APPLE with 0 durability // Enchanted Golden Apples are GOLDEN_APPLE with 1 durability if (item == null) { return false; } if (item.getDurability() != 1) { return false; } Material material = item.getType(); return material.equals(Material.GOLDEN_APPLE); } public void replaceEnchantedGoldenApple( String player_name, ItemStack item, int inventory_max_stack_size) { if (!isEnchantedGoldenApple(item)) { return; } int stack_size = max_golden_apple_stack_; if (inventory_max_stack_size < max_golden_apple_stack_) { stack_size = inventory_max_stack_size; } info(String.format( "Replaced %d Enchanted with %d Normal Golden Apples for %s", item.getAmount(), stack_size, player_name)); item.setDurability((short)0); item.setAmount(stack_size); } @BahHumbug(opt="ench_gold_app_craftable") public void removeRecipies() { if (config_.get("ench_gold_app_craftable").getBool()) { return; } Iterator<Recipe> it = getServer().recipeIterator(); while (it.hasNext()) { Recipe recipe = it.next(); ItemStack resulting_item = recipe.getResult(); if ( // !ench_gold_app_craftable_ && isEnchantedGoldenApple(resulting_item)) { it.remove(); info("Enchanted Golden Apple Recipe disabled"); } } } // EventHandler registered in onPlayerInteractAll @BahHumbug(opt="ench_gold_app_edible") public void onPlayerEatGoldenApple(PlayerInteractEvent event) { // The event when eating is cancelled before even LOWEST fires when the // player clicks on AIR. if (config_.get("ench_gold_app_edible").getBool()) { return; } Player player = event.getPlayer(); Inventory inventory = player.getInventory(); ItemStack item = event.getItem(); replaceEnchantedGoldenApple( player.getName(), item, inventory.getMaxStackSize()); } // Enchanted Book public boolean isNormalBook(ItemStack item) { if (item == null) { return false; } Material material = item.getType(); return material.equals(Material.BOOK); } @BahHumbug(opt="ench_book_craftable") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPrepareItemEnchantEvent(PrepareItemEnchantEvent event) { if (config_.get("ench_book_craftable").getBool()) { return; } ItemStack item = event.getItem(); if (isNormalBook(item)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onEnchantItemEvent(EnchantItemEvent event) { if (config_.get("ench_book_craftable").getBool()) { return; } ItemStack item = event.getItem(); if (isNormalBook(item)) { event.setCancelled(true); Player player = event.getEnchanter(); warning( "Prevented book enchant. This should not trigger. Watch player " + player.getName()); } } // Stop Cobble generation from lava+water private static final BlockFace[] faces_ = new BlockFace[] { BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN }; private BlockFace WaterAdjacentLava(Block lava_block) { for (BlockFace face : faces_) { Block block = lava_block.getRelative(face); Material material = block.getType(); if (material.equals(Material.WATER) || material.equals(Material.STATIONARY_WATER)) { return face; } } return BlockFace.SELF; } public void ConvertLava(Block block) { int data = (int)block.getData(); if (data == 0) { return; } Material material = block.getType(); if (!material.equals(Material.LAVA) && !material.equals(Material.STATIONARY_LAVA)) { return; } if (isLavaSourceNear(block, 3)) { return; } BlockFace face = WaterAdjacentLava(block); if (face == BlockFace.SELF) { return; } block.setType(Material.AIR); } public boolean isLavaSourceNear(Block block, int ttl) { int data = (int)block.getData(); if (data == 0) { Material material = block.getType(); if (material.equals(Material.LAVA) || material.equals(Material.STATIONARY_LAVA)) { return true; } } if (ttl <= 0) { return false; } for (BlockFace face : faces_) { Block child = block.getRelative(face); if (isLavaSourceNear(child, ttl - 1)) { return true; } } return false; } public void LavaAreaCheck(Block block, int ttl) { ConvertLava(block); if (ttl <= 0) { return; } for (BlockFace face : faces_) { Block child = block.getRelative(face); LavaAreaCheck(child, ttl - 1); } } @BahHumbugs ({ @BahHumbug(opt="cobble_from_lava"), @BahHumbug(opt="cobble_from_lava_scan_radius", type=OptType.Int, def="0") }) @EventHandler(priority = EventPriority.LOWEST) public void onBlockPhysicsEvent(BlockPhysicsEvent event) { if (config_.get("cobble_from_lava").getBool()) { return; } Block block = event.getBlock(); LavaAreaCheck(block, config_.get("cobble_from_lava_scan_radius").getInt()); } // Counteract 1.4.6 protection enchant nerf @BahHumbug(opt="scale_protection_enchant", def="true") @EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { if (!config_.get("scale_protection_enchant").getBool()) { return; } int damage = (int)event.getDamage(); if (damage <= 0) { return; } DamageCause cause = event.getCause(); if (!cause.equals(DamageCause.ENTITY_ATTACK) && !cause.equals(DamageCause.PROJECTILE)) { return; } Entity entity = event.getEntity(); if (!(entity instanceof Player)) { return; } Player defender = (Player)entity; PlayerInventory inventory = defender.getInventory(); int enchant_level = 0; for (ItemStack armor : inventory.getArmorContents()) { enchant_level += armor.getEnchantmentLevel(Enchantment.PROTECTION_ENVIRONMENTAL); } int damage_adjustment = 0; if (enchant_level >= 3 && enchant_level <= 6) { // 0 to 2 damage_adjustment = prng_.nextInt(3); } else if (enchant_level >= 7 && enchant_level <= 10) { // 0 to 3 damage_adjustment = prng_.nextInt(4); } else if (enchant_level >= 11 && enchant_level <= 14) { // 1 to 4 damage_adjustment = prng_.nextInt(4) + 1; } else if (enchant_level >= 15) { // 2 to 4 damage_adjustment = prng_.nextInt(3) + 2; } damage = Math.max(damage - damage_adjustment, 0); event.setDamage(damage); } @BahHumbug(opt="player_max_health", type=OptType.Int, def="20") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPlayerJoinEvent(PlayerJoinEvent event) { Player player = event.getPlayer(); player.setMaxHealth(config_.get("player_max_health").getInt()); } // Prevent entity dup bug @BahHumbug(opt="fix_rail_dup_bug", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPistonPushRail(BlockPistonExtendEvent e) { if (!config_.get("fix_rail_dup_bug").getBool()) { return; } for (Block b : e.getBlocks()) { Material t = b.getType(); if (t == Material.RAILS || t == Material.POWERED_RAIL || t == Material.DETECTOR_RAIL) { e.setCancelled(true); return; } } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onRailPlace(BlockPlaceEvent e) { if (!config_.get("fix_rail_dup_bug").getBool()) { return; } Block b = e.getBlock(); Material t = b.getType(); if (t == Material.RAILS || t == Material.POWERED_RAIL || t == Material.DETECTOR_RAIL) { for (BlockFace face : faces_) { t = b.getRelative(face).getType(); if (t == Material.PISTON_STICKY_BASE || t == Material.PISTON_EXTENSION || t == Material.PISTON_MOVING_PIECE || t == Material.PISTON_BASE) { e.setCancelled(true); return; } } } } // Give introduction book to n00bs @EventHandler public void OnPlayerFirstJoin(PlayerJoinEvent event){ Player player = event.getPlayer(); if (player.hasPlayedBefore()) { return; } giveN00bBook(player); } public void giveN00bBook(Player player) { Inventory inv = player.getInventory(); inv.addItem(createN00bBook()); } public ItemStack createN00bBook() { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta sbook = (BookMeta)book.getItemMeta(); sbook.setTitle(config_.getTitle()); sbook.setAuthor(config_.getAuthor()); sbook.setPages(config_.getPages()); book.setItemMeta(sbook); return book; } // Fix player in vehicle logout bug private static final int air_material_id_ = Material.AIR.getId(); @BahHumbug(opt="fix_vehicle_logout_bug", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onDisallowVehicleLogout(PlayerQuitEvent event) { if (!config_.get("fix_vehicle_logout_bug").getBool()) { return; } Player player = event.getPlayer(); Entity vehicle = player.getVehicle(); if (vehicle == null) { return; } Location loc = vehicle.getLocation(); World world = loc.getWorld(); // Vehicle data has been cached, now safe to kick the player out player.leaveVehicle(); // First attempt to place the player just above the vehicle // Normalize the location. Add 1 to Y so it is just above the minecart loc.setX(Math.floor(loc.getX()) + 0.5000); loc.setY(Math.floor(loc.getY()) + 1.0000); loc.setZ(Math.floor(loc.getZ()) + 0.5000); Block block = world.getBlockAt(loc); if (block.getTypeId() == air_material_id_) { block = block.getRelative(BlockFace.UP); if (block.getTypeId() == air_material_id_) { player.teleport(loc); Humbug.info(String.format( "Vehicle logout [%s]: Teleported to %s", player.getName(), loc.toString())); return; } } // The space above the cart was blocked. Scan from the top of the world down // and find 4 vertically contiguous AIR blocks resting above a non-AIR // block. The size is 4 to provide players a way to prevent griefers from // teleporting into small spaces (2 or 3 blocks high). Environment world_type = world.getEnvironment(); int max_height; if (world_type == Environment.NETHER) { max_height = 126; } else { max_height = world.getMaxHeight() - 2; } // Create a sliding window of block types and track how many of those // are AIR. Keep fetching the block below the current block to move down. int air_count = 0; LinkedList<Integer> air_window = new LinkedList<Integer>(); loc.setY((float)max_height); block = world.getBlockAt(loc); for (int i = 0; i < 4; ++i) { int block_type = block.getTypeId(); if (block_type == air_material_id_) { ++air_count; } air_window.addLast(block_type); block = block.getRelative(BlockFace.DOWN); } // Now that the window is prepared, scan down the Y-axis. // 3 to prevent bedrock pocket access while (block.getY() > 3) { int block_type = block.getTypeId(); if (block_type != air_material_id_) { if (air_count == 4) { // Normalize the location on the block's center. Y+1 which is the // first AIR above this block. loc = block.getLocation(); loc.setX(Math.floor(loc.getX()) + 0.5000); loc.setY(Math.floor(loc.getY()) + 1.0000); loc.setZ(Math.floor(loc.getZ()) + 0.5000); player.teleport(loc); Humbug.info(String.format( "Vehicle logout [%s]: Teleported to %s", player.getName(), loc.toString())); return; } } else { // block_type == air_material_id_ ++air_count; } air_window.addLast(block_type); if (air_window.removeFirst() == air_material_id_) { --air_count; } block = block.getRelative(BlockFace.DOWN); } // No space in this (x,z) column to teleport the player. Feed them // to the lions. Humbug.info(String.format( "Vehicle logout [%s]: No space for teleport, killed", player.getName())); player.setHealth(0); } // Playing records in jukeboxen? Gone // EventHandler registered in onPlayerInteract @BahHumbug(opt="disallow_record_playing", def="true") public void onRecordInJukebox(PlayerInteractEvent event) { if (!config_.get("disallow_record_playing").getBool()) { return; } Block cb = event.getClickedBlock(); if (cb == null || cb.getType() != Material.JUKEBOX) { return; } ItemStack his = event.getItem(); if(his != null && his.getType().isRecord()) { event.setCancelled(true); } } // Water in the nether? Nope. @BahHumbugs ({ @BahHumbug(opt="allow_water_in_nether"), @BahHumbug(opt="indestructible_end_portals", def="true") }) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerBucketEmptyEvent(PlayerBucketEmptyEvent e) { if(!config_.get("allow_water_in_nether").getBool()) { if( ( e.getBlockClicked().getBiome() == Biome.HELL ) && ( e.getBucket() == Material.WATER_BUCKET ) ) { e.setCancelled(true); e.getItemStack().setType(Material.BUCKET); e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, 5, 1)); } } if (config_.get("indestructible_end_portals").getBool()) { Block baseBlock = e.getBlockClicked(); BlockFace face = e.getBlockFace(); Block block = baseBlock.getRelative(face); if (block.getType() == Material.ENDER_PORTAL) { e.setCancelled(true); } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockFromToEvent(BlockFromToEvent e) { if(!config_.get("allow_water_in_nether").getBool()) { if( e.getToBlock().getBiome() == Biome.HELL ) { if( ( e.getBlock().getType() == Material.WATER ) || ( e.getBlock().getType() == Material.STATIONARY_WATER ) ) { e.setCancelled(true); } } } if (config_.get("indestructible_end_portals").getBool()) { if (e.getToBlock().getType() == Material.ENDER_PORTAL) { e.setCancelled(true); } } } // Nerfs Strength Potions to Pre-1.6 Levels @BahHumbugs ({ @BahHumbug(opt="nerf_strength", def="true") }) @EventHandler public void onPlayerDamage(EntityDamageByEntityEvent event) { if(!config_.get("nerf_strength").getBool()) { return; } if (!(event.getDamager() instanceof Player)) { return; } Player player = (Player)event.getDamager(); if (player.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) { for (PotionEffect Effect : player.getActivePotionEffects()) { if (Effect.getType().equals(PotionEffectType.INCREASE_DAMAGE)) { double DamagePercentage = (Effect.getAmplifier() + 1) * 1.3D + 1.0D; int NewDamage; if (event.getDamage() / DamagePercentage <= 1.0D) { NewDamage = (Effect.getAmplifier() + 1) * 3 + 1; } else { NewDamage = (int)(event.getDamage() / DamagePercentage) + (Effect.getAmplifier() + 1) * 3; } event.setDamage(NewDamage); break; } } } } // Buffs health splash to pre-1.6 levels @BahHumbugs ({ @BahHumbug(opt="buff_health", def="true") }) @EventHandler public void onPotionSplash(PotionSplashEvent event) { if(!config_.get("nerf_strength").getBool()) { return; } ThrownPotion p = event.getPotion(); for(PotionEffect effect : event.getEntity().getEffects()) { if(!(effect.getType().getName().equalsIgnoreCase("heal"))) { // Splash potion of poison return; } } for(LivingEntity entity : event.getAffectedEntities()) { if(entity instanceof Player) { entity.setHealth(entity.getHealth()+4); } } } // Bow shots cause slow debuff @BahHumbugs ({ @BahHumbug(opt="projectile_slow_chance", type=OptType.Int, def="30"), @BahHumbug(opt="projectile_slow_ticks", type=OptType.Int, def="100") }) @EventHandler public void onEDBE(EntityDamageByEntityEvent event) { int rate = config_.get("projectile_slow_chance").getInt(); if (rate <= 0 || rate > 100) { return; } if (!(event.getEntity() instanceof Player)) { return; } boolean damager_is_player_arrow = false; int chance_scaling = 0; Entity damager_entity = event.getDamager(); if (damager_entity != null) { // public LivingEntity CraftArrow.getShooter() // Playing this game to not have to take a hard dependency on // craftbukkit internals. try { Class<?> damager_class = damager_entity.getClass(); if (damager_class.getName().endsWith(".CraftArrow")) { Method getShooter = damager_class.getMethod("getShooter"); Object result = getShooter.invoke(damager_entity); if (result instanceof Player) { damager_is_player_arrow = true; String player_name = ((Player)result).getName(); if (bow_level_.containsKey(player_name)) { chance_scaling = bow_level_.get(player_name); } } } } catch(Exception ex) {} } if (!damager_is_player_arrow) { return; } rate += chance_scaling * 5; int percent = prng_.nextInt(100); if (percent < rate){ int ticks = config_.get("projectile_slow_ticks").getInt(); Player player = (Player)event.getEntity(); player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, ticks, 1, false)); } } // Used to track bow enchantment levels per player private Map<String, Integer> bow_level_ = new TreeMap<String, Integer>(); @EventHandler public void onEntityShootBow(EntityShootBowEvent event) { if (!(event.getEntity() instanceof Player)) { return; } int ench_level = 0; ItemStack bow = event.getBow(); Map<Enchantment, Integer> enchants = bow.getEnchantments(); for (Enchantment ench : enchants.keySet()) { int tmp_ench_level = 0; if (ench.equals(Enchantment.KNOCKBACK) || ench.equals(Enchantment.ARROW_KNOCKBACK)) { tmp_ench_level = enchants.get(ench) * 2; } else if (ench.equals(Enchantment.ARROW_DAMAGE)) { tmp_ench_level = enchants.get(ench); } if (tmp_ench_level > ench_level) { ench_level = tmp_ench_level; } } bow_level_.put( ((Player)event.getEntity()).getName(), ench_level); } // Change ender pearl velocity! @BahHumbug(opt="ender_pearl_launch_velocity", type=OptType.Double, def="1.0000001") @EventHandler public void onEnderPearlThrow(ProjectileLaunchEvent event) { Entity entity = (Entity)event.getEntity(); if (!(entity instanceof EnderPearl)) { return; } double adjustment = config_.get("ender_pearl_launch_velocity").getDouble(); if (adjustment < 1.00001 && adjustment > 0.99999) { return; } entity.setVelocity(entity.getVelocity().multiply(adjustment)); } // Ender pearl cooldown timer private class PearlTeleportInfo { public long last_teleport; public long teleport_count; public boolean notified_player; } private Map<String, PearlTeleportInfo> pearl_teleport_info_ = new TreeMap<String, PearlTeleportInfo>(); // EventHandler registered in onPlayerInteractAll public void onPlayerPearlTeleport(PlayerInteractEvent event) { if (!config_.get("ender_pearl_teleportation_throttled").getBool()) { return; } if (event.getItem() == null || !event.getItem().getType().equals(Material.ENDER_PEARL)) { return; } Action action = event.getAction(); if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) { return; } long current_time = System.currentTimeMillis(); String player_name = event.getPlayer().getName(); PearlTeleportInfo teleport_info = pearl_teleport_info_.get(player_name); if (teleport_info == null) { teleport_info = new PearlTeleportInfo(); teleport_info.teleport_count = 1; teleport_info.last_teleport = current_time; teleport_info.notified_player = false; } else { long time_diff = current_time - teleport_info.last_teleport; long block_window = teleport_info.teleport_count * 5000; if (block_window > 60000) { block_window = 60000; } if (block_window > time_diff) { if (!teleport_info.notified_player) { event.getPlayer().sendMessage(String.format( "Pearl Teleport Cooldown: %ds", (block_window - time_diff + 500) / 1000)); teleport_info.notified_player = true; } event.setCancelled(true); } else if (block_window + 10000 > time_diff) { teleport_info.teleport_count++; teleport_info.last_teleport = current_time; teleport_info.notified_player = false; } else { teleport_info.teleport_count = 1; teleport_info.last_teleport = current_time; teleport_info.notified_player = false; } } pearl_teleport_info_.put(player_name, teleport_info); } // BottleO refugees // Changes the yield from an XP bottle @BahHumbugs ({ @BahHumbug(opt="disable_experience", def="true"), @BahHumbug(opt="xp_per_bottle", type=OptType.Int, def="10") }) @EventHandler(priority=EventPriority.HIGHEST) public void onExpBottleEvent(ExpBottleEvent event) { final int bottle_xp = config_.get("xp_per_bottle").getInt(); if (config_.get("disable_experience").getBool()) { ((Player) event.getEntity().getShooter()).giveExp(bottle_xp); event.setExperience(0); } else { event.setExperience(bottle_xp); } } // Diables all XP gain except when manually changed via code. @EventHandler public void onPlayerExpChangeEvent(PlayerExpChangeEvent event) { if (config_.get("disable_experience").getBool()) { event.setAmount(0); } } // Find the end portals public static final int ender_portal_id_ = Material.ENDER_PORTAL.getId(); public static final int ender_portal_frame_id_ = Material.ENDER_PORTAL_FRAME.getId(); private Set<Long> end_portal_scanned_chunks_ = new TreeSet<Long>(); @BahHumbug(opt="find_end_portals", type=OptType.String) @EventHandler public void onFindEndPortals(ChunkLoadEvent event) { String scanWorld = config_.get("find_end_portals").getString(); if (scanWorld.isEmpty()) { return; } World world = event.getWorld(); if (!world.getName().equalsIgnoreCase(scanWorld)) { return; } Chunk chunk = event.getChunk(); long chunk_id = (long)chunk.getX() << 32L + (long)chunk.getZ(); if (end_portal_scanned_chunks_.contains(chunk_id)) { return; } end_portal_scanned_chunks_.add(chunk_id); int chunk_x = chunk.getX() * 16; int chunk_end_x = chunk_x + 16; int chunk_z = chunk.getZ() * 16; int chunk_end_z = chunk_z + 16; int max_height = 0; for (int x = chunk_x; x < chunk_end_x; x += 3) { for (int z = chunk_z; z < chunk_end_z; ++z) { int height = world.getMaxHeight(); if (height > max_height) { max_height = height; } } } for (int y = 1; y <= max_height; ++y) { int z_adj = 0; for (int x = chunk_x; x < chunk_end_x; ++x) { for (int z = chunk_z + z_adj; z < chunk_end_z; z += 3) { int block_type = world.getBlockTypeIdAt(x, y, z); if (block_type == ender_portal_id_ || block_type == ender_portal_frame_id_) { info(String.format("End portal found at %d,%d", x, z)); return; } } // This funkiness results in only searching 48 of the 256 blocks on // each y-level. 81.25% fewer blocks checked. ++z_adj; if (z_adj >= 3) { z_adj = 0; x += 2; } } } } // Prevent inventory access while in a vehicle, unless it's the Player's @BahHumbugs ({ @BahHumbug(opt="prevent_opening_container_carts", def="true"), @BahHumbug(opt="prevent_vehicle_inventory_open", def="true") }) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPreventVehicleInvOpen(InventoryOpenEvent event) { // Cheap break-able conditional statement while (config_.get("prevent_vehicle_inventory_open").getBool()) { HumanEntity human = event.getPlayer(); if (!(human instanceof Player)) { break; } if (!human.isInsideVehicle()) { break; } InventoryHolder holder = event.getInventory().getHolder(); if (holder == human) { break; } event.setCancelled(true); break; } if (config_.get("prevent_opening_container_carts").getBool() && !event.isCancelled()) { InventoryHolder holder = event.getInventory().getHolder(); if (holder instanceof StorageMinecart || holder instanceof HopperMinecart) { event.setCancelled(true); } } } // General public void onEnable() { registerEvents(); registerCommands(); loadConfiguration(); removeRecipies(); global_instance_ = this; info("Enabled"); } public boolean isInitiaized() { return global_instance_ != null; } public boolean toBool(String value) { if (value.equals("1") || value.equalsIgnoreCase("true")) { return true; } return false; } public int toInt(String value, int default_value) { try { return Integer.parseInt(value); } catch(Exception e) { return default_value; } } public double toDouble(String value, double default_value) { try { return Double.parseDouble(value); } catch(Exception e) { return default_value; } } public int toMaterialId(String value, int default_value) { try { return Integer.parseInt(value); } catch(Exception e) { Material mat = Material.matchMaterial(value); if (mat != null) { return mat.getId(); } } return default_value; } public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player && command.getName().equals("introbook")) { Player sendBookTo = (Player)sender; if (args.length >= 1) { Player possible = Bukkit.getPlayerExact(args[0]); if (possible != null) { sendBookTo = possible; } } giveN00bBook(sendBookTo); return true; } if (!(sender instanceof ConsoleCommandSender) || !command.getName().equals("humbug") || args.length < 1) { return false; } String option = args[0]; String value = null; String subvalue = null; boolean set = false; boolean subvalue_set = false; String msg = ""; if (args.length > 1) { value = args[1]; set = true; } if (args.length > 2) { subvalue = args[2]; subvalue_set = true; } ConfigOption opt = config_.get(option); if (opt != null) { if (set) { opt.set(value); } msg = String.format("%s = %s", option, opt.getString()); } else if (option.equals("debug")) { if (set) { config_.setDebug(toBool(value)); } msg = String.format("debug = %s", config_.getDebug()); } else if (option.equals("loot_multiplier")) { String entity_type = "generic"; if (set && subvalue_set) { entity_type = value; value = subvalue; } if (set) { config_.setLootMultiplier( entity_type, toInt(value, config_.getLootMultiplier(entity_type))); } msg = String.format( "loot_multiplier(%s) = %d", entity_type, config_.getLootMultiplier(entity_type)); } else if (option.equals("remove_mob_drops")) { if (set && subvalue_set) { if (value.equals("add")) { config_.addRemoveItemDrop(toMaterialId(subvalue, -1)); } else if (value.equals("del")) { config_.removeRemoveItemDrop(toMaterialId(subvalue, -1)); } } msg = String.format("remove_mob_drops = %s", config_.toDisplayRemoveItemDrops()); } else if (option.equals("save")) { config_.save(); msg = "Configuration saved"; } else if (option.equals("reload")) { config_.reload(); msg = "Configuration loaded"; } else { msg = String.format("Unknown option %s", option); } sender.sendMessage(msg); return true; } public void registerCommands() { ConsoleCommandSender console = getServer().getConsoleSender(); console.addAttachment(this, "humbug.console", true); } private void registerEvents() { getServer().getPluginManager().registerEvents(this, this); } private void loadConfiguration() { config_ = Config.initialize(this); } }
package com.njackson.application.modules; import android.content.Context; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.location.LocationManager; import android.util.Log; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.fitness.Fitness; import com.google.android.gms.fitness.RecordingApi; import com.google.android.gms.fitness.SessionsApi; import com.google.android.gms.location.ActivityRecognition; import com.njackson.activities.MainActivity; import com.njackson.activityrecognition.ActivityRecognitionIntentService; import com.njackson.activityrecognition.ActivityRecognitionServiceCommand; import com.njackson.analytics.IAnalytics; import com.njackson.analytics.Parse; import com.njackson.application.MainThreadBus; import com.njackson.application.PebbleBikeApplication; import com.njackson.activities.SettingsActivity; import com.njackson.changelog.CLChangeLog; import com.njackson.changelog.ChangeLogBuilder; import com.njackson.changelog.IChangeLog; import com.njackson.changelog.IChangeLogBuilder; import com.njackson.fit.GoogleFitServiceCommand; import com.njackson.fragments.AltitudeFragment; import com.njackson.fragments.SpeedFragment; import com.njackson.fragments.StartButtonFragment; import com.njackson.gps.GPSServiceCommand; import com.njackson.gps.IForegroundServiceStarter; import com.njackson.gps.MainServiceForegroundStarter; import com.njackson.hrm.Hrm; import com.njackson.hrm.HrmServiceCommand; import com.njackson.hrm.IHrm; import com.njackson.live.ILiveTracking; import com.njackson.live.LiveServiceCommand; import com.njackson.live.LiveTracking; import com.njackson.oruxmaps.IOruxMaps; import com.njackson.oruxmaps.OruxMaps; import com.njackson.oruxmaps.OruxMapsServiceCommand; import com.njackson.pebble.PebbleDataReceiver; import com.njackson.pebble.PebbleServiceCommand; import com.njackson.pebble.canvas.CanvasWrapper; import com.njackson.pebble.canvas.ICanvasWrapper; import com.njackson.service.IServiceCommand; import com.njackson.service.MainService; import com.njackson.state.GPSDataStore; import com.njackson.state.IGPSDataStore; import com.njackson.utils.AltitudeGraphReduce; import com.njackson.utils.BootUpReceiver; import com.njackson.utils.googleplay.GoogleFitSessionManager; import com.njackson.utils.googleplay.GooglePlayServices; import com.njackson.utils.googleplay.IGoogleFitSessionManager; import com.njackson.utils.googleplay.IGooglePlayServices; import com.njackson.utils.services.IServiceStarter; import com.njackson.utils.services.ServiceStarter; import com.njackson.pebble.IMessageManager; import com.njackson.pebble.MessageManager; import com.njackson.utils.time.ITime; import com.njackson.utils.time.ITimer; import com.njackson.utils.time.Time; import com.njackson.utils.time.Timer; import com.njackson.utils.version.AndroidVersion; import com.njackson.utils.version.PebbleVersion; import com.njackson.utils.watchface.IInstallWatchFace; import com.njackson.utils.watchface.InstallPebbleWatchFace; import com.squareup.otto.Bus; import com.squareup.otto.ThreadEnforcer; import java.util.Arrays; import java.util.List; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import de.cketti.library.changelog.ChangeLog; import static android.content.Context.LOCATION_SERVICE; import static android.content.Context.SENSOR_SERVICE; @Module(library = true,complete=false,injects = { PebbleBikeApplication.class, MainActivity.class, SettingsActivity.class, StartButtonFragment.class, SpeedFragment.class, AltitudeFragment.class, MainService.class, ActivityRecognitionIntentService.class, GPSServiceCommand.class, PebbleServiceCommand.class, LiveServiceCommand.class, OruxMapsServiceCommand.class, GoogleFitServiceCommand.class, ActivityRecognitionServiceCommand.class, PebbleDataReceiver.class, HrmServiceCommand.class, Hrm.class, SpeedFragment.class, MessageManager.class, BootUpReceiver.class, }) public class AndroidModule { private final String TAG = "PB-AndroidModule"; private PebbleBikeApplication application = null; public AndroidModule(){} public AndroidModule(PebbleBikeApplication application) { this.application = application; } /** * Allow the application context to be injected but require that it be annotated with * {@link ForApplication @Annotation} to explicitly differentiate it from an activity context. */ @Provides @Singleton @ForApplication Context provideApplicationContext() { return application; } @Provides @Singleton Bus providesBus() { return new MainThreadBus(new Bus(ThreadEnforcer.ANY)); } @Provides @Singleton LocationManager provideLocationManager() { return (LocationManager) application.getSystemService(LOCATION_SERVICE); } @Provides @Singleton SensorManager provideSensorManager() { return (SensorManager) application.getSystemService(SENSOR_SERVICE); } @Provides @Singleton SharedPreferences provideSharedPreferences() { return application.getSharedPreferences("com.njackson_preferences", Context.MODE_PRIVATE); } @Provides @Singleton IGPSDataStore providesGPSDataStore(SharedPreferences preferences) { return new GPSDataStore(preferences, application); } @Provides @Singleton @Named("GoogleActivity") GoogleApiClient provideActivityRecognitionClient() { return new GoogleApiClient.Builder(application).addApi(ActivityRecognition.API).build(); } @Provides @Singleton @Named("GoogleFit") GoogleApiClient provideFitnessAPIClient() { return new GoogleApiClient.Builder(application) .addApi(Fitness.API) .addScope(Fitness.SCOPE_ACTIVITY_READ) .addScope(Fitness.SCOPE_BODY_READ_WRITE) .build(); } @Provides IGoogleFitSessionManager providesGoogleFitSessionManager() { return new GoogleFitSessionManager(application, new GooglePlayServices(), Fitness.SessionsApi); } @Provides @Singleton IServiceStarter provideServiceStarter(Bus bus, SharedPreferences preferences) { return new ServiceStarter(application, preferences, bus); } @Provides @Singleton AltitudeGraphReduce providesAltitudeGraphReduce() { return new AltitudeGraphReduce(); } @Provides @Singleton public IMessageManager providesMessageManager(SharedPreferences preferences) { return new MessageManager(preferences, application); } @Provides IOruxMaps providesOruxMaps() { return new OruxMaps(application); } @Provides IHrm providesHrm() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { // BLE requires 4.3 (Api level 18) try { return new Hrm(application); } catch (NoClassDefFoundError e) { // bug with some 4.1/4.2 devices that report Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 !!! Log.e(TAG, "NoClassDefFoundError: " + e.getMessage()); return null; } } else { return null; } } @Provides @Named("LiveTrackingMmt") ILiveTracking provideLiveTrackingMmt() { return new LiveTracking(application, LiveTracking.TYPE_MMT, providesBus()); } @Provides @Named("LiveTrackingJayPS") ILiveTracking provideLiveTrackingJayps() { return new LiveTracking(application, LiveTracking.TYPE_JAYPS, providesBus()); } @Provides @Singleton IAnalytics providesAnalytics() { return new Parse(); } @Provides IInstallWatchFace providesWatchFaceInstall() { return new InstallPebbleWatchFace(new AndroidVersion(), new PebbleVersion()); } @Provides IGooglePlayServices providesGooglePlayServices() { return new GooglePlayServices(); } @Provides RecordingApi providesGoogleFitRecordingApi() { return Fitness.RecordingApi; } @Provides SessionsApi providesGoogleFitSessionsApi() { return Fitness.SessionsApi; } @Provides ITimer providesTimer() { return new Timer(); } @Provides ITime providesTime() { return new Time(); } @Provides IForegroundServiceStarter providesForegroundServiceStarter() { return new MainServiceForegroundStarter(); } @Provides ICanvasWrapper providesCanvasWrapper() { return new CanvasWrapper(); } @Provides IChangeLogBuilder providesChangeLogBuilder() { return new ChangeLogBuilder(); } @Provides List<IServiceCommand> providesServiceCommands() { return Arrays.asList( new GPSServiceCommand(), new PebbleServiceCommand(), new ActivityRecognitionServiceCommand(), new OruxMapsServiceCommand(), new LiveServiceCommand(), new GoogleFitServiceCommand(), new HrmServiceCommand() ); } }
package in.testpress.testpress.ui; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.widget.ImageView; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import in.testpress.core.TestpressSdk; import in.testpress.core.TestpressSession; import in.testpress.course.TestpressCourse; import in.testpress.exam.TestpressExam; import in.testpress.store.TestpressStore; import in.testpress.testpress.Injector; import in.testpress.testpress.R; import in.testpress.testpress.TestpressServiceProvider; import in.testpress.testpress.authenticator.LoginActivity; import in.testpress.testpress.authenticator.ResetPasswordActivity; import in.testpress.testpress.core.Constants; import in.testpress.testpress.core.TestpressService; import in.testpress.testpress.ui.utils.DeeplinkHandler; import in.testpress.testpress.util.CommonUtils; import in.testpress.testpress.util.UpdateAppDialogManager; import in.testpress.util.Assert; import in.testpress.util.ViewUtils; import static in.testpress.core.TestpressSdk.ACTION_PRESSED_HOME; import static in.testpress.core.TestpressSdk.COURSE_CONTENT_DETAIL_REQUEST_CODE; import static in.testpress.core.TestpressSdk.COURSE_CONTENT_LIST_REQUEST_CODE; import static in.testpress.course.TestpressCourse.CHAPTER_URL; import static in.testpress.course.TestpressCourse.COURSE_ID; import static in.testpress.store.TestpressStore.CONTINUE_PURCHASE; import static in.testpress.store.TestpressStore.STORE_REQUEST_CODE; import static in.testpress.testpress.BuildConfig.BASE_URL; import static in.testpress.testpress.core.Constants.Http.CHAPTERS_PATH; public class SplashScreenActivity extends Activity { @Inject protected TestpressServiceProvider serviceProvider; @InjectView(R.id.splash_image) ImageView splashImage; // Splash screen timer private static final int SPLASH_TIME_OUT = 2000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Injector.inject(this); ButterKnife.inject(this); UpdateAppDialogManager.monitor(this); final DeeplinkHandler deeplinkHandler = new DeeplinkHandler(this, serviceProvider); new Handler().postDelayed(new Runnable() { @Override public void run() { deeplinkHandler.handleDeepLinkUrl(getIntent().getData(), true); } }, SPLASH_TIME_OUT); } private void gotoHome() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); splashImage.setImageResource(R.drawable.splash_screen); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == STORE_REQUEST_CODE) { if (data != null && data.getBooleanExtra(CONTINUE_PURCHASE, false)) { // User pressed continue purchase button. TestpressSession session = TestpressSdk.getTestpressSession(this); assert session != null; TestpressStore.show(this, session); } else { // User pressed goto home button. gotoHome(); } } else { // Result code OK will come if attempted an exam & back press gotoHome(); } } else if (resultCode == RESULT_CANCELED) { if (data != null && data.getBooleanExtra(ACTION_PRESSED_HOME, false)) { TestpressSession testpressSession = TestpressSdk.getTestpressSession(this); Assert.assertNotNull("TestpressSession must not be null.", testpressSession); switch (requestCode) { case COURSE_CONTENT_DETAIL_REQUEST_CODE: case COURSE_CONTENT_LIST_REQUEST_CODE: int courseId = data.getIntExtra(COURSE_ID, 0); String chapterUrl = data.getStringExtra(CHAPTER_URL); if (chapterUrl != null) { // Show contents list or child chapters of the chapter url given TestpressCourse.showChapterContents(this, chapterUrl, testpressSession); return; } else if (courseId != 0) { // Show grand parent chapters list on home press from sub chapters list TestpressCourse.showChapters(this, null, courseId, testpressSession); return; } break; } // Go to home if user pressed home button & no other data passed in result intent gotoHome(); } else { gotoHome(); } } } }
package com.oracle.graal.phases.common; import static com.oracle.graal.phases.GraalOptions.*; import java.util.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.Graph.Mark; import com.oracle.graal.graph.iterators.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.StructuredGraph.GuardsStage; import com.oracle.graal.nodes.calc.*; import com.oracle.graal.nodes.cfg.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.schedule.*; import com.oracle.graal.phases.tiers.*; /** * Processes all {@link Lowerable} nodes to do their lowering. */ public class LoweringPhase extends BasePhase<PhaseContext> { final class LoweringToolImpl implements LoweringTool { private final PhaseContext context; private final NodeBitMap activeGuards; private GuardingNode guardAnchor; private FixedWithNextNode lastFixedNode; private ControlFlowGraph cfg; public LoweringToolImpl(PhaseContext context, GuardingNode guardAnchor, NodeBitMap activeGuards, FixedWithNextNode lastFixedNode, ControlFlowGraph cfg) { this.context = context; this.guardAnchor = guardAnchor; this.activeGuards = activeGuards; this.lastFixedNode = lastFixedNode; this.cfg = cfg; } @Override public ConstantReflectionProvider getConstantReflection() { return context.getConstantReflection(); } @Override public MetaAccessProvider getMetaAccess() { return context.getMetaAccess(); } @Override public LoweringProvider getLowerer() { return context.getLowerer(); } @Override public Replacements getReplacements() { return context.getReplacements(); } @Override public GuardingNode getCurrentGuardAnchor() { return guardAnchor; } @Override public GuardingNode createNullCheckGuard(GuardedNode guardedNode, ValueNode object) { if (ObjectStamp.isObjectNonNull(object)) { // Short cut creation of null check guard if the object is known to be non-null. return null; } StructuredGraph graph = guardedNode.asNode().graph(); if (graph.getGuardsStage().ordinal() > GuardsStage.FLOATING_GUARDS.ordinal()) { NullCheckNode nullCheck = graph.add(new NullCheckNode(object)); graph.addBeforeFixed((FixedNode) guardedNode, nullCheck); return nullCheck; } else { GuardingNode guard = createGuard(graph.unique(new IsNullNode(object)), DeoptimizationReason.NullCheckException, DeoptimizationAction.InvalidateReprofile, true); assert guardedNode.getGuard() == null; guardedNode.setGuard(guard); return guard; } } @Override public GuardingNode createGuard(LogicNode condition, DeoptimizationReason deoptReason, DeoptimizationAction action) { return createGuard(condition, deoptReason, action, false); } @Override public Assumptions assumptions() { return context.getAssumptions(); } @Override public GuardingNode createGuard(LogicNode condition, DeoptimizationReason deoptReason, DeoptimizationAction action, boolean negated) { if (condition.graph().getGuardsStage().ordinal() > StructuredGraph.GuardsStage.FLOATING_GUARDS.ordinal()) { throw new GraalInternalError("Cannot create guards after guard lowering"); } if (OptEliminateGuards.getValue()) { for (Node usage : condition.usages()) { if (!activeGuards.isNew(usage) && activeGuards.isMarked(usage) && ((GuardNode) usage).negated() == negated) { return (GuardNode) usage; } } } GuardNode newGuard = guardAnchor.asNode().graph().unique(new GuardNode(condition, guardAnchor, deoptReason, action, negated)); if (OptEliminateGuards.getValue()) { activeGuards.grow(); activeGuards.mark(newGuard); } return newGuard; } @Override public Block getBlockFor(Node node) { return cfg.blockFor(node); } public FixedWithNextNode lastFixedNode() { return lastFixedNode; } private void setLastFixedNode(FixedWithNextNode n) { assert n.isAlive() : n; lastFixedNode = n; } } private final CanonicalizerPhase canonicalizer; public LoweringPhase(CanonicalizerPhase canonicalizer) { this.canonicalizer = canonicalizer; } /** * Checks that second lowering of a given graph did not introduce any new nodes. * * @param graph a graph that was just {@linkplain #lower lowered} * @throws AssertionError if the check fails */ private boolean checkPostLowering(StructuredGraph graph, PhaseContext context) { Mark expectedMark = graph.getMark(); lower(graph, context, 1); Mark mark = graph.getMark(); assert mark.equals(expectedMark) : graph + ": a second round in the current lowering phase introduced these new nodes: " + graph.getNewNodes(expectedMark).snapshot(); return true; } @Override protected void run(final StructuredGraph graph, PhaseContext context) { lower(graph, context, 0); assert checkPostLowering(graph, context); } private void lower(StructuredGraph graph, PhaseContext context, int i) { IncrementalCanonicalizerPhase<PhaseContext> incrementalCanonicalizer = new IncrementalCanonicalizerPhase<>(canonicalizer); incrementalCanonicalizer.appendPhase(new Round(i, context)); incrementalCanonicalizer.apply(graph, context); assert graph.verify(); } /** * Checks that lowering of a given node did not introduce any new {@link Lowerable} nodes that * could be lowered in the current {@link LoweringPhase}. Such nodes must be recursively lowered * as part of lowering {@code node}. * * @param node a node that was just lowered * @param preLoweringMark the graph mark before {@code node} was lowered * @param unscheduledUsages set of {@code node}'s usages that were unscheduled before it was * lowered * @throws AssertionError if the check fails */ private static boolean checkPostNodeLowering(Node node, LoweringToolImpl loweringTool, Mark preLoweringMark, Collection<Node> unscheduledUsages) { StructuredGraph graph = (StructuredGraph) node.graph(); Mark postLoweringMark = graph.getMark(); NodeIterable<Node> newNodesAfterLowering = graph.getNewNodes(preLoweringMark); if (node instanceof FloatingNode) { if (!unscheduledUsages.isEmpty()) { for (Node n : newNodesAfterLowering) { assert !(n instanceof FixedNode) : node.graph() + ": cannot lower floatable node " + node + " as it introduces fixed node(s) but has the following unscheduled usages: " + unscheduledUsages; } } } for (Node n : newNodesAfterLowering) { if (n instanceof Lowerable) { ((Lowerable) n).lower(loweringTool); Mark mark = graph.getMark(); assert postLoweringMark.equals(mark) : graph + ": lowering of " + node + " produced lowerable " + n + " that should have been recursively lowered as it introduces these new nodes: " + graph.getNewNodes(postLoweringMark).snapshot(); } } return true; } private final class Round extends Phase { private final PhaseContext context; private final SchedulePhase schedule; private Round(int iteration, PhaseContext context) { super("LoweringIteration" + iteration); this.context = context; this.schedule = new SchedulePhase(); } @Override public void run(StructuredGraph graph) { schedule.apply(graph, false); processBlock(schedule.getCFG().getStartBlock(), graph.createNodeBitMap(), null); } private void processBlock(Block block, NodeBitMap activeGuards, GuardingNode parentAnchor) { GuardingNode anchor = parentAnchor; if (anchor == null) { anchor = block.getBeginNode(); } anchor = process(block, activeGuards, anchor); // Process always reached block first. Block alwaysReachedBlock = block.getPostdominator(); if (alwaysReachedBlock != null && alwaysReachedBlock.getDominator() == block) { processBlock(alwaysReachedBlock, activeGuards, anchor); } // Now go for the other dominators. for (Block dominated : block.getDominated()) { if (dominated != alwaysReachedBlock) { assert dominated.getDominator() == block; processBlock(dominated, activeGuards, null); } } if (parentAnchor == null && OptEliminateGuards.getValue()) { for (GuardNode guard : anchor.asNode().usages().filter(GuardNode.class)) { if (activeGuards.contains(guard)) { activeGuards.clear(guard); } } } } private GuardingNode process(final Block b, final NodeBitMap activeGuards, final GuardingNode startAnchor) { final LoweringToolImpl loweringTool = new LoweringToolImpl(context, startAnchor, activeGuards, b.getBeginNode(), schedule.getCFG()); // Lower the instructions of this block. List<ScheduledNode> nodes = schedule.nodesFor(b); for (Node node : nodes) { if (node.isDeleted()) { // This case can happen when previous lowerings deleted nodes. continue; } // Cache the next node to be able to reconstruct the previous of the next node // after lowering. FixedNode nextNode = null; if (node instanceof FixedWithNextNode) { nextNode = ((FixedWithNextNode) node).next(); } else { nextNode = loweringTool.lastFixedNode().next(); } if (node instanceof Lowerable) { Collection<Node> unscheduledUsages = null; assert (unscheduledUsages = getUnscheduledUsages(node)) != null; Mark preLoweringMark = node.graph().getMark(); ((Lowerable) node).lower(loweringTool); if (node == startAnchor && node.isDeleted()) { loweringTool.guardAnchor = BeginNode.prevBegin(nextNode); } assert checkPostNodeLowering(node, loweringTool, preLoweringMark, unscheduledUsages); } if (!nextNode.isAlive()) { // can happen when the rest of the block is killed by lowering // (e.g. by an unconditional deopt) break; } else { Node nextLastFixed = nextNode.predecessor(); if (!(nextLastFixed instanceof FixedWithNextNode)) { // insert begin node, to have a valid last fixed for next lowerable node. // This is about lowering a FixedWithNextNode to a control split while this // FixedWithNextNode is followed by some kind of BeginNode. // For example the when a FixedGuard followed by a loop exit is lowered to a // control-split + deopt. BeginNode begin = node.graph().add(new BeginNode()); nextLastFixed.replaceFirstSuccessor(nextNode, begin); begin.setNext(nextNode); nextLastFixed = begin; } loweringTool.setLastFixedNode((FixedWithNextNode) nextLastFixed); } } return loweringTool.getCurrentGuardAnchor(); } /** * Gets all usages of a floating, lowerable node that are unscheduled. * <p> * Given that the lowering of such nodes may introduce fixed nodes, they must be lowered in * the context of a usage that dominates all other usages. The fixed nodes resulting from * lowering are attached to the fixed node context of the dominating usage. This ensures the * post-lowering graph still has a valid schedule. * * @param node a {@link Lowerable} node */ private Collection<Node> getUnscheduledUsages(Node node) { List<Node> unscheduledUsages = new ArrayList<>(); if (node instanceof FloatingNode) { for (Node usage : node.usages()) { if (usage instanceof ScheduledNode) { Block usageBlock = schedule.getCFG().blockFor(usage); if (usageBlock == null) { unscheduledUsages.add(usage); } } } } return unscheduledUsages; } } }
package controllers; import com.basho.riak.client.IRiakClient; import com.basho.riak.client.RiakException; import com.basho.riak.client.RiakFactory; import com.basho.riak.client.RiakRetryFailedException; import com.basho.riak.client.bucket.Bucket; import com.google.common.base.Strings; import com.google.common.escape.Escaper; import com.google.common.html.HtmlEscapers; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Base64; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import models.CityList; import models.Dogpark; import models.DogparkSignup; import models.DogparkSignupList; import ninja.Result; import ninja.Results; import ninja.lifecycle.Dispose; import ninja.lifecycle.Start; import ninja.params.Param; import ninja.params.PathParam; import ninja.postoffice.Mail; import ninja.postoffice.Postoffice; import ninja.session.FlashScope; import ninja.utils.NinjaProperties; import org.slf4j.Logger; @Singleton public class DogparkController { public static final String RIAK_HOST = "riak.host"; public static final String RIAK_PORT = "riak.port"; public static final String BUCKET_NAME = "dogparkmeetups"; public static final String KEY_CITIES = "cities"; public static final String VIEW_404_NOT_FOUND = "views/system/404notFound.ftl.html"; // Guice injected fields private final Logger logger; private final NinjaProperties properties; private final Provider<Mail> mailProvider; private final Postoffice postoffice; private IRiakClient riakClient; private Bucket bucket; @Inject public DogparkController( Logger logger, NinjaProperties properties, Provider<Mail> mailProvider, Postoffice postoffice) { this.logger = logger; this.properties = properties; this.mailProvider = mailProvider; this.postoffice = postoffice; } @Start(order = 10) public void initRiakClientAndBucket() throws RiakException { String host = properties.getWithDefault(RIAK_HOST, "127.0.0.1"); int port = properties.getIntegerWithDefault(RIAK_PORT, 8087); logger.info("Initializing RiakClient on " + host + ":" + port + "..."); riakClient = RiakFactory.pbcClient(host, port); bucket = riakClient.fetchBucket(BUCKET_NAME).execute(); } @Dispose(order = 10) public void shutdownRiakClient() { if (riakClient != null) { logger.info("Shutting down RiakClient..."); riakClient.shutdown(); } } public Result allDogparks() throws RiakRetryFailedException { CityList cities = bucket.fetch(KEY_CITIES, CityList.class).execute(); List<Dogpark> dogparks = cities.stream() .flatMap(city -> city.dogparks.stream()) .collect(Collectors.toList()); return Results.json().render(dogparks); } public Result dogparkListPage() throws RiakRetryFailedException { CityList cities = bucket.fetch(KEY_CITIES, CityList.class).execute(); return Results.html().render("cities", cities); } public Result dogparkPage(@PathParam("id") String dogparkId) throws RiakRetryFailedException { if (dogparkId == null) { return Results.notFound().html().template(VIEW_404_NOT_FOUND); } Optional<Dogpark> dogpark = getDogparkFromDb(dogparkId); if (dogpark.isPresent()) { return Results.html().render("dogpark", dogpark.get()); } else { return Results.notFound().html().template(VIEW_404_NOT_FOUND); } } public Result dogparkSignups( @PathParam("id") String dogparkId, @Param("yearMonth") String yearMonth) throws RiakRetryFailedException { if (dogparkId == null) { return Results.notFound().json(); } Instant timeLower = YearMonth.parse(yearMonth) .atDay(1) .minusMonths(1) .atStartOfDay() .toInstant(ZoneOffset.UTC); Instant timeUpper = YearMonth.parse(yearMonth) .atDay(1) .plusMonths(6) .atStartOfDay() .toInstant(ZoneOffset.UTC); DogparkSignupList allSignups = bucket.fetch(dogparkId, DogparkSignupList.class).execute(); if (allSignups != null) { // Might very well be empty List<DogparkSignup> signups = allSignups.stream() .filter(signup -> { Instant arrival = signup.arrivalTime.toInstant(); return arrival.isAfter(timeLower) && arrival.isBefore(timeUpper); }) .peek(signup -> signup.cancellationCode = null) .sorted((signup1, signup2) -> signup1.arrivalTime.compareTo(signup2.arrivalTime)) .collect(Collectors.toList()); return Results.json().render(signups); } else { return Results.json().render(Collections.emptyList()); } } public Result signupPage( @PathParam("id") String dogparkId, @Param("date") String date) throws RiakRetryFailedException { // Parse to validate LocalDate localDate = LocalDate.parse(date.trim()); Optional<Dogpark> dogpark = getDogparkFromDb(dogparkId); if (dogpark.isPresent()) { return Results.html().render("dogpark", dogpark.get()).render("date", date); } return Results.notFound().html().template(VIEW_404_NOT_FOUND); } public Result doSignupPost( FlashScope flashScope, @PathParam("id") String dogparkId, @Param("date") String date, @Param("timeOfArrival") String timeOfArrival, @Param("email") String email, DogparkSignup newSignup) throws RiakRetryFailedException { Optional<Dogpark> dogpark = getDogparkFromDb(dogparkId); if (!dogpark.isPresent()) { return Results.notFound().html().template(VIEW_404_NOT_FOUND); } // Escape against HTML Escaper htmlEscaper = HtmlEscapers.htmlEscaper(); newSignup.dogBreed = htmlEscaper.escape(newSignup.dogBreed); newSignup.dogName = htmlEscaper.escape(newSignup.dogName); newSignup.dogWeightClass = htmlEscaper.escape(newSignup.dogWeightClass); // Generate UUID cancellation code newSignup.generateCancellationCode(); // Parse and set arrival time timeOfArrival = timeOfArrival.trim().replace('.', ':'); LocalDateTime arrivalTimestamp = LocalDateTime.parse(date + " " + timeOfArrival, DateTimeFormatter.ofPattern("yyyy-MM-dd H:m")); ZoneId zoneId = ZoneId.of("Europe/Helsinki"); newSignup.arrivalTime = Date.from(arrivalTimestamp.toInstant(ZonedDateTime.now(zoneId).getOffset())); // Add to signups list DogparkSignupList signups = bucket.fetch(dogparkId, DogparkSignupList.class).execute(); if (signups == null) { signups = new DogparkSignupList(); } signups.add(newSignup); bucket.store(dogparkId, signups).execute(); // If wanted, send cancellation code via email if (!Strings.isNullOrEmpty(email)) { try { sendCancellationCodeViaEmail(email, dogpark.get(), newSignup); } catch (Exception ex) { logger.error(ex.toString()); } } flashScope.put("signupSuccessfulMsg", getCancellationCodeMessage(dogpark.get(), newSignup)); return Results.redirect("/dogparks/" + dogparkId); } public Result doCancelSignupPost( FlashScope flashScope, @Param("cancellationCode") String publicCancellationCode) throws RiakRetryFailedException { boolean cancelSuccessful = false; String decoded; try { decoded = new String( Base64.getDecoder().decode(publicCancellationCode), StandardCharsets.ISO_8859_1 ); } catch (IllegalArgumentException iaex) { decoded = ""; } String[] parts = decoded.split(":"); if (parts.length >= 2) { String dogparkId = parts[0]; String cancellationCode = parts[1]; DogparkSignupList signups = bucket.fetch(dogparkId, DogparkSignupList.class).execute(); if (signups != null) { Optional<DogparkSignup> cancellableSignup = signups.stream() .filter(signup -> signup.cancellationCode.equals(cancellationCode)) .findFirst(); if (cancellableSignup.isPresent()) { signups.remove(cancellableSignup.get()); bucket.store(dogparkId, signups).execute(); cancelSuccessful = true; Optional<Dogpark> dogpark = getDogparkFromDb(dogparkId); flashScope.put("cancellationMsg", getCancellationSuccessMsg(dogpark.get(), cancellableSignup.get())); } } } if (cancelSuccessful) { flashScope.success("cancel.success"); } else { flashScope.error("cancel.invalidCancellationCode"); } return Results.redirect("/cancel"); } private Optional<Dogpark> getDogparkFromDb(String dogparkId) throws RiakRetryFailedException { Optional<Dogpark> dogpark = bucket.fetch(KEY_CITIES, CityList.class).execute().stream() .flatMap(city -> city.dogparks.stream()) .filter(park -> dogparkId.equalsIgnoreCase(park.id)) .findFirst(); return dogpark; } private void sendCancellationCodeViaEmail(String email, Dogpark dogpark, DogparkSignup signup) throws Exception { Mail mail = mailProvider.get(); mail.setSubject("Peruutuskoodi"); mail.addTo(email); mail.setFrom("koirapuistomiitit@gmail.com"); mail.setCharset("utf-8"); mail.setBodyText(getCancellationCodeMessage(dogpark, signup)); postoffice.send(mail); } private static String formPublicCancellationCode(String dogparkId, DogparkSignup signup) { String rawCode = dogparkId + ":" + signup.cancellationCode; String result = Base64.getEncoder().encodeToString(rawCode.getBytes(StandardCharsets.ISO_8859_1)); return result; } private static String getCancellationCodeMessage(Dogpark dogpark, DogparkSignup signup) { String publicCancellationCode = formPublicCancellationCode(dogpark.id, signup); return "Peruutuskoodisi koirapuiston \"" + dogpark.name + "\" ilmoittautumiseen \"" + signup.toString() + "\" on: " + publicCancellationCode; } private static String getCancellationSuccessMsg(Dogpark dogpark, DogparkSignup signup) { String publicCancellationCode = formPublicCancellationCode(dogpark.id, signup); return "Peruutettu koirapuiston \"" + dogpark.name + "\" ilmoittautuminen \"" + signup.toString() + "\"."; } }
package uk.ac.ebi.atlas.trader.cache.loader; import com.google.common.collect.Sets; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import uk.ac.ebi.atlas.experimentimport.ExperimentDAO; import uk.ac.ebi.atlas.experimentimport.ExperimentDTO; import uk.ac.ebi.atlas.model.experiment.ExperimentDesign; import uk.ac.ebi.atlas.model.experiment.ExperimentType; import uk.ac.ebi.atlas.model.Species; import uk.ac.ebi.atlas.model.experiment.differential.Contrast; import uk.ac.ebi.atlas.model.experiment.differential.microarray.MicroarrayExperiment; import uk.ac.ebi.atlas.model.experiment.differential.microarray.MicroarrayExperimentConfiguration; import uk.ac.ebi.atlas.trader.ArrayDesignTrader; import uk.ac.ebi.atlas.trader.ConfigurationTrader; import uk.ac.ebi.atlas.trader.SpeciesFactory; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class MicroarrayExperimentFactoryTest { private static final String ACCESSION = "accession"; private static final String ARRAYDESIGN_ID = "arraydesignId"; private static final String ARRAYDESIGN_NAME = "arraydesignName"; private static final String SPECIES_STRING = "species"; private static final Species SPECIES = new Species(SPECIES_STRING, SPECIES_STRING, "ensembl","kingdom"); private static final String ACCESS_KEY = "AN_UUID"; @Mock private ConfigurationTrader configurationTraderMock; @Mock private SpeciesFactory speciesFactory; @Mock private MicroarrayExperimentConfiguration experimentConfigurationMock; @Mock private ExperimentDTO experimentDTOMock; @Mock private Contrast contrastMock; @Mock private ExperimentDAO experimentDAOMock; @Mock private ExperimentDesign experimentDesignMock; @Mock private ArrayDesignTrader arrayDesignTraderMock; private MicroarrayExperimentFactory subject; @Before public void setUp() throws Exception { subject = new MicroarrayExperimentFactory(configurationTraderMock, speciesFactory, arrayDesignTraderMock); when(experimentDTOMock.getExperimentAccession()).thenReturn(ACCESSION); when(experimentDTOMock.getExperimentType()).thenReturn(ExperimentType.MICROARRAY_1COLOUR_MRNA_DIFFERENTIAL); when(experimentDTOMock.getAccessKey()).thenReturn(ACCESS_KEY); when(experimentDTOMock.getPubmedIds()).thenReturn(Sets.newHashSet("pubmed1")); when(speciesFactory.create(experimentDTOMock)).thenReturn(SPECIES); when(configurationTraderMock.getMicroarrayExperimentConfiguration(ACCESSION)).thenReturn(experimentConfigurationMock); when(experimentConfigurationMock.getContrasts()).thenReturn(Sets.newHashSet(contrastMock)); when(experimentConfigurationMock.getArrayDesignAccessions()).thenReturn(Sets.newTreeSet(Sets.newHashSet(ARRAYDESIGN_ID))); when(arrayDesignTraderMock.getArrayDesignNames(Sets.newTreeSet(Sets.newHashSet(ARRAYDESIGN_ID)))).thenReturn (Sets.newTreeSet(Sets.newHashSet(ARRAYDESIGN_NAME))); when(experimentDAOMock.findPublicExperiment(ACCESSION)).thenReturn(experimentDTOMock); } @Test public void testLoad() throws Exception { MicroarrayExperiment microarrayExperiment = subject.create(experimentDTOMock, "description", experimentDesignMock); assertThat(microarrayExperiment.getAccession(), is(ACCESSION)); assertThat(microarrayExperiment.getArrayDesignAccessions(), hasItem(ARRAYDESIGN_ID)); assertThat(microarrayExperiment.getSpecies(), is(SPECIES)); assertThat(microarrayExperiment.getExperimentDesign(), is(experimentDesignMock)); assertThat(microarrayExperiment.getArrayDesignNames(), hasItem(ARRAYDESIGN_NAME)); } }
package de.gymnew.sudoku.model; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Sudoku { private Field[][] fields; private Row[] rows; private Column[] columns; private Block[][] blocks; public Sudoku() { fields = new Field[9][9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { fields[i][j] = new Field(); } } // TODO Create Rows, Columns and Blocks } public Field getField(int column, int row) { return fields[column][row]; } @Override public Sudoku clone() { Sudoku sudoku = new Sudoku(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { Field src = fields[i][j]; Field dst = sudoku.getField(i, j); dst.setValue(src.getValue()); dst.addNotes(src.getNotes()); } } return null; } @Override public String toString() { String s = ""; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { s += fields[i][j].getValue(); } s += "|"; } return s; } private void load(String string) { // TODO Auto-generated method stub for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { string.charAt(); } } } public static Sudoku load(File file) throws IOException { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); Sudoku s = new Sudoku(); s.load(br.readLine()); br.close(); fr.close(); return s; } public void save(File file) throws IOException{ FileWriter fw = new FileWriter(file); fw.write(toString()); fw.flush(); fw.close(); } }
package no.hyper.dateintervalpicker; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class DateIntervalPicker extends Activity implements View.OnTouchListener{ private GridView calendar; private CalendarAdapter adapter; private Date fromDate, toDate; private int downPos; private ArrayList<LinearLayout> selectedItems; private int swipe; private static final int LEFT = -1; private static final int NONE = 0; private static final int RIGHT = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_date_interval_picker); calendar = (GridView) findViewById(R.id.calendar_grid); adapter = new CalendarAdapter(this, R.layout.date_item); calendar.setAdapter(adapter); calendar.setOnTouchListener(this); selectedItems = new ArrayList<LinearLayout>(); ((TextView) findViewById(R.id.month)).setText(adapter.getMonthString()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.date_interval_picker, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void changeMonth(View v) { if (v.getId() == R.id.next_month) { adapter.nextMonth(); } else if (v.getId() == R.id.prev_month) { adapter.previousMonth(); } ((TextView) findViewById(R.id.month)).setText(adapter.getMonthString()); } @Override public boolean onTouch(View view, MotionEvent e) { if (e.getActionMasked() == MotionEvent.ACTION_DOWN) { clearSelected(); downPos = calendar.pointToPosition((int) e.getX(), (int) e.getY()); if (downPos >= adapter.getStartPosition()) { selectItem(downPos); } return true; } if (e.getActionMasked() == MotionEvent.ACTION_MOVE) { int pos = calendar.pointToPosition((int)e.getX(),(int) e.getY()); if (pos > downPos) { swipe = RIGHT; clearSelected(); for (int i = downPos; i <= pos; i++) { selectItem(i); } } //pos is -1 if inside grid but on empty cell else if (pos < downPos && pos > -1) { swipe = LEFT; clearSelected(); //reverse adding to have the lowest date at index 0 for (int i = pos; i <= downPos; i++) { selectItem(i); } } paintSelected(); return true; } if (e.getActionMasked() == MotionEvent.ACTION_UP) { swipe = NONE; if ( ! selectedItems.isEmpty() ) { CharSequence dateDown = ((TextView) selectedItems.get(0).findViewById(R.id.date)).getText(); CharSequence dateUp = ((TextView) selectedItems.get(selectedItems.size() - 1).findViewById(R.id.date)).getText(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, adapter.getYear()); cal.set(Calendar.MONTH, adapter.getMonth()); cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt((String) dateDown)); fromDate = cal.getTime(); cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt((String) dateUp)); toDate = cal.getTime(); } return true; } return false; } private void selectItem(int position) { LinearLayout ll = (LinearLayout) calendar.getItemAtPosition(position); if ( ll != null && ll.isEnabled()) { selectedItems.add(ll); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void paintSelected() { if ( ! selectedItems.isEmpty() ) { if (selectedItems.size() == 1) { View v = selectedItems.get(0); v.setBackground(getResources().getDrawable(R.drawable.selected_single_item)); ((TextView) v.findViewById(R.id.date)).setTextColor(Color.WHITE); } else { View v = selectedItems.get(0); v.setBackground(getResources().getDrawable(R.drawable.selected_left_edge)); ((TextView) v.findViewById(R.id.date)).setTextColor(Color.WHITE); for (int i = 1; i < selectedItems.size() - 1; i++) { v = selectedItems.get(i); //make rounded corners on the edges of each week if (calendar.getPositionForView(v) % 7 == 6) { v.setBackground(getResources().getDrawable(R.drawable.selected_right_edge)); } else if (calendar.getPositionForView(v) % 7 == 0) { v.setBackground(getResources().getDrawable(R.drawable.selected_left_edge)); } else { v.setBackground(getResources().getDrawable(R.drawable.selected)); } ((TextView) v.findViewById(R.id.date)).setTextColor(Color.WHITE); } v = selectedItems.get(selectedItems.size() - 1); v.setBackground(getResources().getDrawable(R.drawable.selected_right_edge)); ((TextView) v.findViewById(R.id.date)).setTextColor(Color.WHITE); } } } private void clearSelected() { for ( LinearLayout ll : selectedItems ) { ll.setBackgroundColor(Color.WHITE); ((TextView) ll.findViewById(R.id.date)).setTextColor(Color.DKGRAY); } selectedItems.clear(); } public void confirm(View v) { if ( fromDate != null) { Intent intent = new Intent(); intent.putExtra("from", fromDate.getTime()); intent.putExtra("to", toDate.getTime()); this.setResult(100, intent); Toast.makeText(this, fromDate.toString() + " to " + toDate, Toast.LENGTH_LONG).show(); } else { this.setResult(-100); Toast.makeText(this, "No dates selected", Toast.LENGTH_LONG).show(); } this.finish(); } }
package org.openlmis.core.presenter; import android.support.annotation.Nullable; import com.google.inject.Inject; import org.openlmis.core.LMISApp; import org.openlmis.core.R; import org.openlmis.core.exceptions.LMISException; import org.openlmis.core.manager.MovementReasonManager; import org.openlmis.core.manager.SharedPreferenceMgr; import org.openlmis.core.model.DraftInventory; import org.openlmis.core.model.DraftLotItem; import org.openlmis.core.model.Inventory; import org.openlmis.core.model.LotOnHand; import org.openlmis.core.model.Product; import org.openlmis.core.model.StockCard; import org.openlmis.core.model.StockMovementItem; import org.openlmis.core.model.repository.InventoryRepository; import org.openlmis.core.model.repository.ProductRepository; import org.openlmis.core.model.repository.StockRepository; import org.openlmis.core.utils.DateUtil; import org.openlmis.core.view.BaseView; import org.openlmis.core.view.viewmodel.InventoryViewModel; import org.openlmis.core.view.viewmodel.LotMovementViewModel; import org.roboguice.shaded.goole.common.base.Function; import org.roboguice.shaded.goole.common.base.Predicate; import org.roboguice.shaded.goole.common.collect.FluentIterable; import org.roboguice.shaded.goole.common.collect.ImmutableList; import java.util.Comparator; import java.util.Date; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; import static org.roboguice.shaded.goole.common.collect.FluentIterable.from; public class InventoryPresenter extends Presenter { @Inject ProductRepository productRepository; @Inject StockRepository stockRepository; @Inject InventoryRepository inventoryRepository; @Inject SharedPreferenceMgr sharedPreferenceMgr; InventoryView view; @Override public void attachView(BaseView v) { view = (InventoryView) v; } public Observable<List<InventoryViewModel>> loadInventory() { return Observable.create(new Observable.OnSubscribe<List<InventoryViewModel>>() { @Override public void call(final Subscriber<? super List<InventoryViewModel>> subscriber) { try { List<Product> inventoryProducts = productRepository.listProductsArchivedOrNotInStockCard(); List<InventoryViewModel> availableStockCardsForAddNewDrug = from(inventoryProducts) .transform(new Function<Product, InventoryViewModel>() { @Override public InventoryViewModel apply(Product product) { return convertProductToStockCardViewModel(product); } }).toList(); subscriber.onNext(availableStockCardsForAddNewDrug); subscriber.onCompleted(); } catch (LMISException e) { e.reportToFabric(); subscriber.onError(e); } } }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()); } @Nullable private InventoryViewModel convertProductToStockCardViewModel(Product product) { try { InventoryViewModel viewModel; if (product.isArchived()) { viewModel = new InventoryViewModel(stockRepository.queryStockCardByProductId(product.getId())); } else { viewModel = new InventoryViewModel(product); } viewModel.setChecked(false); return viewModel; } catch (LMISException e) { e.reportToFabric(); } return null; } public Observable<List<InventoryViewModel>> loadPhysicalInventory() { return Observable.create(new Observable.OnSubscribe<List<InventoryViewModel>>() { @Override public void call(Subscriber<? super List<InventoryViewModel>> subscriber) { try { List<StockCard> validStockCardsForPhysicalInventory = getValidStockCardsForPhysicalInventory(); List<InventoryViewModel> inventoryViewModels = convertStockCardsToStockCardViewModels(validStockCardsForPhysicalInventory); restoreDraftInventory(inventoryViewModels); inventoryRepository.clearDraft(); subscriber.onNext(inventoryViewModels); subscriber.onCompleted(); } catch (LMISException e) { subscriber.onError(e); } } }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()); } private List<InventoryViewModel> convertStockCardsToStockCardViewModels(List<StockCard> validStockCardsForPhysicalInventory) { return FluentIterable.from(validStockCardsForPhysicalInventory).transform(new Function<StockCard, InventoryViewModel>() { @Override public InventoryViewModel apply(StockCard stockCard) { InventoryViewModel inventoryViewModel = new InventoryViewModel(stockCard); if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_lot_management)) { try { setExistingLotViewModels(inventoryViewModel); } catch (LMISException e) { e.reportToFabric(); } } return inventoryViewModel; } }).toList(); } private List<StockCard> getValidStockCardsForPhysicalInventory() throws LMISException { return from(stockRepository.list()).filter(new Predicate<StockCard>() { @Override public boolean apply(StockCard stockCard) { return !stockCard.getProduct().isKit() && stockCard.getProduct().isActive() && !stockCard.getProduct().isArchived(); } }).toList(); } protected void restoreDraftInventory(List<InventoryViewModel> inventoryViewModels) throws LMISException { List<DraftInventory> draftList = inventoryRepository.queryAllDraft(); for (InventoryViewModel model : inventoryViewModels) { for (DraftInventory draftInventory : draftList) { if (model.getStockCardId() == draftInventory.getStockCard().getId()) { model.initExpiryDates(draftInventory.getExpireDates()); model.setQuantity(formatQuantity(draftInventory.getQuantity())); if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_lot_management)) { populateLotMovementModelWithDraftLotItem(model, draftInventory); } } } } } private void populateLotMovementModelWithDraftLotItem(InventoryViewModel model, DraftInventory draftInventory) { List<LotMovementViewModel> existingLotMovementViewModelList = model.getExistingLotMovementViewModelList(); List<LotMovementViewModel> newAddedLotMovementVieModelList = model.getLotMovementViewModelList(); for (DraftLotItem draftLotItem : draftInventory.getDraftLotItemListWrapper()) { if (draftLotItem.isNewAdded()) { if (isNotInExistingLots(draftLotItem, existingLotMovementViewModelList)) { LotMovementViewModel newLotMovementViewModel = new LotMovementViewModel(); newLotMovementViewModel.setQuantity(draftLotItem.getQuantity().toString()); newLotMovementViewModel.setLotNumber(draftLotItem.getLotNumber()); newLotMovementViewModel.setExpiryDate(DateUtil.formatDate(draftLotItem.getExpirationDate(), DateUtil.DATE_FORMAT_ONLY_MONTH_AND_YEAR)); newAddedLotMovementVieModelList.add(newLotMovementViewModel); } } else { for (LotMovementViewModel existingLotMovementViewModel : existingLotMovementViewModelList) { if (draftLotItem.getLotNumber().equals(existingLotMovementViewModel.getLotNumber())) { existingLotMovementViewModel.setQuantity(draftLotItem.getQuantity().toString()); } } } } } private boolean isNotInExistingLots(DraftLotItem draftLotItem, List<LotMovementViewModel> existingLotMovementViewModelList) { for (LotMovementViewModel lotMovementViewModel : existingLotMovementViewModelList) { if (draftLotItem.getLotNumber().equals(lotMovementViewModel.getLotNumber())) { return false; } } return true; } private String formatQuantity(Long quantity) { return quantity == null ? "" : quantity.toString(); } protected void initOrArchiveBackStockCards(List<InventoryViewModel> list) { for (InventoryViewModel model : list) { if (model.isChecked()) { initOrArchiveBackStockCard(model); } } } private void initOrArchiveBackStockCard(InventoryViewModel model) { try { if (model.getProduct().isArchived()) { StockCard stockCard = model.getStockCard(); stockCard.getProduct().setArchived(false); stockRepository.updateStockCardWithProduct(stockCard); return; } if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_lot_management)) { createStockCardAndInventoryMovementWithLot(model); } else { createStockCardAndInventoryMovement(model); } } catch (LMISException e) { e.reportToFabric(); } } private void createStockCardAndInventoryMovementWithLot(InventoryViewModel model) throws LMISException { StockCard stockCard = new StockCard(); stockCard.setProduct(model.getProduct()); StockMovementItem movementItem = new StockMovementItem(stockCard, model); stockCard.setStockOnHand(movementItem.getStockOnHand()); stockRepository.addStockMovementAndUpdateStockCard(movementItem); } private StockCard createStockCardAndInventoryMovement(InventoryViewModel model) throws LMISException { StockCard stockCard = new StockCard(); stockCard.setProduct(model.getProduct()); stockCard.setStockOnHand(Long.parseLong(model.getQuantity())); if (stockCard.getStockOnHand() != 0) { stockCard.setExpireDates(DateUtil.formatExpiryDateString(model.getExpiryDates())); } else { stockCard.setExpireDates(""); } stockRepository.createOrUpdateStockCardWithStockMovement(stockCard); return stockCard; } protected StockMovementItem calculateAdjustment(InventoryViewModel model, StockCard stockCard) { long inventory; if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_lot_management)) { inventory = model.getLotListQuantityTotalAmount(); } else { inventory = Long.parseLong(model.getQuantity()); } long stockOnHand = model.getStockOnHand(); StockMovementItem item = new StockMovementItem(); item.setSignature(model.getSignature()); item.setMovementDate(new Date()); item.setMovementQuantity(Math.abs(inventory - stockOnHand)); item.setStockOnHand(inventory); item.setStockCard(stockCard); if (inventory > stockOnHand) { item.setReason(MovementReasonManager.INVENTORY_POSITIVE); item.setMovementType(MovementReasonManager.MovementType.POSITIVE_ADJUST); } else if (inventory < stockOnHand) { item.setReason(MovementReasonManager.INVENTORY_NEGATIVE); item.setMovementType(MovementReasonManager.MovementType.NEGATIVE_ADJUST); } else { item.setReason(MovementReasonManager.INVENTORY); item.setMovementType(MovementReasonManager.MovementType.PHYSICAL_INVENTORY); } if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_lot_management)) { ImmutableList<LotMovementViewModel> existingLotMovementViewModelList = FluentIterable.from(model.getExistingLotMovementViewModelList()).filter(new Predicate<LotMovementViewModel>() { @Override public boolean apply(LotMovementViewModel lotMovementViewModel) { return lotMovementViewModel.quantityGreaterThanZero(); } }).toList(); item.populateLotAndResetStockOnHandOfLotAccordingPhysicalAdjustment(existingLotMovementViewModelList, model.getLotMovementViewModelList()); } return item; } public void savePhysicalInventory(List<InventoryViewModel> list) { view.loading(); Subscription subscription = saveDraftInventoryObservable(list).subscribe(nextMainPageAction, errorAction); subscriptions.add(subscription); } private Observable<Object> saveDraftInventoryObservable(final List<InventoryViewModel> list) { return Observable.create(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> subscriber) { try { for (InventoryViewModel model : list) { inventoryRepository.createDraft(model.parseDraftInventory()); } subscriber.onNext(null); subscriber.onCompleted(); } catch (LMISException e) { subscriber.onError(e); e.reportToFabric(); } } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); } public void signPhysicalInventory() { if (view.validateInventory()) { view.showSignDialog(); } } public void doPhysicalInventory(List<InventoryViewModel> list, final String sign) { view.loading(); for (InventoryViewModel viewModel : list) { viewModel.setSignature(sign); } Subscription subscription = stockMovementObservable(list).subscribe(nextMainPageAction, errorAction); subscriptions.add(subscription); } protected Observable<Object> stockMovementObservable(final List<InventoryViewModel> list) { return Observable.create(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> subscriber) { try { for (InventoryViewModel model : list) { StockCard stockCard = model.getStockCard(); if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_lot_management)) { stockCard.setStockOnHand(model.getLotListQuantityTotalAmount()); } else { stockCard.setStockOnHand(Long.parseLong(model.getQuantity())); } if (stockCard.getStockOnHand() == 0) { stockCard.setExpireDates(""); } stockRepository.addStockMovementAndUpdateStockCard(calculateAdjustment(model, stockCard)); } inventoryRepository.clearDraft(); sharedPreferenceMgr.setLatestPhysicInventoryTime(DateUtil.formatDate(new Date(), DateUtil.DATE_TIME_FORMAT)); saveInventoryDate(); subscriber.onNext(null); subscriber.onCompleted(); } catch (LMISException e) { subscriber.onError(e); e.reportToFabric(); } } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); } private void saveInventoryDate() { inventoryRepository.save(new Inventory()); } protected Action1<Object> nextMainPageAction = new Action1<Object>() { @Override public void call(Object o) { view.loaded(); view.goToParentPage(); } }; protected Action1<Throwable> errorAction = new Action1<Throwable>() { @Override public void call(Throwable throwable) { view.loaded(); view.showErrorMessage(throwable.getMessage()); } }; public void doInitialInventory(final List<InventoryViewModel> list) { if (view.validateInventory()) { view.loading(); Subscription subscription = initStockCardObservable(list).subscribe(nextMainPageAction); subscriptions.add(subscription); } } protected Observable<Object> initStockCardObservable(final List<InventoryViewModel> list) { return Observable.create(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> subscriber) { initOrArchiveBackStockCards(list); subscriber.onNext(null); subscriber.onCompleted(); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); } private void setExistingLotViewModels(InventoryViewModel inventoryViewModel) throws LMISException { ImmutableList<LotMovementViewModel> lotMovementViewModels = null; try { lotMovementViewModels = FluentIterable.from(stockRepository.getNonEmptyLotOnHandByStockCard(inventoryViewModel.getStockCard().getId())).transform(new Function<LotOnHand, LotMovementViewModel>() { @Override public LotMovementViewModel apply(LotOnHand lotOnHand) { return new LotMovementViewModel(lotOnHand.getLot().getLotNumber(), DateUtil.formatDate(lotOnHand.getLot().getExpirationDate(), DateUtil.DATE_FORMAT_ONLY_MONTH_AND_YEAR), lotOnHand.getQuantityOnHand().toString(), MovementReasonManager.MovementType.RECEIVE); } }).toSortedList(new Comparator<LotMovementViewModel>() { @Override public int compare(LotMovementViewModel lot1, LotMovementViewModel lot2) { return DateUtil.parseString(lot1.getExpiryDate(), DateUtil.DATE_FORMAT_ONLY_MONTH_AND_YEAR).compareTo(DateUtil.parseString(lot2.getExpiryDate(), DateUtil.DATE_FORMAT_ONLY_MONTH_AND_YEAR)); } }); } catch (LMISException e) { e.printStackTrace(); } inventoryViewModel.setExistingLotMovementViewModelList(lotMovementViewModels); } public interface InventoryView extends BaseView { void goToParentPage(); boolean validateInventory(); void showErrorMessage(String msg); void showSignDialog(); } }
package <%=packageName%>.domain; <% if (databaseType == 'sql') { %>import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Type;<% } %> import org.joda.time.LocalDateTime;<% if (databaseType == 'nosql') { %> import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field;<% } %><% if (databaseType == 'sql') { %> import javax.persistence.*;<% } %> import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; /** * Persist AuditEvent managed by the Spring Boot actuator * @see org.springframework.boot.actuate.audit.AuditEvent */ <% if (databaseType == 'sql') { %>@Entity @Table(name = "T_PERSISTENT_AUDIT_EVENT") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)<% } %><% if (databaseType == 'nosql') { %> @Document(collection = "T_PERSISTENT_AUDIT_EVENT")<% } %> public class PersistentAuditEvent { @Id<% if (databaseType == 'sql') { %> @GeneratedValue(strategy = GenerationType.TABLE) @Column(name = "event_id") private Long id;<% } else { %> @Field("event_id") private long id;<% } %> @NotNull<% if (databaseType == 'sql') { %> @Column(nullable = false)<% } %> private String principal; <% if (databaseType == 'sql') { %>@Column(name = "event_date") @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")<% } %> private LocalDateTime auditEventDate; <% if (databaseType == 'sql') { %> @Column(name = "event_type")<% } %><% if (databaseType == 'nosql') { %> @Field("event_type")<% } %> private String auditEventType; <% if (databaseType == 'sql') { %>@ElementCollection @MapKeyColumn(name="name") @Column(name="value") @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))<% } %> private Map<String, String> data = new HashMap<>(); <% if (databaseType == 'sql') { %> public Long getId() { return id; } public void setId(Long id) { this.id = id; }<% } else { %> public long getId() { return id; } public void setId(Long id) { this.id = id; }<% } %> public String getPrincipal() { return principal; } public void setPrincipal(String principal) { this.principal = principal; } public LocalDateTime getAuditEventDate() { return auditEventDate; } public void setAuditEventDate(LocalDateTime auditEventDate) { this.auditEventDate = auditEventDate; } public String getAuditEventType() { return auditEventType; } public void setAuditEventType(String auditEventType) { this.auditEventType = auditEventType; } public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data; } }
package fr.pierrelemee; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import fr.pierrelemee.route.RouteMatching; import fr.pierrelemee.route.RouterException; import java.io.IOException; import java.net.InetSocketAddress; public class WebApplication implements HttpHandler { private static final Integer DEFAULT_PORT = 8123; protected Router router; protected Renderer renderer; protected SessionManager sessionManager; public WebApplication() { this(new Router()); } public WebApplication(Router router) { this(router, null, null); } public WebApplication(Renderer renderer) { this(new Router(), null, renderer); } public WebApplication(SessionManager sessionManager) { this(new Router(), sessionManager); } public WebApplication(Router router, Renderer renderer) { this(router, null, renderer); } public WebApplication(SessionManager sessionManager, Renderer renderer) { this(new Router(), sessionManager, renderer); } public WebApplication(Router router, SessionManager sessionManager) { this(router, sessionManager, null); } public WebApplication(Router router, SessionManager sessionManager, Renderer renderer) { this.router = router; this.renderer = renderer; this.sessionManager = sessionManager; } public void addController(Controller controller) throws RouterException { for (Route route : controller.routes()) { this.router.addRoute(route); } } public void handle(HttpExchange exchange) throws IOException { WebResponse response = this.process(WebRequest.fromExchange(exchange)); exchange.getResponseHeaders().putAll(response.getHeaders()); exchange.sendResponseHeaders(response.getStatus(), response.getBody().getBytes().length); exchange.getResponseBody().write(response.getBody().getBytes()); exchange.getResponseBody().flush(); exchange.getResponseBody().close(); } public WebResponse onRequest (WebRequest request, Session session) { // Override if needed return null; } public void onResponse (WebResponse response, Session session) { if (session != null && !session.isSent()) { response.addCookie(Cookie.Builder.create(this.sessionManager.getSessionCookieName()).setValue(session.getHash()).build()); } } public WebResponse process(WebRequest request) { System.out.println("Requested: " + request.getPath()); Session session = this.sessionManager != null ? this.sessionManager.extract(request) : null; WebResponse response = this.onRequest(request, session); if (response == null) { response = this.getResponse(request, session); } this.onResponse(response, session); if (this.renderer != null && response.getTemplate() != null) { response.writeBody(this.renderer.render(response.getTemplate())); } return response; } protected WebResponse getResponse(WebRequest request, Session session) { RouteMatching matching = this.router.match(request); if (matching.hasRoute()) { try { request.addVariables(matching.getVariables()); return matching.getRoute().getProcess().process(request, session); } catch (Exception e) { e.printStackTrace(); return WebResponse .status(500) .writeBody("Internal server error"); } } return WebResponse .status(404) .writeBody("Not found"); } public void start() throws Exception { this.start(DEFAULT_PORT); } public void start(int port) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", this); server.setExecutor(null); server.start(); } }
package io.kaitai.struct; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.util.Arrays; import java.util.zip.DataFormatException; import java.util.zip.Inflater; public abstract class KaitaiStream implements Closeable { protected int bitsLeft = 0; protected long bits = 0; @Override abstract public void close() throws IOException; //region Stream positioning /** * Check if stream pointer is at the end of stream. * @return true if we are located at the end of the stream */ abstract public boolean isEof(); /** * Set stream pointer to designated position (int). * @param newPos new position (offset in bytes from the beginning of the stream) */ abstract public void seek(int newPos); /** * Set stream pointer to designated position (long). * @param newPos new position (offset in bytes from the beginning of the stream) */ abstract public void seek(long newPos); /** * Get current position of a stream pointer. * @return pointer position, number of bytes from the beginning of the stream */ abstract public int pos(); /** * Get total size of the stream in bytes. * @return size of the stream in bytes */ abstract public long size(); //endregion //region Integer numbers //region Signed /** * Reads one signed 1-byte integer, returning it properly as Java's "byte" type. * @return 1-byte integer read from a stream */ abstract public byte readS1(); //region Big-endian abstract public short readS2be(); abstract public int readS4be(); abstract public long readS8be(); //endregion //region Little-endian abstract public short readS2le(); abstract public int readS4le(); abstract public long readS8le(); //endregion //endregion //region Unsigned abstract public int readU1(); //region Big-endian abstract public int readU2be(); abstract public long readU4be(); /** * Reads one unsigned 8-byte integer in big-endian encoding. As Java does not * have a primitive data type to accomodate it, we just reuse {@link #readS8be()}. * @return 8-byte signed integer (pretending to be unsigned) read from a stream */ public long readU8be() { return readS8be(); } //endregion //region Little-endian abstract public int readU2le(); abstract public long readU4le(); /** * Reads one unsigned 8-byte integer in little-endian encoding. As Java does not * have a primitive data type to accomodate it, we just reuse {@link #readS8le()}. * @return 8-byte signed integer (pretending to be unsigned) read from a stream */ public long readU8le() { return readS8le(); } //endregion //endregion //endregion //region Floating point numbers //region Big-endian abstract public float readF4be(); abstract public double readF8be(); //endregion //region Little-endian abstract public float readF4le(); abstract public double readF8le(); //endregion //endregion //region Unaligned bit values public void alignToByte() { bits = 0; bitsLeft = 0; } public long readBitsIntBe(int n) { int bitsNeeded = n - bitsLeft; if (bitsNeeded > 0) { // 1 bit => 1 byte // 8 bits => 1 byte // 9 bits => 2 bytes int bytesNeeded = ((bitsNeeded - 1) / 8) + 1; byte[] buf = readBytes(bytesNeeded); for (byte b : buf) { bits <<= 8; // b is signed byte, convert to unsigned using "& 0xff" trick bits |= (b & 0xff); bitsLeft += 8; } } // raw mask with required number of 1s, starting from lowest bit long mask = getMaskOnes(n); // shift "bits" to align the highest bits with the mask & derive the result int shiftBits = bitsLeft - n; long res = (bits >>> shiftBits) & mask; // clear top bits that we've just read => AND with 1s bitsLeft -= n; mask = getMaskOnes(bitsLeft); bits &= mask; return res; } /** * Unused since Kaitai Struct Compiler v0.9+ - compatibility with older versions * * @deprecated use {@link #readBitsIntBe(int)} instead */ @Deprecated public long readBitsInt(int n) { return readBitsIntBe(n); } public long readBitsIntLe(int n) { int bitsNeeded = n - bitsLeft; if (bitsNeeded > 0) { // 1 bit => 1 byte // 8 bits => 1 byte // 9 bits => 2 bytes int bytesNeeded = ((bitsNeeded - 1) / 8) + 1; byte[] buf = readBytes(bytesNeeded); for (byte b : buf) { bits |= ((long) (b & 0xff) << bitsLeft); bitsLeft += 8; } } // raw mask with required number of 1s, starting from lowest bit long mask = getMaskOnes(n); // derive reading result long res = bits & mask; // remove bottom bits that we've just read by shifting bits >>>= n; bitsLeft -= n; return res; } private static long getMaskOnes(int n) { if (n == 64) { return 0xffffffffffffffffL; } else { return (1L << n) - 1; } } //endregion //region Byte arrays /** * Reads designated number of bytes from the stream. * @param n number of bytes to read * @return read bytes as byte array */ abstract public byte[] readBytes(long n); /** * Reads all the remaining bytes in a stream as byte array. * @return all remaining bytes in a stream as byte array */ abstract public byte[] readBytesFull(); abstract public byte[] readBytesTerm(int term, boolean includeTerm, boolean consumeTerm, boolean eosError); /** * Checks that next bytes in the stream match match expected fixed byte array. * It does so by determining number of bytes to compare, reading them, and doing * the actual comparison. If they differ, throws a {@link UnexpectedDataError} * runtime exception. * @param expected contents to be expected * @return read bytes as byte array, which are guaranteed to equal to expected * @throws UnexpectedDataError if read data from stream isn't equal to given data * @deprecated Not used anymore in favour of validators. */ @Deprecated public byte[] ensureFixedContents(byte[] expected) { byte[] actual = readBytes(expected.length); if (!Arrays.equals(actual, expected)) throw new UnexpectedDataError(actual, expected); return actual; } public static byte[] bytesStripRight(byte[] bytes, byte padByte) { int newLen = bytes.length; while (newLen > 0 && bytes[newLen - 1] == padByte) newLen return Arrays.copyOf(bytes, newLen); } public static byte[] bytesTerminate(byte[] bytes, byte term, boolean includeTerm) { int newLen = 0; int maxLen = bytes.length; while (newLen < maxLen && bytes[newLen] != term) newLen++; if (includeTerm && newLen < maxLen) newLen++; return Arrays.copyOf(bytes, newLen); } /** * Checks if supplied number of bytes is a valid number of elements for Java * byte array: converts it to int, if it is, or throws an exception if it is not. * @param n number of bytes for byte array as long * @return number of bytes, converted to int */ protected int toByteArrayLength(long n) { if (n > Integer.MAX_VALUE) { throw new IllegalArgumentException( "Java byte arrays can be indexed only up to 31 bits, but " + n + " size was requested" ); } if (n < 0) { throw new IllegalArgumentException( "Byte array size can't be negative, but " + n + " size was requested" ); } return (int) n; } //endregion //region Byte array processing /** * Performs a XOR processing with given data, XORing every byte of input with a single * given value. * @param data data to process * @param key value to XOR with * @return processed data */ public static byte[] processXor(byte[] data, int key) { int dataLen = data.length; byte[] r = new byte[dataLen]; for (int i = 0; i < dataLen; i++) r[i] = (byte) (data[i] ^ key); return r; } /** * Performs a XOR processing with given data, XORing every byte of input with a key * array, repeating key array many times, if necessary (i.e. if data array is longer * than key array). * @param data data to process * @param key array of bytes to XOR with * @return processed data */ public static byte[] processXor(byte[] data, byte[] key) { int dataLen = data.length; int valueLen = key.length; byte[] r = new byte[dataLen]; int j = 0; for (int i = 0; i < dataLen; i++) { r[i] = (byte) (data[i] ^ key[j]); j = (j + 1) % valueLen; } return r; } /** * Performs a circular left rotation shift for a given buffer by a given amount of bits, * using groups of groupSize bytes each time. Right circular rotation should be performed * using this procedure with corrected amount. * @param data source data to process * @param amount number of bits to shift by * @param groupSize number of bytes per group to shift * @return copy of source array with requested shift applied */ public static byte[] processRotateLeft(byte[] data, int amount, int groupSize) { byte[] r = new byte[data.length]; switch (groupSize) { case 1: for (int i = 0; i < data.length; i++) { byte bits = data[i]; r[i] = (byte) (((bits & 0xff) << amount) | ((bits & 0xff) >>> (8 - amount))); } break; default: throw new UnsupportedOperationException("unable to rotate group of " + groupSize + " bytes yet"); } return r; } private final static int ZLIB_BUF_SIZE = 4096; /** * Performs an unpacking ("inflation") of zlib-compressed data with usual zlib headers. * @param data data to unpack * @return unpacked data * @throws RuntimeException if data can't be decoded */ public static byte[] processZlib(byte[] data) { Inflater ifl = new Inflater(); ifl.setInput(data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[ZLIB_BUF_SIZE]; while (!ifl.finished()) { try { int decBytes = ifl.inflate(buf); baos.write(buf, 0, decBytes); } catch (DataFormatException e) { throw new RuntimeException(e); } } ifl.end(); return baos.toByteArray(); } //endregion //region Misc runtime operations /** * Performs modulo operation between two integers: dividend `a` * and divisor `b`. Divisor `b` is expected to be positive. The * result is always 0 &lt;= x &lt;= b - 1. * @param a dividend * @param b divisor * @return result */ public static int mod(int a, int b) { if (b <= 0) throw new ArithmeticException("mod divisor <= 0"); int r = a % b; if (r < 0) r += b; return r; } /** * Performs modulo operation between two integers: dividend `a` * and divisor `b`. Divisor `b` is expected to be positive. The * result is always 0 &lt;= x &lt;= b - 1. * @param a dividend * @param b divisor * @return result */ public static long mod(long a, long b) { if (b <= 0) throw new ArithmeticException("mod divisor <= 0"); long r = a % b; if (r < 0) r += b; return r; } /** * Compares two byte arrays in lexicographical order. Makes extra effort * to compare bytes properly, as *unsigned* bytes, i.e. [0x90] would be * greater than [0x10]. * @param a first byte array to compare * @param b second byte array to compare * @return negative number if a &lt; b, 0 if a == b, positive number if a &gt; b * @see Comparable#compareTo(Object) */ public static int byteArrayCompare(byte[] a, byte[] b) { if (a == b) return 0; int al = a.length; int bl = b.length; int minLen = Math.min(al, bl); for (int i = 0; i < minLen; i++) { int cmp = (a[i] & 0xff) - (b[i] & 0xff); if (cmp != 0) return cmp; } // Reached the end of at least one of the arrays if (al == bl) { return 0; } else { return al - bl; } } /** * Finds the minimal byte in a byte array, treating bytes as * unsigned values. * @param b byte array to scan * @return minimal byte in byte array as integer */ public static int byteArrayMin(byte[] b) { int min = Integer.MAX_VALUE; for (int i = 0; i < b.length; i++) { int value = b[i] & 0xff; if (value < min) min = value; } return min; } /** * Finds the maximal byte in a byte array, treating bytes as * unsigned values. * @param b byte array to scan * @return maximal byte in byte array as integer */ public static int byteArrayMax(byte[] b) { int max = 0; for (int i = 0; i < b.length; i++) { int value = b[i] & 0xff; if (value > max) max = value; } return max; } //endregion /** * Exception class for an error that occurs when some fixed content * was expected to appear, but actual data read was different. * * @deprecated Not used anymore in favour of {@code Validation*}-exceptions. */ @Deprecated public static class UnexpectedDataError extends RuntimeException { public UnexpectedDataError(byte[] actual, byte[] expected) { super( "Unexpected fixed contents: got " + byteArrayToHex(actual) + ", was waiting for " + byteArrayToHex(expected) ); } private static String byteArrayToHex(byte[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i > 0) sb.append(' '); sb.append(String.format("%02x", arr[i])); } return sb.toString(); } } /** * Error that occurs when default endianness should be decided with a * switch, but nothing matches (although using endianness expression * implies that there should be some positive result). */ public static class UndecidedEndiannessError extends RuntimeException {} /** * Common ancestor for all error originating from Kaitai Struct usage. * Stores KSY source path, pointing to an element supposedly guilty of * an error. */ public static class KaitaiStructError extends RuntimeException { public KaitaiStructError(String msg, String srcPath) { super(srcPath + ": " + msg); this.srcPath = srcPath; } protected String srcPath; } /** * Common ancestor for all validation failures. Stores pointer to * KaitaiStream IO object which was involved in an error. */ public static class ValidationFailedError extends KaitaiStructError { public ValidationFailedError(String msg, KaitaiStream io, String srcPath) { super("at pos " + io.pos() + ": validation failed: " + msg, srcPath); this.io = io; } protected KaitaiStream io; protected static String byteArrayToHex(byte[] arr) { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < arr.length; i++) { if (i > 0) sb.append(' '); sb.append(String.format("%02x", arr[i])); } sb.append(']'); return sb.toString(); } } /** * Signals validation failure: we required "actual" value to be equal to * "expected", but it turned out that it's not. */ public static class ValidationNotEqualError extends ValidationFailedError { public ValidationNotEqualError(byte[] expected, byte[] actual, KaitaiStream io, String srcPath) { super("not equal, expected " + byteArrayToHex(expected) + ", but got " + byteArrayToHex(actual), io, srcPath); } public ValidationNotEqualError(Object expected, Object actual, KaitaiStream io, String srcPath) { super("not equal, expected " + expected + ", but got " + actual, io, srcPath); } protected Object expected; protected Object actual; } public static class ValidationLessThanError extends ValidationFailedError { public ValidationLessThanError(byte[] expected, byte[] actual, KaitaiStream io, String srcPath) { super("not in range, min " + byteArrayToHex(expected) + ", but got " + byteArrayToHex(actual), io, srcPath); } public ValidationLessThanError(Object min, Object actual, KaitaiStream io, String srcPath) { super("not in range, min " + min + ", but got " + actual, io, srcPath); } protected Object min; protected Object actual; } public static class ValidationGreaterThanError extends ValidationFailedError { public ValidationGreaterThanError(byte[] expected, byte[] actual, KaitaiStream io, String srcPath) { super("not in range, max " + byteArrayToHex(expected) + ", but got " + byteArrayToHex(actual), io, srcPath); } public ValidationGreaterThanError(Object max, Object actual, KaitaiStream io, String srcPath) { super("not in range, max " + max + ", but got " + actual, io, srcPath); } protected Object max; protected Object actual; } public static class ValidationNotAnyOfError extends ValidationFailedError { public ValidationNotAnyOfError(Object actual, KaitaiStream io, String srcPath) { super("not any of the list, got " + actual, io, srcPath); } protected Object actual; } public static class ValidationExprError extends ValidationFailedError { public ValidationExprError(Object actual, KaitaiStream io, String srcPath) { super("not matching the expression, got " + actual, io, srcPath); } protected Object actual; } }
package io.praesid.livestats; import lombok.EqualsAndHashCode; import lombok.ToString; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import java.util.Arrays; import java.util.concurrent.locks.StampedLock; @ThreadSafe @ToString(exclude = {"lock", "initLock"}) @EqualsAndHashCode(exclude = {"lock", "initLock", "positionDeltas"}) public final class Quantile { private static final int N_MARKERS = 5; // positionDeltas and idealPositions must be updated if this is changed private transient final StampedLock lock; private transient final StampedLock initLock; // Immutable once set, how far the ideal positions move for each item. Use getPositionDeltas to lazy load it // length of positionDeltas and idealPositions is N_MARKERS-1 because the lowest idealPosition is always 1 private transient double[] positionDeltas; @GuardedBy("lock") private final double[] idealPositions; @GuardedBy("lock") private final double[] positions = {1, 2, 3, 4, 5}; @GuardedBy("lock") private final double[] heights = new double[N_MARKERS]; @GuardedBy("initLock,lock") // guarded by both write locks, so either read lock guarantees visibility private int initializedMarkers = 0; public final double percentile; /** * Constructs a single quantile object */ public Quantile(double percentile) { this.lock = new StampedLock(); this.initLock = new StampedLock(); this.percentile = percentile; idealPositions = new double[]{1 + 2 * percentile, 1 + 4 * percentile, 3 + 2 * percentile, 5}; } /** * This constructor is for Gson. It initializes the locks. The other values will be overridden by Gson. */ private Quantile() { this.lock = new StampedLock(); this.initLock = new StampedLock(); this.percentile = Double.NaN; this.idealPositions = null; } private double[] getPositionDeltas() { if (positionDeltas == null) { positionDeltas = new double[]{percentile / 2, percentile, (1 + percentile) / 2, 1}; } return positionDeltas; } /** * @return The current approximation of the configured quantile. */ public double quantile() { final long optimisticStamp = lock.tryOptimisticRead(); double quantile = heights[initializedMarkers / 2]; // Let's just accept that this is not accurate pre init if (!lock.validate(optimisticStamp)) { final long readStamp = lock.readLock(); quantile = heights[initializedMarkers / 2]; lock.unlock(readStamp); } return quantile; } /** * Decays the currently recorded and ideal positions by decayMultiplier */ public void decay(final double decayMultiplier) { if (decayMultiplier == 1) { return; } final long writeStamp = lock.writeLock(); if (initializedMarkers == N_MARKERS) { for (int i = 0; i < idealPositions.length; i++) { idealPositions[i] *= decayMultiplier; positions[i + 1] *= decayMultiplier; } } lock.unlock(writeStamp); } /** * Adds another datum */ public void add(final double item, final double targetMin, final double targetMax) { final long writeStamp = lock.writeLock(); try { if (initializedMarkers < N_MARKERS) { // As noted, either lock gives visibility, both are taken for write heights[initializedMarkers] = item; final long initWriteStamp = initLock.writeLock(); initializedMarkers++; initLock.unlock(initWriteStamp); Arrays.sort(heights, 0, initializedMarkers); // Always sort, simplifies quantile() initially return; } if (targetMax > heights[N_MARKERS - 2]) { heights[N_MARKERS - 1] = targetMax; } else { heights[N_MARKERS - 1] = heights[N_MARKERS - 2] + Math.ulp(heights[N_MARKERS - 2]); } if (targetMin < heights[1]) { heights[0] = targetMin; } else { heights[0] = heights[1] - Math.ulp(heights[1]); } positions[N_MARKERS - 1]++; // Because marker N_MARKERS-1 is max, it always gets incremented for (int i = N_MARKERS - 2; heights[i] > item; i--) { // Increment all other markers > item positions[i]++; } for (int i = 0; i < idealPositions.length; i++) { idealPositions[i] += getPositionDeltas()[i]; // updated desired positions } adjust(); } finally { lock.unlock(writeStamp); } } private void adjust() { for (int i = 1; i < N_MARKERS - 1; i++) { final double position = positions[i]; final double positionDelta = idealPositions[i - 1] - position; if ((positionDelta >= 1 && positions[i + 1] > position + 1) || (positionDelta <= -1 && positions[i - 1] < position - 1)) { final int direction = positionDelta > 0 ? 1 : -1; final double heightBelow = heights[i - 1]; // q(i-1) final double height = heights[i]; final double heightAbove = heights[i + 1]; // q(i+1) final double positionBelow = positions[i - 1]; // n(i-1) final double positionAbove = positions[i + 1]; // n(i+1) // q + d / (n(i+1) - n(i-1)) * // ((n - n(i-1) + d) * (q(i+1) - q) / (n(i+1) - n) + (n(i+1) - n - d) * (q - q(i-1)) / (n - n(i-1))) final double signedPositionRange = direction / (positionAbove - positionBelow); final double xBelow = position - positionBelow; final double xAbove = positionAbove - position; final double upperHalf = (xBelow + direction) * (heightAbove - height) / xAbove; final double lowerHalf = (xAbove - direction) * (height - heightBelow) / xBelow; final double newHeight = height + signedPositionRange * (upperHalf + lowerHalf); if (heightBelow < newHeight && newHeight < heightAbove) { heights[i] = newHeight; } else { // use linear form final double rise = heights[i + direction] - height; final double run = positions[i + direction] - position; heights[i] = height + Math.copySign(rise / run, direction); } positions[i] = position + direction; } } } }
package io.projectreactor; import groovy.text.markup.MarkupTemplateEngine; import groovy.text.markup.TemplateConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import ratpack.error.ClientErrorHandler; import ratpack.func.Action; import ratpack.groovy.Groovy; import ratpack.groovy.template.internal.MarkupTemplateRenderer; import ratpack.handling.Chain; import ratpack.spring.config.EnableRatpack; import java.util.HashMap; import java.util.Map; /** * Main Application for the Project Reactor home site. */ @Configuration @ComponentScan @EnableAutoConfiguration @EnableRatpack public class Application { private static final Logger LOG = LoggerFactory.getLogger(Application.class); private static final String CURRENT_VERSION = "2.0.1.RELEASE"; @Bean public MarkupTemplateEngine markupTemplateEngine() { TemplateConfiguration config = new TemplateConfiguration(); config.setAutoIndent(true); config.setAutoNewLine(true); config.setCacheTemplates(false); return new MarkupTemplateEngine(config); } @Bean public MarkupTemplateRenderer markupTemplateRenderer() { return new MarkupTemplateRenderer(markupTemplateEngine()); } @Bean public ClientErrorHandler clientErrorHandler() { return (ctx, statusCode) -> { LOG.error("client error: {}", statusCode); }; } @Bean public Action<Chain> ratpack() { return chain -> { chain.get("", ctx -> { Map<String, Object> model = createModel("Home", "home"); ctx.render(Groovy.groovyMarkupTemplate(model, "templates/index.gtpl")); }).get("docs/reference/streams.html", ctx -> { ctx.redirect("index.html"); }); }; } public static void main(String... args) { SpringApplication.run(Application.class, args); } private static final Map<String, Object> createModel(String title, String type) { Map<String, Object> model = new HashMap<>(); model.put("title", title); model.put("type", type); model.put("currentVersion", CURRENT_VERSION); return model; } }
package landmaster.plustic.util; import java.lang.invoke.*; import java.lang.reflect.*; import java.util.*; import java.util.Optional; import org.apache.commons.lang3.*; import org.apache.commons.lang3.StringUtils; import com.google.common.base.*; import landmaster.plustic.*; import landmaster.plustic.api.*; import landmaster.plustic.block.*; import landmaster.plustic.fluids.*; import net.darkhax.tesla.capability.*; import net.minecraft.block.*; import net.minecraft.block.state.*; import net.minecraft.entity.*; import net.minecraft.entity.player.*; import net.minecraft.item.*; import net.minecraft.network.play.server.*; import net.minecraft.potion.*; import net.minecraft.util.*; import net.minecraft.util.math.*; import net.minecraft.world.*; import net.minecraftforge.energy.*; import net.minecraftforge.fluids.*; import net.minecraftforge.fml.common.*; import net.minecraftforge.fml.common.registry.*; import net.minecraftforge.oredict.*; import slimeknights.tconstruct.smeltery.block.*; import slimeknights.tconstruct.library.*; import slimeknights.tconstruct.library.materials.*; import slimeknights.tconstruct.library.modifiers.Modifier; public class Utils { private static final Map<String, Material> tinkerMaterials; static { try { Field temp = TinkerRegistry.class.getDeclaredField("materials"); temp.setAccessible(true); tinkerMaterials = (Map<String, Material>) MethodHandles.lookup().unreflectGetter(temp).invokeExact(); } catch (Throwable e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } } private static final Map<String, ModContainer> tinkerMaterialRegisteredByMod; static { try { Field temp = TinkerRegistry.class.getDeclaredField("materialRegisteredByMod"); temp.setAccessible(true); tinkerMaterialRegisteredByMod = (Map<String, ModContainer>) MethodHandles.lookup().unreflectGetter(temp) .invokeExact(); } catch (Throwable e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } } public static void forceOut(String material) { if (tinkerMaterials.remove(material) != null) { PlusTiC.log.info(String.format("Forcing out material %s", material)); } } public static void forceOutModsMaterial(String material, String... anyOfTheseModids) { Optional.ofNullable(tinkerMaterialRegisteredByMod.get(material)) .filter(cont -> ArrayUtils.contains(anyOfTheseModids, cont.getModId())) .ifPresent(cont -> forceOut(material)); } /** * Pushes a material into a lower priority. * * @param displace * the identifier of the material to be pushed */ public static void displace(String displace) { Material displaced = tinkerMaterials.remove(displace); tinkerMaterials.put(displace, displaced); } public static boolean matchesOre(ItemStack is, String od) { return OreDictionary.doesOreNameExist(od) && !is.isEmpty() && ArrayUtils.contains(OreDictionary.getOreIDs(is), OreDictionary.getOreID(od)); } public static AxisAlignedBB AABBfromVecs(Vec3d v1, Vec3d v2) { return new AxisAlignedBB(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z); } /** * Based on * {@link slimeknights.tconstruct.library.utils.EntityUtil#raytraceEntityPlayerLook(EntityPlayer, float)}, * except with a predicate to filter out unwanted entities. */ public static RayTraceResult raytraceEntityPlayerLookWithPred(EntityPlayer player, float range, Predicate<? super Entity> pred) { Vec3d eye = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ); // Entity.getPositionEyes Vec3d look = player.getLook(1.0f); return raytraceEntityWithPred(player, eye, look, range, true, pred); } /** * Based on * {@link slimeknights.tconstruct.library.utils.EntityUtil#raytraceEntity(Entity, Vec3d, Vec3d, double, boolean)}, * except with a predicate to filter out unwanted entities. */ public static RayTraceResult raytraceEntityWithPred(Entity entity, Vec3d start, Vec3d look, double range, boolean ignoreCanBeCollidedWith, Predicate<? super Entity> pred) { // Vec3 look = entity.getLook(partialTicks); Vec3d direction = start.addVector(look.x * range, look.y * range, look.z * range); // Vec3 direction = vec3.addVector(vec31.x * d0, vec31.y * d0, vec31.z * Entity pointedEntity = null; Vec3d hit = null; AxisAlignedBB bb = entity.getEntityBoundingBox().expand(look.x * range, look.y * range, look.z * range) .expand(1, 1, 1); List<Entity> entitiesInArea = entity.getEntityWorld().getEntitiesInAABBexcluding(entity, bb, Predicates.and(pred, EntitySelectors.NOT_SPECTATING)); double range2 = range; // range to the current candidate. Used to find // the closest entity. for (Entity candidate : entitiesInArea) { if (ignoreCanBeCollidedWith || candidate.canBeCollidedWith()) { // does our vector go through the entity? double colBorder = candidate.getCollisionBorderSize(); AxisAlignedBB entityBB = candidate.getEntityBoundingBox().expand(colBorder, colBorder, colBorder); RayTraceResult movingobjectposition = entityBB.calculateIntercept(start, direction); // needs special casing: vector starts inside the entity if (entityBB.contains(start)) { if (0.0D < range2 || range2 == 0.0D) { pointedEntity = candidate; hit = movingobjectposition == null ? start : movingobjectposition.hitVec; range2 = 0.0D; } } else if (movingobjectposition != null) { double dist = start.distanceTo(movingobjectposition.hitVec); if (dist < range2 || range2 == 0.0D) { if (candidate == entity.getRidingEntity() && !entity.canRiderInteract()) { if (range2 == 0.0D) { pointedEntity = candidate; hit = movingobjectposition.hitVec; } } else { pointedEntity = candidate; hit = movingobjectposition.hitVec; range2 = dist; } } } } } if (pointedEntity != null && range2 < range) { return new RayTraceResult(pointedEntity, hit); } return null; } public static void addModifierItem(Modifier modifier, String modid, String name) { addModifierItem(modifier, modid, name, 0); } public static void addModifierItem(Modifier modifier, String modid, String name, int meta) { addModifierItem(modifier, modid, name, meta, 1, 1); } public static void addModifierItem(Modifier modifier, String modid, String name, int meta, int needed, int matched) { if (modifier == null) return; ItemStack is = new ItemStack(Item.REGISTRY.getObject(new ResourceLocation(modid, name)), 1, meta); modifier.addItem(is, needed, matched); } public static FluidMolten fluidMetal(String name, int color) { return registerFluid(new FluidMolten(name, color)); } public static void initFluidMetal(Fluid fluid) { registerMoltenBlock(fluid); FluidRegistry.addBucketForFluid(fluid); PlusTiC.proxy.registerFluidModels(fluid); } public static <T extends Fluid> T registerFluid(T fluid) { fluid.setUnlocalizedName(ModInfo.MODID + "." + fluid.getName().toLowerCase(Locale.US)); FluidRegistry.registerFluid(fluid); return fluid; } public static <T extends Block> T registerBlock(T block, String name) { block.setUnlocalizedName(ModInfo.MODID + "." + name); block.setRegistryName(ModInfo.MODID + "." + name); Item ib = new ItemBlock(block).setRegistryName(block.getRegistryName()); ForgeRegistries.BLOCKS.register(block); ForgeRegistries.ITEMS.register(ib); return block; } public static BlockMolten registerMoltenBlock(Fluid fluid) { BlockMolten block = new BlockMolten(fluid); return registerBlock(block, "molten_" + fluid.getName()); } public static void setDispItem(Material mat, String modid, String name) { if (mat == null) return; mat.setRepresentativeItem(Item.REGISTRY.getObject(new ResourceLocation(modid, name))); } public static void setDispItem(Material mat, String modid, String name, int meta) { if (mat == null) return; ItemStack is = new ItemStack(Item.REGISTRY.getObject(new ResourceLocation(modid, name)), 1, meta); mat.setRepresentativeItem(is); } public static void setDispItem(Material mat, String ore) { List<ItemStack> ores = OreDictionary.getOres(ore); if (mat == null || ores.isEmpty()) return; mat.setRepresentativeItem(ores.get(0)); } public static int gcd(int a, int b, int... rest) { if (rest.length > 0) { int[] rest1 = new int[rest.length - 1]; System.arraycopy(rest, 1, rest1, 0, rest1.length); return gcd(gcd(a, b), rest[0], rest1); } return b == 0 ? a : gcd(b, a % b); } public static void teleportPlayerTo(EntityPlayerMP player, Coord4D coord) { if (player.dimension != coord.dimensionId) { int id = player.dimension; WorldServer oldWorld = player.mcServer.getWorld(player.dimension); player.dimension = coord.dimensionId; WorldServer newWorld = player.mcServer.getWorld(player.dimension); player.connection.sendPacket(new SPacketRespawn(player.dimension, player.getEntityWorld().getDifficulty(), newWorld.getWorldInfo().getTerrainType(), player.interactionManager.getGameType())); oldWorld.removeEntityDangerously(player); player.isDead = false; if (player.isEntityAlive()) { newWorld.spawnEntity(player); player.setLocationAndAngles(coord.xCoord + 0.5, coord.yCoord + 1, coord.zCoord + 0.5, player.rotationYaw, player.rotationPitch); newWorld.updateEntityWithOptionalForce(player, false); player.setWorld(newWorld); } player.mcServer.getPlayerList().preparePlayer(player, oldWorld); player.connection.setPlayerLocation(coord.xCoord + 0.5, coord.yCoord + 1, coord.zCoord + 0.5, player.rotationYaw, player.rotationPitch); player.interactionManager.setWorld(newWorld); player.mcServer.getPlayerList().updateTimeAndWeatherForPlayer(player, newWorld); player.mcServer.getPlayerList().syncPlayerInventory(player); for (PotionEffect potioneffect : player.getActivePotionEffects()) { player.connection.sendPacket(new SPacketEntityEffect(player.getEntityId(), potioneffect)); } player.connection.sendPacket( new SPacketSetExperience(player.experience, player.experienceTotal, player.experienceLevel)); // Force // sync FMLCommonHandler.instance().firePlayerChangedDimensionEvent(player, id, coord.dimensionId); } else { player.connection.setPlayerLocation(coord.xCoord + 0.5, coord.yCoord + 1, coord.zCoord + 0.5, player.rotationYaw, player.rotationPitch); } } private static final MethodHandle getCollisionBoundingBoxM; static { try { MethodHandle temp; try { temp = MethodHandles.lookup().findVirtual(IBlockState.class, "func_185890_d", MethodType.methodType(AxisAlignedBB.class, IBlockAccess.class, BlockPos.class)); } catch (NoSuchMethodException e) { temp = MethodHandles.lookup().findVirtual(IBlockState.class, "func_185890_d", MethodType.methodType(AxisAlignedBB.class, World.class, BlockPos.class)); } getCollisionBoundingBoxM = temp; } catch (Throwable e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } } public static AxisAlignedBB getCollisionBoundingBox(IBlockState state, World world, BlockPos pos) { try { return (AxisAlignedBB) getCollisionBoundingBoxM.invoke(state, world, pos); } catch (Throwable e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } } public static boolean canTeleportTo(EntityPlayer player, Coord4D dest) { if (dest == null) return false; for (int i = 1; i <= 2; ++i) { if (getCollisionBoundingBox(dest.add(0, i, 0).blockState(), dest.world(), dest.pos()) != null) { return false; } } return true; } public static int extractEnergy(ItemStack is, int amount, boolean simulate) { if (is != null) { if (is.hasCapability(CapabilityEnergy.ENERGY, null)) { return is.getCapability(CapabilityEnergy.ENERGY, null).extractEnergy(amount, simulate); } if (Loader.isModLoaded("tesla") && is.hasCapability(TeslaCapabilities.CAPABILITY_PRODUCER, null)) { return (int) is.getCapability(TeslaCapabilities.CAPABILITY_PRODUCER, null).takePower(amount, simulate); } } return 0; } public static class ItemMatGroup { public Item nugget, ingot; public Block block; public ItemMatGroup() { } public ItemMatGroup(Item nugget, Item ingot, Block block) { this.nugget = nugget; this.ingot = ingot; this.block = block; } } public static ItemMatGroup registerMatGroup(String name) { ItemMatGroup img = new ItemMatGroup(); img.nugget = new Item().setUnlocalizedName(name + "nugget").setRegistryName(name + "nugget"); img.nugget.setCreativeTab(TinkerRegistry.tabGeneral); ForgeRegistries.ITEMS.register(img.nugget); OreDictionary.registerOre("nugget" + StringUtils.capitalize(name), img.nugget); PlusTiC.proxy.registerItemRenderer(img.nugget, 0, name + "nugget"); img.ingot = new Item().setUnlocalizedName(name + "ingot").setRegistryName(name + "ingot"); img.ingot.setCreativeTab(TinkerRegistry.tabGeneral); ForgeRegistries.ITEMS.register(img.ingot); OreDictionary.registerOre("ingot" + StringUtils.capitalize(name), img.ingot); PlusTiC.proxy.registerItemRenderer(img.ingot, 0, name + "ingot"); img.block = new MetalBlock(name + "block"); img.block.setCreativeTab(TinkerRegistry.tabGeneral); ItemBlock bitem = new ItemBlock(img.block); ForgeRegistries.BLOCKS.register(img.block); ForgeRegistries.ITEMS.register(bitem.setRegistryName(img.block.getRegistryName())); OreDictionary.registerOre("block" + StringUtils.capitalize(name), img.block); PlusTiC.proxy.registerItemRenderer(bitem, 0, name + "block"); return img; } }
package mytown.core.utils; import cpw.mods.fml.common.registry.GameRegistry; import mytown.core.MyEssentialsCore; import mytown.core.utils.teleport.EssentialsTeleporter; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.play.server.S2FPacketSetSlot; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.UserList; import net.minecraft.server.management.UserListOps; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * @author Joe Goett * All utilities that are exclusively for EntityPlayerMP or EntityPlayer go here. */ public class PlayerUtils { /** * Takes the amount of items specified. * Returns false if player doesn't have the items necessary */ public static boolean takeItemFromPlayer(EntityPlayer player, String itemName, int amount) { String[] split = itemName.split(":"); return takeItemFromPlayer(player, GameRegistry.findItem(split[0], split[1]), amount, split.length == 3 ? Integer.parseInt(split[2]) : -1); } /** * Takes a specified amount of the itemStack from the player's inventory. */ public static boolean takeItemFromPlayer(EntityPlayer player, ItemStack itemStack, int amount) { return takeItemFromPlayer(player, itemStack.getItem(), amount, itemStack.getItemDamage()); } /** * Takes the amount of items specified. * Returns false if player doesn't have the items necessary */ public static boolean takeItemFromPlayer(EntityPlayer player, Item item, int amount, int meta) { List<Integer> slots = new ArrayList<Integer>(); int itemSum = 0; for (int i = 0; i < player.inventory.mainInventory.length; i++) { ItemStack itemStack = player.inventory.mainInventory[i]; if (itemStack == null) continue; if (itemStack.getItem() == item && (meta == -1 || itemStack.getItemDamage() == meta)) { slots.add(i); itemSum += itemStack.stackSize; if(itemSum >= amount) break; } } if(itemSum < amount) return false; for(int i : slots) { if(player.inventory.mainInventory[i].stackSize >= amount) { player.inventory.decrStackSize(i, amount); Slot slot = player.openContainer.getSlotFromInventory(player.inventory, i); ((EntityPlayerMP) player).playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, slot.slotNumber, player.inventory.mainInventory[i])); return true; } else { int stackSize = player.inventory.mainInventory[i].stackSize; player.inventory.decrStackSize(i, stackSize); amount -= stackSize; Slot slot = player.openContainer.getSlotFromInventory(player.inventory, i); ((EntityPlayerMP) player).playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, slot.slotNumber, player.inventory.mainInventory[i])); } } return true; } /** * Gives the amount of items specified. */ public static void giveItemToPlayer(EntityPlayer player, String itemName, int amount) { String[] split = itemName.split(":"); giveItemToPlayer(player, GameRegistry.findItem(split[0], split[1]), amount, split.length > 2 ? Integer.parseInt(split[2]) : 0); } /** * Gives the amount of items specified. */ public static void giveItemToPlayer(EntityPlayer player, ItemStack itemStack, int amount) { giveItemToPlayer(player, itemStack.getItem(), amount, itemStack.getItemDamage()); } /** * Gives the amount of items specified. */ public static void giveItemToPlayer(EntityPlayer player, Item item, int amount, int meta) { for (int left = amount; left > 0; left -= 64) { ItemStack stack = new ItemStack(item, left > 64 ? 64 : left, meta); //stack = addToInventory(player.inventory, stack); int i = -1; for(int j = 0; j < player.inventory.mainInventory.length; j++) { if (player.inventory.mainInventory[j] != null && player.inventory.mainInventory[j].getItem() == item && player.inventory.mainInventory[j].getItemDamage() == meta && player.inventory.mainInventory[j].stackSize + stack.stackSize <= 64) { i = j; break; } } if(i == -1) { for(int j = 0; j < player.inventory.mainInventory.length; j++) { if(player.inventory.mainInventory[j] == null) { i = j; break; } } if(i != -1) player.inventory.mainInventory[i] = stack; } else { player.inventory.mainInventory[i].stackSize += amount; } if (i == -1) { // Drop it on the ground if it fails to add to the inventory EntityUtils.dropAsEntity(player.getEntityWorld(), (int) player.posX, (int) player.posY, (int) player.posZ, stack); } else { // get the actual inventory Slot: Slot slot = player.openContainer.getSlotFromInventory(player.inventory, i); // send S2FPacketSetSlot to the player with the new / changed stack (or null) ((EntityPlayerMP) player).playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, slot.slotNumber, player.inventory.mainInventory[i])); } } } /** * Teleports player to the dimension without creating any nether portals of sorts. * Most of it is code from Delpi (from minecraftforge forums). Thank you! */ public static void teleport(EntityPlayerMP player, int dim, double x, double y, double z) { // Offset locations for accuracy x = x + 0.5d; y = y + 1.0d; z = z + 0.5d; player.motionX = player.motionY = player.motionZ = 0.0D; player.setPosition(x, y, z); if (player.worldObj.provider.dimensionId != dim) { World world = DimensionManager.getWorld(dim); player.mcServer.getConfigurationManager().transferPlayerToDimension(player, dim, new EssentialsTeleporter((WorldServer)world)); } } /** * Returns whether or not a player is OP. */ @SuppressWarnings("unchecked") public static boolean isOp(EntityPlayer player) { if(player == null) return false; if(player.getGameProfile() == null) return false; UserListOps ops = MinecraftServer.getServer().getConfigurationManager().func_152603_m(); try { Class clazz = Class.forName("net.minecraft.server.management.UserList"); Method method = clazz.getDeclaredMethod("func_152692_d", Object.class); method.setAccessible(true); return (Boolean)method.invoke(ops, player.getGameProfile()); } catch (Exception e) { for(Method mt : UserList.class.getMethods()) { MyEssentialsCore.Instance.log.info(mt.getName()); } e.printStackTrace(); } return false; } }
package net.emaze.dysfunctional; import java.util.concurrent.atomic.AtomicLong; import net.emaze.dysfunctional.dispatching.actions.Action; import net.emaze.dysfunctional.dispatching.actions.BinaryAction; import net.emaze.dysfunctional.dispatching.actions.TernaryAction; import net.emaze.dysfunctional.dispatching.delegates.BinaryDelegate; import net.emaze.dysfunctional.dispatching.delegates.Delegate; import net.emaze.dysfunctional.dispatching.delegates.Provider; import net.emaze.dysfunctional.dispatching.delegates.TernaryDelegate; import net.emaze.dysfunctional.dispatching.logic.BinaryPredicate; import net.emaze.dysfunctional.dispatching.logic.Predicate; import net.emaze.dysfunctional.dispatching.logic.Proposition; import net.emaze.dysfunctional.dispatching.logic.TernaryPredicate; import net.emaze.dysfunctional.dispatching.spying.BinaryCapturingAction; import net.emaze.dysfunctional.dispatching.spying.BinaryCapturingDelegate; import net.emaze.dysfunctional.dispatching.spying.BinaryCapturingPredicate; import net.emaze.dysfunctional.dispatching.spying.BinaryMonitoringAction; import net.emaze.dysfunctional.dispatching.spying.BinaryMonitoringDelegate; import net.emaze.dysfunctional.dispatching.spying.BinaryMonitoringPredicate; import net.emaze.dysfunctional.dispatching.spying.CapturingAction; import net.emaze.dysfunctional.dispatching.spying.CapturingDelegate; import net.emaze.dysfunctional.dispatching.spying.CapturingPredicate; import net.emaze.dysfunctional.dispatching.spying.CapturingProposition; import net.emaze.dysfunctional.dispatching.spying.CapturingProvider; import net.emaze.dysfunctional.dispatching.spying.MonitoringAction; import net.emaze.dysfunctional.dispatching.spying.MonitoringDelegate; import net.emaze.dysfunctional.dispatching.spying.MonitoringPredicate; import net.emaze.dysfunctional.dispatching.spying.MonitoringProposition; import net.emaze.dysfunctional.dispatching.spying.MonitoringProvider; import net.emaze.dysfunctional.dispatching.spying.MonitoringRunnable; import net.emaze.dysfunctional.dispatching.spying.TernaryCapturingAction; import net.emaze.dysfunctional.dispatching.spying.TernaryCapturingDelegate; import net.emaze.dysfunctional.dispatching.spying.TernaryCapturingPredicate; import net.emaze.dysfunctional.dispatching.spying.TernaryMonitoringAction; import net.emaze.dysfunctional.dispatching.spying.TernaryMonitoringDelegate; import net.emaze.dysfunctional.dispatching.spying.TernaryMonitoringPredicate; import net.emaze.dysfunctional.options.Box; /** * * @author rferranti */ public abstract class Spies { /** * Proxies a proposition, spying for result. * * @param proposition the proposition to be spied * @param result a box that will be containing spied result * @return the proxied proposition */ public static Proposition spy(Proposition proposition, Box<Boolean> result) { return new CapturingProposition(proposition, result); } /** * Proxies a provider, spying for result. * * @param <R> the provider result type * @param provider the provider to be spied * @param result a box that will be containing spied result * @return the proxied provider */ public static <R> Provider<R> spy(Provider<R> provider, Box<R> result) { return new CapturingProvider<R>(provider, result); } /** * Proxies a delegate spying for result and parameter. * * @param <R> the delegate result type * @param <T> the delegate parameter type * @param delegate the delegate to be spied * @param result a box that will be containing spied result * @param param a box that will be containing spied param * @return the proxied delegate */ public static <R, T> Delegate<R, T> spy(Delegate<R, T> delegate, Box<R> result, Box<T> param) { return new CapturingDelegate<R, T>(delegate, result, param); } /** * Proxies a binary delegate spying for result and parameters. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param delegate the delegate to be spied * @param result a box that will be containing spied result * @param param1 a box that will be containing the first spied parameter * @param param2 a box that will be containing the second spied parameter * @return the proxied delegate */ public static <R, T1, T2> BinaryDelegate<R, T1, T2> spy(BinaryDelegate<R, T1, T2> delegate, Box<R> result, Box<T1> param1, Box<T2> param2) { return new BinaryCapturingDelegate<R, T1, T2>(delegate, result, param1, param2); } /** * Proxies a ternary delegate spying for result and parameters. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param <T3> the delegate third parameter type * @param delegate the delegate to be spied * @param result a box that will be containing spied result * @param param1 a box that will be containing the first spied parameter * @param param2 a box that will be containing the second spied parameter * @param param3 a box that will be containing the third spied parameter * @return the proxied delegate */ public static <R, T1, T2, T3> TernaryDelegate<R, T1, T2, T3> spy(TernaryDelegate<R, T1, T2, T3> delegate, Box<R> result, Box<T1> param1, Box<T2> param2, Box<T3> param3) { return new TernaryCapturingDelegate<R, T1, T2, T3>(delegate, result, param1, param2, param3); } /** * Proxies a predicate spying for result and parameter. * * @param <T> the predicate parameter type * @param predicate the predicateto be spied * @param result a box that will be containing spied result * @param param a box that will be containing the spied parameter * @return the proxied predicate */ public static <T> Predicate<T> spy(Predicate<T> predicate, Box<Boolean> result, Box<T> param) { return new CapturingPredicate<T>(predicate, result, param); } /** * Proxies a binary predicate spying for result and parameters. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param predicate the predicate to be spied * @param result a box that will be containing spied result * @param param1 a box that will be containing the first spied parameter * @param param2 a box that will be containing the second spied parameter * @return the proxied predicate */ public static <T1, T2> BinaryPredicate<T1, T2> spy(BinaryPredicate<T1, T2> predicate, Box<Boolean> result, Box<T1> param1, Box<T2> param2) { return new BinaryCapturingPredicate<T1, T2>(predicate, result, param1, param2); } /** * Proxies a ternary predicate spying for result and parameters. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param <T3> the predicate third parameter type * @param predicate the predicate to be spied * @param result a box that will be containing spied result * @param param1 a box that will be containing the first spied parameter * @param param2 a box that will be containing the second spied parameter * @param param3 a box that will be containing the third spied parameter * @return the proxied predicate */ public static <T1, T2, T3> TernaryPredicate<T1, T2, T3> spy(TernaryPredicate<T1, T2, T3> predicate, Box<Boolean> result, Box<T1> param1, Box<T2> param2, Box<T3> param3) { return new TernaryCapturingPredicate<T1, T2, T3>(predicate, result, param1, param2, param3); } /** * Proxies an action spying for parameter. * * @param <T> the action parameter type * @param action the action to be spied * @param param a box that will be containing the spied parameter * @return the proxied action */ public static <T> Action<T> spy(Action<T> action, Box<T> param) { return new CapturingAction<T>(action, param); } /** * Proxies a binary action spying for parameters. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param action the action that will be spied * @param param1 a box that will be containing the first spied parameter * @param param2 a box that will be containing the second spied parameter * @return the proxied action */ public static <T1, T2> BinaryAction<T1, T2> spy(BinaryAction<T1, T2> action, Box<T1> param1, Box<T2> param2) { return new BinaryCapturingAction<T1, T2>(action, param1, param2); } /** * Proxies a ternary action spying for parameters. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param <T3> the action third parameter type * @param action the action that will be spied * @param param1 a box that will be containing the first spied parameter * @param param2 a box that will be containing the second spied parameter * @param param3 a box that will be containing the third spied parameter * @return the proxied action */ public static <T1, T2, T3> TernaryAction<T1, T2, T3> spy(TernaryAction<T1, T2, T3> action, Box<T1> param1, Box<T2> param2, Box<T3> param3) { return new TernaryCapturingAction<T1, T2, T3>(action, param1, param2, param3); } /** * Proxies a ternary delegate spying for result. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param <T3> the delegate third parameter type * @param delegate the delegate that will be spied * @param result a box that will be containing spied result * @return the proxied delegate */ public static <R, T1, T2, T3> TernaryDelegate<R, T1, T2, T3> spyRes(TernaryDelegate<R, T1, T2, T3> delegate, Box<R> result) { return spy(delegate, result, Box.<T1>empty(), Box.<T2>empty(), Box.<T3>empty()); } /** * Proxies a ternary delegate spying for first parameter. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param <T3> the delegate third parameter type * @param delegate the delegate that will be spied * @param param1 a box that will be containing the first spied parameter * @return the proxied delegate */ public static <R, T1, T2, T3> TernaryDelegate<R, T1, T2, T3> spy1st(TernaryDelegate<R, T1, T2, T3> delegate, Box<T1> param1) { return spy(delegate, Box.<R>empty(), param1, Box.<T2>empty(), Box.<T3>empty()); } /** * Proxies a ternary delegate spying for second parameter * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param <T3> the delegate third parameter type * @param delegate the delegate that will be spied * @param param2 a box that will be containing the second spied parameter * @return the proxied delegate */ public static <R, T1, T2, T3> TernaryDelegate<R, T1, T2, T3> spy2nd(TernaryDelegate<R, T1, T2, T3> delegate, Box<T2> param2) { return spy(delegate, Box.<R>empty(), Box.<T1>empty(), param2, Box.<T3>empty()); } /** * Proxies a ternary delegate spying for third parameter. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param <T3> the delegate third parameter type * @param delegate the delegate that will be spied * @param param3 a box that will be containing the third spied parameter * @return the proxied delegate */ public static <R, T1, T2, T3> TernaryDelegate<R, T1, T2, T3> spy3rd(TernaryDelegate<R, T1, T2, T3> delegate, Box<T3> param3) { return spy(delegate, Box.<R>empty(), Box.<T1>empty(), Box.<T2>empty(), param3); } /** * Proxies a binary delegate spying for result. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param delegate the delegate that will be spied * @param result a box that will be containing spied result * @return the proxied delegate */ public static <R, T1, T2> BinaryDelegate<R, T1, T2> spyRes(BinaryDelegate<R, T1, T2> delegate, Box<R> result) { return spy(delegate, result, Box.<T1>empty(), Box.<T2>empty()); } /** * Proxies a binary delegate spying for first parameter. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param delegate the delegate that will be spied * @param param1 a box that will be containing the first spied parameter * @return the proxied delegate */ public static <R, T1, T2> BinaryDelegate<R, T1, T2> spy1st(BinaryDelegate<R, T1, T2> delegate, Box<T1> param1) { return spy(delegate, Box.<R>empty(), param1, Box.<T2>empty()); } /** * Proxies a binary delegate spying for second parameter. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param delegate the delegate that will be spied * @param param2 a box that will be containing the second spied parameter * @return the proxied delegate */ public static <R, T1, T2> BinaryDelegate<R, T1, T2> spy2nd(BinaryDelegate<R, T1, T2> delegate, Box<T2> param2) { return spy(delegate, Box.<R>empty(), Box.<T1>empty(), param2); } /** * Proxies a delegate spying for result. * * @param <R> the delegate result type * @param <T> the delegate parameter type * @param delegate the delegate that will be spied * @param result a box that will be containing spied result * @return the proxied delegate */ public static <R, T> Delegate<R, T> spyRes(Delegate<R, T> delegate, Box<R> result) { return spy(delegate, result, Box.<T>empty()); } /** * Proxies a delegate spying for parameter. * * @param <R> the delegate result type * @param <T> the delegate parameter type * @param delegate the delegate that will be spied * @param param a box that will be containing spied parameter * @return the proxied delegate */ public static <R, T> Delegate<R, T> spy1st(Delegate<R, T> delegate, Box<T> param) { return spy(delegate, Box.<R>empty(), param); } /** * Proxies a ternary action spying for first parameter. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param <T3> the action third parameter type * @param action the action that will be spied * @param param1 a box that will be containing the first spied parameter * @return the proxied action */ public static <T1, T2, T3> TernaryAction<T1, T2, T3> spy1st(TernaryAction<T1, T2, T3> action, Box<T1> param1) { return spy(action, param1, Box.<T2>empty(), Box.<T3>empty()); } /** * Proxies a ternary action spying for second parameter. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param <T3> the action third parameter type * @param action the action that will be spied * @param param2 a box that will be containing the second spied parameter * @return the proxied action */ public static <T1, T2, T3> TernaryAction<T1, T2, T3> spy2nd(TernaryAction<T1, T2, T3> action, Box<T2> param2) { return spy(action, Box.<T1>empty(), param2, Box.<T3>empty()); } /** * Proxies a ternary action spying for third parameter. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param <T3> the action third parameter type * @param action the action that will be spied * @param param3 a box that will be containing the third spied parameter * @return the proxied action */ public static <T1, T2, T3> TernaryAction<T1, T2, T3> spy3rd(TernaryAction<T1, T2, T3> action, Box<T3> param3) { return spy(action, Box.<T1>empty(), Box.<T2>empty(), param3); } /** * Proxies a binary action spying for first parameter. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param action the action that will be spied * @param param1 a box that will be containing the first spied parameter * @return the proxied action */ public static <T1, T2> BinaryAction<T1, T2> spy1st(BinaryAction<T1, T2> action, Box<T1> param1) { return spy(action, param1, Box.<T2>empty()); } /** * Proxies a binary action spying for second parameter. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param action the action that will be spied * @param param2 a box that will be containing the second spied parameter * @return the proxied action */ public static <T1, T2> BinaryAction<T1, T2> spy2nd(BinaryAction<T1, T2> action, Box<T2> param2) { return spy(action, Box.<T1>empty(), param2); } /** * Proxies a binary action spying for first parameter. * * @param <T> the action parameter type * @param action the action that will be spied * @param param a box that will be containing the spied parameter * @return the proxied action */ public static <T> Action<T> spy1st(Action<T> action, Box<T> param) { return spy(action, param); } /** * Proxies a ternary predicate spying for result. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param <T3> the predicate third parameter type * @param predicate the predicate that will be spied * @param result a box that will be containing spied result * @return the proxied predicate */ public static <T1, T2, T3> TernaryPredicate<T1, T2, T3> spyRes(TernaryPredicate<T1, T2, T3> predicate, Box<Boolean> result) { return spy(predicate, result, Box.<T1>empty(), Box.<T2>empty(), Box.<T3>empty()); } /** * Proxies a ternary predicate spying for first parameter. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param <T3> the predicate third parameter type * @param predicate the predicate that will be spied * @param param1 a box that will be containing the first spied parameter * @return the proxied predicate */ public static <T1, T2, T3> TernaryPredicate<T1, T2, T3> spy1st(TernaryPredicate<T1, T2, T3> predicate, Box<T1> param1) { return spy(predicate, Box.<Boolean>empty(), param1, Box.<T2>empty(), Box.<T3>empty()); } /** * Proxies a ternary predicate spying for second parameter. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param <T3> the predicate third parameter type * @param predicate the predicate that will be spied * @param param2 a box that will be containing the second spied parameter * @return the proxied predicate */ public static <T1, T2, T3> TernaryPredicate<T1, T2, T3> spy2nd(TernaryPredicate<T1, T2, T3> predicate, Box<T2> param2) { return spy(predicate, Box.<Boolean>empty(), Box.<T1>empty(), param2, Box.<T3>empty()); } /** * Proxies a ternary predicate spying for third parameter. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param <T3> the predicate third parameter type * @param predicate the predicate that will be spied * @param param3 a box that will be containing the third spied parameter * @return the proxied predicate */ public static <T1, T2, T3> TernaryPredicate<T1, T2, T3> spy3rd(TernaryPredicate<T1, T2, T3> predicate, Box<T3> param3) { return spy(predicate, Box.<Boolean>empty(), Box.<T1>empty(), Box.<T2>empty(), param3); } /** * Proxies a binary predicate spying for result. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param predicate the predicate that will be spied * @param result a box that will be containing spied result * @return the proxied predicate */ public static <T1, T2> BinaryPredicate<T1, T2> spyRes(BinaryPredicate<T1, T2> predicate, Box<Boolean> result) { return spy(predicate, result, Box.<T1>empty(), Box.<T2>empty()); } /** * Proxies a binary predicate spying for first parameter * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param predicate the predicate that will be spied * @param param1 a box that will be containing the first spied parameter * @return the proxied predicate */ public static <T1, T2> BinaryPredicate<T1, T2> spy1st(BinaryPredicate<T1, T2> predicate, Box<T1> param1) { return spy(predicate, Box.<Boolean>empty(), param1, Box.<T2>empty()); } /** * Proxies a binary predicate spying for second parameter. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param predicate the predicate that will be spied * @param param2 a box that will be containing the second spied parameter * @return the proxied predicate */ public static <T1, T2> BinaryPredicate<T1, T2> spy2nd(BinaryPredicate<T1, T2> predicate, Box<T2> param2) { return spy(predicate, Box.<Boolean>empty(), Box.<T1>empty(), param2); } /** * Proxies a predicate spying for result. * * @param <T> the predicate parameter type * @param predicate the predicate that will be spied * @param result a box that will be containing spied result * @return the proxied predicate */ public static <T> Predicate<T> spyRes(Predicate<T> predicate, Box<Boolean> result) { return spy(predicate, result, Box.<T>empty()); } /** * Proxies a predicate spying for parameter. * * @param <T> the predicate parameter type * @param predicate the predicate that will be spied * @param param a box that will be containing spied parameter * @return the proxied predicate */ public static <T> Predicate<T> spy1st(Predicate<T> predicate, Box<T> param) { return spy(predicate, Box.<Boolean>empty(), param); } /** * Monitors calls to an action. * * @param <T> the action parameter type * @param action the action that will be monitored * @param calls a value holder accumulating calls * @return the proxied action */ public static <T> Action<T> monitor(Action<T> action, AtomicLong calls) { return new MonitoringAction<T>(action, calls); } /** * Monitors calls to a delegate. * * @param <R> the delegate result type * @param <T> the delegate parameter type * @param delegate the delegate that will be monitored * @param calls a value holder accumulating calls * @return the proxied delegate */ public static <R, T> Delegate<R, T> monitor(Delegate<R, T> delegate, AtomicLong calls) { return new MonitoringDelegate<R, T>(delegate, calls); } /** * Monitors calls to a predicate. * * @param <T> the predicate parameter type * @param predicate the predicate that will be monitored * @param calls a value holder accumulating calls * @return the proxied predicate */ public static <T> Predicate<T> monitor(Predicate<T> predicate, AtomicLong calls) { return new MonitoringPredicate<T>(predicate, calls); } /** * Monitors calls to a proposition. * * @param proposition the proposition that will be monitored * @param calls a value holder accumulating calls * @return the proxied proposition */ public static Proposition monitor(Proposition proposition, AtomicLong calls) { return new MonitoringProposition(proposition, calls); } /** * Monitors calls to a provider. * * @param <R> the provider result type * @param provider the provider that will be monitored * @param calls a value holder accumulating calls * @return the proxied provider */ public static <R> Provider<R> monitor(Provider<R> provider, AtomicLong calls) { return new MonitoringProvider<R>(provider, calls); } /** * Monitors calls to a runnable. * * @param runnable the runnable that will be monitored * @param calls a value holder accumulating calls * @return the proxied runnable */ public static Runnable monitor(Runnable runnable, AtomicLong calls) { return new MonitoringRunnable(runnable, calls); } /** * Monitors calls to a binary action. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param action the action that will be monitored * @param calls a value holder accumulating calls * @return the proxied action */ public static <T1, T2> BinaryAction<T1, T2> monitor(BinaryAction<T1, T2> action, AtomicLong calls) { return new BinaryMonitoringAction<T1, T2>(action, calls); } /** * Monitors calls to a binary delegate. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param delegate the delegate that will be monitored * @param calls a value holder accumulating calls * @return the proxied delegate */ public static <R, T1, T2> BinaryDelegate<R, T1, T2> monitor(BinaryDelegate<R, T1, T2> delegate, AtomicLong calls) { return new BinaryMonitoringDelegate<R, T1, T2>(delegate, calls); } /** * Monitors calls to a binary predicate * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param predicate the predicate that will be monitored * @param calls a value holder accumulating calls * @return the proxied predicate */ public static <T1, T2> BinaryPredicate<T1, T2> monitor(BinaryPredicate<T1, T2> predicate, AtomicLong calls) { return new BinaryMonitoringPredicate<T1, T2>(predicate, calls); } /** * Monitors calls to a ternary action. * * @param <T1> the action first parameter type * @param <T2> the action second parameter type * @param <T3> the action third parameter type * @param action the action that will be monitored * @param calls a value holder accumulating calls * @return the proxied action */ public static <T1, T2, T3> TernaryAction<T1, T2, T3> monitor(TernaryAction<T1, T2, T3> action, AtomicLong calls) { return new TernaryMonitoringAction<T1, T2, T3>(action, calls); } /** * Monitors calls to a ternary delegate. * * @param <R> the delegate result type * @param <T1> the delegate first parameter type * @param <T2> the delegate second parameter type * @param <T3> the delegate third parameter type * @param delegate the delegate that will be monitored * @param calls a value holder accumulating calls * @return the proxied delegate */ public static <R, T1, T2, T3> TernaryDelegate<R, T1, T2, T3> monitor(TernaryDelegate<R, T1, T2, T3> delegate, AtomicLong calls) { return new TernaryMonitoringDelegate<R, T1, T2, T3>(delegate, calls); } /** * Monitors calls to a ternary predicate. * * @param <T1> the predicate first parameter type * @param <T2> the predicate second parameter type * @param <T3> the predicate third parameter type * @param predicate the predicate that will be monitored * @param calls a value holder accumulating calls * @return the proxied predicate */ public static <T1, T2, T3> TernaryPredicate<T1, T2, T3> monitor(TernaryPredicate<T1, T2, T3> predicate, AtomicLong calls) { return new TernaryMonitoringPredicate<T1, T2, T3>(predicate, calls); } }
package net.sf.jabref.gui; import com.jgoodies.looks.HeaderStyle; import com.jgoodies.looks.Options; import net.sf.jabref.*; import net.sf.jabref.bibtex.EntryTypes; import net.sf.jabref.exporter.*; import net.sf.jabref.external.ExternalFileTypeEditor; import net.sf.jabref.external.push.PushToApplicationButton; import net.sf.jabref.external.push.PushToApplications; import net.sf.jabref.groups.EntryTableTransferHandler; import net.sf.jabref.groups.GroupSelector; import net.sf.jabref.gui.actions.*; import net.sf.jabref.gui.desktop.JabRefDesktop; import net.sf.jabref.gui.help.HelpFiles; import net.sf.jabref.gui.help.HelpAction; import net.sf.jabref.gui.journals.ManageJournalsAction; import net.sf.jabref.gui.keyboard.KeyBinding; import net.sf.jabref.gui.keyboard.KeyBindingRepository; import net.sf.jabref.gui.keyboard.KeyBindingsDialog; import net.sf.jabref.gui.menus.ChangeEntryTypeMenu; import net.sf.jabref.gui.menus.help.DonateAction; import net.sf.jabref.gui.menus.help.ForkMeOnGitHubAction; import net.sf.jabref.gui.preftabs.PreferencesDialog; import net.sf.jabref.gui.util.FocusRequester; import net.sf.jabref.gui.util.PositionWindow; import net.sf.jabref.gui.worker.AbstractWorker; import net.sf.jabref.gui.worker.MarkEntriesAction; import net.sf.jabref.importer.*; import net.sf.jabref.importer.fetcher.GeneralFetcher; import net.sf.jabref.logic.CustomEntryTypesManager; import net.sf.jabref.logic.integrity.IntegrityCheck; import net.sf.jabref.logic.integrity.IntegrityMessage; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.logging.GuiAppender; import net.sf.jabref.logic.preferences.LastFocusedTabPreferences; import net.sf.jabref.logic.util.OS; import net.sf.jabref.logic.util.io.FileUtil; import net.sf.jabref.model.database.BibDatabase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.sf.jabref.gui.help.AboutAction; import net.sf.jabref.gui.help.AboutDialog; import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.model.entry.BibtexEntryTypes; import net.sf.jabref.model.entry.EntryType; import net.sf.jabref.model.entry.IEEETranEntryTypes; import net.sf.jabref.openoffice.OpenOfficePanel; import net.sf.jabref.specialfields.*; import net.sf.jabref.sql.importer.DbImportAction; import net.sf.jabref.util.ManageKeywordsAction; import net.sf.jabref.util.MassSetFieldAction; import osx.macadapter.MacAdapter; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * The main window of the application. */ public class JabRefFrame extends JFrame implements OutputPrinter { private static final Log LOGGER = LogFactory.getLog(JabRefFrame.class); private static final boolean biblatexMode = Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_MODE); final JSplitPane contentPane = new JSplitPane(); private final JabRefPreferences prefs = Globals.prefs; private PreferencesDialog prefsDialog; private int lastTabbedPanelSelectionIndex = -1; // The sidepane manager takes care of populating the sidepane. public SidePaneManager sidePaneManager; public JTabbedPane tabbedPane; // initialized at constructor private final Insets marg = new Insets(1, 0, 2, 0); private final JabRef jabRef; private PositionWindow pw; private final GeneralAction checkIntegrity = new GeneralAction(Actions.CHECK_INTEGRITY, Localization.menuTitle("Check integrity")) { @Override public void actionPerformed(ActionEvent e) { IntegrityCheck check = new IntegrityCheck(); List<IntegrityMessage> messages = check.checkBibtexDatabase(getCurrentBasePanel().database()); if (messages.isEmpty()) { JOptionPane.showMessageDialog(getCurrentBasePanel(), Localization.lang("No problems found.")); } else { // prepare data model Object[][] model = new Object[messages.size()][3]; int i = 0; for (IntegrityMessage message : messages) { model[i][0] = message.getEntry().getCiteKey(); model[i][1] = message.getFieldName(); model[i][2] = message.getMessage(); i++; } // construct view JTable table = new JTable( model, new Object[] {"key", "field", "message"} ); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); ListSelectionModel selectionModel = table.getSelectionModel(); selectionModel.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { String citeKey = (String) model[table.getSelectedRow()][0]; String fieldName = (String) model[table.getSelectedRow()][1]; getCurrentBasePanel().editEntryByKeyAndFocusField(citeKey, fieldName); } } }); table.getColumnModel().getColumn(0).setPreferredWidth(80); table.getColumnModel().getColumn(1).setPreferredWidth(30); table.getColumnModel().getColumn(2).setPreferredWidth(250); table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); JScrollPane scrollPane = new JScrollPane(table); String title = Localization.lang("%0 problem(s) found", String.valueOf(messages.size())); JDialog dialog = new JDialog(JabRefFrame.this, title, false); dialog.add(scrollPane); dialog.setSize(600, 500); // show view dialog.setVisible(true); } } }; class ToolBar extends OSXCompatibleToolbar { void addAction(Action a) { JButton b = new JButton(a); b.setText(null); if (!OS.OS_X) { b.setMargin(marg); } // create a disabled Icon for FontBasedIcons as Swing does not automatically create one Object obj = a.getValue(Action.LARGE_ICON_KEY); if ((obj instanceof IconTheme.FontBasedIcon)) { b.setDisabledIcon(((IconTheme.FontBasedIcon) obj).createDisabledIcon()); } add(b); } void addJToogleButton(JToggleButton button) { button.setText(null); if (!OS.OS_X) { button.setMargin(marg); } Object obj = button.getAction().getValue(Action.LARGE_ICON_KEY); if ((obj instanceof IconTheme.FontBasedIcon)) { button.setDisabledIcon(((IconTheme.FontBasedIcon) obj).createDisabledIcon()); } add(button); } } private final ToolBar tlb = new ToolBar(); private final JMenuBar mb = new JMenuBar(); private final GridBagLayout gbl = new GridBagLayout(); private final GridBagConstraints con = new GridBagConstraints(); final JLabel statusLine = new JLabel("", SwingConstants.LEFT); private final JLabel statusLabel = new JLabel( Localization.lang("Status") + ':', SwingConstants.LEFT); private final JProgressBar progressBar = new JProgressBar(); private final FileHistoryMenu fileHistory = new FileHistoryMenu(prefs, this); // The help window. public final AboutDialog helpDiag = new AboutDialog(this); // Here we instantiate menu/toolbar actions. Actions regarding // the currently open database are defined as a GeneralAction // with a unique command string. This causes the appropriate // BasePanel's runCommand() method to be called with that command. // Note: GeneralAction's constructor automatically gets translations // for the name and message strings. /* References to the toggle buttons in the toolbar */ // the groups interface public JToggleButton groupToggle; public JToggleButton previewToggle; public JToggleButton fetcherToggle; final OpenDatabaseAction open = new OpenDatabaseAction(this, true); private final AbstractAction editModeAction = new EditModeAction(); private final AbstractAction quit = new CloseAction(); private final AbstractAction selectKeys = new SelectKeysAction(); private final AbstractAction newDatabaseAction = new NewDatabaseAction(this); private final AbstractAction newSubDatabaseAction = new NewSubDatabaseAction(this); private final AbstractAction forkMeOnGitHubAction = new ForkMeOnGitHubAction(); private final AbstractAction donationAction = new DonateAction(); private final AbstractAction help = new HelpAction(Localization.menuTitle("JabRef help"), Localization.lang("JabRef help"), HelpFiles.helpContents, Globals.getKeyPrefs().getKey(KeyBinding.HELP)); private final AbstractAction about = new AboutAction(Localization.menuTitle("About JabRef"), helpDiag, Localization.lang("About JabRef"), IconTheme.getImage("about")); private final AbstractAction editEntry = new GeneralAction(Actions.EDIT, Localization.menuTitle("Edit entry"), Localization.lang("Edit entry"), Globals.getKeyPrefs().getKey(KeyBinding.EDIT_ENTRY), IconTheme.JabRefIcon.EDIT_ENTRY.getIcon()); private final AbstractAction focusTable = new GeneralAction(Actions.FOCUS_TABLE, Localization.menuTitle("Focus entry table"), Localization.lang("Move the keyboard focus to the entry table"), Globals.getKeyPrefs().getKey(KeyBinding.FOCUS_ENTRY_TABLE)); private final AbstractAction save = new GeneralAction(Actions.SAVE, Localization.menuTitle("Save database"), Localization.lang("Save database"), Globals.getKeyPrefs().getKey(KeyBinding.SAVE_DATABASE), IconTheme.JabRefIcon.SAVE.getIcon()); private final AbstractAction saveAs = new GeneralAction(Actions.SAVE_AS, Localization.menuTitle("Save database as ..."), Localization.lang("Save database as ..."), Globals.getKeyPrefs().getKey(KeyBinding.SAVE_DATABASE_AS)); private final AbstractAction saveAll = new SaveAllAction(JabRefFrame.this); private final AbstractAction saveSelectedAs = new GeneralAction(Actions.SAVE_SELECTED_AS, Localization.menuTitle("Save selected as ..."), Localization.lang("Save selected as ...")); private final AbstractAction saveSelectedAsPlain = new GeneralAction(Actions.SAVE_SELECTED_AS_PLAIN, Localization.menuTitle("Save selected as plain BibTeX..."), Localization.lang("Save selected as plain BibTeX...")); private final AbstractAction exportAll = ExportFormats.getExportAction(this, false); private final AbstractAction exportSelected = ExportFormats.getExportAction(this, true); private final AbstractAction importCurrent = ImportFormats.getImportAction(this, false); private final AbstractAction importNew = ImportFormats.getImportAction(this, true); public final AbstractAction nextTab = new ChangeTabAction(true); public final AbstractAction prevTab = new ChangeTabAction(false); private final AbstractAction sortTabs = new SortTabsAction(this); private final AbstractAction undo = new GeneralAction(Actions.UNDO, Localization.menuTitle("Undo"), Localization.lang("Undo"), Globals.getKeyPrefs().getKey(KeyBinding.UNDO), IconTheme.JabRefIcon.UNDO.getIcon()); private final AbstractAction redo = new GeneralAction(Actions.REDO, Localization.menuTitle("Redo"), Localization.lang("Redo"), Globals.getKeyPrefs().getKey(KeyBinding.REDO), IconTheme.JabRefIcon.REDO.getIcon()); final AbstractAction forward = new GeneralAction(Actions.FORWARD, Localization.menuTitle("Forward"), Localization.lang("Forward"), Globals.getKeyPrefs().getKey(KeyBinding.FORWARD), IconTheme.JabRefIcon.RIGHT.getIcon()); final AbstractAction back = new GeneralAction(Actions.BACK, Localization.menuTitle("Back"), Localization.lang("Back"), Globals.getKeyPrefs().getKey(KeyBinding.BACK), IconTheme.JabRefIcon.LEFT.getIcon()); private final AbstractAction deleteEntry = new GeneralAction(Actions.DELETE, Localization.menuTitle("Delete entry"), Localization.lang("Delete entry"), Globals.getKeyPrefs().getKey(KeyBinding.DELETE_ENTRY), IconTheme.JabRefIcon.DELETE_ENTRY.getIcon()); private final AbstractAction copy = new EditAction(Actions.COPY, Localization.menuTitle("Copy"), Localization.lang("Copy"), Globals.getKeyPrefs().getKey(KeyBinding.COPY), IconTheme.JabRefIcon.COPY.getIcon()); private final AbstractAction paste = new EditAction(Actions.PASTE, Localization.menuTitle("Paste"), Localization.lang("Paste"), Globals.getKeyPrefs().getKey(KeyBinding.PASTE), IconTheme.JabRefIcon.PASTE.getIcon()); private final AbstractAction cut = new EditAction(Actions.CUT, Localization.menuTitle("Cut"), Localization.lang("Cut"), Globals.getKeyPrefs().getKey(KeyBinding.CUT), IconTheme.JabRefIcon.CUT.getIcon()); private final AbstractAction mark = new GeneralAction(Actions.MARK_ENTRIES, Localization.menuTitle("Mark entries"), Localization.lang("Mark entries"), Globals.getKeyPrefs().getKey(KeyBinding.MARK_ENTRIES), IconTheme.JabRefIcon.MARK_ENTRIES.getIcon()); private final AbstractAction unmark = new GeneralAction(Actions.UNMARK_ENTRIES, Localization.menuTitle("Unmark entries"), Localization.lang("Unmark entries"), Globals.getKeyPrefs().getKey(KeyBinding.UNMARK_ENTRIES), IconTheme.JabRefIcon.UNMARK_ENTRIES.getIcon()); private final AbstractAction unmarkAll = new GeneralAction(Actions.UNMARK_ALL, Localization.menuTitle("Unmark all")); private final AbstractAction toggleRelevance = new GeneralAction( Relevance.getInstance().getValues().get(0).getActionName(), Relevance.getInstance().getValues().get(0).getMenuString(), Relevance.getInstance().getValues().get(0).getToolTipText(), IconTheme.JabRefIcon.RELEVANCE.getIcon()); private final AbstractAction toggleQualityAssured = new GeneralAction( Quality.getInstance().getValues().get(0).getActionName(), Quality.getInstance().getValues().get(0).getMenuString(), Quality.getInstance().getValues().get(0).getToolTipText(), IconTheme.JabRefIcon.QUALITY_ASSURED.getIcon()); private final AbstractAction togglePrinted = new GeneralAction( Printed.getInstance().getValues().get(0).getActionName(), Printed.getInstance().getValues().get(0).getMenuString(), Printed.getInstance().getValues().get(0).getToolTipText(), IconTheme.JabRefIcon.PRINTED.getIcon()); private final AbstractAction manageSelectors = new GeneralAction(Actions.MANAGE_SELECTORS, Localization.menuTitle("Manage content selectors")); private final AbstractAction normalSearch = new GeneralAction(Actions.SEARCH, Localization.menuTitle("Search"), Localization.lang("Search"), Globals.getKeyPrefs().getKey(KeyBinding.SEARCH), IconTheme.JabRefIcon.SEARCH.getIcon()); private final AbstractAction copyKey = new GeneralAction(Actions.COPY_KEY, Localization.menuTitle("Copy BibTeX key"), Globals.getKeyPrefs().getKey(KeyBinding.COPY_BIBTEX_KEY)); private final AbstractAction copyCiteKey = new GeneralAction(Actions.COPY_CITE_KEY, Localization.menuTitle( "Copy \\cite{BibTeX key}"), Globals.getKeyPrefs().getKey(KeyBinding.COPY_CITE_BIBTEX_KEY)); private final AbstractAction copyKeyAndTitle = new GeneralAction(Actions.COPY_KEY_AND_TITLE, Localization.menuTitle("Copy BibTeX key and title"), Globals.getKeyPrefs().getKey(KeyBinding.COPY_BIBTEX_KEY_AND_TITLE)); private final AbstractAction mergeDatabaseAction = new GeneralAction(Actions.MERGE_DATABASE, Localization.menuTitle("Append database"), Localization.lang("Append contents from a BibTeX database into the currently viewed database")); private final AbstractAction selectAll = new GeneralAction(Actions.SELECT_ALL, Localization.menuTitle("Select all"), Globals.getKeyPrefs().getKey(KeyBinding.SELECT_ALL)); private final AbstractAction replaceAll = new GeneralAction(Actions.REPLACE_ALL, Localization.menuTitle("Replace string"), Globals.getKeyPrefs().getKey(KeyBinding.REPLACE_STRING)); private final AbstractAction editPreamble = new GeneralAction(Actions.EDIT_PREAMBLE, Localization.menuTitle("Edit preamble"), Localization.lang("Edit preamble"), Globals.getKeyPrefs().getKey(KeyBinding.EDIT_PREAMBLE)); private final AbstractAction editStrings = new GeneralAction(Actions.EDIT_STRINGS, Localization.menuTitle("Edit strings"), Localization.lang("Edit strings"), Globals.getKeyPrefs().getKey(KeyBinding.EDIT_STRINGS), IconTheme.JabRefIcon.EDIT_STRINGS.getIcon()); private final AbstractAction customizeAction = new CustomizeEntryTypeAction(); private final AbstractAction toggleToolbar = new AbstractAction(Localization.menuTitle("Hide/show toolbar")) { { putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.HIDE_SHOW_TOOLBAR)); putValue(Action.SHORT_DESCRIPTION, Localization.lang("Hide/show toolbar")); } @Override public void actionPerformed(ActionEvent e) { tlb.setVisible(!tlb.isVisible()); } }; private final AbstractAction toggleGroups = new GeneralAction(Actions.TOGGLE_GROUPS, Localization.menuTitle("Toggle groups interface"), Localization.lang("Toggle groups interface"), Globals.getKeyPrefs().getKey(KeyBinding.TOGGLE_GROUPS_INTERFACE), IconTheme.JabRefIcon.TOGGLE_GROUPS.getIcon()); private final AbstractAction addToGroup = new GeneralAction(Actions.ADD_TO_GROUP, Localization.lang("Add to group")); private final AbstractAction removeFromGroup = new GeneralAction(Actions.REMOVE_FROM_GROUP, Localization.lang("Remove from group")); private final AbstractAction moveToGroup = new GeneralAction(Actions.MOVE_TO_GROUP, Localization.lang("Move to group")); private final AbstractAction togglePreview = new GeneralAction(Actions.TOGGLE_PREVIEW, Localization.menuTitle("Toggle entry preview"), Localization.lang("Toggle entry preview"), Globals.getKeyPrefs().getKey(KeyBinding.TOGGLE_ENTRY_PREVIEW), IconTheme.JabRefIcon.TOGGLE_ENTRY_PREVIEW.getIcon()); private final AbstractAction toggleHighlightAny = new GeneralAction(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_ANY, Localization.menuTitle("Highlight groups matching any selected entry"), Localization.lang("Highlight groups matching any selected entry")); private final AbstractAction toggleHighlightAll = new GeneralAction(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_ALL, Localization.menuTitle("Highlight groups matching all selected entries"), Localization.lang("Highlight groups matching all selected entries")); final AbstractAction switchPreview = new GeneralAction(Actions.SWITCH_PREVIEW, Localization.menuTitle("Switch preview layout"), Globals.getKeyPrefs().getKey(KeyBinding.SWITCH_PREVIEW_LAYOUT)); private final AbstractAction makeKeyAction = new GeneralAction(Actions.MAKE_KEY, Localization.menuTitle("Autogenerate BibTeX keys"), Localization.lang("Autogenerate BibTeX keys"), Globals.getKeyPrefs().getKey(KeyBinding.AUTOGENERATE_BIBTEX_KEYS), IconTheme.JabRefIcon.MAKE_KEY.getIcon()); private final AbstractAction writeXmpAction = new GeneralAction(Actions.WRITE_XMP, Localization.menuTitle("Write XMP-metadata to PDFs"), Localization.lang("Will write XMP-metadata to the PDFs linked from selected entries."), Globals.getKeyPrefs().getKey(KeyBinding.WRITE_XMP)); private final AbstractAction openFolder = new GeneralAction(Actions.OPEN_FOLDER, Localization.menuTitle("Open folder"), Localization.lang("Open folder"), Globals.getKeyPrefs().getKey(KeyBinding.OPEN_FOLDER)); private final AbstractAction openFile = new GeneralAction(Actions.OPEN_EXTERNAL_FILE, Localization.menuTitle("Open file"), Localization.lang("Open file"), Globals.getKeyPrefs().getKey(KeyBinding.OPEN_FILE), IconTheme.JabRefIcon.FILE.getIcon()); private final AbstractAction openUrl = new GeneralAction(Actions.OPEN_URL, Localization.menuTitle("Open URL or DOI"), Localization.lang("Open URL or DOI"), Globals.getKeyPrefs().getKey(KeyBinding.OPEN_URL_OR_DOI), IconTheme.JabRefIcon.WWW.getIcon()); private final AbstractAction dupliCheck = new GeneralAction(Actions.DUPLI_CHECK, Localization.menuTitle("Find duplicates"), IconTheme.JabRefIcon.FIND_DUPLICATES.getIcon()); private final AbstractAction plainTextImport = new GeneralAction(Actions.PLAIN_TEXT_IMPORT, Localization.menuTitle("New entry from plain text"), Globals.getKeyPrefs().getKey(KeyBinding.NEW_FROM_PLAIN_TEXT)); private final AbstractAction customExpAction = new CustomizeExportsAction(); private final AbstractAction customImpAction = new CustomizeImportsAction(); private final AbstractAction customFileTypesAction = ExternalFileTypeEditor.getAction(this); private final AbstractAction exportToClipboard = new GeneralAction(Actions.EXPORT_TO_CLIPBOARD, Localization.menuTitle("Export selected entries to clipboard"), IconTheme.JabRefIcon.EXPORT_TO_CLIPBOARD.getIcon()); private final AbstractAction autoSetFile = new GeneralAction(Actions.AUTO_SET_FILE, Localization.lang("Synchronize file links"), Globals.getKeyPrefs().getKey(KeyBinding.SYNCHRONIZE_FILES)); private final AbstractAction abbreviateMedline = new GeneralAction(Actions.ABBREVIATE_MEDLINE, Localization.menuTitle("Abbreviate journal names (MEDLINE)"), Localization.lang("Abbreviate journal names of the selected entries (MEDLINE abbreviation)")); private final AbstractAction abbreviateIso = new GeneralAction(Actions.ABBREVIATE_ISO, Localization.menuTitle("Abbreviate journal names (ISO)"), Localization.lang("Abbreviate journal names of the selected entries (ISO abbreviation)"), Globals.getKeyPrefs().getKey(KeyBinding.ABBREVIATE)); private final AbstractAction unabbreviate = new GeneralAction(Actions.UNABBREVIATE, Localization.menuTitle("Unabbreviate journal names"), Localization.lang("Unabbreviate journal names of the selected entries"), Globals.getKeyPrefs().getKey(KeyBinding.UNABBREVIATE)); private final AbstractAction manageJournals = new ManageJournalsAction(this); private final AbstractAction databaseProperties = new DatabasePropertiesAction(); private final AbstractAction bibtexKeyPattern = new BibtexKeyPatternAction(); private final AbstractAction errorConsole = new ErrorConsoleAction(this, Globals.streamEavesdropper, GuiAppender.cache); private final AbstractAction dbConnect = new GeneralAction(Actions.DB_CONNECT, Localization.menuTitle("Connect to external SQL database"), Localization.lang("Connect to external SQL database")); private final AbstractAction dbExport = new GeneralAction(Actions.DB_EXPORT, Localization.menuTitle("Export to external SQL database"), Localization.lang("Export to external SQL database")); private final AbstractAction cleanupEntries = new GeneralAction(Actions.CLEANUP, Localization.menuTitle("Cleanup entries"), Localization.lang("Cleanup entries"), Globals.getKeyPrefs().getKey(KeyBinding.CLEANUP), IconTheme.JabRefIcon.CLEANUP_ENTRIES.getIcon()); private final AbstractAction mergeEntries = new GeneralAction(Actions.MERGE_ENTRIES, Localization.menuTitle("Merge entries"), Localization.lang("Merge entries"), IconTheme.JabRefIcon.MERGE_ENTRIES.getIcon()); private final AbstractAction dbImport = new DbImportAction(this).getAction(); private final AbstractAction downloadFullText = new GeneralAction(Actions.DOWNLOAD_FULL_TEXT, Localization.menuTitle("Look up full text document"), Localization.lang("Follow DOI or URL link and try to locate PDF full text document")); private final AbstractAction increaseFontSize = new IncreaseTableFontSizeAction(); private final AbstractAction decreseFontSize = new DecreaseTableFontSizeAction(); private final AbstractAction resolveDuplicateKeys = new GeneralAction(Actions.RESOLVE_DUPLICATE_KEYS, Localization.menuTitle("Resolve duplicate BibTeX keys"), Localization.lang("Find and remove duplicate BibTeX keys"), Globals.getKeyPrefs().getKey(KeyBinding.RESOLVE_DUPLICATE_BIBTEX_KEYS)); private final AbstractAction sendAsEmail = new GeneralAction(Actions.SEND_AS_EMAIL, Localization.lang("Send as email"), IconTheme.JabRefIcon.EMAIL.getIcon()); final MassSetFieldAction massSetField = new MassSetFieldAction(this); final ManageKeywordsAction manageKeywords = new ManageKeywordsAction(this); private final GeneralAction findUnlinkedFiles = new GeneralAction( FindUnlinkedFilesDialog.ACTION_COMMAND, FindUnlinkedFilesDialog.ACTION_MENU_TITLE, FindUnlinkedFilesDialog.ACTION_SHORT_DESCRIPTION, Globals.getKeyPrefs().getKey(KeyBinding.FIND_UNLINKED_FILES) ); private final AutoLinkFilesAction autoLinkFile = new AutoLinkFilesAction(); private PushToApplicationButton pushExternalButton; private GeneralFetcher generalFetcher; private final List<Action> fetcherActions = new LinkedList<>(); public GroupSelector groupSelector; // The action for adding a new entry of unspecified type. private final NewEntryAction newEntryAction = new NewEntryAction(this, Globals.getKeyPrefs().getKey(KeyBinding.NEW_ENTRY)); private final List<NewEntryAction> newSpecificEntryAction = getNewEntryActions(); private List<NewEntryAction> getNewEntryActions() { List<NewEntryAction> actions = new ArrayList<>(); if (biblatexMode) { for (String key : EntryTypes.getAllTypes()) { actions.add(new NewEntryAction(this, key)); } } else { // Bibtex for (EntryType type : BibtexEntryTypes.ALL) { KeyStroke keyStroke = ChangeEntryTypeMenu.entryShortCuts.get(type.getName()); if (keyStroke == null) { actions.add(new NewEntryAction(this, type.getName())); } else { actions.add(new NewEntryAction(this, type.getName(), keyStroke)); } } // ieeetran for (EntryType type : IEEETranEntryTypes.ALL) { actions.add(new NewEntryAction(this, type.getName())); } // custom types for (EntryType type : CustomEntryTypesManager.ALL) { actions.add(new NewEntryAction(this, type.getName())); } } return actions; } public JabRefFrame(JabRef jabRef) { this.jabRef = jabRef; init(); updateEnabledState(); } private JPopupMenu tabPopupMenu() { JPopupMenu popupMenu = new JPopupMenu(); // Close actions JMenuItem close = new JMenuItem(Localization.lang("Close")); JMenuItem closeOthers = new JMenuItem(Localization.lang("Close Others")); JMenuItem closeAll = new JMenuItem(Localization.lang("Close All")); close.addActionListener(closeDatabaseAction); closeOthers.addActionListener(closeOtherDatabasesAction); closeAll.addActionListener(closeAllDatabasesAction); popupMenu.add(close); popupMenu.add(closeOthers); popupMenu.add(closeAll); popupMenu.addSeparator(); JMenuItem databasePropertiesBtn = new JMenuItem(Localization.lang("Database properties")); databasePropertiesBtn.addActionListener(databaseProperties); popupMenu.add(databasePropertiesBtn); JMenuItem bibtexKeyPatternBtn = new JMenuItem(Localization.lang("BibTeX key patterns")); bibtexKeyPatternBtn.addActionListener(bibtexKeyPattern); popupMenu.add(bibtexKeyPatternBtn); JMenuItem manageSelectorsBtn = new JMenuItem(Localization.lang("Manage content selectors")); manageSelectorsBtn.addActionListener(manageSelectors); popupMenu.add(manageSelectorsBtn); return popupMenu; } private void init() { tabbedPane = new DragDropPopupPane(tabPopupMenu()); MyGlassPane glassPane = new MyGlassPane(); setGlassPane(glassPane); setTitle(GUIGlobals.frameTitle); setIconImage(new ImageIcon(IconTheme.getIconUrl("jabrefIcon48")).getImage()); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (OS.OS_X) { JabRefFrame.this.setVisible(false); } else { new CloseAction().actionPerformed(null); } } }); initSidePane(); initLayout(); initActions(); // Show the toolbar if it was visible at last shutdown: tlb.setVisible(Globals.prefs.getBoolean(JabRefPreferences.TOOLBAR_VISIBLE)); setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds()); pw = new PositionWindow(this, JabRefPreferences.POS_X, JabRefPreferences.POS_Y, JabRefPreferences.SIZE_X, JabRefPreferences.SIZE_Y); positionWindowOnScreen(); // Set up a ComponentListener that saves the last size and position of the dialog this.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Save dialog position pw.storeWindowPosition(); } @Override public void componentMoved(ComponentEvent e) { // Save dialog position pw.storeWindowPosition(); } }); tabbedPane.setBorder(null); tabbedPane.setForeground(GUIGlobals.inActiveTabbed); /* * The following state listener makes sure focus is registered with the * correct database when the user switches tabs. Without this, * cut/paste/copy operations would some times occur in the wrong tab. */ tabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { markActiveBasePanel(); BasePanel bp = getCurrentBasePanel(); if (bp != null) { groupToggle.setSelected(sidePaneManager.isComponentVisible("groups")); previewToggle.setSelected(Globals.prefs.getBoolean(JabRefPreferences.PREVIEW_ENABLED)); fetcherToggle.setSelected(sidePaneManager.isComponentVisible(generalFetcher.getTitle())); Globals.focusListener.setFocused(bp.mainTable); setWindowTitle(); // Update search autocompleter with information for the correct database: bp.updateSearchManager(); // Set correct enabled state for Back and Forward actions: bp.setBackAndForwardEnabledState(); new FocusRequester(bp.mainTable); } } }); //Note: The registration of Apple event is at the end of initialization, because //if the events happen too early (ie when the window is not initialized yet), the //opened (double-clicked) documents are not displayed. if (OS.OS_X) { try { new MacAdapter().registerMacEvents(this); } catch (Exception e) { LOGGER.fatal("Could not interface with Mac OS X methods.", e); } } } private void positionWindowOnScreen() { if (!prefs.getBoolean(JabRefPreferences.WINDOW_MAXIMISED)) { pw.setWindowPosition(); } } /** * Tries to open a browser with the given URL * <p> * All errors are logged * * @param url the url to open */ public void openBrowser(String url) { try { JabRefDesktop.openBrowser(url); output(Localization.lang("External viewer called") + '.'); } catch (IOException ex) { output(Localization.lang("Error") + ": " + ex.getMessage()); LOGGER.debug("Cannot open browser.", ex); } } /** * Sets the title of the main window. */ public void setWindowTitle() { BasePanel panel = getCurrentBasePanel(); String mode = biblatexMode ? " (" + Localization.lang("%0 mode", "BibLaTeX") + ")" : " (" + Localization.lang("%0 mode", "BibTeX") + ")"; // no database open if (panel == null) { setTitle(GUIGlobals.frameTitle + mode); return; } String changeFlag = panel.isModified() ? "*" : ""; if (panel.getDatabaseFile() == null) { setTitle(GUIGlobals.frameTitle + " - " + GUIGlobals.untitledTitle + changeFlag + mode); } else { String databaseFile = panel.getDatabaseFile().getPath(); setTitle(GUIGlobals.frameTitle + " - " + databaseFile + changeFlag + mode); } } private void initSidePane() { sidePaneManager = new SidePaneManager(this); GUIGlobals.sidePaneManager = this.sidePaneManager; GUIGlobals.helpDiag = this.helpDiag; groupSelector = new GroupSelector(this, sidePaneManager); generalFetcher = new GeneralFetcher(sidePaneManager, this); sidePaneManager.register("groups", groupSelector); } /** * The MacAdapter calls this method when a ".bib" file has been double-clicked from the Finder. */ public void openAction(String filePath) { File file = new File(filePath); // all the logic is done in openIt. Even raising an existing panel open.openFile(file, true); } // General info dialog. The MacAdapter calls this method when "About" // is selected from the application menu. public void about() { // reuse the normal about action // null as parameter is OK as the code of actionPerformed does not rely on the data sent in the event. about.actionPerformed(null); } // General preferences dialog. The MacAdapter calls this method when "Preferences..." // is selected from the application menu. public void preferences() { //PrefsDialog.showPrefsDialog(JabRefFrame.this, prefs); AbstractWorker worker = new AbstractWorker() { @Override public void run() { output(Localization.lang("Opening preferences...")); if (prefsDialog == null) { prefsDialog = new PreferencesDialog(JabRefFrame.this, jabRef); PositionWindow.placeDialog(prefsDialog, JabRefFrame.this); } else { prefsDialog.setValues(); } } @Override public void update() { prefsDialog.setVisible(true); output(""); } }; worker.getWorker().run(); worker.getCallBack().update(); } public JabRefPreferences prefs() { return prefs; } /** * Tears down all things started by JabRef * <p> * FIXME: Currently some threads remain and therefore hinder JabRef to be closed properly * * @param filenames the filenames of all currently opened files - used for storing them if prefs openLastEdited is set to true */ private void tearDownJabRef(List<String> filenames) { JabRefExecutorService.INSTANCE.shutdownEverything(); dispose(); if (getCurrentBasePanel() != null) { getCurrentBasePanel().saveDividerLocation(); } //prefs.putBoolean(JabRefPreferences.WINDOW_MAXIMISED, (getExtendedState()&MAXIMIZED_BOTH)>0); prefs.putBoolean(JabRefPreferences.WINDOW_MAXIMISED, getExtendedState() == Frame.MAXIMIZED_BOTH); prefs.putBoolean(JabRefPreferences.TOOLBAR_VISIBLE, tlb.isVisible()); // Store divider location for side pane: int width = contentPane.getDividerLocation(); if (width > 0) { prefs.putInt(JabRefPreferences.SIDE_PANE_WIDTH, width); } if (prefs.getBoolean(JabRefPreferences.OPEN_LAST_EDITED)) { // Here we store the names of all current files. If // there is no current file, we remove any // previously stored filename. if (filenames.isEmpty()) { prefs.remove(JabRefPreferences.LAST_EDITED); } else { prefs.putStringList(JabRefPreferences.LAST_EDITED, filenames); File focusedDatabase = getCurrentBasePanel().getDatabaseFile(); new LastFocusedTabPreferences(prefs).setLastFocusedTab(focusedDatabase); } } fileHistory.storeHistory(); prefs.customExports.store(); prefs.customImports.store(); CustomEntryTypesManager.saveCustomEntryTypes(prefs); // Clear autosave files: if (Globals.autoSaveManager != null) { Globals.autoSaveManager.clearAutoSaves(); } prefs.flush(); // dispose all windows, even if they are not displayed anymore for (Window window : Window.getWindows()) { window.dispose(); } // shutdown any timers that are may be active if (Globals.autoSaveManager != null) { Globals.stopAutoSaveManager(); } } /** * General info dialog. The MacAdapter calls this method when "Quit" * is selected from the application menu, Cmd-Q is pressed, or "Quit" is selected from the Dock. * The function returns a boolean indicating if quitting is ok or not. * <p> * Non-OSX JabRef calls this when choosing "Quit" from the menu * <p> * SIDE EFFECT: tears down JabRef * * @return true if the user chose to quit; false otherwise */ public boolean quit() { // Ask here if the user really wants to close, if the base // has not been saved since last save. boolean close = true; List<String> filenames = new ArrayList<>(); if (tabbedPane.getTabCount() > 0) { for (int i = 0; i < tabbedPane.getTabCount(); i++) { if (getBasePanelAt(i).isModified()) { tabbedPane.setSelectedIndex(i); String filename; if (getBasePanelAt(i).getDatabaseFile() == null) { filename = GUIGlobals.untitledTitle; } else { filename = getBasePanelAt(i).getDatabaseFile().getAbsolutePath(); } int answer = showSaveDialog(filename); if ((answer == JOptionPane.CANCEL_OPTION) || (answer == JOptionPane.CLOSED_OPTION)) { return false; } if (answer == JOptionPane.YES_OPTION) { // The user wants to save. try { //getCurrentBasePanel().runCommand("save"); SaveDatabaseAction saveAction = new SaveDatabaseAction(getCurrentBasePanel()); saveAction.runCommand(); if (saveAction.isCancelled() || !saveAction.isSuccess()) { // The action was either cancelled or unsuccessful. // Break! output(Localization.lang("Unable to save database")); close = false; } } catch (Throwable ex) { // Something prevented the file // from being saved. Break!!! close = false; break; } } } if (getBasePanelAt(i).getDatabaseFile() != null) { filenames.add(getBasePanelAt(i).getDatabaseFile().getAbsolutePath()); } } } if (close) { for (int i = 0; i < tabbedPane.getTabCount(); i++) { if (getBasePanelAt(i).isSaving()) { // There is a database still being saved, so we need to wait. WaitForSaveOperation w = new WaitForSaveOperation(this); w.show(); // This method won't return until cancelled or the save operation is done. if (w.cancelled()) { return false; // The user clicked cancel. } } } tearDownJabRef(filenames); return true; } return false; } private void initLayout() { tabbedPane.putClientProperty(Options.NO_CONTENT_BORDER_KEY, Boolean.TRUE); setProgressBarVisible(false); pushExternalButton = new PushToApplicationButton(this, PushToApplications.APPLICATIONS); fillMenu(); createToolBar(); getContentPane().setLayout(gbl); contentPane.setDividerSize(2); contentPane.setBorder(null); //getContentPane().setBackground(GUIGlobals.lightGray); con.fill = GridBagConstraints.HORIZONTAL; con.anchor = GridBagConstraints.WEST; con.weightx = 1; con.weighty = 0; con.gridwidth = GridBagConstraints.REMAINDER; //gbl.setConstraints(mb, con); //getContentPane().add(mb); setJMenuBar(mb); con.anchor = GridBagConstraints.NORTH; //con.gridwidth = 1;//GridBagConstraints.REMAINDER;; gbl.setConstraints(tlb, con); getContentPane().add(tlb); Component lim = Box.createGlue(); gbl.setConstraints(lim, con); //getContentPane().add(lim); /* JPanel empt = new JPanel(); empt.setBackground(GUIGlobals.lightGray); gbl.setConstraints(empt, con); getContentPane().add(empt); con.insets = new Insets(1,0,1,1); con.anchor = GridBagConstraints.EAST; con.weightx = 0; gbl.setConstraints(searchManager, con); getContentPane().add(searchManager);*/ con.gridwidth = GridBagConstraints.REMAINDER; con.weightx = 1; con.weighty = 0; con.fill = GridBagConstraints.BOTH; con.anchor = GridBagConstraints.WEST; con.insets = new Insets(0, 0, 0, 0); lim = Box.createGlue(); gbl.setConstraints(lim, con); getContentPane().add(lim); //tabbedPane.setVisible(false); //tabbedPane.setForeground(GUIGlobals.lightGray); con.weighty = 1; gbl.setConstraints(contentPane, con); getContentPane().add(contentPane); UIManager.put("TabbedPane.contentBorderInsets", new Insets(0, 0, 0, 0)); contentPane.setRightComponent(tabbedPane); contentPane.setLeftComponent(sidePaneManager.getPanel()); sidePaneManager.updateView(); JPanel status = new JPanel(); status.setLayout(gbl); con.weighty = 0; con.weightx = 0; con.gridwidth = 1; con.insets = new Insets(0, 2, 0, 0); gbl.setConstraints(statusLabel, con); status.add(statusLabel); con.weightx = 1; con.insets = new Insets(0, 4, 0, 0); con.gridwidth = 1; gbl.setConstraints(statusLine, con); status.add(statusLine); con.weightx = 0; con.gridwidth = GridBagConstraints.REMAINDER; con.insets = new Insets(2, 4, 2, 2); gbl.setConstraints(progressBar, con); status.add(progressBar); con.weightx = 1; con.gridwidth = GridBagConstraints.REMAINDER; statusLabel.setForeground(GUIGlobals.entryEditorLabelColor.darker()); con.insets = new Insets(0, 0, 0, 0); gbl.setConstraints(status, con); getContentPane().add(status); // Drag and drop for tabbedPane: TransferHandler xfer = new EntryTableTransferHandler(null, this, null); tabbedPane.setTransferHandler(xfer); tlb.setTransferHandler(xfer); mb.setTransferHandler(xfer); sidePaneManager.getPanel().setTransferHandler(xfer); } /** * Returns the indexed BasePanel. * * @param i Index of base */ public BasePanel getBasePanelAt(int i) { return (BasePanel) tabbedPane.getComponentAt(i); } public void showBasePanelAt(int i) { tabbedPane.setSelectedIndex(i); } public void showBasePanel(BasePanel bp) { tabbedPane.setSelectedComponent(bp); } /** * Returns the currently viewed BasePanel. */ public BasePanel getCurrentBasePanel() { return (BasePanel) tabbedPane.getSelectedComponent(); } /** * @return the BasePanel count. */ public int getBasePanelCount() { return tabbedPane.getComponentCount(); } /** * handle the color of active and inactive JTabbedPane tabs */ public void markActiveBasePanel() { int now = tabbedPane.getSelectedIndex(); int len = tabbedPane.getTabCount(); if ((lastTabbedPanelSelectionIndex > -1) && (lastTabbedPanelSelectionIndex < len)) { tabbedPane.setForegroundAt(lastTabbedPanelSelectionIndex, GUIGlobals.inActiveTabbed); } if ((now > -1) && (now < len)) { tabbedPane.setForegroundAt(now, GUIGlobals.activeTabbed); } lastTabbedPanelSelectionIndex = now; } private int getTabIndex(JComponent comp) { for (int i = 0; i < tabbedPane.getTabCount(); i++) { if (tabbedPane.getComponentAt(i) == comp) { return i; } } return -1; } public JTabbedPane getTabbedPane() { return tabbedPane; } public void setTabTitle(JComponent comp, String title, String toolTip) { int index = getTabIndex(comp); tabbedPane.setTitleAt(index, title); tabbedPane.setToolTipTextAt(index, toolTip); } class GeneralAction extends MnemonicAwareAction { private final String command; public GeneralAction(String command, String text) { this.command = command; putValue(Action.NAME, text); } public GeneralAction(String command, String text, String description) { this.command = command; putValue(Action.NAME, text); putValue(Action.SHORT_DESCRIPTION, description); } public GeneralAction(String command, String text, Icon icon) { super(icon); this.command = command; putValue(Action.NAME, text); } public GeneralAction(String command, String text, String description, Icon icon) { super(icon); this.command = command; putValue(Action.NAME, text); putValue(Action.SHORT_DESCRIPTION, description); } public GeneralAction(String command, String text, KeyStroke key) { this.command = command; putValue(Action.NAME, text); putValue(Action.ACCELERATOR_KEY, key); } public GeneralAction(String command, String text, String description, KeyStroke key) { this.command = command; putValue(Action.NAME, text); putValue(Action.SHORT_DESCRIPTION, description); putValue(Action.ACCELERATOR_KEY, key); } public GeneralAction(String command, String text, String description, KeyStroke key, Icon icon) { super(icon); this.command = command; putValue(Action.NAME, text); putValue(Action.SHORT_DESCRIPTION, description); putValue(Action.ACCELERATOR_KEY, key); } @Override public void actionPerformed(ActionEvent e) { if (tabbedPane.getTabCount() > 0) { try { ((BasePanel) tabbedPane.getSelectedComponent()).runCommand(command); } catch (Throwable ex) { ex.printStackTrace(); } } else { LOGGER.info("Action '" + command + "' must be disabled when no database is open."); } } } private void fillMenu() { //mb.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH); mb.setBorder(null); JMenu file = JabRefFrame.subMenu(Localization.menuTitle("File")); JMenu edit = JabRefFrame.subMenu(Localization.menuTitle("Edit")); JMenu search = JabRefFrame.subMenu(Localization.menuTitle("Search")); JMenu groups = JabRefFrame.subMenu(Localization.menuTitle("Groups")); JMenu bibtex = JabRefFrame.subMenu(Localization.menuTitle("BibTeX")); JMenu quality = JabRefFrame.subMenu(Localization.menuTitle("Quality")); JMenu view = JabRefFrame.subMenu(Localization.menuTitle("View")); JMenu tools = JabRefFrame.subMenu(Localization.menuTitle("Tools")); JMenu options = JabRefFrame.subMenu(Localization.menuTitle("Options")); JMenu newSpec = JabRefFrame.subMenu(Localization.menuTitle("New entry...")); JMenu helpMenu = JabRefFrame.subMenu(Localization.menuTitle("Help")); file.add(newDatabaseAction); file.add(open); //opendatabaseaction file.add(mergeDatabaseAction); file.add(save); file.add(saveAs); file.add(saveAll); file.add(saveSelectedAs); file.add(saveSelectedAsPlain); file.addSeparator(); file.add(importNew); file.add(importCurrent); file.add(exportAll); file.add(exportSelected); file.addSeparator(); file.add(dbConnect); file.add(dbImport); file.add(dbExport); file.addSeparator(); file.add(databaseProperties); file.addSeparator(); file.add(fileHistory); file.addSeparator(); file.add(editModeAction); file.addSeparator(); file.add(closeDatabaseAction); file.add(quit); mb.add(file); edit.add(undo); edit.add(redo); edit.addSeparator(); edit.add(cut); edit.add(copy); edit.add(paste); edit.addSeparator(); edit.add(copyKey); edit.add(copyCiteKey); edit.add(copyKeyAndTitle); edit.add(exportToClipboard); edit.add(sendAsEmail); edit.addSeparator(); edit.add(mark); JMenu markSpecific = JabRefFrame.subMenu(Localization.menuTitle("Mark specific color")); for (int i = 0; i < EntryMarker.MAX_MARKING_LEVEL; i++) { markSpecific.add(new MarkEntriesAction(this, i).getMenuItem()); } edit.add(markSpecific); edit.add(unmark); edit.add(unmarkAll); edit.addSeparator(); if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED)) { JMenu m; if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING)) { m = new JMenu(); RightClickMenu.populateSpecialFieldMenu(m, Rank.getInstance(), this); edit.add(m); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE)) { edit.add(toggleRelevance); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY)) { edit.add(toggleQualityAssured); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY)) { m = new JMenu(); RightClickMenu.populateSpecialFieldMenu(m, Priority.getInstance(), this); edit.add(m); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED)) { edit.add(togglePrinted); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ)) { m = new JMenu(); RightClickMenu.populateSpecialFieldMenu(m, ReadStatus.getInstance(), this); edit.add(m); } edit.addSeparator(); } edit.add(manageKeywords); edit.addSeparator(); edit.add(selectAll); mb.add(edit); search.add(normalSearch); search.add(replaceAll); search.add(massSetField); search.addSeparator(); search.add(generalFetcher.getAction()); if (prefs.getBoolean(JabRefPreferences.WEB_SEARCH_VISIBLE)) { sidePaneManager.register(generalFetcher.getTitle(), generalFetcher); sidePaneManager.show(generalFetcher.getTitle()); } mb.add(search); groups.add(toggleGroups); groups.addSeparator(); groups.add(addToGroup); groups.add(removeFromGroup); groups.add(moveToGroup); groups.addSeparator(); groups.add(toggleHighlightAny); groups.add(toggleHighlightAll); mb.add(groups); view.add(back); view.add(forward); view.add(focusTable); view.add(nextTab); view.add(prevTab); view.add(sortTabs); view.addSeparator(); view.add(increaseFontSize); view.add(decreseFontSize); view.addSeparator(); view.add(toggleToolbar); view.add(generalFetcher.getAction()); view.add(toggleGroups); view.add(togglePreview); view.add(switchPreview); mb.add(view); bibtex.add(newEntryAction); for (NewEntryAction a : newSpecificEntryAction) { newSpec.add(a); } bibtex.add(newSpec); bibtex.add(plainTextImport); bibtex.addSeparator(); bibtex.add(editEntry); bibtex.add(editPreamble); bibtex.add(editStrings); bibtex.addSeparator(); bibtex.add(customizeAction); bibtex.addSeparator(); bibtex.add(deleteEntry); mb.add(bibtex); quality.add(dupliCheck); quality.add(mergeEntries); quality.addSeparator(); quality.add(resolveDuplicateKeys); quality.add(checkIntegrity); quality.add(cleanupEntries); quality.add(makeKeyAction); quality.addSeparator(); quality.add(autoSetFile); quality.add(findUnlinkedFiles); quality.add(autoLinkFile); quality.add(downloadFullText); mb.add(quality); tools.add(newSubDatabaseAction); tools.add(writeXmpAction); OpenOfficePanel otp = OpenOfficePanel.getInstance(); otp.init(this, sidePaneManager); tools.add(otp.getMenuItem()); tools.add(pushExternalButton.getMenuAction()); tools.addSeparator(); tools.add(openFolder); tools.add(openFile); tools.add(openUrl); tools.addSeparator(); tools.add(abbreviateIso); tools.add(abbreviateMedline); tools.add(unabbreviate); mb.add(tools); options.add(showPrefs); AbstractAction genFieldsCustomization = new GenFieldsCustomizationAction(); options.add(genFieldsCustomization); options.add(customExpAction); options.add(customImpAction); options.add(customFileTypesAction); options.add(manageJournals); options.add(manageSelectors); options.add(selectKeys); mb.add(options); helpMenu.add(help); helpMenu.addSeparator(); helpMenu.add(errorConsole); helpMenu.addSeparator(); helpMenu.add(forkMeOnGitHubAction); helpMenu.add(donationAction); helpMenu.addSeparator(); helpMenu.add(about); mb.add(helpMenu); createDisabledIconsForMenuEntries(mb); } public static JMenu subMenu(String name) { int i = name.indexOf('&'); JMenu res; if (i >= 0) { res = new JMenu(name.substring(0, i) + name.substring(i + 1)); char mnemonic = Character.toUpperCase(name.charAt(i + 1)); res.setMnemonic((int) mnemonic); } else { res = new JMenu(name); } return res; } public void addParserResult(ParserResult pr, boolean raisePanel) { if (pr.toOpenTab()) { // Add the entries to the open tab. BasePanel panel = getCurrentBasePanel(); if (panel == null) { // There is no open tab to add to, so we create a new tab: addTab(pr.getDatabase(), pr.getFile(), pr.getMetaData(), pr.getEncoding(), raisePanel); } else { List<BibEntry> entries = new ArrayList<>(pr.getDatabase().getEntries()); addImportedEntries(panel, entries, false); } } else { addTab(pr.getDatabase(), pr.getFile(), pr.getMetaData(), pr.getEncoding(), raisePanel); } } private void createToolBar() { tlb.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH); tlb.setBorder(null); tlb.setRollover(true); tlb.setFloatable(false); tlb.addAction(newDatabaseAction); tlb.addAction(open); tlb.addAction(save); tlb.addAction(saveAll); tlb.addSeparator(); tlb.addAction(cut); tlb.addAction(copy); tlb.addAction(paste); tlb.addAction(undo); tlb.addAction(redo); tlb.addSeparator(); tlb.addAction(back); tlb.addAction(forward); tlb.addSeparator(); tlb.addAction(newEntryAction); tlb.addAction(editEntry); tlb.addAction(editStrings); tlb.addAction(deleteEntry); tlb.addSeparator(); tlb.addAction(makeKeyAction); tlb.addAction(cleanupEntries); tlb.addAction(mergeEntries); tlb.addSeparator(); tlb.addAction(mark); tlb.addAction(unmark); tlb.addSeparator(); if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED)) { if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING)) { tlb.add(net.sf.jabref.specialfields.SpecialFieldDropDown.generateSpecialFieldButtonWithDropDown(Rank.getInstance(), this)); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE)) { tlb.addAction(toggleRelevance); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY)) { tlb.addAction(toggleQualityAssured); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY)) { tlb.add(net.sf.jabref.specialfields.SpecialFieldDropDown.generateSpecialFieldButtonWithDropDown(Priority.getInstance(), this)); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED)) { tlb.addAction(togglePrinted); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ)) { tlb.add(net.sf.jabref.specialfields.SpecialFieldDropDown.generateSpecialFieldButtonWithDropDown(ReadStatus.getInstance(), this)); } tlb.addSeparator(); } fetcherToggle = new JToggleButton(generalFetcher.getAction()); tlb.addJToogleButton(fetcherToggle); previewToggle = new JToggleButton(togglePreview); tlb.addJToogleButton(previewToggle); groupToggle = new JToggleButton(toggleGroups); tlb.addJToogleButton(groupToggle); tlb.addSeparator(); tlb.add(pushExternalButton.getComponent()); tlb.addSeparator(); tlb.add(donationAction); } public void output(final String s) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { statusLine.setText(s); statusLine.repaint(); } }); } public void stopShowingSearchResults() { for (int i = 0; i < tabbedPane.getTabCount(); i++) { getBasePanelAt(i).getFilterSearchToggle().stop(); } } private List<Object> openDatabaseOnlyActions = new LinkedList<>(); private List<Object> severalDatabasesOnlyActions = new LinkedList<>(); private void initActions() { openDatabaseOnlyActions = new LinkedList<>(); openDatabaseOnlyActions.addAll(Arrays.asList(manageSelectors, mergeDatabaseAction, newSubDatabaseAction, save, saveAs, saveSelectedAs, saveSelectedAsPlain, undo, redo, cut, deleteEntry, copy, paste, mark, unmark, unmarkAll, editEntry, selectAll, copyKey, copyCiteKey, copyKeyAndTitle, editPreamble, editStrings, toggleGroups, makeKeyAction, normalSearch, mergeEntries, cleanupEntries, exportToClipboard, replaceAll, sendAsEmail, downloadFullText, writeXmpAction, findUnlinkedFiles, addToGroup, removeFromGroup, moveToGroup, autoLinkFile, resolveDuplicateKeys, openUrl, openFolder, openFile, togglePreview, dupliCheck, autoSetFile, newEntryAction, plainTextImport, massSetField, manageKeywords, pushExternalButton.getMenuAction(), closeDatabaseAction, switchPreview, checkIntegrity, toggleHighlightAny, toggleHighlightAll, databaseProperties, abbreviateIso, abbreviateMedline, unabbreviate, exportAll, exportSelected, importCurrent, saveAll, dbConnect, dbExport, focusTable)); openDatabaseOnlyActions.addAll(fetcherActions); openDatabaseOnlyActions.addAll(newSpecificEntryAction); severalDatabasesOnlyActions = new LinkedList<>(); severalDatabasesOnlyActions.addAll(Arrays .asList(nextTab, prevTab, sortTabs)); tabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { updateEnabledState(); } }); } /** * Takes a list of Object and calls the method setEnabled on them, depending on whether it is an Action or a Component. * * @param list List that should contain Actions and Components. * @param enabled */ private static void setEnabled(List<Object> list, boolean enabled) { for (Object o : list) { if (o instanceof Action) { ((Action) o).setEnabled(enabled); } if (o instanceof Component) { ((Component) o).setEnabled(enabled); } } } private int previousTabCount = -1; /** * Enable or Disable all actions based on the number of open tabs. * <p> * The action that are affected are set in initActions. */ public void updateEnabledState() { int tabCount = tabbedPane.getTabCount(); if (tabCount != previousTabCount) { previousTabCount = tabCount; JabRefFrame.setEnabled(openDatabaseOnlyActions, tabCount > 0); JabRefFrame.setEnabled(severalDatabasesOnlyActions, tabCount > 1); } if (tabCount == 0) { back.setEnabled(false); forward.setEnabled(false); } } /** * This method causes all open BasePanels to set up their tables * anew. When called from PrefsDialog3, this updates to the new * settings. */ public void setupAllTables() { // This action can be invoked without an open database, so // we have to check if we have one before trying to invoke // methods to execute changes in the preferences. // We want to notify all tabs about the changes to // avoid problems when changing the column set. for (int i = 0; i < tabbedPane.getTabCount(); i++) { BasePanel bf = getBasePanelAt(i); // Update tables: if (bf.getDatabase() != null) { bf.setupMainPanel(); } } } public BasePanel addTab(BibDatabase db, File file, MetaData metaData, Charset encoding, boolean raisePanel) { // ensure that non-null parameters are really non-null if (metaData == null) { metaData = new MetaData(); } if (encoding == null) { encoding = Globals.prefs.getDefaultEncoding(); } BasePanel bp = new BasePanel(JabRefFrame.this, db, file, metaData, encoding); addTab(bp, file, raisePanel); return bp; } private List<String> collectDatabaseFilePaths() { List<String> dbPaths = new ArrayList<>(getBasePanelCount()); for (int i = 0; i < getBasePanelCount(); i++) { try { // db file exists if (getBasePanelAt(i).getDatabaseFile() == null) { dbPaths.add(""); } else { dbPaths.add(getBasePanelAt(i).getDatabaseFile().getCanonicalPath()); } } catch (IOException ex) { LOGGER.error("Invalid database file path: " + ex.getMessage()); } } return dbPaths; } private List<String> getUniquePathParts() { List<String> dbPaths = collectDatabaseFilePaths(); return FileUtil.uniquePathSubstrings(dbPaths); } public void updateAllTabTitles() { List<String> paths = getUniquePathParts(); for (int i = 0; i < getBasePanelCount(); i++) { String uniqPath = paths.get(i); File file = getBasePanelAt(i).getDatabaseFile(); if ((file != null) && !uniqPath.equals(file.getName())) { // remove filename uniqPath = uniqPath.substring(0, uniqPath.lastIndexOf(File.separator)); tabbedPane.setTitleAt(i, getBasePanelAt(i).getTabTitle() + " \u2014 " + uniqPath); } else if ((file != null) && uniqPath.equals(file.getName())) { // set original filename (again) tabbedPane.setTitleAt(i, getBasePanelAt(i).getTabTitle()); } } } public void addTab(BasePanel bp, File file, boolean raisePanel) { // add tab tabbedPane.add(bp.getTabTitle(), bp); tabbedPane.setToolTipTextAt(tabbedPane.getTabCount() - 1, file == null ? null : file.getAbsolutePath()); // update all tab titles updateAllTabTitles(); if (raisePanel) { tabbedPane.setSelectedComponent(bp); } } /** * Creates icons for the disabled state for all JMenuItems with FontBasedIcons in the given menuElement. * This is necessary as Swing is not able to generate default disabled icons for font based icons. * * @param menuElement the menuElement for which disabled icons should be generated */ public void createDisabledIconsForMenuEntries(MenuElement menuElement) { for (MenuElement subElement : menuElement.getSubElements()) { if ((subElement instanceof JMenu) || (subElement instanceof JPopupMenu)) { createDisabledIconsForMenuEntries(subElement); } else if (subElement instanceof JMenuItem) { JMenuItem item = (JMenuItem) subElement; if (item.getIcon() instanceof IconTheme.FontBasedIcon) { item.setDisabledIcon(((IconTheme.FontBasedIcon) item.getIcon()).createDisabledIcon()); } } } } class SelectKeysAction extends AbstractAction { public SelectKeysAction() { super(Localization.lang("Customize key bindings")); this.putValue(Action.SMALL_ICON, IconTheme.JabRefIcon.KEY_BINDINGS.getSmallIcon()); } @Override public void actionPerformed(ActionEvent e) { KeyBindingsDialog d = new KeyBindingsDialog(new KeyBindingRepository(Globals.getKeyPrefs().getKeyBindings())); d.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); d.pack(); //setSize(300,500); PositionWindow.placeDialog(d, JabRefFrame.this); d.setVisible(true); } } /** * The action concerned with closing the window. */ class CloseAction extends MnemonicAwareAction { public CloseAction() { putValue(Action.NAME, Localization.menuTitle("Quit")); putValue(Action.SHORT_DESCRIPTION, Localization.lang("Quit JabRef")); putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.QUIT_JABREF)); } @Override public void actionPerformed(ActionEvent e) { quit(); } } // The action for closing the current database and leaving the window open. private final CloseDatabaseAction closeDatabaseAction = new CloseDatabaseAction(); private final CloseAllDatabasesAction closeAllDatabasesAction = new CloseAllDatabasesAction(); private final CloseOtherDatabasesAction closeOtherDatabasesAction = new CloseOtherDatabasesAction(); // The action for opening the preferences dialog. private final AbstractAction showPrefs = new ShowPrefsAction(); class ShowPrefsAction extends MnemonicAwareAction { public ShowPrefsAction() { super(IconTheme.JabRefIcon.PREFERENCES.getIcon()); putValue(Action.NAME, Localization.menuTitle("Preferences")); putValue(Action.SHORT_DESCRIPTION, Localization.lang("Preferences")); } @Override public void actionPerformed(ActionEvent e) { preferences(); } } /** * This method does the job of adding imported entries into the active * database, or into a new one. It shows the ImportInspectionDialog if * preferences indicate it should be used. Otherwise it imports directly. * * @param panel The BasePanel to add to. * @param entries The entries to add. * @param openInNew Should the entries be imported into a new database? */ private void addImportedEntries(final BasePanel panel, final List<BibEntry> entries, final boolean openInNew) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ImportInspectionDialog diag = new ImportInspectionDialog(JabRefFrame.this, panel, BibtexFields.DEFAULT_INSPECTION_FIELDS, Localization.lang("Import"), openInNew); diag.addEntries(entries); diag.entryListComplete(); PositionWindow.placeDialog(diag, JabRefFrame.this); diag.setVisible(true); diag.toFront(); } }); } public FileHistoryMenu getFileHistory() { return fileHistory; } /** * Set the preview active state for all BasePanel instances. * * @param enabled */ public void setPreviewActive(boolean enabled) { for (int i = 0; i < tabbedPane.getTabCount(); i++) { getBasePanelAt(i).setPreviewActive(enabled); } } public void removeCachedEntryEditors() { for (int j = 0; j < tabbedPane.getTabCount(); j++) { BasePanel bp = (BasePanel) tabbedPane.getComponentAt(j); bp.entryEditors.clear(); } } /** * This method shows a wait cursor and blocks all input to the JFrame's contents. */ public void block() { getGlassPane().setVisible(true); } /** * This method reverts the cursor to normal, and stops blocking input to the JFrame's contents. * There are no adverse effects of calling this method redundantly. */ public void unblock() { getGlassPane().setVisible(false); } /** * Set the visibility of the progress bar in the right end of the * status line at the bottom of the frame. * <p> * If not called on the event dispatch thread, this method uses * SwingUtilities.invokeLater() to do the actual operation on the EDT. */ public void setProgressBarVisible(final boolean visible) { if (SwingUtilities.isEventDispatchThread()) { progressBar.setVisible(visible); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setVisible(visible); } }); } } /** * Sets the current value of the progress bar. * <p> * If not called on the event dispatch thread, this method uses * SwingUtilities.invokeLater() to do the actual operation on the EDT. */ public void setProgressBarValue(final int value) { if (SwingUtilities.isEventDispatchThread()) { progressBar.setValue(value); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(value); } }); } } /** * Sets the indeterminate status of the progress bar. * <p> * If not called on the event dispatch thread, this method uses * SwingUtilities.invokeLater() to do the actual operation on the EDT. */ public void setProgressBarIndeterminate(final boolean value) { if (SwingUtilities.isEventDispatchThread()) { progressBar.setIndeterminate(value); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setIndeterminate(value); } }); } } /** * Sets the maximum value of the progress bar. Always call this method * before using the progress bar, to set a maximum value appropriate to * the task at hand. * <p> * If not called on the event dispatch thread, this method uses * SwingUtilities.invokeLater() to do the actual operation on the EDT. */ public void setProgressBarMaximum(final int value) { if (SwingUtilities.isEventDispatchThread()) { progressBar.setMaximum(value); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setMaximum(value); } }); } } class ChangeTabAction extends MnemonicAwareAction { private final boolean next; public ChangeTabAction(boolean next) { putValue(Action.NAME, next ? Localization.menuTitle("Next tab") : Localization.menuTitle("Previous tab")); this.next = next; putValue(Action.ACCELERATOR_KEY, next ? Globals.getKeyPrefs().getKey(KeyBinding.NEXT_TAB) : Globals.getKeyPrefs().getKey(KeyBinding.PREVIOUS_TAB)); } @Override public void actionPerformed(ActionEvent e) { int i = tabbedPane.getSelectedIndex(); int newI = next ? i + 1 : i - 1; if (newI < 0) { newI = tabbedPane.getTabCount() - 1; } if (newI == tabbedPane.getTabCount()) { newI = 0; } tabbedPane.setSelectedIndex(newI); } } /** * Class for handling general actions; cut, copy and paste. The focused component is * kept track of by Globals.focusListener, and we call the action stored under the * relevant name in its action map. */ class EditAction extends MnemonicAwareAction { private final String command; public EditAction(String command, String menuTitle, String description, KeyStroke key, Icon icon) { super(icon); this.command = command; putValue(Action.NAME, menuTitle); putValue(Action.ACCELERATOR_KEY, key); putValue(Action.SHORT_DESCRIPTION, description); } @Override public void actionPerformed(ActionEvent e) { LOGGER.debug(Globals.focusListener.getFocused().toString()); JComponent source = Globals.focusListener.getFocused(); try { source.getActionMap().get(command).actionPerformed(new ActionEvent(source, 0, command)); } catch (NullPointerException ex) { // No component is focused, so we do nothing. } } } class CustomizeExportsAction extends MnemonicAwareAction { public CustomizeExportsAction() { putValue(Action.NAME, Localization.menuTitle("Manage custom exports")); } @Override public void actionPerformed(ActionEvent e) { ExportCustomizationDialog ecd = new ExportCustomizationDialog(JabRefFrame.this); ecd.setVisible(true); } } class CustomizeImportsAction extends MnemonicAwareAction { public CustomizeImportsAction() { putValue(Action.NAME, Localization.menuTitle("Manage custom imports")); } @Override public void actionPerformed(ActionEvent e) { ImportCustomizationDialog ecd = new ImportCustomizationDialog(JabRefFrame.this); ecd.setVisible(true); } } class CustomizeEntryTypeAction extends MnemonicAwareAction { public CustomizeEntryTypeAction() { putValue(Action.NAME, Localization.menuTitle("Customize entry types")); } @Override public void actionPerformed(ActionEvent e) { JDialog dl = new EntryCustomizationDialog(JabRefFrame.this); PositionWindow.placeDialog(dl, JabRefFrame.this); dl.setVisible(true); } } class GenFieldsCustomizationAction extends MnemonicAwareAction { public GenFieldsCustomizationAction() { putValue(Action.NAME, Localization.menuTitle("Set up general fields")); } @Override public void actionPerformed(ActionEvent e) { GenFieldsCustomizer gf = new GenFieldsCustomizer(JabRefFrame.this); PositionWindow.placeDialog(gf, JabRefFrame.this); gf.setVisible(true); } } class DatabasePropertiesAction extends MnemonicAwareAction { private DatabasePropertiesDialog propertiesDialog; public DatabasePropertiesAction() { putValue(Action.NAME, Localization.menuTitle("Database properties")); } @Override public void actionPerformed(ActionEvent e) { if (propertiesDialog == null) { propertiesDialog = new DatabasePropertiesDialog(JabRefFrame.this); } propertiesDialog.setPanel(getCurrentBasePanel()); PositionWindow.placeDialog(propertiesDialog, JabRefFrame.this); propertiesDialog.setVisible(true); } } class BibtexKeyPatternAction extends MnemonicAwareAction { private BibtexKeyPatternDialog bibtexKeyPatternDialog; public BibtexKeyPatternAction() { putValue(Action.NAME, Localization.lang("BibTeX key patterns")); } @Override public void actionPerformed(ActionEvent e) { JabRefPreferences.getInstance(); if (bibtexKeyPatternDialog == null) { // if no instance of BibtexKeyPatternDialog exists, create new one bibtexKeyPatternDialog = new BibtexKeyPatternDialog(JabRefFrame.this, getCurrentBasePanel()); } else { // BibtexKeyPatternDialog allows for updating content based on currently selected panel bibtexKeyPatternDialog.setPanel(getCurrentBasePanel()); } PositionWindow.placeDialog(bibtexKeyPatternDialog, JabRefFrame.this); bibtexKeyPatternDialog.setVisible(true); } } class IncreaseTableFontSizeAction extends MnemonicAwareAction { public IncreaseTableFontSizeAction() { putValue(Action.NAME, Localization.menuTitle("Increase table font size")); putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.INCREASE_TABLE_FONT_SIZE)); } @Override public void actionPerformed(ActionEvent event) { int currentSize = GUIGlobals.CURRENTFONT.getSize(); GUIGlobals.CURRENTFONT = new Font(GUIGlobals.CURRENTFONT.getFamily(), GUIGlobals.CURRENTFONT.getStyle(), currentSize + 1); Globals.prefs.putInt(JabRefPreferences.FONT_SIZE, currentSize + 1); for (int i = 0; i < getBasePanelCount(); i++) { getBasePanelAt(i).updateTableFont(); } } } class DecreaseTableFontSizeAction extends MnemonicAwareAction { public DecreaseTableFontSizeAction() { putValue(Action.NAME, Localization.menuTitle("Decrease table font size")); putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.DECREASE_TABLE_FONT_SIZE)); } @Override public void actionPerformed(ActionEvent event) { int currentSize = GUIGlobals.CURRENTFONT.getSize(); if (currentSize < 2) { return; } GUIGlobals.CURRENTFONT = new Font(GUIGlobals.CURRENTFONT.getFamily(), GUIGlobals.CURRENTFONT.getStyle(), currentSize - 1); Globals.prefs.putInt(JabRefPreferences.FONT_SIZE, currentSize - 1); for (int i = 0; i < getBasePanelCount(); i++) { getBasePanelAt(i).updateTableFont(); } } } private static class MyGlassPane extends JPanel { //ForegroundLabel infoLabel = new ForegroundLabel("Showing search"); public MyGlassPane() { addKeyListener(new KeyAdapter() { // Nothing }); addMouseListener(new MouseAdapter() { // Nothing }); /* infoLabel.setForeground(new Color(255, 100, 100, 124)); setLayout(new BorderLayout()); add(infoLabel, BorderLayout.CENTER);*/ super.setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // Override isOpaque() to prevent the glasspane from hiding the window contents: @Override public boolean isOpaque() { return false; } } @Override public void showMessage(Object message, String title, int msgType) { JOptionPane.showMessageDialog(this, message, title, msgType); } @Override public void setStatus(String s) { output(s); } @Override public void showMessage(String message) { JOptionPane.showMessageDialog(this, message); } public int showSaveDialog(String filename) { Object[] options = {Localization.lang("Save changes"), Localization.lang("Discard changes"), Localization.lang("Return to JabRef")}; return JOptionPane.showOptionDialog(JabRefFrame.this, Localization.lang("Database '%0' has changed.", filename), Localization.lang("Save before closing"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); } private void closeTab(BasePanel panel) { // empty tab without database if (panel == null) { return; } if (panel.isModified()) { if (confirmClose(panel)) { removeTab(panel); } } else { removeTab(panel); } } // Ask if the user really wants to close, if the base has not been saved private boolean confirmClose(BasePanel panel) { boolean close = false; String filename; if (panel.getDatabaseFile() == null) { filename = GUIGlobals.untitledTitle; } else { filename = panel.getDatabaseFile().getAbsolutePath(); } int answer = showSaveDialog(filename); if (answer == JOptionPane.YES_OPTION) { // The user wants to save. try { SaveDatabaseAction saveAction = new SaveDatabaseAction(panel); saveAction.runCommand(); if (saveAction.isSuccess()) { close = true; } } catch (Throwable ex) { // do not close } } else if (answer == JOptionPane.NO_OPTION) { // discard changes close = true; } return close; } private void removeTab(BasePanel panel) { panel.cleanUp(); AutoSaveManager.deleteAutoSaveFile(panel); tabbedPane.remove(panel); if (tabbedPane.getTabCount() > 0) { markActiveBasePanel(); } setWindowTitle(); updateEnabledState(); output(Localization.lang("Closed database") + '.'); // update tab titles updateAllTabTitles(); } public class CloseDatabaseAction extends MnemonicAwareAction { public CloseDatabaseAction() { super(IconTheme.JabRefIcon.CLOSE.getSmallIcon()); putValue(Action.NAME, Localization.menuTitle("Close database")); putValue(Action.SHORT_DESCRIPTION, Localization.lang("Close the current database")); putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DATABASE)); } @Override public void actionPerformed(ActionEvent e) { closeTab(getCurrentBasePanel()); } } public class CloseAllDatabasesAction extends MnemonicAwareAction { @Override public void actionPerformed(ActionEvent e) { final Component[] panels = tabbedPane.getComponents(); for (Component p : panels) { closeTab((BasePanel) p); } } } public class CloseOtherDatabasesAction extends MnemonicAwareAction { @Override public void actionPerformed(ActionEvent e) { final BasePanel active = getCurrentBasePanel(); final Component[] panels = tabbedPane.getComponents(); for (Component p : panels) { if (p != active) { closeTab((BasePanel) p); } } } } }
package net.tenorite.modes; import net.tenorite.badges.BadgeValidator; import net.tenorite.core.Tempo; import net.tenorite.game.*; import net.tenorite.game.listeners.SuddenDeath; import net.tenorite.protocol.Message; import net.tenorite.protocol.PlayerWonMessage; import net.tenorite.util.Scheduler; import org.springframework.stereotype.Component; import java.util.*; import java.util.function.Consumer; import static net.tenorite.badges.BadgeValidators.*; import static net.tenorite.game.PlayingStats.*; @Component public final class SevenOFour extends GameMode { private static final Comparator<PlayingStats> BY_FOUR_LINE_COMBOS = (o1, o2) -> o1.getNrOfFourLineCombos() - o2.getNrOfFourLineCombos(); private static final Comparator<PlayingStats> COMPARATOR = BY_FOUR_LINE_COMBOS.reversed() // most four line combos first .thenComparing(BY_COMBOS.reversed()) // most combos first .thenComparing(BY_LEVEL.reversed()) // highest levels first .thenComparing(BY_BLOCKS.reversed()) // most blocks first .thenComparing(BY_MAX_HEIGTH); // lowest field first public static final GameModeId ID = GameModeId.of("SOF"); private static final GameRules RULES = GameRules.gameRules(b -> b .classicRules(false) .specialAdded(0) .specialCapacity(0) ); public SevenOFour() { super(ID, RULES); } @Override public String getTitle(Tempo tempo) { return "Seven 'o Four"; } @Override public String getDescription(Tempo tempo) { return "7 Four Line Combos to win!"; } @Override public GameListener createGameListener(Scheduler scheduler, Consumer<Message> channel) { return new Listener(channel).and(new SuddenDeath(300, 10, 1, scheduler, channel)); } @Override public Comparator<PlayingStats> getPlayingStatsComparator() { return COMPARATOR; } @Override public List<BadgeValidator> getBadgeValidators() { return Arrays.asList( competitor(ID), likeAPro(ID), likeAKing(ID), imOnFire(ID), justKeepTrying(ID), fastAndFurious(ID), eliminator(ID), eradicator(ID), dropsInTheBucket(ID), dropItLikeItsHot(ID) ); } private static final class Listener implements GameListener { private static final int TARGET = 7; private final Consumer<Message> channel; private Map<Integer, Integer> nrOfFourLines = new HashMap<>(); Listener(Consumer<Message> channel) { this.channel = channel; } @Override public void onClassicStyleAdd(Player sender, int lines) { if (lines == 4 && incr(sender.getSlot()) >= TARGET) { channel.accept(PlayerWonMessage.of(sender.getSlot())); } } private int incr(int sender) { return nrOfFourLines.compute(sender, (k, v) -> v == null ? 1 : v + 1); } } }
package org.jtrfp.trcl; import java.awt.Color; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Queue; import java.util.TimerTask; import java.util.concurrent.Executor; import org.jtrfp.trcl.beh.BehaviorNotFoundException; import org.jtrfp.trcl.beh.FacingObject; import org.jtrfp.trcl.beh.HasDescription; import org.jtrfp.trcl.beh.MatchDirection; import org.jtrfp.trcl.beh.MatchPosition; import org.jtrfp.trcl.beh.RequestsMentionOnBriefing; import org.jtrfp.trcl.beh.RotateAroundObject; import org.jtrfp.trcl.beh.SkyCubeCloudModeUpdateBehavior; import org.jtrfp.trcl.beh.ui.UserInputWeaponSelectionBehavior; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.ResourceManager; import org.jtrfp.trcl.core.TRFactory; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.ctl.ControllerMapperFactory.ControllerMapper; import org.jtrfp.trcl.ctl.ControllerSink; import org.jtrfp.trcl.ctl.ControllerSinksFactory.ControllerSinks; import org.jtrfp.trcl.ext.tr.GPUFactory.GPUFeature; import org.jtrfp.trcl.file.LVLFile; import org.jtrfp.trcl.file.TXTMissionBriefFile; import org.jtrfp.trcl.flow.TransientExecutor; import org.jtrfp.trcl.game.Game; import org.jtrfp.trcl.game.Game.GameRunMode; import org.jtrfp.trcl.gpu.GL33Model; import org.jtrfp.trcl.gpu.Renderer; import org.jtrfp.trcl.gui.BriefingLayout; import org.jtrfp.trcl.img.vq.ColorPaletteVectorList; import org.jtrfp.trcl.miss.Mission; import org.jtrfp.trcl.miss.Mission.Briefing; import org.jtrfp.trcl.miss.Mission.MissionSummary; import org.jtrfp.trcl.miss.TunnelSystemFactory.TunnelSystem; import org.jtrfp.trcl.obj.DEFObject; import org.jtrfp.trcl.obj.Sprite2D; import org.jtrfp.trcl.obj.WorldObject; import org.jtrfp.trcl.shell.GameShellFactory.GameShell; public class BriefingScreen extends RenderableSpacePartitioningGrid { public static final String NEXT_SCREEN_CTL = "Next Screen"; private static final double Z_INCREMENT = .00001; private static final double Z_START = -.99999; private static final double BRIEFING_SPRITE_Z = Z_START; private static final double TEXT_Z = BRIEFING_SPRITE_Z + Z_INCREMENT; private static final double TEXT_BG_Z = TEXT_Z + Z_INCREMENT; public static final double MAX_Z_DEPTH = TEXT_BG_Z + Z_INCREMENT; private final TR tr; private final Sprite2D briefingScreen; private final CharAreaDisplay briefingChars; private final Sprite2D blackRectangle; private volatile double scrollPos = 0; private final double scrollIncrement; private ArrayList<Runnable> scrollFinishCallbacks = new ArrayList<Runnable>(); private ColorPaletteVectorList palette; private TimerTask scrollTimer; private WorldObject planetObject; private final BriefingLayout layout; //private final ControllerBarrier fireBarrier; //private final RunStateListener runStateListener = new RunStateListener(); private TypeRunStateHandler runStateListener; private Runnable scrollFinishCallback; private final Collection<Runnable>nextScreenRunnable = new ArrayList<>(2); private PropertyChangeListener nextScreenPCL; public abstract class BriefingStage implements Briefing { private final LVLFile lvl; public BriefingStage(LVLFile lvl){ this.lvl = lvl; } public LVLFile getLvl() { return lvl; } }//end BriefingState public class PlanetDisplay extends BriefingStage { public PlanetDisplay(LVLFile lvl) { super(lvl); } }//end PlanetDisplay public class EnemyBriefings extends BriefingStage { public EnemyBriefings(LVLFile lvl) { super(lvl); } }//end EnemyBriefings public class SpecificEnemyBriefing extends EnemyBriefings { private final Queue<DEFObject> enemyDEFs; public SpecificEnemyBriefing(LVLFile lvl, Queue<DEFObject> enemyDEFs) { super(lvl); this.enemyDEFs = enemyDEFs; }//end constructor public Queue<DEFObject> getEnemyDEFs() { return enemyDEFs; } }//end EnemyBriefing public class MissionSummaryState implements Briefing { private final LVLFile lvl; private final MissionSummary summary; public MissionSummaryState(MissionSummary summary, LVLFile lvl) { this.lvl = lvl; this.summary = summary; } public LVLFile getLvl() { return lvl; } public MissionSummary getSummary() { return summary; } }//end MissionSummary public BriefingScreen(final TR tr, GLFont font, final BriefingLayout layout, String debugName) { super(); this.layout=layout; final ControllerMapper cm = Features.get(Features.getSingleton(), ControllerMapper.class); final ControllerSinks controllerInputs = Features.get(cm, ControllerSinks.class); final ControllerSink nextScreenSink = controllerInputs.getSink(NEXT_SCREEN_CTL); final ControllerSink fireButtonSink = controllerInputs.getSink(UserInputWeaponSelectionBehavior.FIRE); //fireBarrier = new ControllerBarrier( // controllerInputs.getSink(UserInputWeaponSelectionBehavior.FIRE), // controllerInputs.getSink(NEXT_SCREEN_CTL)); briefingScreen = new Sprite2D(tr,0, 2, 2, tr.getResourceManager().getSpecialRAWAsTextures("BRIEF.RAW", tr.getGlobalPalette(), Features.get(tr, GPUFeature.class).getGl(), 0,false, true),true,"BriefingScreen."+debugName); add(briefingScreen); this.tr = tr; briefingChars = new CharAreaDisplay(layout.getFontSizeGL(),layout.getNumCharsPerLine(),layout.getNumLines(),tr,font); blockingAddBranch(briefingChars); final Point2D.Double textPos = layout.getTextPosition(); briefingChars.setPosition(textPos.getX(), textPos.getY(), TEXT_Z); briefingScreen.setPosition(0,0,BRIEFING_SPRITE_Z); briefingScreen.notifyPositionChange(); briefingScreen.setImmuneToOpaqueDepthTest(true); briefingScreen.setActive(true); briefingScreen.setVisible(true); blackRectangle = new Sprite2D(0, 2, .6, Features.get(tr,GPUFeature.class).textureManager.get().solidColor(Color.BLACK), false,"BriefingScreen.blackRectangle."+debugName); add(blackRectangle); blackRectangle.setImmuneToOpaqueDepthTest(true); blackRectangle.setPosition(0, -.7, TEXT_BG_Z); blackRectangle.setVisible(true); blackRectangle.setActive(true); scrollIncrement = layout.getScrollIncrement(); tr.addPropertyChangeListener(TRFactory.RUN_STATE, runStateListener = new TypeRunStateHandler(Briefing.class){ TypeRunStateHandler startPlanetBriefingHandler = new TypeRunStateHandler(PlanetDisplay.class){ private Runnable briefingExitRunnable; @Override public void enteredRunState(Object oldState, Object newState) { System.out.println("START PLANET BRIEFING"); final PlanetDisplay pd = (PlanetDisplay)newState; final Game game = Features.get(tr,GameShell.class).getGame(); //Set up planet brief game.getPlayer().setActive(false); final TXTMissionBriefFile txtMBF = tr.getResourceManager().getMissionText(pd.getLvl().getBriefingTextFile()); String content = txtMBF.getMissionText().replace("\r",""); planetDisplayMode(txtMBF.getPlanetModelFile(),txtMBF.getPlanetTextureFile(), pd.getLvl()); final String playerName = game.getPlayerName(); for(String token:layout.getNameTokens()) content=content.replace(token, playerName); setContent(content); startScroll(); nextScreenRunnable.add(briefingExitRunnable = new Runnable(){ @Override public void run() { tr.setRunState(new EnemyBriefings(pd.getLvl())); }}); final boolean [] mWait = new boolean[]{false}; addScrollFinishCallback(scrollFinishCallback = new Runnable(){ @Override public void run() { //synchronized(mWait){mWait[0] = true; mWait.notifyAll();} //Need to run in transient thread to change run state final Executor executor = TransientExecutor.getSingleton(); synchronized(executor){ executor.execute(new Runnable(){ @Override public void run() { tr.setRunState(new EnemyBriefings(pd.getLvl())); }}); }//end sync(exeuctor) }}); }//end enteredRunState @Override public void exitedRunState(Object oldState, Object newState) { removeScrollFinishCallback(scrollFinishCallback); stopScroll(); nextScreenRunnable.remove(briefingExitRunnable); }}, enemyIntroHandler = new TypeRunStateHandler(EnemyBriefings.class){ @Override public void enteredRunState(Object oldState, Object newState) { final Game game = Features.get(tr,GameShell.class).getGame(); final Renderer renderer = tr.mainRenderer; final BriefingStage newStage = (BriefingStage)newState; //final SkySystem skySystem = game.getCurrentMission().getOverworldSystem().getSkySystem(); renderer.getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(true); /* renderer.getSkyCube().setSkyCubeGen(skySystem.getBelowCloudsSkyCubeGen()); renderer.setAmbientLight(skySystem.getSuggestedAmbientLight()); renderer.setSunColor(skySystem.getSuggestedSunColor()); */ final OverworldSystem overworldSystem = game.getCurrentMission().getOverworldSystem(); overworldSystem.applyToRenderer(renderer); final List<DEFObject> defObjects = overworldSystem.getDefList(); final ArrayDeque<DEFObject> defs = new ArrayDeque<>(); for(DEFObject obj:defObjects) if(obj.hasBehavior(RequestsMentionOnBriefing.class)) defs.add(obj); final Executor executor = TransientExecutor.getSingleton(); synchronized(executor){ executor.execute(new Runnable(){ @Override public void run() { tr.setRunState(new SpecificEnemyBriefing(newStage.getLvl(),defs)); }}); }//end sync(executor) }//end enteredRunState(...) @Override public void exitedRunState(Object oldState, Object newState) { // TODO Auto-generated method stub }}; final PropertyChangeListener specificEnemyIntroHandler = new PropertyChangeListener(){ Runnable nextScreen; @Override public void propertyChange(PropertyChangeEvent evt) { final Object newValue = evt.getNewValue(), oldValue = evt.getOldValue(); final Game game = Features.get(tr,GameShell.class).getGame(); final Renderer renderer = tr.mainRenderer; final Camera camera = renderer.getCamera(); if( !(newValue instanceof SpecificEnemyBriefing) && oldValue instanceof SpecificEnemyBriefing ) { camera.probeForBehavior(FacingObject.class).setEnable(false); camera.probeForBehavior(RotateAroundObject.class).setEnable(false); camera.probeForBehavior(MatchPosition.class).setEnable(true); camera.probeForBehavior(MatchDirection.class).setEnable(true); nextScreenRunnable.remove(nextScreen); }//end if(leaving enemy briefing) else if( newValue instanceof SpecificEnemyBriefing && newValue != oldValue ) { final SpecificEnemyBriefing briefing = (SpecificEnemyBriefing)newValue; final DEFObject def = briefing.getEnemyDEFs().poll(); if( def == null){ final Executor executor = TransientExecutor.getSingleton(); synchronized(executor){ executor.execute(new Runnable(){ @Override public void run() { game.getCurrentMission().switchToOverworldState(); }}); }//end sync(executor) }//end if(null) else { //Requests mention on briefing String descriptionString; try{descriptionString = def.probeForBehavior(HasDescription.class).getHumanReadableDescription(); } catch(BehaviorNotFoundException e){ descriptionString = null; } if(descriptionString == null) descriptionString = "[no description]"; final boolean vis = def.isVisible(); final boolean act = def.isActive(); def.setActive(true); def.setVisible(true); camera.probeForBehavior(FacingObject.class).setTarget(def); camera.probeForBehavior(FacingObject.class).setHeadingOffset(layout.cameraHeadingAdjust()); camera.probeForBehavior(RotateAroundObject.class).setTarget(def); camera.probeForBehavior(RotateAroundObject.class).setAngularVelocityRPS(.3); //Roughly center the object (ground objects have their bottom at Y=0) if(def.getModel().getTriangleList()!=null){ camera.probeForBehavior(RotateAroundObject.class).setOffset( new double []{ 0, def.getModel(). getTriangleList(). getMaximumVertexDims(). getY(), 0}); camera.probeForBehavior(RotateAroundObject.class).setDistance( def.getModel().getTriangleList().getMaximumVertexDims().getX()*3);} else if(def.getModel().getTransparentTriangleList()!=null){ camera.probeForBehavior(RotateAroundObject.class).setOffset( new double []{ 0, def.getModel(). getTransparentTriangleList(). getMaximumVertexDims(). getY(), 0}); camera.probeForBehavior(RotateAroundObject.class).setDistance( def.getModel().getTransparentTriangleList().getMaximumVertexDims().getX()*6);} //If this intro takes place in the chamber, enter chamber mode. //boolean chamberMode = false; final boolean chamberMode = def.isShieldGen() || def.isBoss(); if(chamberMode){ final OverworldSystem overworldSystem = game.getCurrentMission().getOverworldSystem(); overworldSystem.setChamberMode(true); } def.tick(System.currentTimeMillis());//Make sure its position and state is sane. camera.tick(System.currentTimeMillis());//Make sure the camera knows what is going on. def.setRespondToTick(false);//freeze stopScroll(); briefingChars.setScrollPosition(layout.getNumLines()-2); setContent(descriptionString); //fireBarrier.waitForEvent(); nextScreenRunnable.add(nextScreen = new Runnable(){ @Override public void run() { //Restore previous state. def.setVisible(vis); def.setActive(act); def.setRespondToTick(true);//unfreeze if(chamberMode){ final OverworldSystem overworldSystem = game.getCurrentMission().getOverworldSystem(); overworldSystem.setChamberMode(false);} tr.setRunState(new SpecificEnemyBriefing(briefing.getLvl(),briefing.getEnemyDEFs())); }}); }//end if(requestsMention) }//end if(SpecificEnemyBriefing) }//end propertyChange(...) }, missionSummaryHandler = new TypeRunStateHandler(MissionSummaryState.class) { Runnable nextScreen; @Override public void enteredRunState(Object oldState, Object newState) { final MissionSummaryState ms = (MissionSummaryState)newState; final LVLFile lvl = ms.getLvl(); final MissionSummary summary = ms.getSummary(); final Game game = Features.get(tr,GameShell.class).getGame(); final TunnelSystem ts = Features.get(game.getCurrentMission(), TunnelSystem.class); game.getPlayer().setActive(false); briefingChars.setScrollPosition(layout.getNumLines()-2); setContent("Air targets destroyed: "+summary.getAirTargetsDestroyed()+ "\nGround targets destroyed: "+summary.getGroundTargetsDestroyed()+ "\nVegetation destroyed: "+summary.getFoliageDestroyed()+ "\nTunnels found: "+(int)((1.-(double)ts.getTunnelsRemaining().size()/(double)ts.getTotalNumTunnels())*100.)+"%"); final TXTMissionBriefFile txtMBF = tr.getResourceManager().getMissionText(lvl.getBriefingTextFile()); planetDisplayMode(txtMBF.getPlanetModelFile(),txtMBF.getPlanetTextureFile(),lvl); //fireBarrier.waitForEvent(); nextScreenRunnable.add(nextScreen = new Runnable(){ @Override public void run() { final Mission mission = game.getCurrentMission(); mission.missionComplete(); }}); }//end enteredRunState() @Override public void exitedRunState(Object oldState, Object newState) { final Camera camera = tr.mainRenderer.getCamera(); camera.probeForBehavior(MatchPosition.class) .setEnable(true); camera.probeForBehavior(MatchDirection.class) .setEnable(true); camera.probeForBehavior(FacingObject.class) .setEnable(false); camera.probeForBehavior(RotateAroundObject.class).setEnable(false); nextScreenRunnable.remove(nextScreen); }//end exitedRunState() }; @Override public void enteredRunState(Object oldState, Object newState) { tr.addPropertyChangeListener(TRFactory.RUN_STATE, startPlanetBriefingHandler); tr.addPropertyChangeListener(TRFactory.RUN_STATE, enemyIntroHandler); tr.addPropertyChangeListener(TRFactory.RUN_STATE, specificEnemyIntroHandler); tr.addPropertyChangeListener(TRFactory.RUN_STATE, missionSummaryHandler); fireButtonSink.addPropertyChangeListener(nextScreenPCL = new PropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent evt) { if((Double)evt.getNewValue() > .5 && (Double)evt.getOldValue() < .5) { final Collection<Runnable> nextScreenRunnables = BriefingScreen.this.nextScreenRunnable; final Executor executor = TransientExecutor.getSingleton(); synchronized(executor){ for(Runnable r:nextScreenRunnables) executor.execute(r); nextScreenRunnables.clear(); }//end sync(executor) } }}); nextScreenSink.addPropertyChangeListener(nextScreenPCL); final PropertyChangeEvent evt = new PropertyChangeEvent(this, TRFactory.RUN_STATE, oldState, newState); startPlanetBriefingHandler.propertyChange(evt); enemyIntroHandler .propertyChange(evt); specificEnemyIntroHandler .propertyChange(evt); missionSummaryHandler .propertyChange(evt); }//end enteredRunState(...) @Override public void exitedRunState(Object oldState, Object newState) { tr.removePropertyChangeListener(TRFactory.RUN_STATE, startPlanetBriefingHandler); tr.removePropertyChangeListener(TRFactory.RUN_STATE, enemyIntroHandler); tr.removePropertyChangeListener(TRFactory.RUN_STATE, specificEnemyIntroHandler); tr.removePropertyChangeListener(TRFactory.RUN_STATE, missionSummaryHandler); final PropertyChangeEvent evt = new PropertyChangeEvent(this, TRFactory.RUN_STATE, oldState, newState); startPlanetBriefingHandler.propertyChange(evt); enemyIntroHandler .propertyChange(evt); specificEnemyIntroHandler .propertyChange(evt); missionSummaryHandler .propertyChange(evt); //tr.removePropertyChangeListener(TRFactory.RUN_STATE, this); fireButtonSink.removePropertyChangeListener(nextScreenPCL); nextScreenSink.removePropertyChangeListener(nextScreenPCL); nextScreenRunnable.clear(); }}); //XXX Kludge to clean up the run state listeners if the game is aborted, else they will reference leak and keep reacting even when new BriefingScreens are created. tr.addPropertyChangeListener(TRFactory.RUN_STATE, new TypeRunStateHandler (GameRunMode.class){ @Override public void enteredRunState(Object oldState, Object newState) {} @Override public void exitedRunState(Object oldState, Object newState) { tr.removePropertyChangeListener(TRFactory.RUN_STATE, this); tr.removePropertyChangeListener(TRFactory.RUN_STATE, runStateListener); final PropertyChangeEvent evt = new PropertyChangeEvent(this, TRFactory.RUN_STATE, oldState, newState); runStateListener.propertyChange(evt); }}); }//end constructor protected void notifyScrollFinishCallbacks() { for(Runnable r:scrollFinishCallbacks){ r.run(); } }//end notifyScrollFinishCallbacks() public void addScrollFinishCallback(Runnable r){ scrollFinishCallbacks.add(r); } public void removeScrollFinishCallback(Runnable r){ scrollFinishCallbacks.remove(r); } public void setContent(String content) { briefingChars.setContent(content); } public void startScroll() { scrollPos=0; tr.getThreadManager().getLightweightTimer().scheduleAtFixedRate(scrollTimer = new TimerTask(){ @Override public void run() { scrollPos+=scrollIncrement; briefingChars.setScrollPosition(scrollPos); if(scrollPos>briefingChars.getNumActiveLines()+layout.getNumLines()){ BriefingScreen.this.stopScroll(); notifyScrollFinishCallbacks(); scrollFinishCallbacks.clear(); } }}, 0, 20); }//end startScroll() public void stopScroll() { scrollTimer.cancel(); } private void planetDisplayMode(String planetModelFile, String planetTextureFile, LVLFile lvl){ final ResourceManager rm = tr.getResourceManager(); final Camera camera = tr.mainRenderer.getCamera(); //TODO: Depth range //Planet introduction if(planetObject!=null){ remove(planetObject); planetObject=null; } try{ final boolean isPlanetTextureNull = planetTextureFile.toLowerCase().contentEquals("null.raw"); final GL33Model planetModel = rm.getBINModel(planetModelFile, isPlanetTextureNull? null : rm.getRAWAsTexture(planetTextureFile, getPalette(lvl), null, false, true), 8,false,getPalette(lvl),null); planetObject = new WorldObject(planetModel); planetObject.setPosition(0, TRFactory.mapSquareSize*20, 0); add(planetObject); planetObject.setVisible(true); camera.probeForBehavior(FacingObject.class) .setTarget(planetObject); camera.probeForBehavior(FacingObject.class) .setHeadingOffset(layout.cameraHeadingAdjust()); camera.probeForBehavior(RotateAroundObject.class).setTarget(planetObject); camera.probeForBehavior(RotateAroundObject.class).setAngularVelocityRPS(.05); camera.probeForBehavior(RotateAroundObject.class).setOffset( new double []{0,-planetModel.getTriangleList().getMaximumVertexDims().getY(),0}); camera.probeForBehavior(RotateAroundObject.class).setDistance( planetModel.getTriangleList().getMaximumVertexDims().getX()*2); }catch(Exception e){tr.showStopper(e);} // Turn the camera to the planet camera.probeForBehavior(MatchPosition.class).setEnable(false); camera.probeForBehavior(MatchDirection.class).setEnable(false); camera.probeForBehavior(RotateAroundObject.class).setEnable(true); camera.probeForBehavior(FacingObject.class).setEnable(true); final Renderer renderer = tr.mainRenderer; renderer.getCamera() .probeForBehavior(SkyCubeCloudModeUpdateBehavior.class) .setEnable(false); renderer.getSkyCube().setSkyCubeGen(SkySystem.SPACE_STARS); renderer.setAmbientLight(SkySystem.SPACE_AMBIENT_LIGHT); renderer.setSunColor(SkySystem.SPACE_SUN_COLOR); }//end planetDisplayMode() public void missionCompleteSummary(LVLFile lvl, MissionSummary summary){ final Game game = Features.get(tr,GameShell.class).getGame(); final Mission mission = game.getCurrentMission(); final TunnelSystem ts = Features.get(mission, TunnelSystem.class); tr.setRunState(new MissionSummaryState(summary,lvl)); }//end missionCompleteSummary() public void briefingSequence(LVLFile lvl) { System.out.println("BriefingScreen.briefingSequence()"); //XXX This is already added in the constructor //tr.addPropertyChangeListener(TRFactory.RUN_STATE, runStateListener);//Removes itself tr.setRunState(new PlanetDisplay(lvl)); }//end briefingSequence private ColorPaletteVectorList getPalette(LVLFile lvl){ if(palette==null){ try{palette = new ColorPaletteVectorList(tr.getResourceManager().getPalette(lvl.getGlobalPaletteFile()));} catch(Exception e){tr.showStopper(e);} }//end if(null) return palette; }//end ColorPaletteVectorList }//end BriefingScreen
package org.opencloudb.net; import java.io.IOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.log4j.Logger; /** * * * @author mycat */ public final class NIOReactor { private static final Logger LOGGER = Logger.getLogger(NIOReactor.class); private final String name; private final RW reactorR; public NIOReactor(String name) throws IOException { this.name = name; this.reactorR = new RW(); } final void startup() { new Thread(reactorR, name + "-RW").start(); } final void postRegister(AbstractConnection c) { reactorR.registerQueue.offer(c); reactorR.selector.wakeup(); } final Queue<AbstractConnection> getRegisterQueue() { return reactorR.registerQueue; } final long getReactCount() { return reactorR.reactCount; } private final class RW implements Runnable { private final Selector selector; private final ConcurrentLinkedQueue<AbstractConnection> registerQueue; private long reactCount; private RW() throws IOException { this.selector = Selector.open(); this.registerQueue = new ConcurrentLinkedQueue<AbstractConnection>(); } @Override public void run() { final Selector selector = this.selector; Set<SelectionKey> keys = null; for (;;) { ++reactCount; try { selector.select(500L); register(selector); keys = selector.selectedKeys(); for (SelectionKey key : keys) { AbstractConnection con = null; try { Object att = key.attachment(); if (att != null) { con = (AbstractConnection) att; if (key.isValid() && key.isReadable()) { try { con.asynRead(); } catch (IOException e) { LOGGER.warn("caught err:", e); con.close("program err:" + e.toString()); continue; } catch (Exception e) { LOGGER.debug("caught err:", e); con.close("program err:" + e.toString()); continue; } } if (key.isValid() && key.isWritable()) { con.doNextWriteCheck(); } } else { key.cancel(); } } catch (CancelledKeyException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(con + " socket key canceled"); } } catch (Exception e) { LOGGER.warn(con + " " + e); } } } catch (Exception e) { LOGGER.warn(name, e); } finally { if (keys != null) { keys.clear(); } } } } private void register(Selector selector) { AbstractConnection c = null; if (registerQueue.isEmpty()) { return; } while ((c = registerQueue.poll()) != null) { try { ((NIOSocketWR) c.getSocketWR()).register(selector); c.register(); } catch (Exception e) { LOGGER.warn("register error ", e); c.close("register err"); } } } } }
package org.paltree.palnote.main; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("/fxml/Window.fxml")); primaryStage.setTitle("PaLNote"); primaryStage.setScene(new Scene(root, 800, 600)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
package org.scijava.script; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.script.ScriptException; import org.scijava.Context; import org.scijava.Contextual; import org.scijava.ItemIO; import org.scijava.ItemVisibility; import org.scijava.NullContextException; import org.scijava.command.Command; import org.scijava.convert.ConvertService; import org.scijava.log.LogService; import org.scijava.module.AbstractModuleInfo; import org.scijava.module.DefaultMutableModuleItem; import org.scijava.module.ModuleException; import org.scijava.parse.ParseService; import org.scijava.plugin.Parameter; import org.scijava.util.DigestUtils; import org.scijava.util.FileUtils; /** * Metadata about a script. * <p> * This class is responsible for parsing the script for parameters. See * {@link #parseParameters()} for details. * </p> * * @author Curtis Rueden * @author Johannes Schindelin */ public class ScriptInfo extends AbstractModuleInfo implements Contextual { private static final int PARAM_CHAR_MAX = 640 * 1024; // should be enough ;-) private final String path; private final String script; @Parameter private Context context; @Parameter private LogService log; @Parameter private ScriptService scriptService; @Parameter private ParseService parser; @Parameter private ConvertService convertService; /** True iff the return value is explicitly declared as an output. */ private boolean returnValueDeclared; /** * Creates a script metadata object which describes the given script file. * * @param context The SciJava application context to use when populating * service inputs. * @param file The script file. */ public ScriptInfo(final Context context, final File file) { this(context, file.getPath()); } /** * Creates a script metadata object which describes the given script file. * * @param context The SciJava application context to use when populating * service inputs. * @param path Path to the script file. */ public ScriptInfo(final Context context, final String path) { this(context, path, null); } /** * Creates a script metadata object which describes a script provided by the * given {@link Reader}. * * @param context The SciJava application context to use when populating * service inputs. * @param path Pseudo-path to the script file. This file does not actually * need to exist, but rather provides a name for the script with file * extension. * @param reader Reader which provides the script itself (i.e., its contents). */ public ScriptInfo(final Context context, final String path, final Reader reader) { setContext(context); this.path = path; String script = null; if (reader != null) { try { script = getReaderContentsAsString(reader); } catch (final IOException exc) { log.error("Error reading script: " + path, exc); } } this.script = script; } // -- ScriptInfo methods -- /** * Gets the path to the script on disk. * <p> * If the path doesn't actually exist on disk, then this is a pseudo-path * merely for the purpose of naming the script with a file extension, and the * actual script content is delivered by the {@link BufferedReader} given by * {@link #getReader()}. * </p> */ public String getPath() { return path; } /** * Gets a reader which delivers the script's content. * <p> * This might be null, in which case the content is stored in a file on disk * given by {@link #getPath()}. * </p> */ public BufferedReader getReader() { if (script == null) { return null; } return new BufferedReader(new StringReader(script), PARAM_CHAR_MAX); } /** * Parses the script's input and output parameters from the script header. * <p> * This method is called automatically the first time any parameter accessor * method is called ({@link #getInput}, {@link #getOutput}, {@link #inputs()}, * {@link #outputs()}, etc.). Subsequent calls will reparse the parameters. * <p> * SciJava's scripting framework supports specifying @{@link Parameter}-style * inputs and outputs in a preamble. The format is a simplified version of the * Java @{@link Parameter} annotation syntax. The following syntaxes are * supported: * </p> * <ul> * <li>{@code // @<type> <varName>}</li> * <li>{@code // @<type>(<attr1>=<value1>, ..., <attrN>=<valueN>) <varName>}</li> * <li>{@code // @<IOType> <type> <varName>}</li> * <li> * {@code // @<IOType>(<attr1>=<value1>, ..., <attrN>=<valueN>) <type> <varName>} * </li> * </ul> * <p> * Where: * </p> * <ul> * <li>{@code //} = the comment style of the scripting language, so that the * parameter line is ignored by the script engine itself.</li> * <li>{@code <IOType>} = one of {@code INPUT}, {@code OUTPUT}, or * {@code BOTH}.</li> * <li>{@code <varName>} = the name of the input or output variable.</li> * <li>{@code <type>} = the Java {@link Class} of the variable.</li> * <li>{@code <attr*>} = an attribute key.</li> * <li>{@code <value*>} = an attribute value.</li> * </ul> * <p> * See the @{@link Parameter} annotation for a list of valid attributes. * </p> * <p> * Here are a few examples: * </p> * <ul> * <li>{@code // @Dataset dataset}</li> * <li>{@code // @double(type=OUTPUT) result}</li> * <li>{@code // @BOTH ImageDisplay display}</li> * <li>{@code // @INPUT(persist=false, visibility=INVISIBLE) boolean verbose}</li> * parameters will be parsed and filled just like @{@link Parameter} * -annotated fields in {@link Command}s. * </ul> */ // NB: Widened visibility from AbstractModuleInfo. @Override public void parseParameters() { clearParameters(); returnValueDeclared = false; try { final BufferedReader in; if (script == null) { in = new BufferedReader(new FileReader(getPath())); } else { in = getReader(); } while (true) { final String line = in.readLine(); if (line == null) break; // NB: Scan for lines containing an '@' with no prior alphameric // characters. This assumes that only non-alphanumeric characters can // be used as comment line markers. if (line.matches("^[^\\w]*@.*")) { final int at = line.indexOf('@'); parseParam(line.substring(at + 1)); } else if (line.matches(".*\\w.*")) break; } in.close(); if (!returnValueDeclared) addReturnValue(); } catch (final IOException exc) { log.error("Error reading script: " + path, exc); } catch (final ScriptException exc) { log.error("Invalid parameter syntax for script: " + path, exc); } } /** Gets whether the return value is explicitly declared as an output. */ public boolean isReturnValueDeclared() { return returnValueDeclared; } // -- ModuleInfo methods -- @Override public String getDelegateClassName() { return ScriptModule.class.getName(); } @Override public Class<?> loadDelegateClass() { return ScriptModule.class; } @Override public ScriptModule createModule() throws ModuleException { return new ScriptModule(this); } // -- Contextual methods -- @Override public Context context() { if (context == null) throw new NullContextException(); return context; } @Override public Context getContext() { return context; } @Override public void setContext(final Context context) { context.inject(this); } // -- Identifiable methods -- @Override public String getIdentifier() { return "script:" + path; } // -- Locatable methods -- @Override public String getLocation() { return new File(path).toURI().normalize().toString(); } @Override public String getVersion() { final File file = new File(path); if (!file.exists()) return null; // no version for non-existent script try { return DigestUtils.bestHex(FileUtils.readFile(file)); } catch (final IOException exc) { log.error(exc); } final Date lastModified = FileUtils.getModifiedTime(file); final String datestamp = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss").format(lastModified); return datestamp; } // -- Helper methods -- private void parseParam(final String param) throws ScriptException { final int lParen = param.indexOf("("); final int rParen = param.lastIndexOf(")"); if (rParen < lParen) { throw new ScriptException("Invalid parameter: " + param); } if (lParen < 0) parseParam(param, parseAttrs("()")); else { final String cutParam = param.substring(0, lParen) + param.substring(rParen + 1); final String attrs = param.substring(lParen + 1, rParen); parseParam(cutParam, parseAttrs(attrs)); } } private void parseParam(final String param, final Map<String, Object> attrs) throws ScriptException { final String[] tokens = param.trim().split("[ \t\n]+"); checkValid(tokens.length >= 1, param); final String typeName, varName; if (isIOType(tokens[0])) { // assume syntax: <IOType> <type> <varName> checkValid(tokens.length >= 3, param); attrs.put("type", tokens[0]); typeName = tokens[1]; varName = tokens[2]; } else { // assume syntax: <type> <varName> checkValid(tokens.length >= 2, param); typeName = tokens[0]; varName = tokens[1]; } final Class<?> type = scriptService.lookupClass(typeName); addItem(varName, type, attrs); if (ScriptModule.RETURN_VALUE.equals(varName)) returnValueDeclared = true; } /** Parses a comma-delimited list of {@code key=value} pairs into a map. */ private Map<String, Object> parseAttrs(final String attrs) { return parser.parse(attrs).asMap(); } private boolean isIOType(final String token) { return convertService.convert(token, ItemIO.class) != null; } private void checkValid(final boolean valid, final String param) throws ScriptException { if (!valid) throw new ScriptException("Invalid parameter: " + param); } /** Adds an output for the value returned by the script itself. */ private void addReturnValue() throws ScriptException { final HashMap<String, Object> attrs = new HashMap<>(); attrs.put("type", "OUTPUT"); addItem(ScriptModule.RETURN_VALUE, Object.class, attrs); } private <T> void addItem(final String name, final Class<T> type, final Map<String, Object> attrs) { final DefaultMutableModuleItem<T> item = new DefaultMutableModuleItem<>(this, name, type); for (final String key : attrs.keySet()) { final Object value = attrs.get(key); assignAttribute(item, key, value); } if (item.isInput()) registerInput(item); if (item.isOutput()) registerOutput(item); } private <T> void assignAttribute(final DefaultMutableModuleItem<T> item, final String k, final Object v) { // CTR: There must be an easier way to do this. // Just compile the thing using javac? Or parse via javascript, maybe? if (is(k, "callback")) item.setCallback(as(v, String.class)); else if (is(k, "choices")) item.setChoices(asList(v, item.getType())); else if (is(k, "columns")) item.setColumnCount(as(v, int.class)); else if (is(k, "description")) item.setDescription(as(v, String.class)); else if (is(k, "initializer")) item.setInitializer(as(v, String.class)); else if (is(k, "type")) item.setIOType(as(v, ItemIO.class)); else if (is(k, "label")) item.setLabel(as(v, String.class)); else if (is(k, "max")) item.setMaximumValue(as(v, item.getType())); else if (is(k, "min")) item.setMinimumValue(as(v, item.getType())); else if (is(k, "name")) item.setName(as(v, String.class)); else if (is(k, "persist")) item.setPersisted(as(v, boolean.class)); else if (is(k, "persistKey")) item.setPersistKey(as(v, String.class)); else if (is(k, "required")) item.setRequired(as(v, boolean.class)); else if (is(k, "softMax")) item.setSoftMaximum(as(v, item.getType())); else if (is(k, "softMin")) item.setSoftMinimum(as(v, item.getType())); else if (is(k, "stepSize")) item.setStepSize(as(v, double.class)); else if (is(k, "style")) item.setWidgetStyle(as(v, String.class)); else if (is(k, "visibility")) item.setVisibility(as(v, ItemVisibility.class)); else if (is(k, "value")) item.setDefaultValue(as(v, item.getType())); else item.set(k, v.toString()); } /** Super terse comparison helper method. */ private boolean is(final String key, final String desired) { return desired.equalsIgnoreCase(key); } /** Super terse conversion helper method. */ private <T> T as(final Object v, final Class<T> type) { return convertService.convert(v, type); } private <T> List<T> asList(final Object v, final Class<T> type) { final ArrayList<T> result = new ArrayList<>(); final List<?> list = as(v, List.class); for (final Object item : list) { result.add(as(item, type)); } return result; } /** * Read entire contents of a Reader and return as String. * * @param reader {@link Reader} whose contents should be returned as String. * Expected to never be <code>null</code>. * @return contents of reader as String. * @throws IOException If an I/O error occurs * @throws NullPointerException If reader is <code>null</code> */ private static String getReaderContentsAsString(final Reader reader) throws IOException, NullPointerException { final char[] buffer = new char[8192]; final StringBuilder builder = new StringBuilder(); int read; while ((read = reader.read(buffer)) != -1) { builder.append(buffer, 0, read); } return builder.toString(); } }
package org.wahlzeit.model; import com.google.appengine.api.images.Image; import com.google.appengine.api.images.ImagesServiceFactory; import com.google.appengine.tools.cloudstorage.GcsFileOptions; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.GcsInputChannel; import com.google.appengine.tools.cloudstorage.GcsOutputChannel; import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsServiceFactory; import com.google.appengine.tools.cloudstorage.RetryParams; import java.io.IOException; import java.net.URLConnection; import java.nio.ByteBuffer; import java.security.InvalidParameterException; import java.util.logging.Logger; public class GcsAdapter { private static final Logger log = Logger.getLogger(GcsAdapter.class.getName()); private static final String BUCKET_NAME = "data"; // 2 MB Buffer, does not limit the size of the files private static final int BUFFER_LENGTH = 2 * 1024 * 1024; private static final GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance()); private static final String DEFAULT_IMAGE_MIME_TYPE = "image/jpeg"; private static GcsAdapter instance = null; /** * @methodtype get */ public static GcsAdapter getInstance() { if (instance == null) { instance = new GcsAdapter(); } return instance; } private GcsAdapter() { } /** * @methodtype wrapper * * Saves the image in the Google Cloud Storage, so you can access it via owner and filename again. * An existing file of that owner with that file name is overwritten. * * @throws InvalidParameterException - one parameter = null or invalid filename * * @see #readFromCloudStorage(String, String) */ public void writeImageToCloudStorage(Image image, String ownerName, String filename) throws InvalidParameterException, IOException { assertValidString(ownerName); assertValidImage(image); assertValidFileName(filename); GcsFilename gcsFilename = createGcsFileName(ownerName, filename); writeToCloudStorage(image, gcsFilename); } /** * @methodtype wrapper * * Saves the image in the Google Cloud Storage, so you can access it via ownerName, photoId and size again. * An existing file of that owner with that file name is overwritten. * * @throws InvalidParameterException - one parameter = null or invalid filename * * @see #readFromCloudStorage(String, String, String) */ public void writeToCloudStorage(Image image, String ownerName, String photoIdAsString, String size) throws InvalidParameterException, IOException { assertValidString(ownerName); assertValidString(photoIdAsString); assertValidString(size); assertValidImage(image); GcsFilename gcsFilename = createGcsFileName(ownerName, photoIdAsString, size); writeToCloudStorage(image, gcsFilename); } /** * @methodtype command * * Writes the file that is read from <code>input</code>into the google cloud storage under the * specified <code>fileName</code>. * * @throws IOException - when can not write to Google Cloud Storage */ private void writeToCloudStorage(Image image, GcsFilename gcsFilename) throws IOException { log.info("Write file '" + gcsFilename.getObjectName() + "' to cloud storage into the bucket '" + gcsFilename.getBucketName() + "'."); String fileType = URLConnection.guessContentTypeFromName(gcsFilename.getObjectName()); log.info("Found filetype " + fileType + " for " + gcsFilename.getObjectName()); GcsFileOptions.Builder fileOptionsBuilder = new GcsFileOptions.Builder(); if (fileType != null) { fileOptionsBuilder.mimeType(fileType); } else { fileOptionsBuilder.mimeType(DEFAULT_IMAGE_MIME_TYPE); } GcsFileOptions fileOptions = fileOptionsBuilder.build(); GcsOutputChannel outputChannel = gcsService.createOrReplace(gcsFilename, fileOptions); outputChannel.write(ByteBuffer.wrap(image.getImageData())); outputChannel.close(); } public Image readFromCloudStorage(String ownerName, String filename) throws IllegalArgumentException, IOException { assertValidString(ownerName); assertValidFileName(filename); GcsFilename gcsFilename = createGcsFileName(ownerName, filename); return readFromCloudStorage(gcsFilename); } public Image readFromCloudStorage(String ownerName, String photoIdAsString, String size) throws IllegalArgumentException, IOException { assertValidString(ownerName); assertValidString(photoIdAsString); assertValidString(size); GcsFilename gcsFilename = createGcsFileName(ownerName, photoIdAsString, size); return readFromCloudStorage(gcsFilename); } /** * @methodtype command * * Reads the specified file from Google Cloud Storage. When not found, null is returned. * * @throws IOException - when can not access Google Cloud Storage, e.g. insufficient rights */ private Image readFromCloudStorage(GcsFilename gcsFilename) throws IOException, InvalidParameterException { log.info("Read image " + gcsFilename.getObjectName() + " from bucket " + gcsFilename.getBucketName()); GcsInputChannel readChannel = gcsService.openReadChannel(gcsFilename, 0); ByteBuffer bb = ByteBuffer.allocate(BUFFER_LENGTH); readChannel.read(bb); return ImagesServiceFactory.makeImage(bb.array()); } /** * @methodtype command * <p/> * Creates a <code>GcsFilename</code> for the photo in the specified size. * The name structure is: * <p/> * BUCKET_NAME - ownerName/fileName/photoIdAsString */ private GcsFilename createGcsFileName(String owner, String photoIdAsString, String size) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("photos").append("/").append(photoIdAsString).append("/").append(size); return new GcsFilename(BUCKET_NAME, stringBuilder.toString()); } /** * @methodtype command * <p/> * Creates a <code>GcsFilename</code> for the photo in the specified size. * The name structure is: * <p/> * BUCKET_NAME - ownerName/fileName */ private GcsFilename createGcsFileName(String owner, String fileName) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("photos").append("/").append(fileName); return new GcsFilename(BUCKET_NAME, stringBuilder.toString()); } /** * @methodtype assert */ private void assertValidString(String string) throws IllegalArgumentException { if (string == null || string == "") { throw new IllegalArgumentException("Invalid owner name!"); } } /** * @methodtype assert */ private void assertValidImage(Image image) throws IllegalArgumentException { if (image == null) { throw new IllegalArgumentException("Invalid image!"); } } /** * @methodtype assert */ private void assertValidFileName(String fileName) throws IllegalArgumentException { if (fileName == null || "".equals(fileName)) { throw new IllegalArgumentException("Invalid file name!"); } else if (!fileName.contains(".")) { throw new IllegalArgumentException("Invalid file name, name must contain an ending!"); } } }
package org.xander.katas; import java.util.Arrays; public class OddEvenPrime { static final int range = 10000; static boolean[] sieveOfEratosthenes = new boolean[range]; static { Arrays.fill(sieveOfEratosthenes, true); sieveOfEratosthenes[0] = sieveOfEratosthenes[1] = false; for (int i = 2; i < Math.sqrt(sieveOfEratosthenes.length); i++) { for (int j = 2; i * j < sieveOfEratosthenes.length; j++) { if (sieveOfEratosthenes[i * j]) { sieveOfEratosthenes[i * j] = false; } } } // printResultsForTest(); } public String calculate(int number) { return (sieveOfEratosthenes[number]) ? number + " is prime" : (number % 2 == 0) ? "even" : "odd"; } // private static void printResultsForTest() { // int primeCounter = 0; // System.out.print("{"); // for (int a = 0; a < sieveOfEratosthenes.length; a++) { // if (sieveOfEratosthenes[a]) { // primeCounter++; // System.out.print(a + ", "); // System.out.print("}"); // System.out.println("\n\nThere are " + primeCounter + " prime numbers in the range from \'0\' to \'" + range + "\'"); }
package org.zendesk.client.v2; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder; import com.ning.http.client.ListenableFuture; import com.ning.http.client.Realm; import com.ning.http.client.Request; import com.ning.http.client.RequestBuilder; import com.ning.http.client.Response; import com.ning.http.client.multipart.FilePart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zendesk.client.v2.model.Attachment; import org.zendesk.client.v2.model.Audit; import org.zendesk.client.v2.model.Automation; import org.zendesk.client.v2.model.Comment; import org.zendesk.client.v2.model.Field; import org.zendesk.client.v2.model.Forum; import org.zendesk.client.v2.model.Group; import org.zendesk.client.v2.model.GroupMembership; import org.zendesk.client.v2.model.Identity; import org.zendesk.client.v2.model.JobStatus; import org.zendesk.client.v2.model.Macro; import org.zendesk.client.v2.model.Metric; import org.zendesk.client.v2.model.Organization; import org.zendesk.client.v2.model.OrganizationField; import org.zendesk.client.v2.model.SearchResultEntity; import org.zendesk.client.v2.model.Status; import org.zendesk.client.v2.model.SuspendedTicket; import org.zendesk.client.v2.model.Ticket; import org.zendesk.client.v2.model.TicketForm; import org.zendesk.client.v2.model.TicketResult; import org.zendesk.client.v2.model.Topic; import org.zendesk.client.v2.model.Trigger; import org.zendesk.client.v2.model.TwitterMonitor; import org.zendesk.client.v2.model.User; import org.zendesk.client.v2.model.UserField; import org.zendesk.client.v2.model.hc.Article; import org.zendesk.client.v2.model.hc.ArticleAttachments; import org.zendesk.client.v2.model.hc.Category; import org.zendesk.client.v2.model.hc.Section; import org.zendesk.client.v2.model.hc.Translation; import org.zendesk.client.v2.model.targets.BasecampTarget; import org.zendesk.client.v2.model.targets.CampfireTarget; import org.zendesk.client.v2.model.targets.EmailTarget; import org.zendesk.client.v2.model.targets.PivotalTarget; import org.zendesk.client.v2.model.targets.Target; import org.zendesk.client.v2.model.targets.TwitterTarget; import org.zendesk.client.v2.model.targets.UrlTarget; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; /** * @author stephenc * @since 04/04/2013 13:08 */ public class Zendesk implements Closeable { private static final String JSON = "application/json; charset=UTF-8"; private final boolean closeClient; private final AsyncHttpClient client; private final Realm realm; private final String url; private final String oauthToken; private final ObjectMapper mapper; private final Logger logger; private boolean closed = false; private static final Map<String, Class<? extends SearchResultEntity>> searchResultTypes = searchResultTypes(); private static final Map<String, Class<? extends Target>> targetTypes = targetTypes(); private static Map<String, Class<? extends SearchResultEntity>> searchResultTypes() { Map<String, Class<? extends SearchResultEntity>> result = new HashMap<String, Class<? extends SearchResultEntity>>(); result.put("ticket", Ticket.class); result.put("user", User.class); result.put("group", Group.class); result.put("organization", Organization.class); result.put("topic", Topic.class); result.put("article", Article.class); return Collections.unmodifiableMap(result); } private static Map<String, Class<? extends Target>> targetTypes() { Map<String, Class<? extends Target>> result = new HashMap<String, Class<? extends Target>>(); result.put("url_target", UrlTarget.class); result.put("email_target",EmailTarget.class); result.put("basecamp_target", BasecampTarget.class); result.put("campfire_target", CampfireTarget.class); result.put("pivotal_target", PivotalTarget.class); result.put("twitter_target", TwitterTarget.class); // TODO: Implement other Target types //result.put("clickatell_target", ClickatellTarget.class); //result.put("flowdock_target", FlowdockTarget.class); //result.put("get_satisfaction_target", GetSatisfactionTarget.class); //result.put("yammer_target", YammerTarget.class); return Collections.unmodifiableMap(result); } private Zendesk(AsyncHttpClient client, String url, String username, String password) { this.logger = LoggerFactory.getLogger(Zendesk.class); this.closeClient = client == null; this.oauthToken = null; this.client = client == null ? new AsyncHttpClient() : client; this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2"; if (username != null) { this.realm = new Realm.RealmBuilder() .setScheme(Realm.AuthScheme.BASIC) .setPrincipal(username) .setPassword(password) .setUsePreemptiveAuth(true) .build(); } else { if (password != null) { throw new IllegalStateException("Cannot specify token or password without specifying username"); } this.realm = null; } this.mapper = createMapper(); } private Zendesk(AsyncHttpClient client, String url, String oauthToken) { this.logger = LoggerFactory.getLogger(Zendesk.class); this.closeClient = client == null; this.realm = null; this.client = client == null ? new AsyncHttpClient() : client; this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2"; if (oauthToken != null) { this.oauthToken = oauthToken; } else { throw new IllegalStateException("Cannot specify token or password without specifying username"); } this.mapper = createMapper(); } // Closeable interface methods public boolean isClosed() { return closed || client.isClosed(); } public void close() { if (closeClient && !client.isClosed()) { client.close(); } closed = true; } // Action methods public <T> JobStatus<T> getJobStatus(JobStatus<T> status) { return complete(getJobStatusAsync(status)); } public <T> ListenableFuture<JobStatus<T>> getJobStatusAsync(JobStatus<T> status) { return submit(req("GET", tmpl("/job_statuses/{id}.json").set("id", status.getId())), handleJobStatus(status.getResultsClass())); } public List<JobStatus<HashMap<String, Object>>> getJobStatuses(List<JobStatus> statuses) { return complete(getJobStatusesAsync(statuses)); } public ListenableFuture<List<JobStatus<HashMap<String, Object>>>> getJobStatusesAsync(List<JobStatus> statuses) { List<String> ids = new ArrayList<String>(statuses.size()); for (JobStatus status : statuses) { ids.add(status.getId()); } Class<JobStatus<HashMap<String, Object>>> clazz = (Class<JobStatus<HashMap<String, Object>>>)(Object)JobStatus.class; return submit(req("GET", tmpl("/job_statuses/show_many.json{?ids}").set("ids", ids)), handleList(clazz, "job_statuses")); } public TicketForm getTicketForm(long id) { return complete(submit(req("GET", tmpl("/ticket_forms/{id}.json").set("id", id)), handle(TicketForm.class, "ticket_form"))); } public List<TicketForm> getTicketForms() { return complete(submit(req("GET", cnst("/ticket_forms.json")), handleList(TicketForm.class, "ticket_forms"))); } public Ticket getTicket(long id) { return complete(submit(req("GET", tmpl("/tickets/{id}.json").set("id", id)), handle(Ticket.class, "ticket"))); } public List<Ticket> getTicketIncidents(long id) { return complete(submit(req("GET", tmpl("/tickets/{id}/incidents.json").set("id", id)), handleList(Ticket.class, "tickets"))); } public List<User> getTicketCollaborators(long id) { return complete(submit(req("GET", tmpl("/tickets/{id}/collaborators.json").set("id", id)), handleList(User.class, "users"))); } public void deleteTicket(Ticket ticket) { checkHasId(ticket); deleteTicket(ticket.getId()); } public void deleteTicket(long id) { complete(submit(req("DELETE", tmpl("/tickets/{id}.json").set("id", id)), handleStatus())); } public Ticket createTicket(Ticket ticket) { return complete(submit(req("POST", cnst("/tickets.json"), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public JobStatus<Ticket> createTickets(Ticket... tickets) { return createTickets(Arrays.asList(tickets)); } public JobStatus<Ticket> createTickets(List<Ticket> tickets) { return complete(createTicketsAsync(tickets)); } public ListenableFuture<JobStatus<Ticket>> createTicketsAsync(List<Ticket> tickets) { return submit(req("POST", cnst("/tickets/create_many.json"), JSON, json( Collections.singletonMap("tickets", tickets))), handleJobStatus(Ticket.class)); } public Ticket updateTicket(Ticket ticket) { checkHasId(ticket); return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticket.getId()), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public void markTicketAsSpam(Ticket ticket) { checkHasId(ticket); markTicketAsSpam(ticket.getId()); } public void markTicketAsSpam(long id) { complete(submit(req("PUT", tmpl("/tickets/{id}/mark_as_spam.json").set("id", id)), handleStatus())); } public void deleteTickets(long id, long... ids) { complete(submit(req("DELETE", tmpl("/tickets/destroy_many.json{?ids}").set("ids", idArray(id, ids))), handleStatus())); } public Iterable<Ticket> getTickets() { return new PagedIterable<Ticket>(cnst("/tickets.json"), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsByStatus(Status... ticketStatus) { return new PagedIterable<Ticket>(tmpl("/tickets.json{?status}").set("status", statusArray(ticketStatus)), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsByExternalId(String externalId, boolean includeArchived) { Iterable<Ticket> results = new PagedIterable<Ticket>(tmpl("/tickets.json{?external_id}").set("external_id", externalId), handleList(Ticket.class, "tickets")); if (!includeArchived || results.iterator().hasNext()) { return results; } return new PagedIterable<Ticket>(tmpl("/search.json{?query}{&type}").set("query", "external_id:" + externalId).set("type", "ticket"), handleList(Ticket.class, "results")); } public Iterable<Ticket> getTicketsByExternalId(String externalId) { return getTicketsByExternalId(externalId, false); } public Iterable<Ticket> getTicketsFromSearch(String searchTerm) { return new PagedIterable<Ticket>(tmpl("/search.json{?query}").set("query", searchTerm + "+type:ticket"), handleList(Ticket.class, "results")); } public Iterable<Article> getArticleFromSearch(String searchTerm) { return new PagedIterable<Article>(tmpl("/help_center/articles/search.json{?query}").set("query", searchTerm), handleList(Article.class, "results")); } public Iterable<Article> getArticleFromSearch(String searchTerm, Long sectionId) { return new PagedIterable<Article>(tmpl("/help_center/articles/search.json{?section,query}") .set("query", searchTerm).set("section", sectionId), handleList(Article.class, "results")); } public List<ArticleAttachments> getAttachmentsFromArticle(Long articleID) { return complete(submit(req("GET", tmpl("/help_center/articles/{id}/attachments.json").set("id", articleID)), handleArticleAttachmentsList("article_attachments"))); } public List<Ticket> getTickets(long id, long... ids) { return complete(submit(req("GET", tmpl("/tickets/show_many.json{?ids}").set("ids", idArray(id, ids))), handleList(Ticket.class, "tickets"))); } public Iterable<Ticket> getRecentTickets() { return new PagedIterable<Ticket>(cnst("/tickets/recent.json"), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsIncrementally(Date startTime) { return new PagedIterable<Ticket>( tmpl("/incremental/tickets.json{?start_time}").set("start_time", msToSeconds(startTime.getTime())), handleIncrementalList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsIncrementally(Date startTime, Date endTime) { return new PagedIterable<Ticket>( tmpl("/incremental/tickets.json{?start_time,end_time}") .set("start_time", msToSeconds(startTime.getTime())) .set("end_time", msToSeconds(endTime.getTime())), handleIncrementalList(Ticket.class, "tickets")); } public Iterable<Ticket> getOrganizationTickets(long organizationId) { return new PagedIterable<Ticket>( tmpl("/organizations/{organizationId}/tickets.json").set("organizationId", organizationId), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getUserRequestedTickets(long userId) { return new PagedIterable<Ticket>(tmpl("/users/{userId}/tickets/requested.json").set("userId", userId), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getUserCCDTickets(long userId) { return new PagedIterable<Ticket>(tmpl("/users/{userId}/tickets/ccd.json").set("userId", userId), handleList(Ticket.class, "tickets")); } public Iterable<Metric> getTicketMetrics() { return new PagedIterable<Metric>(cnst("/ticket_metrics.json"), handleList(Metric.class, "ticket_metrics")); } public Metric getTicketMetricByTicket(long id) { return complete(submit(req("GET", tmpl("/tickets/{ticketId}/metrics.json").set("ticketId", id)), handle(Metric.class, "ticket_metric"))); } public Metric getTicketMetric(long id) { return complete(submit(req("GET", tmpl("/ticket_metrics/{ticketMetricId}.json").set("ticketMetricId", id)), handle(Metric.class, "ticket_metric"))); } public Iterable<Audit> getTicketAudits(Ticket ticket) { checkHasId(ticket); return getTicketAudits(ticket.getId()); } public Iterable<Audit> getTicketAudits(Long id) { return new PagedIterable<Audit>(tmpl("/tickets/{ticketId}/audits.json").set("ticketId", id), handleList(Audit.class, "audits")); } public Audit getTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); return getTicketAudit(ticket, audit.getId()); } public Audit getTicketAudit(Ticket ticket, long id) { checkHasId(ticket); return getTicketAudit(ticket.getId(), id); } public Audit getTicketAudit(long ticketId, long auditId) { return complete(submit(req("GET", tmpl("/tickets/{ticketId}/audits/{auditId}.json").set("ticketId", ticketId) .set("auditId", auditId)), handle(Audit.class, "audit"))); } public void trustTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); trustTicketAudit(ticket, audit.getId()); } public void trustTicketAudit(Ticket ticket, long id) { checkHasId(ticket); trustTicketAudit(ticket.getId(), id); } public void trustTicketAudit(long ticketId, long auditId) { complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/trust.json").set("ticketId", ticketId) .set("auditId", auditId)), handleStatus())); } public void makePrivateTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); makePrivateTicketAudit(ticket, audit.getId()); } public void makePrivateTicketAudit(Ticket ticket, long id) { checkHasId(ticket); makePrivateTicketAudit(ticket.getId(), id); } public void makePrivateTicketAudit(long ticketId, long auditId) { complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/make_private.json").set("ticketId", ticketId) .set("auditId", auditId)), handleStatus())); } public List<Field> getTicketFields() { return complete(submit(req("GET", cnst("/ticket_fields.json")), handleList(Field.class, "ticket_fields"))); } public Field getTicketField(long id) { return complete(submit(req("GET", tmpl("/ticket_fields/{id}.json").set("id", id)), handle(Field.class, "ticket_field"))); } public Field createTicketField(Field field) { return complete(submit(req("POST", cnst("/ticket_fields.json"), JSON, json( Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field"))); } public Field updateTicketField(Field field) { checkHasId(field); return complete(submit(req("PUT", tmpl("/ticket_fields/{id}.json").set("id", field.getId()), JSON, json(Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field"))); } public void deleteTicketField(Field field) { checkHasId(field); deleteTicket(field.getId()); } public void deleteTicketField(long id) { complete(submit(req("DELETE", tmpl("/ticket_fields/{id}.json").set("id", id)), handleStatus())); } public Iterable<SuspendedTicket> getSuspendedTickets() { return new PagedIterable<SuspendedTicket>(cnst("/suspended_tickets.json"), handleList(SuspendedTicket.class, "suspended_tickets")); } public void deleteSuspendedTicket(SuspendedTicket ticket) { checkHasId(ticket); deleteSuspendedTicket(ticket.getId()); } public void deleteSuspendedTicket(long id) { complete(submit(req("DELETE", tmpl("/suspended_tickets/{id}.json").set("id", id)), handleStatus())); } public Attachment.Upload createUpload(String fileName, byte[] content) { return createUpload(null, fileName, "application/binary", content); } public Attachment.Upload createUpload(String fileName, String contentType, byte[] content) { return createUpload(null, fileName, contentType, content); } public Attachment.Upload createUpload(String token, String fileName, String contentType, byte[] content) { TemplateUri uri = tmpl("/uploads.json{?filename}{?token}").set("filename", fileName); if (token != null) { uri.set("token", token); } return complete( submit(req("POST", uri, contentType, content), handle(Attachment.Upload.class, "upload"))); } public void associateAttachmentsToArticle(String idArticle, List<Attachment> attachments) { TemplateUri uri = tmpl("/help_center/articles/{article_id}/bulk_attachments.json").set("article_id", idArticle); List<Long> attachmentsIds = new ArrayList<Long>(); for(Attachment item : attachments){ attachmentsIds.add(item.getId()); } complete(submit(req("POST", uri, JSON, json(Collections.singletonMap("attachment_ids", attachmentsIds))), handleStatus())); } public ArticleAttachments createUploadArticle(long articleId, File file) throws IOException { BoundRequestBuilder builder = client.preparePost(tmpl("/help_center/articles/{id}/attachments.json").set("id", articleId).toString()); if (realm != null) { builder.setRealm(realm); } else { builder.addHeader("Authorization", "Bearer " + oauthToken); } builder.setHeader("Content-Type", "multipart/form-data"); builder.addBodyPart( new FilePart("file", file, "application/octet-stream", Charset.forName("UTF-8"), file.getName())); final Request req = builder.build(); return complete(submit(req, handle(ArticleAttachments.class, "article_attachment"))); } public void deleteUpload(Attachment.Upload upload) { checkHasToken(upload); deleteUpload(upload.getToken()); } public void deleteUpload(String token) { complete(submit(req("DELETE", tmpl("/uploads/{token}.json").set("token", token)), handleStatus())); } public Attachment getAttachment(Attachment attachment) { checkHasId(attachment); return getAttachment(attachment.getId()); } public Attachment getAttachment(long id) { return complete(submit(req("GET", tmpl("/attachments/{id}.json").set("id", id)), handle(Attachment.class, "attachment"))); } public void deleteAttachment(Attachment attachment) { checkHasId(attachment); deleteAttachment(attachment.getId()); } public void deleteAttachment(long id) { complete(submit(req("DELETE", tmpl("/attachments/{id}.json").set("id", id)), handleStatus())); } public Iterable<Target> getTargets() { return new PagedIterable<Target>(cnst("/targets.json"), handleTargetList("targets")); } public Target getTarget(long id) { return complete(submit(req("GET", tmpl("/targets/{id}.json").set("id", id)), handle(Target.class, "target"))); } public Target createTarget(Target target) { return complete(submit(req("POST", cnst("/targets.json"), JSON, json(Collections.singletonMap("target", target))), handle(Target.class, "target"))); } public void deleteTarget(long targetId) { complete(submit(req("DELETE", tmpl("/targets/{id}.json").set("id", targetId)), handleStatus())); } public Iterable<Trigger> getTriggers() { return new PagedIterable<Trigger>(cnst("/triggers.json"), handleList(Trigger.class, "triggers")); } public Trigger getTrigger(long id) { return complete(submit(req("GET", tmpl("/triggers/{id}.json").set("id", id)), handle(Trigger.class, "trigger"))); } public Trigger createTrigger(Trigger trigger) { return complete(submit(req("POST", cnst("/triggers.json"), JSON, json(Collections.singletonMap("trigger", trigger))), handle(Trigger.class, "trigger"))); } public Trigger updateTrigger(Long triggerId, Trigger trigger) { return complete(submit(req("PUT", tmpl("/triggers/{id}.json").set("id", triggerId), JSON, json(Collections.singletonMap("trigger", trigger))), handle(Trigger.class, "trigger"))); } public void deleteTrigger(long triggerId) { complete(submit(req("DELETE", tmpl("/triggers/{id}.json").set("id", triggerId)), handleStatus())); } // Automations public Iterable<Automation> getAutomations() { return new PagedIterable<Automation>(cnst("/automations.json"), handleList(Automation.class, "automations")); } public Automation getAutomation(long id) { return complete(submit(req("GET", tmpl("/automations/{id}.json").set("id", id)), handle(Automation.class, "automation"))); } public Automation createAutomation(Automation automation) { return complete(submit( req("POST", cnst("/automations.json"), JSON, json(Collections.singletonMap("automation", automation))), handle(Automation.class, "automation"))); } public Automation updateAutomation(Long automationId, Automation automation) { return complete(submit( req("PUT", tmpl("/automations/{id}.json").set("id", automationId), JSON, json(Collections.singletonMap("automation", automation))), handle(Automation.class, "automation"))); } public void deleteAutomation(long automationId) { complete(submit(req("DELETE", tmpl("/automations/{id}.json").set("id", automationId)), handleStatus())); } public Iterable<TwitterMonitor> getTwitterMonitors() { return new PagedIterable<TwitterMonitor>(cnst("/channels/twitter/monitored_twitter_handles.json"), handleList(TwitterMonitor.class, "monitored_twitter_handles")); } public Iterable<User> getUsers() { return new PagedIterable<User>(cnst("/users.json"), handleList(User.class, "users")); } public Iterable<User> getUsersByRole(String role, String... roles) { // Going to have to build this URI manually, because the RFC6570 template spec doesn't support // variables like ?role[]=...role[]=..., which is what Zendesk requires. // See https://developer.zendesk.com/rest_api/docs/core/users#filters final StringBuilder uriBuilder = new StringBuilder("/users.json"); if (roles.length == 0) { uriBuilder.append("?role=").append(encodeUrl(role)); } else { uriBuilder.append("?role[]=").append(encodeUrl(role)); } for (final String curRole : roles) { uriBuilder.append("&role[]=").append(encodeUrl(curRole)); } return new PagedIterable<User>(cnst(uriBuilder.toString()), handleList(User.class, "users")); } public Iterable<User> getUsersIncrementally(Date startTime) { return new PagedIterable<User>( tmpl("/incremental/users.json{?start_time}").set("start_time", msToSeconds(startTime.getTime())), handleIncrementalList(User.class, "users")); } public Iterable<User> getGroupUsers(long id) { return new PagedIterable<User>(tmpl("/groups/{id}/users.json").set("id", id), handleList(User.class, "users")); } public Iterable<User> getOrganizationUsers(long id) { return new PagedIterable<User>(tmpl("/organizations/{id}/users.json").set("id", id), handleList(User.class, "users")); } public User getUser(long id) { return complete(submit(req("GET", tmpl("/users/{id}.json").set("id", id)), handle(User.class, "user"))); } public User getAuthenticatedUser() { return complete(submit(req("GET", cnst("/users/me.json")), handle(User.class, "user"))); } public Iterable<UserField> getUserFields() { return complete(submit(req("GET", cnst("/user_fields.json")), handleList(UserField.class, "user_fields"))); } public User createUser(User user) { return complete(submit(req("POST", cnst("/users.json"), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public JobStatus<User> createUsers(User... users) { return createUsers(Arrays.asList(users)); } public JobStatus<User> createUsers(List<User> users) { return complete(createUsersAsync(users)); } public ListenableFuture<JobStatus<User>> createUsersAsync(List<User> users) { return submit(req("POST", cnst("/users/create_many.json"), JSON, json( Collections.singletonMap("users", users))), handleJobStatus(User.class)); } public User updateUser(User user) { checkHasId(user); return complete(submit(req("PUT", tmpl("/users/{id}.json").set("id", user.getId()), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public void deleteUser(User user) { checkHasId(user); deleteUser(user.getId()); } public void deleteUser(long id) { complete(submit(req("DELETE", tmpl("/users/{id}.json").set("id", id)), handleStatus())); } public Iterable<User> lookupUserByEmail(String email) { return new PagedIterable<User>(tmpl("/users/search.json{?query}").set("query", email), handleList(User.class, "users")); } public Iterable<User> lookupUserByExternalId(String externalId) { return new PagedIterable<User>(tmpl("/users/search.json{?external_id}").set("external_id", externalId), handleList(User.class, "users")); } public User getCurrentUser() { return complete(submit(req("GET", cnst("/users/me.json")), handle(User.class, "user"))); } public void resetUserPassword(User user, String password) { checkHasId(user); resetUserPassword(user.getId(), password); } public void resetUserPassword(long id, String password) { complete(submit(req("POST", tmpl("/users/{id}/password.json").set("id", id), JSON, json(Collections.singletonMap("password", password))), handleStatus())); } public void changeUserPassword(User user, String oldPassword, String newPassword) { checkHasId(user); Map<String, String> req = new HashMap<String, String>(); req.put("previous_password", oldPassword); req.put("password", newPassword); complete(submit(req("PUT", tmpl("/users/{id}/password.json").set("id", user.getId()), JSON, json(req)), handleStatus())); } public List<Identity> getUserIdentities(User user) { checkHasId(user); return getUserIdentities(user.getId()); } public List<Identity> getUserIdentities(long userId) { return complete(submit(req("GET", tmpl("/users/{id}/identities.json").set("id", userId)), handleList(Identity.class, "identities"))); } public Identity getUserIdentity(User user, Identity identity) { checkHasId(identity); return getUserIdentity(user, identity.getId()); } public Identity getUserIdentity(User user, long identityId) { checkHasId(user); return getUserIdentity(user.getId(), identityId); } public Identity getUserIdentity(long userId, long identityId) { return complete(submit(req("GET", tmpl("/users/{userId}/identities/{identityId}.json").set("userId", userId) .set("identityId", identityId)), handle( Identity.class, "identity"))); } public List<Identity> setUserPrimaryIdentity(User user, Identity identity) { checkHasId(identity); return setUserPrimaryIdentity(user, identity.getId()); } public List<Identity> setUserPrimaryIdentity(User user, long identityId) { checkHasId(user); return setUserPrimaryIdentity(user.getId(), identityId); } public List<Identity> setUserPrimaryIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/make_primary.json").set("userId", userId) .set("identityId", identityId), JSON, null), handleList(Identity.class, "identities"))); } public Identity verifyUserIdentity(User user, Identity identity) { checkHasId(identity); return verifyUserIdentity(user, identity.getId()); } public Identity verifyUserIdentity(User user, long identityId) { checkHasId(user); return verifyUserIdentity(user.getId(), identityId); } public Identity verifyUserIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/verify.json") .set("userId", userId) .set("identityId", identityId), JSON, null), handle(Identity.class, "identity"))); } public Identity requestVerifyUserIdentity(User user, Identity identity) { checkHasId(identity); return requestVerifyUserIdentity(user, identity.getId()); } public Identity requestVerifyUserIdentity(User user, long identityId) { checkHasId(user); return requestVerifyUserIdentity(user.getId(), identityId); } public Identity requestVerifyUserIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/request_verification.json") .set("userId", userId) .set("identityId", identityId), JSON, null), handle(Identity.class, "identity"))); } public void deleteUserIdentity(User user, Identity identity) { checkHasId(identity); deleteUserIdentity(user, identity.getId()); } public void deleteUserIdentity(User user, long identityId) { checkHasId(user); deleteUserIdentity(user.getId(), identityId); } public void deleteUserIdentity(long userId, long identityId) { complete(submit(req("DELETE", tmpl("/users/{userId}/identities/{identityId}.json") .set("userId", userId) .set("identityId", identityId) ), handleStatus())); } public void createUserIdentity(long userId, Identity identity) { complete(submit(req("POST", tmpl("/users/{userId}/identities.json").set("userId", userId), JSON, json( Collections.singletonMap("identity", identity))), handle(Identity.class, "identity"))); } public void createUserIdentity(User user, Identity identity) { complete(submit(req("POST", tmpl("/users/{userId}/identities.json").set("userId", user.getId()), JSON, json( Collections.singletonMap("identity", identity))), handle(Identity.class, "identity"))); } public Iterable<org.zendesk.client.v2.model.Request> getRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getOpenRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/open.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getSolvedRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/solved.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getCCRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/ccd.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(User user) { checkHasId(user); return getUserRequests(user.getId()); } public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(long id) { return new PagedIterable<org.zendesk.client.v2.model.Request>(tmpl("/users/{id}/requests.json").set("id", id), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public org.zendesk.client.v2.model.Request getRequest(long id) { return complete(submit(req("GET", tmpl("/requests/{id}.json").set("id", id)), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public org.zendesk.client.v2.model.Request createRequest(org.zendesk.client.v2.model.Request request) { return complete(submit(req("POST", cnst("/requests.json"), JSON, json(Collections.singletonMap("request", request))), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public org.zendesk.client.v2.model.Request updateRequest(org.zendesk.client.v2.model.Request request) { checkHasId(request); return complete(submit(req("PUT", tmpl("/requests/{id}.json").set("id", request.getId()), JSON, json(Collections.singletonMap("request", request))), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public Iterable<Comment> getRequestComments(org.zendesk.client.v2.model.Request request) { checkHasId(request); return getRequestComments(request.getId()); } public Iterable<Comment> getRequestComments(long id) { return new PagedIterable<Comment>(tmpl("/requests/{id}/comments.json").set("id", id), handleList(Comment.class, "comments")); } public Iterable<Comment> getTicketComments(long id) { return new PagedIterable<Comment>(tmpl("/tickets/{id}/comments.json").set("id", id), handleList(Comment.class, "comments")); } public Comment getRequestComment(org.zendesk.client.v2.model.Request request, Comment comment) { checkHasId(comment); return getRequestComment(request, comment.getId()); } public Comment getRequestComment(org.zendesk.client.v2.model.Request request, long commentId) { checkHasId(request); return getRequestComment(request.getId(), commentId); } public Comment getRequestComment(long requestId, long commentId) { return complete(submit(req("GET", tmpl("/requests/{requestId}/comments/{commentId}.json") .set("requestId", requestId) .set("commentId", commentId)), handle(Comment.class, "comment"))); } public Ticket createComment(long ticketId, Comment comment) { Ticket ticket = new Ticket(); ticket.setComment(comment); return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticketId), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public Ticket createTicketFromTweet(long tweetId, long monitorId) { Map<String,Object> map = new HashMap<String,Object>(); map.put("twitter_status_message_id", tweetId); map.put("monitored_twitter_handle_id", monitorId); return complete(submit(req("POST", cnst("/channels/twitter/tickets.json"), JSON, json(Collections.singletonMap("ticket", map))), handle(Ticket.class, "ticket"))); } public Iterable<Organization> getOrganizations() { return new PagedIterable<Organization>(cnst("/organizations.json"), handleList(Organization.class, "organizations")); } public Iterable<Organization> getOrganizationsIncrementally(Date startTime) { return new PagedIterable<Organization>( tmpl("/incremental/organizations.json{?start_time}").set("start_time", msToSeconds(startTime.getTime())), handleIncrementalList(Organization.class, "organizations")); } public Iterable<OrganizationField> getOrganizationFields() { //The organization_fields api doesn't seem to support paging return complete(submit(req("GET", cnst("/organization_fields.json")), handleList(OrganizationField.class, "organization_fields"))); } public Iterable<Organization> getAutoCompleteOrganizations(String name) { if (name == null || name.length() < 2) { throw new IllegalArgumentException("Name must be at least 2 characters long"); } return new PagedIterable<Organization>(tmpl("/organizations/autocomplete.json{?name}").set("name", name), handleList(Organization.class, "organizations")); } // TODO getOrganizationRelatedInformation public Organization getOrganization(long id) { return complete(submit(req("GET", tmpl("/organizations/{id}.json").set("id", id)), handle(Organization.class, "organization"))); } public Organization createOrganization(Organization organization) { return complete(submit(req("POST", cnst("/organizations.json"), JSON, json( Collections.singletonMap("organization", organization))), handle(Organization.class, "organization"))); } public JobStatus<Organization> createOrganizations(Organization... organizations) { return createOrganizations(Arrays.asList(organizations)); } public JobStatus createOrganizations(List<Organization> organizations) { return complete(createOrganizationsAsync(organizations)); } public ListenableFuture<JobStatus<Organization>> createOrganizationsAsync(List<Organization> organizations) { return submit(req("POST", cnst("/organizations/create_many.json"), JSON, json( Collections.singletonMap("organizations", organizations))), handleJobStatus(Organization.class)); } public Organization updateOrganization(Organization organization) { checkHasId(organization); return complete(submit(req("PUT", tmpl("/organizations/{id}.json").set("id", organization.getId()), JSON, json( Collections.singletonMap("organization", organization))), handle(Organization.class, "organization"))); } public void deleteOrganization(Organization organization) { checkHasId(organization); deleteOrganization(organization.getId()); } public void deleteOrganization(long id) { complete(submit(req("DELETE", tmpl("/organizations/{id}.json").set("id", id)), handleStatus())); } public Iterable<Organization> lookupOrganizationsByExternalId(String externalId) { if (externalId == null || externalId.length() < 2) { throw new IllegalArgumentException("Name must be at least 2 characters long"); } return new PagedIterable<Organization>( tmpl("/organizations/search.json{?external_id}").set("external_id", externalId), handleList(Organization.class, "organizations")); } public Iterable<Group> getGroups() { return new PagedIterable<Group>(cnst("/groups.json"), handleList(Group.class, "groups")); } public Iterable<Group> getAssignableGroups() { return new PagedIterable<Group>(cnst("/groups/assignable.json"), handleList(Group.class, "groups")); } public Group getGroup(long id) { return complete(submit(req("GET", tmpl("/groups/{id}.json").set("id", id)), handle(Group.class, "group"))); } public Group createGroup(Group group) { return complete(submit(req("POST", cnst("/groups.json"), JSON, json( Collections.singletonMap("group", group))), handle(Group.class, "group"))); } public List<Group> createGroups(Group... groups) { return createGroups(Arrays.asList(groups)); } public List<Group> createGroups(List<Group> groups) { return complete(submit(req("POST", cnst("/groups/create_many.json"), JSON, json( Collections.singletonMap("groups", groups))), handleList(Group.class, "results"))); } public Group updateGroup(Group group) { checkHasId(group); return complete(submit(req("PUT", tmpl("/groups/{id}.json").set("id", group.getId()), JSON, json( Collections.singletonMap("group", group))), handle(Group.class, "group"))); } public void deleteGroup(Group group) { checkHasId(group); deleteGroup(group.getId()); } public void deleteGroup(long id) { complete(submit(req("DELETE", tmpl("/groups/{id}.json").set("id", id)), handleStatus())); } public Iterable<Macro> getMacros(){ return new PagedIterable<Macro>(cnst("/macros.json"), handleList(Macro.class, "macros")); } public Macro getMacro(long macroId){ return complete(submit(req("GET", tmpl("/macros/{id}.json").set("id", macroId)), handle(Macro.class, "macro"))); } public Macro createMacro(Macro macro) { return complete(submit( req("POST", cnst("/macros.json"), JSON, json(Collections.singletonMap("macro", macro))), handle(Macro.class, "macro"))); } public Macro updateMacro(Long macroId, Macro macro) { return complete(submit(req("PUT", tmpl("/macros/{id}.json").set("id", macroId), JSON, json(Collections.singletonMap("macro", macro))), handle(Macro.class, "macro"))); } public Ticket macrosShowChangesToTicket(long macroId) { return complete(submit(req("GET", tmpl("/macros/{id}/apply.json").set("id", macroId)), handle(TicketResult.class, "result"))).getTicket(); } public Ticket macrosShowTicketAfterChanges(long ticketId, long macroId) { return complete(submit(req("GET", tmpl("/tickets/{ticket_id}/macros/{id}/apply.json") .set("ticket_id", ticketId) .set("id", macroId)), handle(TicketResult.class, "result"))).getTicket(); } public List<String> addTagToTicket(long id, String... tags) { return complete(submit( req("PUT", tmpl("/tickets/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> addTagToTopics(long id, String... tags) { return complete(submit( req("PUT", tmpl("/topics/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> addTagToOrganisations(long id, String... tags) { return complete(submit( req("PUT", tmpl("/organizations/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> setTagOnTicket(long id, String... tags) { return complete(submit( req("POST", tmpl("/tickets/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> setTagOnTopics(long id, String... tags) { return complete(submit( req("POST", tmpl("/topics/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> setTagOnOrganisations(long id, String... tags) { return complete(submit( req("POST", tmpl("/organizations/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> removeTagFromTicket(long id, String... tags) { return complete(submit( req("DELETE", tmpl("/tickets/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> removeTagFromTopics(long id, String... tags) { return complete(submit( req("DELETE", tmpl("/topics/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> removeTagFromOrganisations(long id, String... tags) { return complete(submit( req("DELETE", tmpl("/organizations/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public Map getIncrementalTicketsResult(long unixEpochTime) { return complete(submit( req("GET", tmpl("/exports/tickets.json?start_time={time}").set( "time", unixEpochTime)), handle(Map.class))); } public Iterable<GroupMembership> getGroupMemberships() { return new PagedIterable<GroupMembership>(cnst("/group_memberships.json"), handleList(GroupMembership.class, "group_memberships")); } public List<GroupMembership> getGroupMembershipByUser(long user_id) { return complete(submit(req("GET", tmpl("/users/{user_id}/group_memberships.json").set("user_id", user_id)), handleList(GroupMembership.class, "group_memberships"))); } public List<GroupMembership> getGroupMemberships(long group_id) { return complete(submit(req("GET", tmpl("/groups/{group_id}/memberships.json").set("group_id", group_id)), handleList(GroupMembership.class, "group_memberships"))); } public Iterable<GroupMembership> getAssignableGroupMemberships() { return new PagedIterable<GroupMembership>(cnst("/group_memberships/assignable.json"), handleList(GroupMembership.class, "group_memberships")); } public List<GroupMembership> getAssignableGroupMemberships(long group_id) { return complete(submit(req("GET", tmpl("/groups/{group_id}/memberships/assignable.json").set("group_id", group_id)), handleList(GroupMembership.class, "group_memberships"))); } public GroupMembership getGroupMembership(long id) { return complete(submit(req("GET", tmpl("/group_memberships/{id}.json").set("id", id)), handle(GroupMembership.class, "group_membership"))); } public GroupMembership getGroupMembership(long user_id, long group_membership_id) { return complete(submit(req("GET", tmpl("/users/{uid}/group_memberships/{gmid}.json").set("uid", user_id) .set("gmid", group_membership_id)), handle(GroupMembership.class, "group_membership"))); } public GroupMembership createGroupMembership(GroupMembership groupMembership) { return complete(submit(req("POST", cnst("/group_memberships.json"), JSON, json( Collections.singletonMap("group_membership", groupMembership))), handle(GroupMembership.class, "group_membership"))); } public GroupMembership createGroupMembership(long user_id, GroupMembership groupMembership) { return complete(submit(req("POST", tmpl("/users/{id}/group_memberships.json").set("id", user_id), JSON, json(Collections.singletonMap("group_membership", groupMembership))), handle(GroupMembership.class, "group_membership"))); } public void deleteGroupMembership(GroupMembership groupMembership) { checkHasId(groupMembership); deleteGroupMembership(groupMembership.getId()); } public void deleteGroupMembership(long id) { complete(submit(req("DELETE", tmpl("/group_memberships/{id}.json").set("id", id)), handleStatus())); } public void deleteGroupMembership(long user_id, GroupMembership groupMembership) { checkHasId(groupMembership); deleteGroupMembership(user_id, groupMembership.getId()); } public void deleteGroupMembership(long user_id, long group_membership_id) { complete(submit(req("DELETE", tmpl("/users/{uid}/group_memberships/{gmid}.json").set("uid", user_id) .set("gmid", group_membership_id)), handleStatus())); } public List<GroupMembership> setGroupMembershipAsDefault(long user_id, GroupMembership groupMembership) { checkHasId(groupMembership); return complete(submit(req("PUT", tmpl("/users/{uid}/group_memberships/{gmid}/make_default.json") .set("uid", user_id).set("gmid", groupMembership.getId()), JSON, json( Collections.singletonMap("group_memberships", groupMembership))), handleList(GroupMembership.class, "results"))); } public Iterable<Forum> getForums() { return new PagedIterable<Forum>(cnst("/forums.json"), handleList(Forum.class, "forums")); } public List<Forum> getForums(long category_id) { return complete(submit(req("GET", tmpl("/categories/{id}/forums.json").set("id", category_id)), handleList(Forum.class, "forums"))); } public Forum getForum(long id) { return complete(submit(req("GET", tmpl("/forums/{id}.json").set("id", id)), handle(Forum.class, "forum"))); } public Forum createForum(Forum forum) { return complete(submit(req("POST", cnst("/forums.json"), JSON, json( Collections.singletonMap("forum", forum))), handle(Forum.class, "forum"))); } public Forum updateForum(Forum forum) { checkHasId(forum); return complete(submit(req("PUT", tmpl("/forums/{id}.json").set("id", forum.getId()), JSON, json( Collections.singletonMap("forum", forum))), handle(Forum.class, "forum"))); } public void deleteForum(Forum forum) { checkHasId(forum); complete(submit(req("DELETE", tmpl("/forums/{id}.json").set("id", forum.getId())), handleStatus())); } public Iterable<Topic> getTopics() { return new PagedIterable<Topic>(cnst("/topics.json"), handleList(Topic.class, "topics")); } public List<Topic> getTopics(long forum_id) { return complete(submit(req("GET", tmpl("/forums/{id}/topics.json").set("id", forum_id)), handleList(Topic.class, "topics"))); } public List<Topic> getTopicsByUser(long user_id) { return complete(submit(req("GET", tmpl("/users/{id}/topics.json").set("id", user_id)), handleList(Topic.class, "topics"))); } public Topic getTopic(long id) { return complete(submit(req("GET", tmpl("/topics/{id}.json").set("id", id)), handle(Topic.class, "topic"))); } public Topic createTopic(Topic topic) { checkHasId(topic); return complete(submit(req("POST", cnst("/topics.json"), JSON, json( Collections.singletonMap("topic", topic))), handle(Topic.class, "topic"))); } public Topic importTopic(Topic topic) { checkHasId(topic); return complete(submit(req("POST", cnst("/import/topics.json"), JSON, json( Collections.singletonMap("topic", topic))), handle(Topic.class, "topic"))); } public List<Topic> getTopics(long id, long... ids) { return complete(submit(req("POST", tmpl("/topics/show_many.json{?ids}").set("ids", idArray(id, ids))), handleList(Topic.class, "topics"))); } public Topic updateTopic(Topic topic) { checkHasId(topic); return complete(submit(req("PUT", tmpl("/topics/{id}.json").set("id", topic.getId()), JSON, json( Collections.singletonMap("topic", topic))), handle(Topic.class, "topic"))); } public void deleteTopic(Topic topic) { checkHasId(topic); complete(submit(req("DELETE", tmpl("/topics/{id}.json").set("id", topic.getId())), handleStatus())); } public Iterable<SearchResultEntity> getSearchResults(String query) { return new PagedIterable<SearchResultEntity>(tmpl("/search.json{?query}").set("query", query), handleSearchList("results")); } public <T extends SearchResultEntity> Iterable<T> getSearchResults(Class<T> type, String query) { return getSearchResults(type, query, null); } public <T extends SearchResultEntity> Iterable<T> getSearchResults(Class<T> type, String query, String params) { String typeName = null; for (Map.Entry<String, Class<? extends SearchResultEntity>> entry : searchResultTypes.entrySet()) { if (type.equals(entry.getValue())) { typeName = entry.getKey(); break; } } if (typeName == null) { return Collections.emptyList(); } return new PagedIterable<T>(tmpl("/search.json{?query,params}") .set("query", query + "+type:" + typeName) .set("params", params), handleList(type, "results")); } public void notifyApp(String json) { complete(submit(req("POST", cnst("/apps/notify.json"), JSON, json.getBytes()), handleStatus())); } public void updateInstallation(int id, String json) { complete(submit(req("PUT", tmpl("/apps/installations/{id}.json").set("id", id), JSON, json.getBytes()), handleStatus())); } // TODO search with sort order // TODO search with query building API // Action methods for Help Center /** * Get all articles from help center. * * @return List of Articles. */ public Iterable<Article> getArticles() { return new PagedIterable<Article>(cnst("/help_center/articles.json"), handleList(Article.class, "articles")); } public Iterable<Article> getArticlesIncrementally(Date startTime) { return new PagedIterable<Article>( tmpl("/help_center/incremental/articles.json{?start_time}") .set("start_time", msToSeconds(startTime.getTime())), handleIncrementalList(Article.class, "articles")); } public List<Article> getArticlesFromPage(int page) { return complete(submit(req("GET", tmpl("/help_center/articles.json?page={page}").set("page", page)), handleList(Article.class, "articles"))); } public Article getArticle(int id) { return complete(submit(req("GET", tmpl("/help_center/articles/{id}.json").set("id", id)), handle(Article.class, "article"))); } public Iterable<Translation> getArticleTranslations(Long articleId) { return new PagedIterable<Translation>( tmpl("/help_center/articles/{articleId}/translations.json").set("articleId", articleId), handleList(Translation.class, "translations")); } public Article createArticle(Article article) { checkHasSectionId(article); return complete(submit(req("POST", tmpl("/help_center/sections/{id}/articles.json").set("id", article.getSectionId()), JSON, json(Collections.singletonMap("article", article))), handle(Article.class, "article"))); } public Article updateArticle(Article article) { checkHasId(article); return complete(submit(req("PUT", tmpl("/help_center/articles/{id}.json").set("id", article.getId()), JSON, json(Collections.singletonMap("article", article))), handle(Article.class, "article"))); } public void deleteArticle(Article article) { checkHasId(article); complete(submit(req("DELETE", tmpl("/help_center/articles/{id}.json").set("id", article.getId())), handleStatus())); } /** * Delete attachment from article. * @param attachment */ public void deleteArticleAttachment(ArticleAttachments attachment) { if (attachment.getId() == 0) { throw new IllegalArgumentException("Attachment requires id"); } deleteArticleAttachment(attachment.getId()); } /** * Delete attachment from article. * @param id attachment identifier. */ public void deleteArticleAttachment(long id) { complete(submit(req("DELETE", tmpl("/help_center/articles/attachments/{id}.json").set("id", id)), handleStatus())); } public List<Category> getCategories() { return complete(submit(req("GET", cnst("/help_center/categories.json")), handleList(Category.class, "categories"))); } public Category getCategory(int id) { return complete(submit(req("GET", tmpl("/help_center/categories/{id}.json").set("id", id)), handle(Category.class, "category"))); } public Iterable<Translation> getCategoryTranslations(Long categoryId) { return new PagedIterable<Translation>( tmpl("/help_center/categories/{categoryId}/translations.json").set("categoryId", categoryId), handleList(Translation.class, "translations")); } public Category createCategory(Category category) { return complete(submit(req("POST", cnst("/help_center/categories.json"), JSON, json(Collections.singletonMap("category", category))), handle(Category.class, "category"))); } public Category updateCategory(Category category) { checkHasId(category); return complete(submit(req("PUT", tmpl("/help_center/categories/{id}.json").set("id", category.getId()), JSON, json(Collections.singletonMap("category", category))), handle(Category.class, "category"))); } public void deleteCategory(Category category) { checkHasId(category); complete(submit(req("DELETE", tmpl("/help_center/categories/{id}.json").set("id", category.getId())), handleStatus())); } public List<Section> getSections() { return complete(submit(req("GET", cnst("/help_center/sections.json")), handleList(Section.class, "sections"))); } public List<Section> getSections(Category category) { checkHasId(category); return complete(submit(req("GET", tmpl("/help_center/categories/{id}/sections.json").set("id", category.getId())), handleList(Section.class, "sections"))); } public Section getSection(int id) { return complete(submit(req("GET", tmpl("/help_center/sections/{id}.json").set("id", id)), handle(Section.class, "section"))); } public Iterable<Translation> getSectionTranslations(Long sectionId) { return new PagedIterable<Translation>( tmpl("/help_center/sections/{sectionId}/translations.json").set("sectionId", sectionId), handleList(Translation.class, "translations")); } public Section createSection(Section section) { return complete(submit(req("POST", cnst("/help_center/sections.json"), JSON, json(Collections.singletonMap("section", section))), handle(Section.class, "section"))); } public Section updateSection(Section section) { checkHasId(section); return complete(submit(req("PUT", tmpl("/help_center/sections/{id}.json").set("id", section.getId()), JSON, json(Collections.singletonMap("section", section))), handle(Section.class, "section"))); } public void deleteSection(Section section) { checkHasId(section); complete(submit(req("DELETE", tmpl("/help_center/sections/{id}.json").set("id", section.getId())), handleStatus())); } // Helper methods private byte[] json(Object object) { try { return mapper.writeValueAsBytes(object); } catch (JsonProcessingException e) { throw new ZendeskException(e.getMessage(), e); } } private <T> ListenableFuture<T> submit(Request request, ZendeskAsyncCompletionHandler<T> handler) { if (logger.isDebugEnabled()) { if (request.getStringData() != null) { logger.debug("Request {} {}\n{}", request.getMethod(), request.getUrl(), request.getStringData()); } else if (request.getByteData() != null) { logger.debug("Request {} {} {} {} bytes", request.getMethod(), request.getUrl(), request.getHeaders().getFirstValue("Content-type"), request.getByteData().length); } else { logger.debug("Request {} {}", request.getMethod(), request.getUrl()); } } return client.executeRequest(request, handler); } private static abstract class ZendeskAsyncCompletionHandler<T> extends AsyncCompletionHandler<T> { @Override public void onThrowable(Throwable t) { if (t instanceof IOException) { throw new ZendeskException(t); } else { super.onThrowable(t); } } } private Request req(String method, Uri template) { return req(method, template.toString()); } private static final Pattern RESTRICTED_PATTERN = Pattern.compile("%2B", Pattern.LITERAL); private Request req(String method, String url) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } else { builder.addHeader("Authorization", "Bearer " + oauthToken); } builder.setUrl(RESTRICTED_PATTERN.matcher(url).replaceAll("+")); // replace out %2B with + due to API restriction return builder.build(); } private Request req(String method, Uri template, String contentType, byte[] body) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } else { builder.addHeader("Authorization", "Bearer " + oauthToken); } builder.setUrl(RESTRICTED_PATTERN.matcher(template.toString()).replaceAll("+")); //replace out %2B with + due to API restriction builder.addHeader("Content-type", contentType); builder.setBody(body); return builder.build(); } protected ZendeskAsyncCompletionHandler<Void> handleStatus() { return new ZendeskAsyncCompletionHandler<Void>() { @Override public Void onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { return null; } throw new ZendeskResponseException(response); } }; } @SuppressWarnings("unchecked") protected <T> ZendeskAsyncCompletionHandler<T> handle(final Class<T> clazz) { return new ZendeskAsyncCompletionHandler<T>() { @Override public T onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { return (T) mapper.reader(clazz).readValue(response.getResponseBodyAsStream()); } if (response.getStatusCode() == 404) { return null; } throw new ZendeskResponseException(response); } }; } private class BasicAsyncCompletionHandler<T> extends ZendeskAsyncCompletionHandler<T> { private final Class<T> clazz; private final String name; private final Class[] typeParams; public BasicAsyncCompletionHandler(Class clazz, String name, Class... typeParams) { this.clazz = clazz; this.name = name; this.typeParams = typeParams; } @Override public T onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { if (typeParams.length > 0) { JavaType type = mapper.getTypeFactory().constructParametricType(clazz, typeParams); return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), type); } return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), clazz); } if (response.getStatusCode() == 404) { return null; } throw new ZendeskResponseException(response); } } protected <T> ZendeskAsyncCompletionHandler<T> handle(final Class<T> clazz, final String name, final Class... typeParams) { return new BasicAsyncCompletionHandler<T>(clazz, name, typeParams); } protected <T> ZendeskAsyncCompletionHandler<JobStatus<T>> handleJobStatus(final Class<T> resultClass) { return new BasicAsyncCompletionHandler<JobStatus<T>>(JobStatus.class, "job_status", resultClass) { @Override public JobStatus<T> onCompleted(Response response) throws Exception { JobStatus<T> result = super.onCompleted(response); result.setResultsClass(resultClass); return result; } }; } private static final String NEXT_PAGE = "next_page"; private static final String END_TIME = "end_time"; private static final String COUNT = "count"; private static final int INCREMENTAL_EXPORT_MAX_COUNT_BY_REQUEST = 1000; private abstract class PagedAsyncCompletionHandler<T> extends ZendeskAsyncCompletionHandler<T> { private String nextPage; public void setPagedProperties(JsonNode responseNode, Class<?> clazz) { JsonNode node = responseNode.get(NEXT_PAGE); if (node == null) { this.nextPage = null; if (logger.isDebugEnabled()) { logger.debug(NEXT_PAGE + " property not found, pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } } else { this.nextPage = node.asText(); } } public String getNextPage() { return nextPage; } public void setNextPage(String nextPage) { this.nextPage = nextPage; } } private class PagedAsyncListCompletionHandler<T> extends PagedAsyncCompletionHandler<List<T>> { private final Class<T> clazz; private final String name; public PagedAsyncListCompletionHandler(Class<T> clazz, String name) { this.clazz = clazz; this.name = name; } @Override public List<T> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes()); setPagedProperties(responseNode, clazz); List<T> values = new ArrayList<T>(); for (JsonNode node : responseNode.get(name)) { values.add(mapper.convertValue(node, clazz)); } return values; } throw new ZendeskResponseException(response); } } protected <T> PagedAsyncCompletionHandler<List<T>> handleList(final Class<T> clazz, final String name) { return new PagedAsyncListCompletionHandler<T>(clazz, name); } private static final long FIVE_MINUTES = TimeUnit.MINUTES.toMillis(5); protected <T> PagedAsyncCompletionHandler<List<T>> handleIncrementalList(final Class<T> clazz, final String name) { return new PagedAsyncListCompletionHandler<T>(clazz, name) { @Override public void setPagedProperties(JsonNode responseNode, Class<?> clazz) { JsonNode node = responseNode.get(NEXT_PAGE); if (node == null) { if (logger.isDebugEnabled()) { logger.debug(NEXT_PAGE + " property not found, pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } setNextPage(null); return; } JsonNode endTimeNode = responseNode.get(END_TIME); if (endTimeNode == null || endTimeNode.asLong() == 0) { if (logger.isDebugEnabled()) { logger.debug(END_TIME + " property not found, incremental export pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } setNextPage(null); return; } /** * A request after five minutes ago will result in a 422 responds from Zendesk. * Therefore, we stop pagination. */ if (TimeUnit.SECONDS.toMillis(endTimeNode.asLong()) > System.currentTimeMillis() - FIVE_MINUTES) { setNextPage(null); } else { // Taking into account documentation found at https://developer.zendesk.com/rest_api/docs/core/incremental_export#polling-strategy JsonNode countNode = responseNode.get(COUNT); if (countNode == null) { if (logger.isDebugEnabled()) { logger.debug(COUNT + " property not found, incremental export pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } setNextPage(null); return; } if (countNode.asInt() < INCREMENTAL_EXPORT_MAX_COUNT_BY_REQUEST) { setNextPage(null); } else { setNextPage(node.asText()); } } } }; } protected PagedAsyncCompletionHandler<List<SearchResultEntity>> handleSearchList(final String name) { return new PagedAsyncCompletionHandler<List<SearchResultEntity>>() { @Override public List<SearchResultEntity> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { JsonNode responseNode = mapper.readTree(response.getResponseBodyAsStream()).get(name); setPagedProperties(responseNode, null); List<SearchResultEntity> values = new ArrayList<SearchResultEntity>(); for (JsonNode node : responseNode) { Class<? extends SearchResultEntity> clazz = searchResultTypes.get(node.get("result_type")); if (clazz != null) { values.add(mapper.convertValue(node, clazz)); } } return values; } throw new ZendeskResponseException(response); } }; } protected PagedAsyncCompletionHandler<List<Target>> handleTargetList(final String name) { return new PagedAsyncCompletionHandler<List<Target>>() { @Override public List<Target> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes()); setPagedProperties(responseNode, null); List<Target> values = new ArrayList<Target>(); for (JsonNode node : responseNode.get(name)) { Class<? extends Target> clazz = targetTypes.get(node.get("type").asText()); if (clazz != null) { values.add(mapper.convertValue(node, clazz)); } } return values; } throw new ZendeskResponseException(response); } }; } protected PagedAsyncCompletionHandler<List<ArticleAttachments>> handleArticleAttachmentsList(final String name) { return new PagedAsyncCompletionHandler<List<ArticleAttachments>>() { @Override public List<ArticleAttachments> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes()); List<ArticleAttachments> values = new ArrayList<ArticleAttachments>(); for (JsonNode node : responseNode.get(name)) { values.add(mapper.convertValue(node, ArticleAttachments.class)); } return values; } throw new ZendeskResponseException(response); } }; } private TemplateUri tmpl(String template) { return new TemplateUri(url + template); } private Uri cnst(String template) { return new FixedUri(url + template); } private void logResponse(Response response) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(), response.getResponseBody()); } if (logger.isTraceEnabled()) { logger.trace("Response headers {}", response.getHeaders()); } } private static final String UTF_8 = "UTF-8"; private static String encodeUrl(String input) { try { return URLEncoder.encode(input, UTF_8); } catch (UnsupportedEncodingException impossible) { return input; } } private static long msToSeconds(long millis) { return TimeUnit.MILLISECONDS.toSeconds(millis); } private boolean isStatus2xx(Response response) { return response.getStatusCode() / 100 == 2; } // Static helper methods private static <T> T complete(ListenableFuture<T> future) { try { return future.get(); } catch (InterruptedException e) { throw new ZendeskException(e.getMessage(), e); } catch (ExecutionException e) { if (e.getCause() instanceof ZendeskException) { throw (ZendeskException) e.getCause(); } throw new ZendeskException(e.getMessage(), e); } } private static void checkHasId(Ticket ticket) { if (ticket.getId() == null) { throw new IllegalArgumentException("Ticket requires id"); } } private static void checkHasId(org.zendesk.client.v2.model.Request request) { if (request.getId() == null) { throw new IllegalArgumentException("Request requires id"); } } private static void checkHasId(Audit audit) { if (audit.getId() == null) { throw new IllegalArgumentException("Audit requires id"); } } private static void checkHasId(Comment comment) { if (comment.getId() == null) { throw new IllegalArgumentException("Comment requires id"); } } private static void checkHasId(Field field) { if (field.getId() == null) { throw new IllegalArgumentException("Field requires id"); } } private static void checkHasId(Attachment attachment) { if (attachment.getId() == null) { throw new IllegalArgumentException("Attachment requires id"); } } private static void checkHasId(User user) { if (user.getId() == null) { throw new IllegalArgumentException("User requires id"); } } private static void checkHasId(Identity identity) { if (identity.getId() == null) { throw new IllegalArgumentException("Identity requires id"); } } private static void checkHasId(Organization organization) { if (organization.getId() == null) { throw new IllegalArgumentException("Organization requires id"); } } private static void checkHasId(Group group) { if (group.getId() == null) { throw new IllegalArgumentException("Group requires id"); } } private static void checkHasId(GroupMembership groupMembership) { if (groupMembership.getId() == null) { throw new IllegalArgumentException("GroupMembership requires id"); } } private void checkHasId(Forum forum) { if (forum.getId() == null) { throw new IllegalArgumentException("Forum requires id"); } } private void checkHasId(Topic topic) { if (topic.getId() == null) { throw new IllegalArgumentException("Topic requires id"); } } private static void checkHasId(Article article) { if (article.getId() == null) { throw new IllegalArgumentException("Article requires id"); } } private static void checkHasSectionId(Article article) { if (article.getSectionId() == null) { throw new IllegalArgumentException("Article requires section id"); } } private static void checkHasId(Category category) { if (category.getId() == null) { throw new IllegalArgumentException("Category requires id"); } } private static void checkHasId(Section section) { if (section.getId() == null) { throw new IllegalArgumentException("Section requires id"); } } private static void checkHasId(SuspendedTicket ticket) { if (ticket == null || ticket.getId() == null) { throw new IllegalArgumentException("SuspendedTicket requires id"); } } private static void checkHasToken(Attachment.Upload upload) { if (upload.getToken() == null) { throw new IllegalArgumentException("Upload requires token"); } } private static List<Long> idArray(long id, long... ids) { List<Long> result = new ArrayList<Long>(ids.length + 1); result.add(id); for (long i : ids) { result.add(i); } return result; } private static List<String> statusArray(Status... statuses) { List<String> result = new ArrayList<String>(statuses.length); for (Status s : statuses) { result.add(s.toString()); } return result; } public static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; } // Helper classes private class PagedIterable<T> implements Iterable<T> { private final Uri url; private final PagedAsyncCompletionHandler<List<T>> handler; private PagedIterable(Uri url, PagedAsyncCompletionHandler<List<T>> handler) { this.handler = handler; this.url = url; } public Iterator<T> iterator() { return new PagedIterator(url); } private class PagedIterator implements Iterator<T> { private Iterator<T> current; private String nextPage; public PagedIterator(Uri url) { this.nextPage = url.toString(); } public boolean hasNext() { if (current == null || !current.hasNext()) { if (nextPage == null || nextPage.equalsIgnoreCase("null")) { return false; } List<T> values = complete(submit(req("GET", nextPage), handler)); nextPage = handler.getNextPage(); current = values.iterator(); } return current.hasNext(); } public T next() { if (!hasNext()) { throw new NoSuchElementException(); } return current.next(); } public void remove() { throw new UnsupportedOperationException(); } } } public static class Builder { private AsyncHttpClient client = null; private final String url; private String username = null; private String password = null; private String token = null; private String oauthToken = null; public Builder(String url) { this.url = url; } public Builder setClient(AsyncHttpClient client) { this.client = client; return this; } public Builder setUsername(String username) { this.username = username; return this; } public Builder setPassword(String password) { this.password = password; if (password != null) { this.token = null; this.oauthToken = null; } return this; } public Builder setToken(String token) { this.token = token; if (token != null) { this.password = null; this.oauthToken = null; } return this; } public Builder setOauthToken(String oauthToken) { this.oauthToken = oauthToken; if (oauthToken != null) { this.password = null; this.token = null; } return this; } public Builder setRetry(boolean retry) { return this; } public Zendesk build() { if (token != null) { return new Zendesk(client, url, username + "/token", token); } else if (oauthToken != null) { return new Zendesk(client, url, oauthToken); } return new Zendesk(client, url, username, password); } } }
package org.zendesk.client.v2; import java.io.*; import java.util.*; import java.util.concurrent.ExecutionException; import org.slf4j.*; import org.zendesk.client.v2.model.*; import org.zendesk.client.v2.model.targets.*; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.ning.http.client.*; import com.ning.http.client.Request; /** * @author stephenc * @since 04/04/2013 13:08 */ public class Zendesk implements Closeable { private static final String JSON = "application/json; charset=UTF-8"; private final boolean closeClient; private final AsyncHttpClient client; private final Realm realm; private final String url; private final ObjectMapper mapper; private final Logger logger; private final String accessToken; private boolean closed = false; private static final Map<String, Class<? extends SearchResultEntity>> searchResultTypes = searchResultTypes(); private static final Map<String, Class<? extends Target>> targetTypes = targetTypes(); private static Map<String, Class<? extends SearchResultEntity>> searchResultTypes() { Map<String, Class<? extends SearchResultEntity>> result = new HashMap<String, Class<? extends SearchResultEntity>>(); result.put("ticket", Ticket.class); result.put("user", User.class); result.put("group", Group.class); result.put("organization", Organization.class); // result.put("topic", Topic.class) TODO add this when supported return Collections.unmodifiableMap(result); } private static Map<String, Class<? extends Target>> targetTypes() { Map<String, Class<? extends Target>> result = new HashMap<String, Class<? extends Target>>(); result.put("url_target", UrlTarget.class); result.put("email_target",EmailTarget.class); result.put("basecamp_target", BasecampTarget.class); result.put("campfire_target", CampfireTarget.class); result.put("pivotal_target", PivotalTarget.class); result.put("twitter_target", TwitterTarget.class); // TODO: Implement other Target types //result.put("clickatell_target", ClickatellTarget.class); //result.put("flowdock_target", FlowdockTarget.class); //result.put("get_satisfaction_target", GetSatisfactionTarget.class); //result.put("yammer_target", YammerTarget.class); return Collections.unmodifiableMap(result); } private Zendesk(AsyncHttpClient client, String url, String username, String password, String accessToken) { this.logger = LoggerFactory.getLogger(Zendesk.class); this.closeClient = client == null; this.client = client == null ? new AsyncHttpClient() : client; this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2"; if (username != null) { this.realm = new Realm.RealmBuilder() .setScheme(Realm.AuthScheme.BASIC) .setPrincipal(username) .setPassword(password) .setUsePreemptiveAuth(true) .build(); } else { if (password != null) { throw new IllegalStateException("Cannot specify token or password without specifying username"); } this.realm = null; } this.accessToken = accessToken; this.mapper = createMapper(); } // Closeable interface methods public boolean isClosed() { return closed || client.isClosed(); } public void close() { if (closeClient && !client.isClosed()) { client.close(); } closed = true; } // Action methods public Ticket getTicket(long id) { return complete(submit(req("GET", tmpl("/tickets/{id}.json").set("id", id)), handle(Ticket.class, "ticket"))); } public List<Ticket> getTicketIncidents(long id) { return complete(submit(req("GET", tmpl("/tickets/{id}/incidents.json").set("id", id)), handleList(Ticket.class, "tickets"))); } public void deleteTicket(Ticket ticket) { checkHasId(ticket); deleteTicket(ticket.getId()); } public void deleteTicket(long id) { complete(submit(req("DELETE", tmpl("/tickets/{id}.json").set("id", id)), handleStatus())); } public Ticket createTicket(Ticket ticket) { return complete(submit(req("POST", cnst("/tickets.json"), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public Ticket updateTicket(Ticket ticket) { checkHasId(ticket); return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticket.getId()), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public void markTicketAsSpam(Ticket ticket) { checkHasId(ticket); markTicketAsSpam(ticket.getId()); } public void markTicketAsSpam(long id) { complete(submit(req("PUT", tmpl("/tickets/{id}/mark_as_spam.json").set("id", id)), handleStatus())); } public void deleteTickets(long id, long... ids) { complete(submit(req("DELETE", tmpl("/tickets/destroy_many.json{?ids}").set("ids", idArray(id, ids))), handleStatus())); } public Iterable<Ticket> getTickets() { return new PagedIterable<Ticket>(cnst("/tickets.json"), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsByStatus(Status... ticketStatus) { return new PagedIterable<Ticket>(tmpl("/tickets.json{?status}").set("status", statusArray(ticketStatus)), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsFromSearch(String searchTerm) { return new PagedIterable<Ticket>(tmpl("/search.json{?query}").set("query", searchTerm+"+type:ticket"), handleList(Ticket.class, "results")); } public List<Ticket> getTickets(long id, long... ids) { return complete(submit(req("GET", tmpl("/tickets/show_many.json{?ids}").set("ids", idArray(id, ids))), handleList(Ticket.class, "tickets"))); } public Iterable<Ticket> getRecentTickets() { return new PagedIterable<Ticket>(cnst("/tickets/recent.json"), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getOrganizationTickets(long organizationId) { return new PagedIterable<Ticket>( tmpl("/organizations/{organizationId}/tickets.json").set("organizationId", organizationId), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getUserRequestedTickets(long userId) { return new PagedIterable<Ticket>(tmpl("/users/{userId}/tickets/requested.json").set("userId", userId), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getUserCCDTickets(long userId) { return new PagedIterable<Ticket>(tmpl("/users/{userId}/tickets/ccd.json").set("userId", userId), handleList(Ticket.class, "tickets")); } public Iterable<Audit> getTicketAudits(Ticket ticket) { checkHasId(ticket); return getTicketAudits(ticket.getId()); } public Iterable<Audit> getTicketAudits(Long id) { return new PagedIterable<Audit>(tmpl("/tickets/{ticketId}/audits.json").set("ticketId", id), handleList(Audit.class, "audits")); } public Audit getTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); return getTicketAudit(ticket, audit.getId()); } public Audit getTicketAudit(Ticket ticket, long id) { checkHasId(ticket); return getTicketAudit(ticket.getId(), id); } public Audit getTicketAudit(long ticketId, long auditId) { return complete(submit(req("GET", tmpl("/tickets/{ticketId}/audits/{auditId}.json").set("ticketId", ticketId).set("auditId", auditId)), handle(Audit.class, "audit"))); } public void trustTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); trustTicketAudit(ticket, audit.getId()); } public void trustTicketAudit(Ticket ticket, long id) { checkHasId(ticket); trustTicketAudit(ticket.getId(), id); } public void trustTicketAudit(long ticketId, long auditId) { complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/trust.json").set("ticketId", ticketId) .set("auditId", auditId)), handleStatus())); } public void makePrivateTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); makePrivateTicketAudit(ticket, audit.getId()); } public void makePrivateTicketAudit(Ticket ticket, long id) { checkHasId(ticket); makePrivateTicketAudit(ticket.getId(), id); } public void makePrivateTicketAudit(long ticketId, long auditId) { complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/make_private.json").set("ticketId", ticketId) .set("auditId", auditId)), handleStatus())); } public List<Field> getTicketFields() { return complete(submit(req("GET", cnst("/ticket_fields.json")), handleList(Field.class, "ticket_fields"))); } public Field getTicketField(long id) { return complete(submit(req("GET", tmpl("/ticket_fields/{id}.json").set("id", id)), handle(Field.class, "ticket_field"))); } public Field createTicketField(Field field) { return complete(submit(req("POST", cnst("/ticket_fields.json"), JSON, json( Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field"))); } public Field updateTicketField(Field field) { checkHasId(field); return complete(submit(req("PUT", tmpl("/ticket_fields/{id}.json").set("id", field.getId()), JSON, json(Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field"))); } public void deleteTicketField(Field field) { checkHasId(field); deleteTicket(field.getId()); } public void deleteTicketField(long id) { complete(submit(req("DELETE", tmpl("/ticket_fields/{id}.json").set("id", id)), handleStatus())); } public Attachment.Upload createUpload(String fileName, byte[] content) { return createUpload(null, fileName, "application/binary", content); } public Attachment.Upload createUpload(String fileName, String contentType, byte[] content) { return createUpload(null, fileName, contentType, content); } public Attachment.Upload createUpload(String token, String fileName, String contentType, byte[] content) { TemplateUri uri = tmpl("/uploads.json{?filename}{?token}").set("filename", fileName); if (token != null) { uri.set("token", token); } return complete( submit(req("POST", uri, contentType, content), handle(Attachment.Upload.class, "upload"))); } public void deleteUpload(Attachment.Upload upload) { checkHasToken(upload); deleteUpload(upload.getToken()); } public void deleteUpload(String token) { complete(submit(req("DELETE", tmpl("/uploads/{token}.json").set("token", token)), handleStatus())); } public Attachment getAttachment(Attachment attachment) { checkHasId(attachment); return getAttachment(attachment.getId()); } public Attachment getAttachment(long id) { return complete(submit(req("GET", tmpl("/attachments/{id}.json").set("id", id)), handle(Attachment.class, "attachment"))); } public void deleteAttachment(Attachment attachment) { checkHasId(attachment); deleteAttachment(attachment.getId()); } public void deleteAttachment(long id) { complete(submit(req("DELETE", tmpl("/attachments/{id}.json").set("id", id)), handleStatus())); } public Iterable<Target> getTargets() { return new PagedIterable<Target>(cnst("/targets.json"), handleTargetList("targets")); } public Target getTarget(long id) { return complete(submit(req("GET", tmpl("/targets/{id}.json").set("id", id)), handle(Target.class, "target"))); } public Target createTarget(Target target) { return complete(submit(req("POST", cnst("/targets.json"), JSON, json(Collections.singletonMap("target", target))), handle(Target.class, "target"))); } public void deleteTarget(long targetId) { complete(submit(req("DELETE", tmpl("/targets/{id}.json").set("id", targetId)), handleStatus())); } public Iterable<Trigger> getTriggers() { return new PagedIterable<Trigger>(cnst("/triggers.json"), handleList(Trigger.class, "triggers")); } public Trigger getTrigger(long id) { return complete(submit(req("GET", tmpl("/triggers/{id}.json").set("id", id)), handle(Trigger.class, "trigger"))); } public Trigger createTrigger(Trigger trigger) { return complete(submit(req("POST", cnst("/triggers.json"), JSON, json(Collections.singletonMap("trigger", trigger))), handle(Trigger.class, "trigger"))); } public void deleteTrigger(long triggerId) { complete(submit(req("DELETE", tmpl("/triggers/{id}.json").set("id", triggerId)), handleStatus())); } public Iterable<User> getUsers() { return new PagedIterable<User>(cnst("/users.json"), handleList(User.class, "users")); } public Iterable<User> getGroupUsers(long id) { return new PagedIterable<User>(tmpl("/groups/{id}/users.json").set("id", id), handleList(User.class, "users")); } public Iterable<User> getOrganizationUsers(long id) { return new PagedIterable<User>(tmpl("/organization/{id}/users.json").set("id", id), handleList(User.class, "users")); } public User getUser(long id) { return complete(submit(req("GET", tmpl("/users/{id}.json").set("id", id)), handle(User.class, "user"))); } public User createUser(User user) { return complete(submit(req("POST", cnst("/users.json"), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public List<User> createUsers(User... users) { return createUsers(Arrays.asList(users)); } public List<User> createUsers(List<User> users) { return complete(submit(req("POST", cnst("/users/create_many.json"), JSON, json( Collections.singletonMap("users", users))), handleList(User.class, "results"))); } public User updateUser(User user) { checkHasId(user); return complete(submit(req("PUT", tmpl("/users/{id}.json").set("id", user.getId()), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public void deleteUser(User user) { checkHasId(user); deleteUser(user.getId()); } public void deleteUser(long id) { complete(submit(req("DELETE", tmpl("/users/{id}.json").set("id", id)), handleStatus())); } public Iterable<User> lookupUserByEmail(String email) { return new PagedIterable<User>(tmpl("/users/search.json{?query}").set("query", email), handleList(User.class, "users")); } public Iterable<User> lookupUserByExternalId(String externalId) { return new PagedIterable<User>(tmpl("/users/search.json{?external_id}").set("external_id", externalId), handleList(User.class, "users")); } public User getCurrentUser() { return complete(submit(req("GET", cnst("/users/me.json")), handle(User.class, "user"))); } public void resetUserPassword(User user, String password) { checkHasId(user); resetUserPassword(user.getId(), password); } public void resetUserPassword(long id, String password) { complete(submit(req("POST", tmpl("/users/{id}/password.json").set("id", id), JSON, json(Collections.singletonMap("password", password))), handleStatus())); } public void changeUserPassword(User user, String oldPassword, String newPassword) { checkHasId(user); Map<String, String> req = new HashMap<String, String>(); req.put("previous_password", oldPassword); req.put("password", newPassword); complete(submit(req("PUT", tmpl("/users/{id}/password.json").set("id", user.getId()), JSON, json(req)), handleStatus())); } public List<Identity> getUserIdentities(User user) { checkHasId(user); return getUserIdentities(user.getId()); } public List<Identity> getUserIdentities(long userId) { return complete(submit(req("GET", tmpl("/users/{id}/identities.json").set("id", userId)), handleList(Identity.class, "identities"))); } public Identity getUserIdentity(User user, Identity identity) { checkHasId(identity); return getUserIdentity(user, identity.getId()); } public Identity getUserIdentity(User user, long identityId) { checkHasId(user); return getUserIdentity(user.getId(), identityId); } public Identity getUserIdentity(long userId, long identityId) { return complete(submit(req("GET", tmpl("/users/{userId}/identities/{identityId}.json").set("userId", userId) .set("identityId", identityId)), handle( Identity.class, "identity"))); } public List<Identity> setUserPrimaryIdentity(User user, Identity identity) { checkHasId(identity); return setUserPrimaryIdentity(user, identity.getId()); } public List<Identity> setUserPrimaryIdentity(User user, long identityId) { checkHasId(user); return setUserPrimaryIdentity(user.getId(), identityId); } public List<Identity> setUserPrimaryIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/make_primary.json").set("userId", userId) .set("identityId", identityId), JSON, null), handleList(Identity.class, "identities"))); } public Identity verifyUserIdentity(User user, Identity identity) { checkHasId(identity); return verifyUserIdentity(user, identity.getId()); } public Identity verifyUserIdentity(User user, long identityId) { checkHasId(user); return verifyUserIdentity(user.getId(), identityId); } public Identity verifyUserIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/verify.json") .set("userId", userId) .set("identityId", identityId), JSON, null), handle(Identity.class, "identity"))); } public Identity requestVerifyUserIdentity(User user, Identity identity) { checkHasId(identity); return requestVerifyUserIdentity(user, identity.getId()); } public Identity requestVerifyUserIdentity(User user, long identityId) { checkHasId(user); return requestVerifyUserIdentity(user.getId(), identityId); } public Identity requestVerifyUserIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/request_verification.json") .set("userId", userId) .set("identityId", identityId), JSON, null), handle(Identity.class, "identity"))); } public void deleteUserIdentity(User user, Identity identity) { checkHasId(identity); deleteUserIdentity(user, identity.getId()); } public void deleteUserIdentity(User user, long identityId) { checkHasId(user); deleteUserIdentity(user.getId(), identityId); } public void deleteUserIdentity(long userId, long identityId) { complete(submit(req("DELETE", tmpl("/users/{userId}/identities/{identityId}.json") .set("userId", userId) .set("identityId", identityId) ), handleStatus())); } public void createUserIdentity(long userId, Identity identity) { complete(submit(req("POST", tmpl("/users/{userId}/identities.json").set("userId", userId), JSON, json( Collections.singletonMap("identity", identity))), handle(Identity.class, "identity"))); } public void createUserIdentity(User user, Identity identity) { complete(submit(req("POST", tmpl("/users/{userId}/identities.json").set("userId", user.getId()), JSON, json( Collections.singletonMap("identity", identity))), handle(Identity.class, "identity"))); } public Iterable<org.zendesk.client.v2.model.Request> getRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getOpenRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/open.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getSolvedRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/solved.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getCCRequests() { return new PagedIterable<org.zendesk.client.v2.model.Request>(cnst("/requests/ccd.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(User user) { checkHasId(user); return getUserRequests(user.getId()); } public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(long id) { return new PagedIterable<org.zendesk.client.v2.model.Request>(tmpl("/users/{id}/requests.json").set("id", id), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public org.zendesk.client.v2.model.Request getRequest(long id) { return complete(submit(req("GET", tmpl("/requests/{id}.json").set("id", id)), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public org.zendesk.client.v2.model.Request createRequest(org.zendesk.client.v2.model.Request request) { return complete(submit(req("POST", cnst("/requests.json"), JSON, json(Collections.singletonMap("request", request))), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public org.zendesk.client.v2.model.Request updateRequest(org.zendesk.client.v2.model.Request request) { checkHasId(request); return complete(submit(req("PUT", tmpl("/requests/{id}.json").set("id", request.getId()), JSON, json(Collections.singletonMap("request", request))), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public Iterable<Comment> getRequestComments(org.zendesk.client.v2.model.Request request) { checkHasId(request); return getRequestComments(request.getId()); } public Iterable<Comment> getRequestComments(long id) { return new PagedIterable<Comment>(tmpl("/requests/{id}/comments.json").set("id", id), handleList(Comment.class, "comments")); } public Iterable<Comment> getTicketComments(long id) { return new PagedIterable<Comment>(tmpl("/tickets/{id}/comments.json").set("id", id), handleList(Comment.class, "comments")); } public Comment getRequestComment(org.zendesk.client.v2.model.Request request, Comment comment) { checkHasId(comment); return getRequestComment(request, comment.getId()); } public Comment getRequestComment(org.zendesk.client.v2.model.Request request, long commentId) { checkHasId(request); return getRequestComment(request.getId(), commentId); } public Comment getRequestComment(long requestId, long commentId) { return complete(submit(req("GET", tmpl("/requests/{requestId}/comments/{commentId}.json") .set("requestId", requestId) .set("commentId", commentId)), handle(Comment.class, "comment"))); } public Ticket createComment(long ticketId, Comment comment) { Ticket ticket = new Ticket(); ticket.setComment(comment); return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticketId), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public Iterable<Organization> getOrganizations() { return new PagedIterable<Organization>(cnst("/organizations.json"), handleList(Organization.class, "organizations")); } public Iterable<Organization> getAutoCompleteOrganizations(String name) { if (name == null || name.length() < 2) { throw new IllegalArgumentException("Name must be at least 2 characters long"); } return new PagedIterable<Organization>(tmpl("/organizations/autocomplete.json{?name}").set("name", name), handleList(Organization.class, "organizations")); } // TODO getOrganizationRelatedInformation public Organization getOrganization(long id) { return complete(submit(req("GET", tmpl("/organizations/{id}.json").set("id", id)), handle(Organization.class, "organization"))); } public Organization createOrganization(Organization organization) { return complete(submit(req("POST", cnst("/organizations.json"), JSON, json( Collections.singletonMap("organization", organization))), handle(Organization.class, "organization"))); } public List<Organization> createOrganizations(Organization... organizations) { return createOrganizations(Arrays.asList(organizations)); } public List<Organization> createOrganizations(List<Organization> organizations) { return complete(submit(req("POST", cnst("/organizations/create_many.json"), JSON, json( Collections.singletonMap("organizations", organizations))), handleList(Organization.class, "results"))); } public Organization updateOrganization(Organization organization) { checkHasId(organization); return complete(submit(req("PUT", tmpl("/organizations/{id}.json").set("id", organization.getId()), JSON, json( Collections.singletonMap("organization", organization))), handle(Organization.class, "organization"))); } public void deleteOrganization(Organization organization) { checkHasId(organization); deleteOrganization(organization.getId()); } public void deleteOrganization(long id) { complete(submit(req("DELETE", tmpl("/organizations/{id}.json").set("id", id)), handleStatus())); } public Iterable<Organization> lookupOrganizationsByExternalId(String externalId) { if (externalId == null || externalId.length() < 2) { throw new IllegalArgumentException("Name must be at least 2 characters long"); } return new PagedIterable<Organization>(tmpl("/organizations/search.json{?external_id}").set("external_id", externalId), handleList(Organization.class, "organizations")); } public Iterable<Group> getGroups() { return new PagedIterable<Group>(cnst("/groups.json"), handleList(Group.class, "groups")); } public Iterable<Group> getAssignableGroups() { return new PagedIterable<Group>(cnst("/groups/assignable.json"), handleList(Group.class, "groups")); } public Group getGroup(long id) { return complete(submit(req("GET", tmpl("/groups/{id}.json").set("id", id)), handle(Group.class, "group"))); } public Group createGroup(Group group) { return complete(submit(req("POST", cnst("/groups.json"), JSON, json( Collections.singletonMap("group", group))), handle(Group.class, "group"))); } public List<Group> createGroups(Group... groups) { return createGroups(Arrays.asList(groups)); } public List<Group> createGroups(List<Group> groups) { return complete(submit(req("POST", cnst("/groups/create_many.json"), JSON, json( Collections.singletonMap("groups", groups))), handleList(Group.class, "results"))); } public Group updateGroup(Group group) { checkHasId(group); return complete(submit(req("PUT", tmpl("/groups/{id}.json").set("id", group.getId()), JSON, json( Collections.singletonMap("group", group))), handle(Group.class, "group"))); } public void deleteGroup(Group group) { checkHasId(group); deleteGroup(group.getId()); } public void deleteGroup(long id) { complete(submit(req("DELETE", tmpl("/groups/{id}.json").set("id", id)), handleStatus())); } public Iterable<SearchResultEntity> getSearchResults(String query) { return new PagedIterable<SearchResultEntity>(tmpl("/search.json{?query}").set("query", query), handleSearchList("results")); } public <T extends SearchResultEntity> Iterable<T> getSearchResults(Class<T> type, String query) { String typeName = null; for (Map.Entry<String,Class<? extends SearchResultEntity>> entry: searchResultTypes.entrySet()) { if (type.equals(entry.getValue())) { typeName = entry.getKey(); break; } } if (typeName == null) return Collections.emptyList(); return new PagedIterable<T>(tmpl("/search.json{?query}").set("query", query + "+type:" + typeName), handleList(type, "results")); } // TODO search with sort order // TODO search with query building API // Helper methods private byte[] json(Object object) { try { return mapper.writeValueAsBytes(object); } catch (JsonProcessingException e) { throw new ZendeskException(e.getMessage(), e); } } private <T> ListenableFuture<T> submit(Request request, AsyncCompletionHandler<T> handler) { try { if (request.getStringData() != null) { logger.debug("Request {} {}\n{}", request.getMethod(), request.getUrl(), request.getStringData()); } else if (request.getByteData() != null) { logger.debug("Request {} {} {} {} bytes", request.getMethod(), request.getUrl(), request.getHeaders().getFirstValue("Content-type"), request.getByteData().length); } else { logger.debug("Request {} {}", request.getMethod(), request.getUrl()); } return client.executeRequest(request, handler); } catch (IOException e) { throw new ZendeskException(e.getMessage(), e); } } private Request req(String method, Uri template) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } addAccessTokenAuth(builder); builder.setUrl(template.toString()); return builder.build(); } private Request req(String method, Uri template, String contentType, byte[] body) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } addAccessTokenAuth(builder); builder.setUrl(template.toString()); builder.addHeader("Content-type", contentType); builder.setBody(body); return builder.build(); } private Request req(String method, Uri template, int page) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } addAccessTokenAuth(builder); builder.addQueryParameter("page", Integer.toString(page)); builder.setUrl(template.toString().replace("%2B", "+")); //replace out %2B with + due to API restriction return builder.build(); } private void addAccessTokenAuth(RequestBuilder builder) { if (accessToken != null) { builder.addHeader("Authorization", "Bearer " + accessToken); } } protected AsyncCompletionHandler<Void> handleStatus() { return new AsyncCompletionHandler<Void>() { @Override public Void onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { return null; } throw new ZendeskResponseException(response); } }; } @SuppressWarnings("unchecked") protected <T> AsyncCompletionHandler<T> handle(final Class<T> clazz) { return new AsyncCompletionHandler<T>() { @Override public T onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { return (T) mapper.reader(clazz).readValue(response.getResponseBodyAsBytes()); } if (response.getStatusCode() == 404) { return null; } throw new ZendeskResponseException(response); } }; } protected <T> AsyncCompletionHandler<T> handle(final Class<T> clazz, final String name) { return new AsyncCompletionHandler<T>() { @Override public T onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { return mapper.convertValue(mapper.readTree(response.getResponseBodyAsBytes()).get(name), clazz); } if (response.getStatusCode() == 404) { return null; } throw new ZendeskResponseException(response); } }; } protected <T> AsyncCompletionHandler<List<T>> handleList(final Class<T> clazz) { return new AsyncCompletionHandler<List<T>>() { @Override public List<T> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { List<T> values = new ArrayList<T>(); for (JsonNode node : mapper.readTree(response.getResponseBodyAsBytes())) { values.add(mapper.convertValue(node, clazz)); } return values; } throw new ZendeskResponseException(response); } }; } protected <T> AsyncCompletionHandler<List<T>> handleList(final Class<T> clazz, final String name) { return new AsyncCompletionHandler<List<T>>() { @Override public List<T> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { List<T> values = new ArrayList<T>(); for (JsonNode node : mapper.readTree(response.getResponseBodyAsBytes()).get(name)) { values.add(mapper.convertValue(node, clazz)); } return values; } throw new ZendeskResponseException(response); } }; } protected AsyncCompletionHandler<List<SearchResultEntity>> handleSearchList(final String name) { return new AsyncCompletionHandler<List<SearchResultEntity>>() { @Override public List<SearchResultEntity> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { List<SearchResultEntity> values = new ArrayList<SearchResultEntity>(); for (JsonNode node : mapper.readTree(response.getResponseBodyAsBytes()).get(name)) { Class<? extends SearchResultEntity> clazz = searchResultTypes.get(node.get("result_type")); if (clazz != null) { values.add(mapper.convertValue(node, clazz)); } } return values; } throw new ZendeskResponseException(response); } }; } protected AsyncCompletionHandler<List<Target>> handleTargetList(final String name) { return new AsyncCompletionHandler<List<Target>>() { @Override public List<Target> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { List<Target> values = new ArrayList<Target>(); for (JsonNode node : mapper.readTree(response.getResponseBodyAsBytes()).get(name)) { Class<? extends Target> clazz = targetTypes.get(node.get("type").asText()); if (clazz != null) { values.add(mapper.convertValue(node, clazz)); } } return values; } throw new ZendeskResponseException(response); } }; } private TemplateUri tmpl(String template) { return new TemplateUri(url + template); } private Uri cnst(String template) { return new FixedUri(url + template); } private void logResponse(Response response) throws IOException { logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(), response.getResponseBody()); if (logger.isTraceEnabled()) { logger.trace("Response headers {}", response.getHeaders()); } } private boolean isStatus2xx(Response response) { return response.getStatusCode() / 100 == 2; } // Static helper methods private static <T> T complete(ListenableFuture<T> future) { try { return future.get(); } catch (InterruptedException e) { throw new ZendeskException(e.getMessage(), e); } catch (ExecutionException e) { if (e.getCause() instanceof ZendeskException) { throw (ZendeskException) e.getCause(); } throw new ZendeskException(e.getMessage(), e); } } private static void checkHasId(Ticket ticket) { if (ticket.getId() == null) { throw new IllegalArgumentException("Ticket requires id"); } } private static void checkHasId(org.zendesk.client.v2.model.Request request) { if (request.getId() == null) { throw new IllegalArgumentException("Request requires id"); } } private static void checkHasId(Audit audit) { if (audit.getId() == null) { throw new IllegalArgumentException("Audit requires id"); } } private static void checkHasId(Comment comment) { if (comment.getId() == null) { throw new IllegalArgumentException("Comment requires id"); } } private static void checkHasId(Field field) { if (field.getId() == null) { throw new IllegalArgumentException("Field requires id"); } } private static void checkHasId(Attachment attachment) { if (attachment.getId() == null) { throw new IllegalArgumentException("Attachment requires id"); } } private static void checkHasId(User user) { if (user.getId() == null) { throw new IllegalArgumentException("User requires id"); } } private static void checkHasId(Identity identity) { if (identity.getId() == null) { throw new IllegalArgumentException("Identity requires id"); } } private static void checkHasId(Organization organization) { if (organization.getId() == null) { throw new IllegalArgumentException("Organization requires id"); } } private static void checkHasId(Group group) { if (group.getId() == null) { throw new IllegalArgumentException("Group requires id"); } } private static void checkHasToken(Attachment.Upload upload) { if (upload.getToken() == null) { throw new IllegalArgumentException("Upload requires token"); } } private static List<Long> idArray(long id, long... ids) { List<Long> result = new ArrayList<Long>(ids.length + 1); result.add(id); for (long i : ids) { result.add(i); } return result; } private static List<String> statusArray(Status... statuses) { List<String> result = new ArrayList<String>(statuses.length); for (Status s : statuses) { result.add(s.toString()); } return result; } public static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; } // Helper classes private class PagedIterable<T> implements Iterable<T> { private final Uri url; private final AsyncCompletionHandler<List<T>> handler; private final int initialPage; private PagedIterable(Uri url, AsyncCompletionHandler<List<T>> handler) { this(url, handler, 1); } private PagedIterable(Uri url, AsyncCompletionHandler<List<T>> handler, int initialPage) { this.handler = handler; this.url = url; this.initialPage = initialPage; } public Iterator<T> iterator() { return new PagedIterator(initialPage); } private class PagedIterator implements Iterator<T> { private Iterator<T> current; private int page; private PagedIterator(int page) { this.page = page; } public boolean hasNext() { if (current == null || !current.hasNext()) { if (page > 0) { List<T> values = complete(submit(req("GET", url, page++), handler)); if (values.isEmpty()) { page = -1; } current = values.iterator(); } else { return false; } } return current.hasNext(); } public T next() { if (!hasNext()) { throw new NoSuchElementException(); } return current.next(); } public void remove() { throw new UnsupportedOperationException(); } } } public static class Builder { private AsyncHttpClient client = null; private final String url; private String username = null; private String password = null; private String token = null; private String accessToken = null; public Builder(String url) { this.url = url; } public Builder setClient(AsyncHttpClient client) { this.client = client; return this; } public Builder setUsername(String username) { this.username = username; return this; } public Builder setPassword(String password) { this.password = password; if (password != null) { this.token = null; } return this; } public Builder setToken(String token) { this.token = token; if (token != null) { this.password = null; } return this; } public Builder setAccessToken(String accessToken) { this.accessToken = accessToken; return this; } public Builder setRetry(boolean retry) { return this; } public Zendesk build() { if (token == null) { return new Zendesk(client, url, username, password, accessToken); } return new Zendesk(client, url, username + "/token", token, accessToken); } } }
package main.java.player.panels; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.JPanel; import javax.swing.JRadioButton; import main.java.player.TDPlayerEngine; /** * Panel to allow user to choose difficulty * @author Michael Han * */ @SuppressWarnings("serial") public class DifficultyPanel extends JPanel{ public static final String EASY = "easy"; public static final String MEDIUM = "medium"; public static final String HARD = "hard"; @SuppressWarnings("unused") private TDPlayerEngine engine; private ButtonGroup difficultyRadioButtonGroup; public DifficultyPanel(TDPlayerEngine myEngine){ engine = myEngine; difficultyRadioButtonGroup = new ButtonGroup(); addRadioButtons(); } private void addRadioButtons(){ //need gameengine to agree that default is easy mode JRadioButton easyButton = new JRadioButton(EASY); easyButton.setActionCommand(EASY); easyButton.setMnemonic(KeyEvent.VK_E); easyButton.setSelected(true); JRadioButton mediumButton = new JRadioButton(MEDIUM); mediumButton.setActionCommand(MEDIUM); mediumButton.setMnemonic(KeyEvent.VK_M); JRadioButton hardButton = new JRadioButton(HARD); hardButton.setActionCommand(HARD); hardButton.setMnemonic(KeyEvent.VK_H); difficultyRadioButtonGroup.add(easyButton); difficultyRadioButtonGroup.add(mediumButton); difficultyRadioButtonGroup.add(hardButton); easyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("easy"); //frame.pack(); } }); mediumButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("medium"); //frame.pack(); } }); hardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("hard"); //frame.pack(); } }); add(easyButton); add(mediumButton); add(hardButton); } }
package pt.uptodate; import com.google.gson.Gson; import pt.uptodate.api.IUpdateable; import pt.uptodate.util.Util; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Strikingwolf */ public class FetchedUpdateable { public final boolean auto; public final int severity; public final String displaySeverity; public final String display; public final String oldDisp; public final String url; public final int old; public final int version; public final String name; /** * Creates a FetchedUpdateable from an IUpdateable with the getRemote * @param mod IUpdateable */ @SuppressWarnings("unchecked") public FetchedUpdateable(IUpdateable mod) { this.name = mod.getName(); Map<String, Object> load = new Gson().fromJson(mod.getRemote(), Map.class); this.auto = (Boolean) load.get("auto"); this.url = (String) load.get("url"); List<Integer> severityL = (List<Integer>) load.get("severity"); List<String> displayL = (List<String>) load.get("display"); List<Integer> versionL = (List<Integer>) load.get("technical"); HashMap<String, String> local = mod.getLocal(); this.old = Integer.valueOf(local.get("technical")); this.oldDisp = local.get("display"); int splitIndex = versionL.indexOf(this.old); this.version = versionL.get(versionL.size() - 1); this.display = displayL.get(versionL.size() - 1); this.severity = Util.max(Util.after(severityL, splitIndex)); this.displaySeverity = makeDisplayS(severity); } /** * Makes a custom FetchedUpdateable from an IUpdateable * @param mod IUpdateable * @param severity severity of update * @param display display version * @param oldDisp old display version * @param url url of download * @param old old version * @param version new version */ public FetchedUpdateable(IUpdateable mod, boolean auto, int severity, String display, String oldDisp, String url, int old, int version) { this(mod, auto, severity, makeDisplayS(severity),display, oldDisp, url, old, version); } /** * Makes a FetchedUpdateable with auto set to false by default * @param mod IUpdateable * @param severity severity of update * @param display display version * @param oldDisp old display version * @param url url of download * @param old old version * @param version new version */ public FetchedUpdateable(IUpdateable mod, int severity, String display, String oldDisp, String url, int old, int version) { this(mod, false, severity, display, oldDisp, url, old, version); } /** * Makes a FetchedUpdateable with auto set to false by default * @param mod IUpdateable * @param severity severity of update * @param display display version * @param displaySeverity display Severity * @param oldDisp old display version * @param url url of download * @param old old version * @param version new version */ public FetchedUpdateable(IUpdateable mod, int severity, String displaySeverity, String display, String oldDisp, String url, int old, int version) { this(mod, false, severity, displaySeverity, display, oldDisp, url, old, version); } /** * Makes a FetchedUpdateable from an IUpdateable * @param mod IUpdateable * @param auto will mod auto-download updates * @param severity severity of update * @param display display version * @param displaySeverity display Severity * @param oldDisp old display version * @param url url of download * @param old old version * @param version new version */ public FetchedUpdateable(IUpdateable mod, boolean auto, int severity, String displaySeverity, String display, String oldDisp, String url, int old, int version) { this(auto, severity, displaySeverity, display, oldDisp, url, old, version, mod.getName()); } /** * Makes a FetchedUpdateable without a display Severity * @param auto will mod auto-download updates * @param severity severity of update * @param display display version * @param oldDisp old display version * @param url url of download * @param old old version * @param version new version * @param modName name of the mod */ public FetchedUpdateable(boolean auto, int severity, String display, String oldDisp, String url, int old, int version, String modName) { this(auto, severity, makeDisplayS(severity), display, oldDisp, url, old, version, modName); } /** * Lowest level constructor. Makes a FetchedUpdateable * @param auto will mod auto-download updates * @param severity severity of update * @param displaySeverity severity to display * @param display display version * @param oldDisp old display version * @param url url of download * @param old old version * @param version new version * @param modName name of the mod */ public FetchedUpdateable(boolean auto, int severity, String displaySeverity, String display, String oldDisp, String url, int old, int version, String modName) { this.auto = auto; this.severity = severity; this.displaySeverity = displaySeverity; this.display = display; this.oldDisp = oldDisp; this.url = url; this.old = old; this.version = version; this.name = modName; } /** * Makes a display severity * @param severity integer severity * @return display severity */ protected static String makeDisplayS(int severity) { if (severity < 2) { return "Normal"; } else if (severity < 3) { return "Severe!"; } return "Critical!!"; } /** * A builder for creating FetchedUpdateables. Example: * <pre><code>FetchedUpdateable fetched = new Builder() * .setAuto(true) * .setDisplay("2.0.0") * .setVersion(200) * .setDisplaySeverity("Critical") * .setSeverity(3) * .setName("ExampleMod") * .setOldDisp("1.0.0") * .setOld(100) * .setUrl("example.com") * .build();</code></pre> * * The Builder can be reused, and <code>build()</code> can be called an infinite amount of times. * * @author CoolSquid */ public static class Builder { private boolean auto; private int severity; private String displaySeverity; private String display; private String oldDisp; private String url; private int old; private int version; private String name; /** * Sets the auto. * * @param auto the auto * @return the builder */ public Builder setAuto(boolean auto) { this.auto = auto; return this; } /** * Sets the severity. * * @param severity the severity * @return the builder */ public Builder setSeverity(int severity) { this.severity = severity; return this; } /** * Sets the display severity. * * @param displaySeverity the display severity * @return the builder */ public Builder setDisplaySeverity(String displaySeverity) { this.displaySeverity = displaySeverity; return this; } /** * Sets the display. * * @param display the display * @return the builder */ public Builder setDisplay(String display) { this.display = display; return this; } /** * Sets the old disp. * * @param oldDisp the old disp * @return the builder */ public Builder setOldDisp(String oldDisp) { this.oldDisp = oldDisp; return this; } /** * Sets the url. * * @param url the url * @return the builder */ public Builder setUrl(String url) { this.url = url; return this; } /** * Sets the old. * * @param old the old * @return the builder */ public Builder setOld(int old) { this.old = old; return this; } /** * Sets the version. * * @param version the version * @return the builder */ public Builder setVersion(int version) { this.version = version; return this; } /** * Sets the name. * * @param name the name * @return the builder */ public Builder setName(String name) { this.name = name; return this; } /** * Builds the fetched updateable. * * @return the fetched updateable */ public FetchedUpdateable build() { return new FetchedUpdateable(this.auto, this.severity, this.displaySeverity, this.display, this.oldDisp, this.url, this.old, this.version, this.name); } } }