answer
stringlengths
17
10.2M
package org.openecard.common; import iso.std.iso_iec._24727.tech.schema.TransmitResponse; import java.util.List; import oasis.names.tc.dss._1_0.core.schema.InternationalStringType; import oasis.names.tc.dss._1_0.core.schema.ResponseBaseType; import oasis.names.tc.dss._1_0.core.schema.Result; import org.openecard.common.apdu.common.CardCommandStatus; import org.openecard.common.apdu.common.CardResponseAPDU; /** * * @author Tobias Wich <tobias.wich@ecsec.de> */ public class WSHelper { public static class WSException extends ECardException { private static final long serialVersionUID = 1L; protected WSException(Result r) { makeException(this, r); } protected WSException(String msg) { makeException(this, msg); } } public static ResponseBaseType checkResult(ResponseBaseType response) throws WSException { Result r = response.getResult(); if (r.getResultMajor().equals(ECardConstants.Major.ERROR)) { if (response instanceof TransmitResponse) { TransmitResponse tr = (TransmitResponse) response; List<byte[]> rApdus = tr.getOutputAPDU(); if(rApdus.size() < 1){ throw new WSException(r); } else { byte[] apdu = CardResponseAPDU.getTrailer(rApdus.get(rApdus.size()-1)); String msg = CardCommandStatus.getMessage(apdu); throw new WSException(msg); } } else { throw new WSException(r); } } return response; } /// functions to create OASIS Result messages public static Result makeResultOK() { Result result = makeResult(ECardConstants.Major.OK, null, null, null); return result; } public static Result makeResultUnknownError(String msg) { Result result = makeResult(ECardConstants.Major.ERROR, ECardConstants.Minor.App.UNKNOWN_ERROR, msg); return result; } public static Result makeResult(String major, String minor, String message) { Result result = makeResult(major, minor, message, "en"); return result; } public static Result makeResultError(String minor, String message) { Result result = makeResult(ECardConstants.Major.ERROR, minor, message, "en"); return result; } public static Result makeResult(Throwable exc) { if (exc instanceof ECardException) { ECardException e = (ECardException) exc; Result result = e.getResult(); return result; } else { Result result = makeResultUnknownError(exc.getMessage()); return result; } } public static Result makeResult(String major, String minor, String message, String lang) { Result r = new Result(); r.setResultMajor(major); r.setResultMinor(minor); if (message != null) { InternationalStringType msg = new InternationalStringType(); msg.setValue(message); msg.setLang(lang); r.setResultMessage(msg); } return r; } public static <C extends Class<T>, T extends ResponseBaseType> T makeResponse(C c, Result r) { try { T t = c.getConstructor().newInstance(); t.setProfile(ECardConstants.Profile.ECARD_1_1); t.setResult(r); return t; } catch (Exception ignore) { return null; } } }
package com.intellij.compiler.ant; import com.intellij.compiler.ant.j2ee.J2EEBuildTarget; import com.intellij.compiler.ant.j2ee.J2EEExplodedBuildTarget; import com.intellij.compiler.ant.j2ee.J2EEJarBuildTarget; import com.intellij.compiler.ant.j2ee.J2EEBuildUtil; import com.intellij.compiler.ant.taskdefs.Path; import com.intellij.compiler.ant.taskdefs.Property; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ProjectJdk; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.Pair; import com.intellij.javaee.make.ModuleBuildProperties; import com.intellij.javaee.make.BuildRecipe; import com.intellij.javaee.make.BuildInstructionVisitor; import com.intellij.javaee.make.J2EEModuleBuildInstruction; import java.io.File; public class ChunkBuild extends CompositeGenerator{ public ChunkBuild(Project project, ModuleChunk chunk, GenerationOptions genOptions) { final File chunkBaseDir = chunk.getBaseDir(); if (chunk.isJ2EEApplication()) { add(new CompileModuleChunkTarget(project, chunk, VirtualFile.EMPTY_ARRAY, VirtualFile.EMPTY_ARRAY, chunkBaseDir, genOptions), 1); } else { if (genOptions.forceTargetJdk) { if (chunk.isJdkInherited()) { add(new Property(BuildProperties.getModuleChunkJdkHomeProperty(chunk.getName()), BuildProperties.propertyRef(BuildProperties.PROPERTY_PROJECT_JDK_HOME))); add(new Property(BuildProperties.getModuleChunkJdkBinProperty(chunk.getName()), BuildProperties.propertyRef(BuildProperties.PROPERTY_PROJECT_JDK_BIN))); add(new Property(BuildProperties.getModuleChunkJdkClasspathProperty(chunk.getName()), BuildProperties.propertyRef(BuildProperties.PROPERTY_PROJECT_JDK_CLASSPATH))); } else { final ProjectJdk jdk = chunk.getJdk(); add(new Property(BuildProperties.getModuleChunkJdkHomeProperty(chunk.getName()), jdk != null? BuildProperties.propertyRef(BuildProperties.getJdkHomeProperty(jdk.getName())): "")); add(new Property(BuildProperties.getModuleChunkJdkBinProperty(chunk.getName()), jdk != null? BuildProperties.propertyRef(BuildProperties.getJdkBinProperty(jdk.getName())): "")); add(new Property(BuildProperties.getModuleChunkJdkClasspathProperty(chunk.getName()), jdk != null? BuildProperties.getJdkPathId(jdk.getName()) : "")); } } add(new Property(BuildProperties.getModuleChunkCompilerArgsProperty(chunk.getName()), BuildProperties.propertyRef(BuildProperties.PROPERTY_COMPILER_ADDITIONAL_ARGS)), 1); final String outputPathUrl = chunk.getOutputDirUrl(); String location = outputPathUrl != null? GenerationUtils.toRelativePath(VirtualFileManager.extractPath(outputPathUrl), chunkBaseDir, BuildProperties.getModuleChunkBasedirProperty(chunk), genOptions, !chunk.isSavePathsRelative()) : CompilerBundle.message("value.undefined"); add(new Property(BuildProperties.getOutputPathProperty(chunk.getName()), location), 1); final String testOutputPathUrl = chunk.getTestsOutputDirUrl(); if (testOutputPathUrl != null) { location = GenerationUtils.toRelativePath(VirtualFileManager.extractPath(testOutputPathUrl), chunkBaseDir, BuildProperties.getModuleChunkBasedirProperty(chunk), genOptions, !chunk.isSavePathsRelative()); } add(new Property(BuildProperties.getOutputPathForTestsProperty(chunk.getName()), location)); add(createBootclasspath(chunk), 1); add(new ModuleChunkClasspath(chunk, genOptions), 1); final ModuleChunkSourcepath moduleSources = new ModuleChunkSourcepath(project, chunk, genOptions); add(moduleSources, 1); add(new CompileModuleChunkTarget(project, chunk, moduleSources.getSourceRoots(), moduleSources.getTestSourceRoots(), chunkBaseDir, genOptions), 1); } add(new CleanModule(chunk), 1); if (chunk.isJ2EE()) { add(new J2EEBuildTarget(chunk, chunkBaseDir, genOptions)); final Pair<Boolean, Boolean> explodedAndJarEnabled = isExplodedAndJarEnabled(project, chunk); if (explodedAndJarEnabled.getFirst()) { add(new J2EEExplodedBuildTarget(chunk, chunkBaseDir, genOptions)); } if (explodedAndJarEnabled.getSecond()) { add(new J2EEJarBuildTarget(chunk, chunkBaseDir, genOptions)); } } } private static Pair<Boolean, Boolean> isExplodedAndJarEnabled(final Project project, final ModuleChunk chunk) { final Module module = chunk.getModules()[0]; final ModuleBuildProperties buildProperties = ModuleBuildProperties.getInstance(module); boolean explodedEnabled = buildProperties.isExplodedEnabled(); boolean jarEnabled = buildProperties.isJarEnabled(); if (!explodedEnabled || !jarEnabled) { final Module[] modules = ModuleManager.getInstance(project).getModules(); for (final Module parentModule : modules) { if (parentModule.getModuleType().isJ2EE() && isModuleIncludedInBuild(module, parentModule)) { final ModuleBuildProperties parentBuildProperties = ModuleBuildProperties.getInstance(parentModule); if (parentBuildProperties.isJarEnabled()) { jarEnabled = true; } if (parentBuildProperties.isExplodedEnabled()) { explodedEnabled = true; } } } } return Pair.create(explodedEnabled, jarEnabled); } private static boolean isModuleIncludedInBuild(final Module includedModule, final Module parentModule) { final BuildRecipe instructions = J2EEBuildUtil.getBuildInstructions(parentModule); return !instructions.visitInstructions(new BuildInstructionVisitor() { public boolean visitJ2EEModuleBuildInstruction(J2EEModuleBuildInstruction instruction) throws Exception { return instruction.isExternalDependencyInstruction() || instruction.getBuildProperties().getModule() != includedModule; } }, false); } private static Generator createBootclasspath(ModuleChunk chunk) { final Path bootclasspath = new Path(BuildProperties.getBootClasspathProperty(chunk.getName())); bootclasspath.add(new Comment(CompilerBundle.message("generated.ant.build.bootclasspath.comment"))); return bootclasspath; } }
package mdbtools.libmdb; import mdbtools.publicapi.RandomAccess; import java.io.IOException; public class file { private static MdbHandle _mdb_open(RandomAccess file /*, boolean writable */) throws IOException { MdbHandle mdb; int key[] = {0x86, 0xfb, 0xec, 0x37, 0x5d, 0x44, 0x9c, 0xfa, 0xc6, 0x5e, 0x28, 0xe6, 0x13, 0xb6}; int j,pos; int bufsize; MdbFile f; mdb = mem.mdb_alloc_handle(); /* need something to bootstrap with, reassign after page 0 is read */ mdb.fmt = MdbFormatConstants.MdbJet3Constants; mdb.f = mem.mdb_alloc_file(); f = mdb.f; // f.filename = filename; // if (writable) // throw new RuntimeException("not ported yet"); // f->writable = TRUE; // f->fd = open(f->filename,O_RDWR); // else // f.fd = new RandomAccess(f.filename); // int i = 1; // if (i == 1) // throw new RuntimeException("implement me"); f.fd = file; f.refs++; if (mdb_read_pg(mdb, 0) == 0) { throw new IOException("Couldn't read first page."); } f.jet_version = mdb_get_int32(mdb, 0x14); if (macros.IS_JET4(mdb)) { mdb.fmt = MdbFormatConstants.MdbJet4Constants; } else { mdb.fmt = MdbFormatConstants.MdbJet3Constants; } /* get the db encryption key and xor it back to clear text */ f.db_key = mdb_get_int32(mdb, 0x3e); f.db_key ^= 0xe15e01b9; /* get the db password located at 0x42 bytes into the file */ for (pos=0;pos<14;pos++) { j = mdb_get_int32(mdb,0x42+pos); j ^= key[pos]; if (j != 0) f.db_passwd[pos] = (char)j; else f.db_passwd[pos] = '\0'; } return mdb; } public static MdbHandle mdb_open(RandomAccess file) throws IOException { return _mdb_open(file); } /** * mdb_read a wrapper for read that bails if anything is wrong */ public static long mdb_read_pg(MdbHandle mdb, long pg) throws IOException { long len; len = _mdb_read_pg(mdb, mdb.pg_buf, pg); /* kan - reset the cur_pos on a new page read */ mdb.cur_pos = 0; /* kan */ return len; } private static long _mdb_read_pg(MdbHandle mdb, byte[] pg_buf, long pg) throws IOException { long len; long offset = pg * mdb.fmt.pg_size; //System.out.println("read page"); if (mdb.f.fd.length() < offset) { //throw new RuntimeException("offset " + offset + " is beyond EOF"); // return 0; pg = (mdb.f.fd.length() - mdb.fmt.pg_size) / mdb.fmt.pg_size; offset = pg * mdb.fmt.pg_size; if (mdb.f.fd.length() < offset) { throw new RuntimeException("offset " + offset + " is beyond EOF"); } } if (mdb.stats != null && mdb.stats.collect) mdb.stats.pg_reads++; mdb.f.fd.seek(offset); len = mdb.f.fd.read(pg_buf,0,mdb.fmt.pg_size); // System.out.println("page was read, offset: "+offset); // System.out.println("[14]: " + unsign(pg_buf[14]) + ", [15]: " + unsign(pg_buf[15])); if (len==-1) { throw new RuntimeException("read error"); } else if (len < mdb.fmt.pg_size) { throw new RuntimeException("EOF reached"); /* fprintf(stderr,"EOF reached %d bytes returned.\n",len, mdb->fmt->pg_size); */ // return 0; } mdb.cur_pg = (short) pg; return len; } public static int _mdb_get_int32(byte[] buf, int offset) { /** @todo convert this */ /* int l; int c; c = buf[offset]; l =c[3]; l<<=8; l+=c[2]; l<<=8; l+=c[1]; l<<=8; l+=c[0]; return l; */ int b1, b2, b3, b4; int pos = offset; // Get the component bytes; b4 is most significant, b1 least. b1 = buf[pos++]; b2 = buf[pos++]; b3 = buf[pos++]; b4 = buf[pos]; // Bytes are signed. Convert [-128, -1] to [128, 255]. if (b1 < 0) { b1 += 256; } if (b2 < 0) { b2 += 256; } if (b3 < 0) { b3 += 256; } if (b4 < 0) { b4 += 256; } // Put the bytes in their proper places in an int. b2 <<= 8; b3 <<= 16; b4 <<= 24; // Return their sum. return (b1 + b2 + b3 + b4); } public static int mdb_get_int32(MdbHandle mdb, int offset) { int l; if (offset < 0 || offset + 4 > mdb.fmt.pg_size) return -1; l = _mdb_get_int32(mdb.pg_buf, offset); mdb.cur_pos+=4; return l; } private static int _mdb_get_int16(byte[] buf, int offset) { return unsign(buf[offset+1])*256+unsign(buf[offset]); /* short b1 , b2; // Get the component bytes; b1 = buf[offset++]; b2 = buf[offset]; // Bytes are signed. Convert [-128, -1] to [128, 255]. if ( b1 < 0 ) b1 += 256; if ( b2 < 0 ) b2 += 256; // Put the bytes in their proper places in a short b2 <<= 8; // Return their sum. return (short) ( b1 + b2 ); */ } public static int mdb_get_int16(MdbHandle mdb, int offset) { int i; if (offset < 0 || offset + 2 > mdb.fmt.pg_size) return -1; i = _mdb_get_int16(mdb.pg_buf, offset); mdb.cur_pos+=2; return i; } public static long mdb_read_alt_pg(MdbHandle mdb, long pg) throws IOException { long len; len = _mdb_read_pg(mdb, mdb.alt_pg_buf, pg); return len; } /* -- not correct - if needed re-port public static int mdb_get_int24_msb(MdbHandle mdb, int offset) { int l; byte[] c; if (offset < 0 || offset + 3 > mdb.fmt.pg_size) return -1; c = mdb.pg_buf; l =c[offset+2]; l<<=8; l+=c[offset+1]; l<<=8; l+=c[offset+0]; mdb.cur_pos+=3; return l; } */ public static int mdb_get_int24(MdbHandle mdb, int offset) { int l; byte[] c; if (offset < 0 || offset + 3 > mdb.fmt.pg_size) return -1; c = mdb.pg_buf; l = unsign(c[offset+2]); l <<= 8; l += unsign(c[offset+1]); l <<= 8; l += unsign(c[offset+0]); mdb.cur_pos += 3; //System.out.println("mdb_get_int_24 [0]: " + unsign(mdb.pg_buf[offset]) + // " [1]: " + unsign(mdb.pg_buf[offset+1]) + // " [2]: " + unsign(mdb.pg_buf[offset+2]) + return l; } public static void mdb_swap_pgbuf(MdbHandle mdb) { byte[] tmpbuf = new byte[MdbHandle.MDB_PGSIZE]; // memcpy(tmpbuf,mdb->pg_buf, MDB_PGSIZE); System.arraycopy(mdb.pg_buf,0,tmpbuf,0,MdbHandle.MDB_PGSIZE); // memcpy(mdb->pg_buf,mdb->alt_pg_buf, MDB_PGSIZE); System.arraycopy(mdb.alt_pg_buf,0,mdb.pg_buf,0,MdbHandle.MDB_PGSIZE); // memcpy(mdb->alt_pg_buf,tmpbuf,MDB_PGSIZE); System.arraycopy(tmpbuf,0,mdb.alt_pg_buf,0,MdbHandle.MDB_PGSIZE); } public static int unsign(byte b) { int i = b; if ( i < 0 ) i += 256; return i; } public static double mdb_get_double(MdbHandle mdb, int offset) { double d; if (offset <0 || offset+4 > mdb.fmt.pg_size) return -1; int currentByte = offset; long accum = 0; for ( int shiftBy = 0; shiftBy < 64; shiftBy +=8 ) { // must cast to long or shift done modulo 32 accum |= ( (long)(mdb.pg_buf[currentByte++] & 0xff)) << shiftBy; } d = Double.longBitsToDouble (accum); mdb.cur_pos+=8; return d; } // return unsigned public static int mdb_get_byte(MdbHandle mdb, int offset) { byte c; c = mdb.pg_buf[offset]; mdb.cur_pos++; return unsign(c); } public static float mdb_get_single(MdbHandle mdb, int offset) { float f; if (offset < 0 || offset+4 > mdb.fmt.pg_size) return -1; int currentByte = offset; int accum = 0; for ( int shiftBy=0; shiftBy<32; shiftBy+=8 ) { accum |= ( mdb.pg_buf[currentByte++] & 0xff ) << shiftBy; } f = Float.intBitsToFloat(accum); mdb.cur_pos+=4; return f; } }
package verification.platu.partialOrders; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import lpn.parser.ExprTree; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.LpnDecomposition.LpnProcess; import verification.platu.main.Options; public class StaticSets { private Transition curTran; private HashMap<Integer, Transition[]> allTransitions; private HashSet<LpnTransitionPair> disableSet; private HashSet<LpnTransitionPair> disableByStealingToken; private HashSet<LpnTransitionPair> enableBySettingEnablingTrue; private ArrayList<ExprTree> conjunctsOfEnabling; private ArrayList<HashSet<LpnTransitionPair>> otherTransSetCurTranEnablingTrue; private HashSet<LpnTransitionPair> curTranSetOtherTranEnablingFalse; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing curTran's assignments. private HashSet<LpnTransitionPair> otherTransSetCurNonPersistentCurTranEnablingFalse; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing another transition's assignments. private HashSet<LpnTransitionPair> modifyAssignment; private String PORdebugFileName; private FileWriter PORdebugFileStream; private BufferedWriter PORdebugBufferedWriter; public StaticSets(Transition curTran, HashMap<Integer,Transition[]> allTransitions) { this.curTran = curTran; this.allTransitions = allTransitions; disableSet = new HashSet<LpnTransitionPair>(); disableByStealingToken = new HashSet<LpnTransitionPair>(); curTranSetOtherTranEnablingFalse = new HashSet<LpnTransitionPair>(); otherTransSetCurNonPersistentCurTranEnablingFalse = new HashSet<LpnTransitionPair>(); enableBySettingEnablingTrue = new HashSet<LpnTransitionPair>(); otherTransSetCurTranEnablingTrue = new ArrayList<HashSet<LpnTransitionPair>>(); conjunctsOfEnabling = new ArrayList<ExprTree>(); modifyAssignment = new HashSet<LpnTransitionPair>(); if (Options.getDebugMode()) { PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg"; try { PORdebugFileStream = new FileWriter(PORdebugFileName, true); } catch (IOException e) { e.printStackTrace(); } PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } } /** * Build a set of transitions that curTran can disable. * @param curLpnIndex */ public void buildCurTranDisableOtherTransSet(int curLpnIndex) { // Test if curTran can disable other transitions by stealing their tokens. if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { Set<Integer> conflictSet = curTran.getConflictSetTransIndices(); conflictSet.remove(curTran.getIndex()); for (Integer i : conflictSet) { LpnTransitionPair lpnTranPair = new LpnTransitionPair(curLpnIndex, i); disableByStealingToken.add(lpnTranPair); } if (Options.getDebugMode()) { // System.out.println(curTran.getName() + " can steal tokens from these transitions:"); // for (Transition t : curTran.getConflictSet()) { // System.out.print(t.getName() + ", "); // System.out.println(); writeStringWithEndOfLineToPORDebugFile(curTran.getName() + " can steal tokens from these transitions:"); for (Transition t : curTran.getConflictSet()) { writeStringToPORDebugFile(t.getName() + ", "); } writeStringWithEndOfLineToPORDebugFile(""); } } } // Test if curTran can disable other transitions by executing its assignments if (!curTran.getAssignments().isEmpty()) { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; ExprTree anotherTranEnablingTree = anotherTran.getEnablingTree(); if (anotherTranEnablingTree != null && (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='f' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='X')) { if (Options.getDebugMode()) { // System.out.println(curTran.getName() + " can disable " + anotherTran.getName() + ". " // + anotherTran.getName() + "'s enabling condition, which is " + anotherTranEnablingTree + ", may become false due to firing of " // + curTran.getName() + "."); // if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F') // System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = F."); // if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='f') // System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = f."); // if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='X') // System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = X."); writeStringWithEndOfLineToPORDebugFile(curTran.getName() + " can disable " + anotherTran.getName() + ". " + anotherTran.getName() + "'s enabling condition (" + anotherTranEnablingTree + "), may become false due to firing of " + curTran.getName() + "."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F') writeStringWithEndOfLineToPORDebugFile("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = F."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='f') writeStringWithEndOfLineToPORDebugFile("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = f."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='X') writeStringWithEndOfLineToPORDebugFile("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = X."); } curTranSetOtherTranEnablingFalse.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(curTranSetOtherTranEnablingFalse); } /** * Build a set of transitions that disable curTran. * @param curLpnIndex * @param allTransitionsToLpnProcesses */ public void buildOtherTransDisableCurTranSet(int curLpnIndex, HashMap<Transition, LpnProcess> allTransitionsToLpnProcesses) { // Test if other transition(s) can disable curTran by stealing their tokens. if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { Set<Integer> conflictSet = curTran.getConflictSetTransIndices(); conflictSet.remove(curTran.getIndex()); for (Integer i : conflictSet) { LpnTransitionPair lpnTranPair = new LpnTransitionPair(curLpnIndex, i); disableByStealingToken.add(lpnTranPair); } if (Options.getDebugMode()) { // System.out.println(curTran.getName() + " can steal tokens from these transitions:"); // for (Transition t : curTran.getConflictSet()) { // System.out.print(t.getName() + ", "); // System.out.println(); writeStringWithEndOfLineToPORDebugFile(curTran.getName() + " can steal tokens from these transitions:"); for (Transition t : curTran.getConflictSet()) { writeStringToPORDebugFile(t.getName() + ", "); } writeStringWithEndOfLineToPORDebugFile(""); } } } // Test if other transitions can disable curTran by executing their assignments if (!curTran.isPersistent()) { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; if (!anotherTran.getAssignments().isEmpty()) { ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='f' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { if (Options.getDebugMode()) { // System.out.println(curTran.getName() + " can be disabled by " + anotherTran.getName() + ". " // + curTran.getName() + "'s enabling condition, which is " + curTranEnablingTree + ", may become false due to firing of " // + anotherTran.getName() + "."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F') // System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = F."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='f') // System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = f."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') // System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); writeStringWithEndOfLineToPORDebugFile(curTran.getName() + " can be disabled by " + anotherTran.getName() + ". " + curTran.getName() + "'s enabling condition (" + curTranEnablingTree + "), may become false due to firing of " + anotherTran.getName() + "."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F') writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = F."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='f') writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = f."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); } otherTransSetCurNonPersistentCurTranEnablingFalse.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(otherTransSetCurNonPersistentCurTranEnablingFalse); buildModifyAssignSet(allTransitionsToLpnProcesses); disableSet.addAll(modifyAssignment); } private boolean tranFormsSelfLoop() { boolean isSelfLoop = false; Place[] curPreset = curTran.getPreset(); Place[] curPostset = curTran.getPostset(); for (Place preset : curPreset) { for (Place postset : curPostset) { if (preset == postset) { isSelfLoop = true; break; } } if (isSelfLoop) break; } return isSelfLoop; } // /** // * Construct a set of transitions that can make the enabling condition of curTran true, by executing their assignments. // */ // public void buildEnableBySettingEnablingTrue() { // for (Integer lpnIndex : allTransitions.keySet()) { // Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); // for (int i = 0; i < allTransInOneLpn.length; i++) { // if (curTran.equals(allTransInOneLpn[i])) // continue; // Transition anotherTran = allTransInOneLpn[i]; // ExprTree curTranEnablingTree = curTran.getEnablingTree(); // if (curTranEnablingTree != null // && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='T' // || curTranEnablingTree.getChange(anotherTran.getAssignments())=='t' // || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { // enableBySettingEnablingTrue.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); // if (Options.getDebugMode()) { // writeStringWithEndOfLineToPORDebugFile(curTran.getName() + " can be enabled by " + anotherTran.getName() + ". " // + curTran.getName() + "'s enabling condition (" + curTranEnablingTree + "), may become true due to firing of " // + anotherTran.getName() + "."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='T') // writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = T."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='t') // writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = t."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') // writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); // public void buildModifyAssignSet() { //// for every transition curTran in T, where T is the set of all transitions, we check t (t != curTran) in T, //// (1) intersection(VA(curTran), supportA(t)) != empty //// (2) intersection(VA(t), supportA(curTran)) != empty //// (3) intersection(VA(t), VA(curTran) != empty //// VA(t0) : set of variables being assigned to (left hand side of the assignment) in transition t0. //// supportA(t0): set of variables appearing in the expressions assigned to the variables of t0 (right hand side of the assignment). // for (Integer lpnIndex : allTransitions.keySet()) { // Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); // for (int i = 0; i < allTransInOneLpn.length; i++) { // if (curTran.equals(allTransInOneLpn[i])) // continue; // Transition anotherTran = allTransInOneLpn[i]; // for (String v : curTran.getAssignTrees().keySet()) { // for (ExprTree anotherTranAssignTree : anotherTran.getAssignTrees().values()) { // if (anotherTranAssignTree != null && anotherTranAssignTree.containsVar(v)) { // modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); // if (Options.getDebugMode()) { //// System.out.println("Variable " + v + " in " + curTran.getName() //// + " may change the right hand side of assignment " + anotherTranAssignTree + " in " + anotherTran.getName()); // for (ExprTree curTranAssignTree : curTran.getAssignTrees().values()) { // for (String v : anotherTran.getAssignTrees().keySet()) { // if (curTranAssignTree != null && curTranAssignTree.containsVar(v)) { // modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); // if (Options.getDebugMode()) { //// System.out.println("Variable " + v + " in " + anotherTran.getName() //// + " may change the right hand side of assignment " + curTranAssignTree + " in " + anotherTran.getName()); // for (String v1 : curTran.getAssignTrees().keySet()) { // for (String v2 : anotherTran.getAssignTrees().keySet()) { // if (v1.equals(v2)) { // modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); // if (Options.getDebugMode()) { //// System.out.println("Variable " + v1 + " are assigned in " + curTran.getName() + " and " + anotherTran.getName()); /** * Construct a set of transitions that can make the enabling condition of curTran true, by executing their assignments. */ public void buildOtherTransSetCurTranEnablingTrue() { ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (!(curTranEnablingTree == null || curTranEnablingTree.toString().equals("TRUE") || curTranEnablingTree.toString().equals("FALSE"))) { buildConjunctsOfEnabling(curTranEnablingTree); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Transition " + curTran.getName() + "'s enabling tree is " + curTranEnablingTree.toString() + " and getOp() returns " + curTranEnablingTree.getOp()); writeStringWithEndOfLineToPORDebugFile(curTran.getName() + "'s enabling transition has the following terms: "); for (int i1=0; i1<conjunctsOfEnabling.size(); i1++) { writeStringWithEndOfLineToPORDebugFile(conjunctsOfEnabling.get(i1).toString()); } } if (!conjunctsOfEnabling.isEmpty()) { for (int index=0; index<conjunctsOfEnabling.size(); index++) { ExprTree conjunct = conjunctsOfEnabling.get(index); HashSet<LpnTransitionPair> transCanEnableConjunct = new HashSet<LpnTransitionPair>(); for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; if (conjunct.getChange(anotherTran.getAssignments())=='T' || conjunct.getChange(anotherTran.getAssignments())=='t' || conjunct.getChange(anotherTran.getAssignments())=='X') { transCanEnableConjunct.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(curTran.getName() + "'s conjunct (" + conjunct.toString() + ") in its enabling condition (" + curTranEnablingTree + ") can be set to true by " + anotherTran.getName() + ". "); if (conjunct.getChange(anotherTran.getAssignments())=='T') writeStringWithEndOfLineToPORDebugFile("The reason is conjunct.getChange(" + anotherTran.getName() + ".getAssignments()) = T."); if (conjunct.getChange(anotherTran.getAssignments())=='t') writeStringWithEndOfLineToPORDebugFile("The reason is conjunct.getChange(" + anotherTran.getName() + ".getAssignments()) = t."); if (conjunct.getChange(anotherTran.getAssignments())=='X') writeStringWithEndOfLineToPORDebugFile("The reason is conjunct.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); } } } } otherTransSetCurTranEnablingTrue.add(index, transCanEnableConjunct); } } } } public void buildConjunctsOfEnabling(ExprTree term) { if (term.getOp().equals("&&")){ buildConjunctsOfEnabling(term.getLeftChild()); buildConjunctsOfEnabling(term.getRightChild()); } else { conjunctsOfEnabling.add(term); } } public ArrayList<ExprTree> getConjunctsOfEnabling() { return conjunctsOfEnabling; } public HashSet<LpnTransitionPair> getModifyAssignSet() { return modifyAssignment; } public HashSet<LpnTransitionPair> getDisableSet() { return disableSet; } public HashSet<LpnTransitionPair> getOtherTransDisableCurTranSet() { HashSet<LpnTransitionPair> otherTransDisableCurTranSet = new HashSet<LpnTransitionPair>(); otherTransDisableCurTranSet.addAll(otherTransSetCurNonPersistentCurTranEnablingFalse); otherTransDisableCurTranSet.addAll(disableByStealingToken); otherTransDisableCurTranSet.addAll(modifyAssignment); return otherTransDisableCurTranSet; } public HashSet<LpnTransitionPair> getCurTranDisableOtherTransSet() { HashSet<LpnTransitionPair> curTranDisableOtherTransSet = new HashSet<LpnTransitionPair>(); curTranDisableOtherTransSet.addAll(disableByStealingToken); curTranDisableOtherTransSet.addAll(curTranSetOtherTranEnablingFalse); return curTranDisableOtherTransSet; } public HashSet<LpnTransitionPair> getEnableBySettingEnablingTrue() { return enableBySettingEnablingTrue; } public HashSet<LpnTransitionPair> getCanEnableBySettingEnablingTrueSet() { HashSet<LpnTransitionPair> curTranInCanEnableSet = new HashSet<LpnTransitionPair>(); curTranInCanEnableSet.addAll(enableBySettingEnablingTrue); return curTranInCanEnableSet; } public ArrayList<HashSet<LpnTransitionPair>> getOtherTransSetCurTranEnablingTrue() { return otherTransSetCurTranEnablingTrue; } public Transition getTran() { return curTran; } /* For every transition curTran in T, where T is the set of all transitions, we check t (t != curTran) in T, (1) intersection(VA(curTran), supportA(t)) != empty (2) intersection(VA(t), supportA(curTran)) != empty (3) intersection(VA(t), VA(curTran) != empty VA(t0) : set of variables being assigned to (left hand side of the assignment) in transition t0. supportA(t0): set of variables appearing in the expressions assigned to the variables of t0 (right hand side of the assignment). */ public void buildModifyAssignSet(HashMap<Transition, LpnProcess> allTransToLpnProcs) { Set<Transition> allTrans = allTransToLpnProcs.keySet(); ArrayList<Transition> transInSingleProcCycle = new ArrayList<Transition>(); if (allTransToLpnProcs.get(curTran).getNoBranchFlag()) { transInSingleProcCycle = allTransToLpnProcs.get(curTran).getProcessTransitions(); } for (Transition anotherTran : allTrans) { if (curTran.equals(anotherTran)) continue; if (transInSingleProcCycle.contains(anotherTran)) // curTran does not have "modify assignments" problem with all transitions in the same process. Because this process // contains only a single cycle, and can only have maximally one transition enabled at any state. continue; for (String v : curTran.getAssignTrees().keySet()) { for (ExprTree anotherTranAssignTree : anotherTran.getAssignTrees().values()) { if (anotherTranAssignTree != null && anotherTranAssignTree.containsVar(v)) { modifyAssignment.add(new LpnTransitionPair(anotherTran.getLpn().getLpnIndex(), anotherTran.getIndex())); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Variable " + v + " in " + curTran.getName() + " may change the right hand side of assignment " + anotherTranAssignTree + " in " + anotherTran.getName()); } } } } for (ExprTree curTranAssignTree : curTran.getAssignTrees().values()) { for (String v : anotherTran.getAssignTrees().keySet()) { if (curTranAssignTree != null && curTranAssignTree.containsVar(v)) { modifyAssignment.add(new LpnTransitionPair(anotherTran.getLpn().getLpnIndex(), anotherTran.getIndex())); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Variable " + v + " in " + anotherTran.getName() + " may change the right hand side of assignment " + curTranAssignTree + " in " + anotherTran.getName()); } } } } for (String v1 : curTran.getAssignTrees().keySet()) { for (String v2 : anotherTran.getAssignTrees().keySet()) { if (v1.equals(v2) && !curTran.getAssignTree(v1).equals(anotherTran.getAssignTree(v2))) { modifyAssignment.add(new LpnTransitionPair(anotherTran.getLpn().getLpnIndex(), anotherTran.getIndex())); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Variable " + v1 + " are assigned in " + curTran.getName() + " and " + anotherTran.getName()); } } } } } } private void writeStringWithEndOfLineToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void writeStringToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); //PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } // public HashSet<LpnTransitionPair> getEnableSet() { // HashSet<LpnTransitionPair> enableSet = new HashSet<LpnTransitionPair>(); // enableSet.addAll(enableByBringingToken); // enableSet.addAll(enableBySettingEnablingTrue); // return enableSet; // private void printIntegerSet(HashSet<Integer> integerSet, String setName) { // if (!setName.isEmpty()) // System.out.print(setName + ": "); // if (integerSet == null) { // System.out.println("null"); // else if (integerSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Integer> curTranDisableIter = integerSet.iterator(); curTranDisableIter.hasNext();) { // Integer tranInDisable = curTranDisableIter.next(); // System.out.print(lpn.getAllTransitions()[tranInDisable] + " "); // System.out.print("\n"); }
package com.google.refine.browsing.util; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Properties; import com.google.refine.expr.ExpressionUtils; import com.google.refine.model.Project; import com.google.refine.model.Row; /** * A utility class for computing the base bins that form the base histograms of * temporal range facets. It evaluates an expression on all the rows of a project to * get temporal values, determines how many bins to distribute those values in, and * bins the rows accordingly. * * This class processes all rows rather than just the filtered rows because it * needs to compute the base bins of a temporal range facet, which remain unchanged * as the user interacts with the facet. */ abstract public class TimeBinIndex { protected int _totalValueCount; protected int _timeValueCount; protected long _min; protected long _max; protected long _step; protected int[] _bins; protected int _timeRowCount; protected int _nonTimeRowCount; protected int _blankRowCount; protected int _errorRowCount; protected boolean _hasError = false; protected boolean _hasNonTime = false; protected boolean _hasTime = false; protected boolean _hasBlank = false; protected long[] steps = { 1, // msec 1000, // sec 1000*60, // min 1000*60*60, // hour 1000*60*60*24, // day 1000*60*60*24*7, // week 1000l*2629746l, // month (average Gregorian year / 12) 1000l*31556952l, // year (average Gregorian year) 1000l*31556952l*10l, // decade 1000l*31556952l*100l, // century 1000l*31556952l*1000l, // millennium }; abstract protected void iterate(Project project, RowEvaluable rowEvaluable, List<Long> allValues); public TimeBinIndex(Project project, RowEvaluable rowEvaluable) { _min = Long.MAX_VALUE; _max = Long.MIN_VALUE; List<Long> allValues = new ArrayList<Long>(); iterate(project, rowEvaluable, allValues); _timeValueCount = allValues.size(); if (_min >= _max) { _step = 1; _min = Math.min(_min, _max); _max = _step; _bins = new int[1]; return; } long diff = _max - _min; for (int i = 0; i < steps.length; i++) { _step = steps[i]; if (diff / _step <= 100) break; } _bins = new int[(int) (diff / _step) + 1]; for (long d : allValues) { int bin = (int) Math.max((d - _min) / _step,0); _bins[bin]++; } } public boolean isTemporal() { return _timeValueCount > _totalValueCount / 2; } public long getMin() { return _min; } public long getMax() { return _max; } public long getStep() { return _step; } public int[] getBins() { return _bins; } public int getTimeRowCount() { return _timeRowCount; } public int getNonTimeRowCount() { return _nonTimeRowCount; } public int getBlankRowCount() { return _blankRowCount; } public int getErrorRowCount() { return _errorRowCount; } protected void processRow( Project project, RowEvaluable rowEvaluable, List<Long> allValues, int rowIndex, Row row, Properties bindings ) { Object value = rowEvaluable.eval(project, rowIndex, row, bindings); if (ExpressionUtils.isError(value)) { _hasError = true; } else if (ExpressionUtils.isNonBlankData(value)) { if (value.getClass().isArray()) { Object[] a = (Object[]) value; for (Object v : a) { _totalValueCount++; if (ExpressionUtils.isError(v)) { _hasError = true; } else if (ExpressionUtils.isNonBlankData(v)) { if (v instanceof Calendar) { v = ((Calendar) v).getTime(); } if (v instanceof Date) { _hasTime = true; processValue(((Date) v).getTime(), allValues); } else { _hasNonTime = true; } } else { _hasBlank = true; } } } else if (value instanceof Collection<?>) { for (Object v : ExpressionUtils.toObjectCollection(value)) { _totalValueCount++; if (ExpressionUtils.isError(v)) { _hasError = true; } else if (ExpressionUtils.isNonBlankData(v)) { if (v instanceof Calendar) { v = ((Calendar) v).getTime(); } if (v instanceof Date) { _hasTime = true; processValue(((Date) v).getTime(), allValues); } else { _hasNonTime = true; } } else { _hasBlank = true; } } } else { _totalValueCount++; if (value instanceof Calendar) { value = ((Calendar) value).getTime(); } if (value instanceof Date) { _hasTime = true; processValue(((Date) value).getTime(), allValues); } else { _hasNonTime = true; } } } else { _hasBlank = true; } } protected void preprocessing() { _hasBlank = false; _hasError = false; _hasNonTime = false; _hasTime = false; } protected void postprocessing() { if (_hasError) { _errorRowCount++; } if (_hasBlank) { _blankRowCount++; } if (_hasTime) { _timeRowCount++; } if (_hasNonTime) { _nonTimeRowCount++; } } protected void processValue(long v, List<Long> allValues) { _min = Math.min(_min, v); _max = Math.max(_max, v); allValues.add(v); } }
package edu.mit.simile.butterfly; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.ExtendedProperties; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.map.ListOrderedMap; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.ResourceNotFoundException; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.EcmaError; import org.mozilla.javascript.Function; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.metaweb.lessen.Utilities; import com.metaweb.lessen.tokenizers.CondensingTokenizer; import com.metaweb.lessen.tokenizers.IndentingTokenizer; import com.metaweb.lessen.tokenizers.Tokenizer; /** * This class is the base implementation of ButterflyModule and * implements the basic functionality that is made available to Butterfly * modules. If you want special functionality that Butterfly does not * expose to your modules, it is highly suggested that you extend this * class instead of implementing the ButterflyModule interface yourself */ public class ButterflyModuleImpl implements ButterflyModule { protected static final Logger _logger = LoggerFactory.getLogger("butterfly.module"); protected ClassLoader _classLoader; protected Timer _timer; protected ServletConfig _config; protected File _path; protected MountPoint _mountPoint; protected ButterflyMounter _mounter; protected String _name; protected File _tempDir; protected ButterflyModule _extended; protected Set<ButterflyModule> _extendedBy = new LinkedHashSet<ButterflyModule>(); protected Set<String> _implementations = new LinkedHashSet<String>(); protected Map<String,ButterflyModule> _dependencies = new HashMap<String,ButterflyModule>(); protected ExtendedProperties _properties; protected Map<String,ButterflyModule> _modules; protected VelocityEngine _templateEngine; protected OrderedMap _scripts = new ListOrderedMap(); protected Set<ButterflyScriptableObject> _scriptables = new LinkedHashSet<ButterflyScriptableObject>(); protected Set<TimerTask> _packers = new HashSet<TimerTask>(); public void init(ServletConfig config) throws Exception { _config = config; scriptInit(); } public void destroy() throws Exception { for (ButterflyScriptableObject scriptable : _scriptables) { scriptable.destroy(); } } public ServletConfig getServletConfig() { return _config; } public ServletContext getServletContext() { return _config.getServletContext(); } public void setClassLoader(ClassLoader classLoader) { _logger.trace("{} -(classloader)-> {}", this, classLoader); this._classLoader = classLoader; } public void setPath(File path) { _logger.trace("{} -(path)-> {}", this, path); this._path = path; } public void setName(String name) { _logger.trace("{} -(name)-> {}", this, name); this._name = name; } public void setExtended(ButterflyModule extended) { _logger.trace("{} -(extends)-> {}", this, extended); this._extended = extended; } public void addExtendedBy(ButterflyModule extendedBy) { _logger.trace("{} -(extended by)-> {}", this, extendedBy); this._extendedBy.add(extendedBy); } public void setMountPoint(MountPoint mountPoint) { _logger.trace("{} -(mount point)-> {}", this, mountPoint); this._mountPoint = mountPoint; } public void setImplementation(String id) { _logger.trace("{} -(implements)-> {}", this, id); this._implementations.add(id); } public void setDependency(String name, ButterflyModule module) { if (!this._dependencies.containsKey(name)) { _logger.trace("{} -({})-> {}", new Object[] { this, name, module} ); this._dependencies.put(name, module); } } public void setModules(Map<String,ButterflyModule> map) { this._modules = map; } @SuppressWarnings("unchecked") public void setScript(URL url, Script script) { _logger.trace("{} -(script)-> {}", this, url); this._scripts.put(url,script); } public void setScriptable(ButterflyScriptableObject scriptable) { _logger.trace("{} -(scriptable)-> {}", this, scriptable.getClassName()); this._scriptables.add(scriptable); } public void setTemplateEngine(VelocityEngine templateEngine) { _logger.trace("{} gets template engine", this); this._templateEngine = templateEngine; } public void setProperties(ExtendedProperties properties) { _logger.trace("{} gets loaded with properties", this); this._properties = properties; } public void setMounter(ButterflyMounter mounter) { _logger.trace("{} gets the module mounter", this); this._mounter = mounter; } public void setTemporaryDir(File tempDir) { _logger.trace("{} -(tempDir)-> {}", this, tempDir); this._tempDir = tempDir; try { FileUtils.deleteDirectory(tempDir); tempDir.mkdirs(); } catch (Exception e) { _logger.error("Error cleaning temporary directory", e); } } public void setTimer(Timer timer) { _logger.trace("{} gets timer", this); this._timer = timer; } public String getName() { return this._name; } public File getPath() { return this._path; } public ExtendedProperties getProperties() { return this._properties; } public MountPoint getMountPoint() { return this._mountPoint; } public ButterflyModule getExtendedModule() { return this._extended; } public Set<ButterflyModule> getExtendingModules() { return this._extendedBy; } public Map<String,ButterflyModule> getDependencies() { return this._dependencies; } public Set<String> getImplementations() { return this._implementations; } public Set<ButterflyScriptableObject> getScriptables() { return this._scriptables; } public VelocityEngine getTemplateEngine() { return this._templateEngine; } public ButterflyModule getModule(String name) { _logger.trace("> getModule({}) [{}]", name, this._name); ButterflyModule module = _dependencies.get(name); if (module == null && _extended != null) { module = _extended.getModule(name); } if (module == null) { module = _modules.get(name); } _logger.trace("< getModule({}) [{}] -> {}", new Object[] { name, this._name, module }); return module; } protected Pattern super_pattern = Pattern.compile("^@@(.*)@@$"); public URL getResource(String resource) { _logger.trace("> getResource({}->{},{})", new Object[] { _name, _extended, resource }); URL u = null; if ("".equals(resource)) { try { u = _path.toURI().toURL(); } catch (MalformedURLException e) { _logger.error("Error", e); } } if (u == null && resource.charAt(0) == '@') { // fast screening for potential matchers Matcher m = super_pattern.matcher(resource); if (m.matches()) { resource = m.group(1); if (_extended != null) { u = _extended.getResource(resource); } } } if (u == null) { try { if (resource.startsWith("file:/")) { u = new URL(resource); } else { if (resource.charAt(0) == '/') resource = resource.substring(1); File f = new File(_path, resource); if (f.exists()) { u = f.toURI().toURL(); } } } catch (MalformedURLException e) { _logger.error("Error", e); } } if (u == null && _extended != null) { u = _extended.getResource(resource); } _logger.trace("< getResource({}->{},{}) -> {}", new Object[] { _name, _extended, resource, u }); return u; } public String getRelativePath(HttpServletRequest request) { _logger.trace("> getRelativePath()"); String path = request.getPathInfo(); String mountPoint = _mountPoint.getMountPoint(); if (path.startsWith(mountPoint)) { path = path.substring(mountPoint.length()); } _logger.trace("< getRelativePath() -> {}", path); return path; } public PrintWriter getFilteringWriter(HttpServletRequest request, HttpServletResponse response, boolean absolute) throws IOException { _logger.trace("> getFilteringWriter() [{},absolute='{}']", this , absolute); LinkRewriter rewriter = new LinkRewriter(response.getWriter(), this, getContextPath(request, absolute)); _logger.trace("< getFilteringWriter() [{},absolute='{}']", this , absolute); return rewriter; } public String getContextPath(HttpServletRequest request, boolean absolute) { return Butterfly.getTrueContextPath(request, absolute); } public String getString(HttpServletRequest request) throws IOException { BufferedReader reader = request.getReader(); StringWriter writer = new StringWriter(); IOUtils.copy(reader, writer); writer.close(); reader.close(); return writer.toString(); } public File getTemporaryDir() { return this._tempDir; } protected Pattern images_pattern = Pattern.compile("^/?.*\\.(jpg|gif|png)$"); protected Pattern mod_inf_pattern = Pattern.compile("^.*/MOD-INF/.*$"); protected String encoding = "UTF-8"; /* * This class encapsulates the 'context action' that Rhino executes * when a request comes. */ class Controller implements ContextAction { private String _path; private HttpServletRequest _request; private HttpServletResponse _response; private Scriptable _scope; public Controller(String path, HttpServletRequest request, HttpServletResponse response) { _path = path; _request = request; _response = response; } public Object run(Context context) { Scriptable scope; try { scope = getScope(context, _request); } catch (Exception e) { throw new RuntimeException ("Error retrieving scope", e); } initScope(context,scope); return process(context, scope); } /* * tell whether or not the controller processed the request * or let it fall thru */ public boolean didRespond() { return ((ScriptableButterfly) _scope.get("butterfly", _scope)).didRespond(); } /* * process the request by invoking the controller "process()" function */ private Object process(Context context, Scriptable scope) { _scope = scope; // save this for the didRespond() method above; Function function = getFunction("process", scope, context); Object[] args = new Object[] { Context.javaToJS(_path, scope), Context.javaToJS(_request, scope), Context.javaToJS(_response, scope) }; return function.call(context, scope, scope, args); } /* * obtain a javascript function from the given scope */ private Function getFunction(String name, Scriptable scope, Context ctx) { Object fun; try { fun = ctx.compileString(name, null, 1, null).exec(ctx, scope); } catch (EcmaError ee) { throw new RuntimeException ("Function '" + name + "()' not found."); } if (!(fun instanceof Function)) { throw new RuntimeException("'" + name + "' is not a function"); } else { return (Function) fun; } } } /** * This method is called by Butterfly when preProcess returns false and allows * modules that want to have a controller in Java instead of Javascript. */ public boolean process(String path, HttpServletRequest request, HttpServletResponse response) throws Exception { if (processScript(path, request, response)) { return true; } Matcher m = null; if (path.equals("") || path.endsWith("/")) { return sendText(request, response, path + "index.html", encoding, "text/html",false); } if (path.endsWith(".js")) { return sendText(request, response, path, encoding, "text/javascript",false); } m = images_pattern.matcher(path); if (m.matches()) { return sendBinary(request, response, path, "image/" + m.group(1)); } if (path.endsWith(".css")) { return sendText(request, response, path, encoding, "text/css",false); } if (path.endsWith(".less")) { return sendLessen(request, response, path, encoding, "text/css",false); } if (path.endsWith(".html")) { return sendText(request, response, path, encoding, "text/html",false); } if (path.endsWith(".xml")) { return sendText(request, response, path, encoding, "application/xml",false); } m = mod_inf_pattern.matcher(path); if (m.matches()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return true; } return false; } public boolean redirect(HttpServletRequest request, HttpServletResponse response, String location) throws Exception { _logger.trace("> redirect: {}", location); String redirectURL = location; if (!location.startsWith("http: String contextPath = getContextPath(request,true); String servletPath = request.getServletPath(); if ("".equals(location)) { location = "/"; } if (servletPath != null) { if (servletPath.startsWith("/")) servletPath = servletPath.substring(1); redirectURL = contextPath + servletPath + location; } else { redirectURL = contextPath + location; } } _logger.info("redirecting to: {}", redirectURL); response.sendRedirect(redirectURL); _logger.trace("< redirect: {}", location); return true; } public boolean sendBinary(HttpServletRequest request, HttpServletResponse response, String file, String mimeType) throws Exception { return send(request, response, getResource(file), false, null, mimeType, null, null, false); } public boolean sendBinary(HttpServletRequest request, HttpServletResponse response, URL resource, String mimeType) throws Exception { return send(request, response, resource, false, null, mimeType, null, null, false); } public boolean sendText(HttpServletRequest request, HttpServletResponse response, String file, String encoding, String mimeType, boolean absolute) throws Exception { return send(request, response, getResource(file), true, encoding, mimeType, null, null, absolute); } public boolean sendText(HttpServletRequest request, HttpServletResponse response, URL resource, String encoding, String mimeType, boolean absolute) throws Exception { return send(request, response, resource, true, encoding, mimeType, null, null, absolute); } public boolean sendWrappedText(HttpServletRequest request, HttpServletResponse response, URL resource, String encoding, String mimeType, String prologue, String epilogue, boolean absolute) throws Exception { return send(request, response, resource, true, encoding, mimeType, prologue, epilogue, absolute); } public boolean sendTextFromTemplate(HttpServletRequest request, HttpServletResponse response, VelocityContext velocity, String template, String encoding, String mimeType, boolean absolute) throws Exception { _logger.trace("> template {} [{}|{}]", new String[] { template, encoding, mimeType }); try { response.setContentType(mimeType); _templateEngine.mergeTemplate(template, encoding, velocity, getFilteringWriter(request, response, absolute)); } catch (ResourceNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } _logger.trace("< template {} [{}|{}]", new String[] { template, encoding, mimeType }); return true; } public boolean sendLessen(HttpServletRequest request, HttpServletResponse response, String path, String encoding, String mimeType, boolean absolute) throws Exception { URL url = getResource(path); Map<String, String> variables = new HashMap<String, String>(); variables.put("module", _name); Tokenizer tokenizer = Utilities.openLess(url, variables); tokenizer = new CondensingTokenizer(tokenizer, false); tokenizer = new IndentingTokenizer(tokenizer); return sendLessenTokenStream(request, response, tokenizer, encoding, "text/css",false); } public boolean sendLessenTokenStream(HttpServletRequest request, HttpServletResponse response, Tokenizer tokenizer, String encoding, String mimeType, boolean absolute) throws Exception { try { response.setContentType(mimeType); Utilities.write(tokenizer, getFilteringWriter(request, response, absolute)); } catch (ResourceNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } return true; } public boolean sendString(HttpServletRequest request, HttpServletResponse response, String str, String encoding, String mimeType) throws Exception { _logger.trace("> string: '{}'", str); response.setContentType(mimeType); response.setCharacterEncoding(encoding); PrintWriter writer = response.getWriter(); writer.write(str); writer.close(); _logger.trace("< string: '{}'", str); return true; } public boolean sendError(HttpServletRequest request, HttpServletResponse response, int code, String str) throws Exception { _logger.trace("> error: '{}' '{}'", code, str); response.sendError(code, str); _logger.trace("< error: '{}' '{}'", code, str); return true; } public static class Level { String name; String href; public Level(String name, String href) { this.name = name; this.href = href; } public String getName() { return name; } public String getHref() { return href; } } public List<Level> makePath(String path, Map<String,String> descs) { LinkedList<Level> ls = new LinkedList<Level>(); String[] paths = path.split("/"); if (paths.length > 1) { String relativePath = (path.endsWith("/")) ? "../" : "./"; for (int i = paths.length - 2; i >= 0; i String p = paths[i]; String desc = descs.get(paths[i]); if (desc == null) desc = p; Level l = new Level(desc,relativePath); relativePath = "../" + relativePath; ls.addFirst(l); } } return ls; } public String toString() { return _name + " [" + this.getClass().getName() + "]"; } public void initScope(Context context, Scriptable scope) { for (ButterflyModule m : _dependencies.values()) { m.initScope(context, scope); } OrderedMapIterator i = _scripts.orderedMapIterator(); while (i.hasNext()) { URL url = (URL) i.next(); _logger.debug("Executing script: {}", url); Script s = (Script) _scripts.get(url); s.exec(context, scope); } } protected void scriptInit() throws Exception { Context context = ContextFactory.getGlobal().enterContext(); Scriptable scope = new ButterflyScope(this, context); initScope(context,scope); String functionName = "init"; try { Object fun = context.compileString(functionName, null, 1, null).exec(context, scope); if (fun != null && fun instanceof Function) { try { ((Function) fun).call(context, scope, scope, new Object[] {}); } catch (EcmaError ee) { _logger.error("Error initializing module " + getName() + " by script function init()", ee); } } } catch (EcmaError ee) { // ignore } } protected boolean processScript(String path, HttpServletRequest request, HttpServletResponse response) throws Exception { boolean result = false; if (_scripts.size() > 0) { Controller controller = new Controller(path, request, response); ContextFactory.getGlobal().call(controller); result = controller.didRespond(); } if (!result && _extended != null && _extended instanceof ButterflyModuleImpl) { result = ((ButterflyModuleImpl) _extended).processScript(path, request, response); } return result; } protected ButterflyScope getScope(Context context, HttpServletRequest request) throws Exception { return new ButterflyScope(this, context); } protected boolean send(HttpServletRequest request, HttpServletResponse response, URL resource, boolean filtering, String encoding, String mimeType, String prologue, String epilogue, boolean absolute) throws Exception { _logger.trace("> send {}", resource); if (resource != null) { URLConnection urlConnection = resource.openConnection(); // NOTE(SM): I've disabled the HTTP caching-related headers for now // we should introduce this back in the future once we start // fine tuning the system but for now since it's hard to // understand when ajax calls are cached or not it's better // to develop without worrying about the cache // long lastModified = urlConnection.getLastModified(); // long ifModifiedSince = request.getDateHeader("If-Modified-Since"); // if (lastModified == 0 || ifModifiedSince / 1000 < lastModified / 1000) { // response.setDateHeader("Last-Modified", lastModified); if (encoding == null) { InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(urlConnection.getInputStream()); response.setHeader("Content-Type", mimeType); output = response.getOutputStream(); IOUtils.copy(input, output); } catch (Exception e) { _logger.error("Error processing " + resource, e); } finally { if (input != null) input.close(); if (output != null) output.close(); } } else { Reader input = null; Writer output = null; try { input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), encoding)); response.setHeader("Content-Type", mimeType + ";charset=" + encoding); response.setCharacterEncoding(encoding); output = (filtering) ? getFilteringWriter(request, response, absolute) : response.getWriter(); if (prologue != null) { output.write(prologue); } IOUtils.copy(input, output); if (epilogue != null) { output.write(epilogue); } } catch (Exception e) { _logger.error("Error processing " + resource, e); } finally { if (input != null) input.close(); if (output != null) output.close(); } } // } else { // response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Couldn't find the specified resource"); } _logger.trace("< send {}", resource); return true; } }
package com.java110.api.listener.room; import com.alibaba.fastjson.JSONObject; import com.java110.api.listener.AbstractServiceApiDataFlowListener; import com.java110.common.constant.ResponseConstant; import com.java110.common.constant.ServiceCodeConstant; import com.java110.common.exception.SMOException; import com.java110.common.util.Assert; import com.java110.common.util.BeanConvertUtil; import com.java110.core.annotation.Java110Listener; import com.java110.core.context.DataFlowContext; import com.java110.core.smo.floor.IFloorInnerServiceSMO; import com.java110.core.smo.room.IRoomInnerServiceSMO; import com.java110.dto.FloorDto; import com.java110.dto.RoomDto; import com.java110.event.service.api.ServiceDataFlowEvent; import com.java110.vo.api.ApiRoomDataVo; import com.java110.vo.api.ApiRoomVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.List; /** * @ClassName QueryRoomsListener * @Description TODO * @Author wuxw * @Date 2019/5/8 0:15 * @Version 1.0 * add by wuxw 2019/5/8 **/ @Java110Listener("queryRoomsListener") public class QueryRoomsListener extends AbstractServiceApiDataFlowListener { @Autowired private IFloorInnerServiceSMO floorInnerServiceSMOImpl; @Autowired private IRoomInnerServiceSMO roomInnerServiceSMOImpl; @Override public String getServiceCode() { return ServiceCodeConstant.SERVICE_CODE_QUERY_ROOMS; } @Override public HttpMethod getHttpMethod() { return HttpMethod.GET; } @Override public void soService(ServiceDataFlowEvent event) { DataFlowContext dataFlowContext = event.getDataFlowContext(); JSONObject reqJson = dataFlowContext.getReqJson(); validateRoomData(reqJson); RoomDto roomDto = BeanConvertUtil.covertBean(reqJson, RoomDto.class); ApiRoomVo apiRoomVo = new ApiRoomVo(); int total = roomInnerServiceSMOImpl.queryRoomsCount(BeanConvertUtil.covertBean(reqJson, RoomDto.class)); apiRoomVo.setTotal(total); if (total > 0) { List<RoomDto> roomDtoList = roomInnerServiceSMOImpl.queryRooms(roomDto); apiRoomVo.setRooms(BeanConvertUtil.covertBeanList(roomDtoList, ApiRoomDataVo.class)); } ResponseEntity<String> responseEntity = new ResponseEntity<String>(JSONObject.toJSONString(apiRoomVo), HttpStatus.OK); dataFlowContext.setResponseEntity(responseEntity); } /** * * * @param reqJson */ private void validateRoomData(JSONObject reqJson) { Assert.jsonObjectHaveKey(reqJson, "communityId", "communityId"); Assert.jsonObjectHaveKey(reqJson, "floorId", "communityId"); Assert.jsonObjectHaveKey(reqJson, "page", "page"); Assert.jsonObjectHaveKey(reqJson, "rows", "rows"); Assert.isInteger(reqJson.getString("page"), "page"); Assert.isInteger(reqJson.getString("rows"), "rows"); Assert.hasLength(reqJson.getString("communityId"), "ID"); int rows = Integer.parseInt(reqJson.getString("rows")); if (rows > MAX_ROW) { throw new SMOException(ResponseConstant.RESULT_CODE_ERROR, "rows 50"); } int total = floorInnerServiceSMOImpl.queryFloorsCount(BeanConvertUtil.covertBean(reqJson, FloorDto.class)); if (total < 1) { throw new IllegalArgumentException("ID"); } } @Override public int getOrder() { return DEFAULT_ORDER; } public IFloorInnerServiceSMO getFloorInnerServiceSMOImpl() { return floorInnerServiceSMOImpl; } public void setFloorInnerServiceSMOImpl(IFloorInnerServiceSMO floorInnerServiceSMOImpl) { this.floorInnerServiceSMOImpl = floorInnerServiceSMOImpl; } public IRoomInnerServiceSMO getRoomInnerServiceSMOImpl() { return roomInnerServiceSMOImpl; } public void setRoomInnerServiceSMOImpl(IRoomInnerServiceSMO roomInnerServiceSMOImpl) { this.roomInnerServiceSMOImpl = roomInnerServiceSMOImpl; } }
package ca.firstvoices.testUtils; import static org.junit.Assert.*; import org.nuxeo.ecm.automation.AutomationService; import org.nuxeo.ecm.automation.OperationContext; import org.nuxeo.ecm.automation.OperationException; import org.nuxeo.ecm.core.api.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; import static org.junit.Assert.assertNotNull; public class ExportTestUtil { private String[] words = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN" }; private DocumentModel word; private DocumentModel dialectDoc; private DocumentModel[] wordArray = null; private static int numMapsInTestList = 4; public DocumentModel getCurrentDialect() { return dialectDoc; } private void recursiveRemove( CoreSession session, DocumentModel parent ) { DocumentModelList children = session.getChildren(parent.getRef()); for( DocumentModel child : children ) { recursiveRemove( session, child ); } session.removeDocument(parent.getRef()); session.save(); } private void startFresh( CoreSession session) { DocumentRef dRef = new PathRef("/FV"); DocumentModel defaultDomain = session.getDocument(dRef); DocumentModelList children = session.getChildren(defaultDomain.getRef()); for( DocumentModel child : children ) { recursiveRemove( session, child ); } } public DocumentModel[] getTestWordsArray(CoreSession session) { DocumentModelList testWords = session.query("SELECT * FROM FVWord WHERE ecm:isVersion = 0"); assertNotNull("Should always have valid list of FVWords", testWords); DocumentModel[] docArray = new DocumentModel[testWords.size()]; int i = 0; for( DocumentModel doc : testWords ) { docArray[i] = doc; i++; } // keep converted array for later wordArray = docArray; return docArray; } public void publishWords( CoreSession session ) { IntStream.range(0, wordArray.length).forEach(i -> assertTrue("Should succesfully publish word", session.followTransition(wordArray[i], "Publish"))); } public void createSetup(CoreSession session ) { startFresh(session); DocumentModel domain = createDocument(session, session.createDocumentModel("/", "FV", "Domain")); createDialectTree(session); createWords(session); session.save(); wordArray = getTestWordsArray(session); assertNotNull("Should have a valid word array(1)", wordArray); publishWords( session ); session.save(); } public DocumentModel createDialectTree(CoreSession session) { assertNotNull("Should have a valid FVLanguageFamiliy", createDocument(session, session.createDocumentModel("/FV", "Family", "FVLanguageFamily"))); assertNotNull( "Should have a valid FVLanguage", createDocument(session, session.createDocumentModel("/FV/Family", "Language", "FVLanguage"))); dialectDoc = createDocument(session, session.createDocumentModel("/FV/Family/Language", "Dialect", "FVDialect")); assertNotNull("Should have a valid FVDialect", dialectDoc); return dialectDoc; } public DocumentModel createDocument(CoreSession session, DocumentModel model) { model.setPropertyValue("dc:title", model.getName()); DocumentModel newDoc = session.createDocument(model); session.save(); return newDoc; } public void createWords( CoreSession session) { Integer i = 0; for (String wordValue : words) { word = session.createDocumentModel("/FV/Family/Language/Dialect/Dictionary", wordValue, "FVWord"); assertNotNull("Should have a valid FVWord model", word); word.setPropertyValue("fv:reference", wordValue ); word = createDocument(session, word ); assertNotNull("Should have a valid FVWord", word); i++; } } // private void commonOperationRunner(AutomationService automationService, DraftEditorService draftEditorServiceInstance, DocumentModel[] docArray, String operationSignature, String uuidKey ) // for( DocumentModel aWord : docArray ) // String uuid = draftEditorServiceInstance.getUUID( aWord, uuidKey ); // if( uuid != null ) // Object returnObj; // OperationContext ctx = new OperationContext(aWord.getCoreSession()); // ctx.setInput(aWord); // Map<String, Object> params = new HashMap<String, Object>(); // try // returnObj = automationService.run(ctx, operationSignature, params); // catch (OperationException e) }
package org.waterforpeople.mapping.app.web.test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.waterforpeople.mapping.app.web.TestHarnessServlet; import org.waterforpeople.mapping.dao.AccessPointDao; import org.waterforpeople.mapping.domain.AccessPoint; import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.standards.dao.LevelOfServiceScoreDao; import com.gallatinsystems.standards.dao.StandardDao; import com.gallatinsystems.standards.domain.LOSScoreToStatusMapping; import com.gallatinsystems.standards.domain.LOSScoreToStatusMapping.LOSColor; import com.gallatinsystems.standards.domain.LevelOfServiceScore; import com.gallatinsystems.standards.domain.LevelOfServiceScore.LevelOfServiceScoreType; import com.gallatinsystems.standards.domain.Standard; import com.gallatinsystems.standards.domain.Standard.StandardComparisons; import com.gallatinsystems.standards.domain.Standard.StandardScope; import com.gallatinsystems.standards.domain.Standard.StandardType; import com.gallatinsystems.standards.domain.Standard.StandardValueType; public class StandardTestLoader { private HttpServletRequest req; private HttpServletResponse resp; private static Logger log = Logger.getLogger(TestHarnessServlet.class .getName()); public StandardTestLoader(HttpServletRequest req, HttpServletResponse resp) { this.req = req; this.resp = resp; } public void loadWaterPointStandard() { StandardDao standardDao = new StandardDao(); // # of Users Standard Standard standard = new Standard(); standard.setAccessPointType(AccessPointType.WATER_POINT); standard.setStandardType(StandardType.WaterPointLevelOfService); standard.setStandardScope(StandardScope.Local); standard.setCountry("BO"); ArrayList<String> posValues = new ArrayList<String>(); posValues.add("500"); standard.setPositiveValues(posValues); standard.setAcessPointAttributeType(StandardValueType.Number); standard.setStandardComparison(StandardComparisons.lessthan); standard.setStandardDescription("Estimated Number of Users"); standard.setAccessPointAttribute("extimatedPopulation"); standardDao.save(standard); // hasSystemBeenDown1DayFlag global boolean true=0 false=1 standard.setAccessPointType(AccessPointType.WATER_POINT); standard.setStandardType(StandardType.WaterPointLevelOfService); standard.setStandardScope(StandardScope.Global); standard.setCountry(""); posValues.removeAll(posValues); posValues.add("false"); standard.setPositiveValues(posValues); standard.setAcessPointAttributeType(StandardValueType.Boolean); standard.setStandardComparison(StandardComparisons.equal); standard.setStandardDescription("Has System Been down in last 30 days"); standard.setAccessPointAttribute("hasSystemBeenDown1DayFlag"); standardDao.save(standard); // provideAdequateQuantity global boolean true=1 flase=0 standard = new Standard(); standard.setAccessPointType(AccessPointType.WATER_POINT); standard.setStandardType(StandardType.WaterPointLevelOfService); standard.setStandardScope(StandardScope.Global); standard.setCountry(""); posValues.removeAll(posValues); posValues.add("true"); standard.setPositiveValues(posValues); standard.setAcessPointAttributeType(StandardValueType.Boolean); standard.setStandardComparison(StandardComparisons.equal); standard.setStandardDescription("Does the water source provide enough drinking water for the community every day of the year?"); standard.setAccessPointAttribute("provideAdequateQuantity"); standardDao.save(standard); // ppmFecalColiform local double < standard = new Standard(); standard.setAccessPointType(AccessPointType.WATER_POINT); standard.setStandardType(StandardType.WaterPointLevelOfService); standard.setStandardScope(StandardScope.Local); standard.setCountry("BO"); posValues.removeAll(posValues); posValues.add("1"); standard.setPositiveValues(posValues); standard.setAcessPointAttributeType(StandardValueType.Number); standard.setStandardComparison(StandardComparisons.lessthan); standard.setStandardDescription("How much fecal coliform were present on the day of collection?"); standard.setAccessPointAttribute("ppmFecalColiform"); standardDao.save(standard); // numberOfLitersPerPersonPerDay local < govt standard standard = new Standard(); standard.setAccessPointType(AccessPointType.WATER_POINT); standard.setStandardType(StandardType.WaterPointLevelOfService); standard.setStandardScope(StandardScope.Local); standard.setCountry("BO"); posValues.removeAll(posValues); posValues.add("10"); standard.setPositiveValues(posValues); standard.setAcessPointAttributeType(StandardValueType.Number); standard.setStandardComparison(StandardComparisons.greaterthan); standard.setStandardDescription("How many liters of water per person per day does this source provide?"); standard.setAccessPointAttribute("numberOfLitersPerPersonPerDay"); standardDao.save(standard); writeln("Saved: " + standard.toString()); } private void loadWaterPointScoreToStatus() { ArrayList<LOSScoreToStatusMapping> losList = new ArrayList<LOSScoreToStatusMapping>(); LOSScoreToStatusMapping losScoreToStatusMapping = new LOSScoreToStatusMapping(); losScoreToStatusMapping .setLevelOfServiceScoreType(LevelOfServiceScoreType.WaterPointLevelOfService); losScoreToStatusMapping.setFloor(0); losScoreToStatusMapping.setCeiling(0); losScoreToStatusMapping.setColor(LOSColor.Black); losList.add(losScoreToStatusMapping); losScoreToStatusMapping = new LOSScoreToStatusMapping(); losScoreToStatusMapping .setLevelOfServiceScoreType(LevelOfServiceScoreType.WaterPointLevelOfService); losScoreToStatusMapping.setFloor(1); losScoreToStatusMapping.setCeiling(1); losScoreToStatusMapping.setColor(LOSColor.Red); losList.add(losScoreToStatusMapping); losScoreToStatusMapping = new LOSScoreToStatusMapping(); losScoreToStatusMapping .setLevelOfServiceScoreType(LevelOfServiceScoreType.WaterPointLevelOfService); losScoreToStatusMapping.setFloor(2); losScoreToStatusMapping.setCeiling(5); losScoreToStatusMapping.setColor(LOSColor.Yellow); losList.add(losScoreToStatusMapping); losScoreToStatusMapping = new LOSScoreToStatusMapping(); losScoreToStatusMapping .setLevelOfServiceScoreType(LevelOfServiceScoreType.WaterPointLevelOfService); losScoreToStatusMapping.setFloor(6); losScoreToStatusMapping.setCeiling(7); losScoreToStatusMapping.setColor(LOSColor.Green); losList.add(losScoreToStatusMapping); BaseDAO<LOSScoreToStatusMapping> losBaseDao = new BaseDAO<LOSScoreToStatusMapping>( LOSScoreToStatusMapping.class); losBaseDao.save(losList); } public void setReq(HttpServletRequest req) { this.req = req; } public HttpServletRequest getReq() { return req; } private void writeln(String message) { try { log.info(message); resp.getWriter().println(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void runTest() { clearAPs(); loadWaterPointStandard(); loadWaterPointScoreToStatus(); AccessPointTest apt = new AccessPointTest(); apt.loadLots(resp, 1); } private void clearAPs() { // DeleteObjectUtil dou = new DeleteObjectUtil(); // dou.deleteAllObjects("AccessPoint"); // writeln("Deleted APs"); // dou.deleteAllObjects("AccessPointScoreComputationItem"); // writeln("Deleted APSCI"); // dou.deleteAllObjects("AccessPointScoreDetail"); // writeln("Deleted APSD"); // dou.deleteAllObjects("AccessPointsStatusSummary"); // writeln("Deleted AccessPointsStatusSummary"); // dou.deleteAllObjects("Standard"); // writeln("Deleted All the Standards"); // dou.deleteAllObjects("LevelOfServiceScore"); // writeln("Deleted All the LevelOfServiceScore"); // dou.deleteAllObjects("LOSScoreToStatusMapping"); // writeln("Deleted All LevelOfServiceScoreToStatusMappings"); } public void listResults(){ listAPScoreAndStatus(); } private void listAPScoreAndStatus() { AccessPointDao apDao = new AccessPointDao(); List<AccessPoint> apList = apDao.list("all"); LevelOfServiceScoreDao lesScoreDao = new LevelOfServiceScoreDao(); for (AccessPoint item : apList) { List<LevelOfServiceScore> losScoreList = lesScoreDao .listByAccessPoint(item.getKey()); writeln("AP: " + item.getKeyString()); for (LevelOfServiceScore losItem : losScoreList) { writeln(" LevelOfServiceScore: " + losItem.getScore() + " Score Date: " + losItem.getLastUpdateDateTime()); for(String detail:losItem.getScoreDetails()){ writeln(" Details: " + detail); } } } } }
//FILE: PositionList.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // DESCRIPTION: Container for the scanning pattern // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // CVS: $Id$ package org.micromanager.navigation; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.utils.MMException; import org.micromanager.utils.MMSerializationException; /** * Navigation list of positions for the XYStage. * Used for multi site acquisition support. */ public class PositionList { private ArrayList<MultiStagePosition> positions_; private final static String ID = "Micro-Manager XY-position list"; private final static String ID_KEY = "ID"; private final static int VERSION = 3; private final static String VERSION_KEY = "VERSION"; private final static String LABEL_KEY = "LABEL"; private final static String DEVICE_KEY = "DEVICE"; private final static String X_KEY = "X"; private final static String Y_KEY = "Y"; private final static String Z_KEY = "Z"; private final static String NUMAXES_KEY = "AXES"; private final static String POSARRAY_KEY = "POSITIONS"; private final static String DEVARRAY_KEY = "DEVICES"; private final static String GRID_ROW_KEY = "GRID_ROW"; private final static String GRID_COL_KEY = "GRID_COL"; private final static String PROPERTIES_KEY = "PROPERTIES"; private final static String DEFAULT_XY_STAGE = "DEFAULT_XY_STAGE"; private final static String DEFAULT_Z_STAGE = "DEFAULT_Z_STAGE"; public final static String AF_KEY = "AUTOFOCUS"; public final static String AF_VALUE_FULL = "full"; public final static String AF_VALUE_INCREMENTAL = "incremental"; public final static String AF_VALUE_NONE = "none"; private HashSet<ChangeListener> listeners_ = new HashSet<ChangeListener>(); public PositionList() { positions_ = new ArrayList<MultiStagePosition>(); } public static PositionList newInstance(PositionList aPl) { PositionList pl = new PositionList(); Iterator<MultiStagePosition> it = aPl.positions_.iterator(); while (it.hasNext()) pl.addPosition(MultiStagePosition.newInstance(it.next())); return pl; } public void addChangeListener(ChangeListener listener) { listeners_.add(listener); } public void removeChangeListener(ChangeListener listener) { listeners_.remove(listener); } public void notifyChangeListeners() { for (ChangeListener listener:listeners_) { listener.stateChanged(new ChangeEvent(this)); } } /** * Returns multi-stage position associated with the position index. * @param idx - position index * @return multi-stage position */ public MultiStagePosition getPosition(int idx) { if (idx < 0 || idx >= positions_.size()) return null; return positions_.get(idx); } /** * Returns a copy of the multi-stage position associated with the position index. * @param idx - position index * @return multi-stage position */ public MultiStagePosition getPositionCopy(int idx) { if (idx < 0 || idx >= positions_.size()) return null; return MultiStagePosition.newInstance(positions_.get(idx)); } /** * Returns position index associated with the position name. * @param posLabel - label (name) of the position * @return index */ public int getPositionIndex(String posLabel) { for (int i=0; i<positions_.size(); i++) { if (positions_.get(i).getLabel().compareTo(posLabel) == 0) return i; } return -1; } /** * Adds a new position to the list. * @param pos - multi-stage position */ public void addPosition(MultiStagePosition pos) { String label = pos.getLabel(); if (!isLabelUnique(label)) { pos.setLabel(generateLabel(label)); } positions_.add(pos); notifyChangeListeners(); } /** * Insert a position into the list. * @param pos - multi-stage position */ public void addPosition(int in0, MultiStagePosition pos) { String label = pos.getLabel(); if (!isLabelUnique(label)) { pos.setLabel(generateLabel(label)); } positions_.add(in0, pos); notifyChangeListeners(); } /** * Replaces position in the list with the new position * @param pos - multi-stage position */ public void replacePosition(int index, MultiStagePosition pos) { if (index >= 0 && index < positions_.size()) { positions_.set(index, pos); notifyChangeListeners(); } } /** * Returns the number of positions contained within the list */ public int getNumberOfPositions() { return positions_.size(); } /** * Empties the list. */ public void clearAllPositions() { positions_.clear(); notifyChangeListeners(); } /** * Removes a specific position based on the index * @param idx - position index */ public void removePosition(int idx) { if (idx >= 0 && idx < positions_.size()) positions_.remove(idx); notifyChangeListeners(); } /** * Initialize the entire array by passing an array of multi-stage positions * @param posArray - array of multi-stage positions */ public void setPositions(MultiStagePosition[] posArray) { positions_.clear(); for (int i=0; i<posArray.length; i++) { positions_.add(posArray[i]); } notifyChangeListeners(); } /** * Returns an array of positions contained in the list. * @return position array */ public MultiStagePosition[] getPositions() { MultiStagePosition[] list = new MultiStagePosition[positions_.size()]; for (int i=0; i<positions_.size(); i++) { list[i] = positions_.get(i); } return list; } /** * Assigns a label to the position index * @param idx - position index * @param label - new label (name) */ public void setLabel(int idx, String label) { if (idx < 0 || idx >= positions_.size()) return; positions_.get(idx).setLabel(label); notifyChangeListeners(); } /** * Serialize object into the JSON encoded stream. * @throws MMSerializationException */ public String serialize() throws MMSerializationException { JSONObject meta = new JSONObject(); try { meta.put(ID_KEY, ID); meta.put(VERSION_KEY, VERSION); JSONArray listOfPositions = new JSONArray(); // iterate on positions for (int i=0; i<positions_.size(); i++) { MultiStagePosition msp = positions_.get(i); JSONObject mspData = new JSONObject(); // annotate position with label mspData.put(LABEL_KEY, positions_.get(i).getLabel()); mspData.put(GRID_ROW_KEY, msp.getGridRow()); mspData.put(GRID_COL_KEY, msp.getGridColumn()); mspData.put(DEFAULT_XY_STAGE, msp.getDefaultXYStage()); mspData.put(DEFAULT_Z_STAGE, msp.getDefaultZStage()); JSONArray devicePosData = new JSONArray(); // iterate on devices for (int j=0; j<msp.size(); j++) { StagePosition sp = msp.get(j); JSONObject stage = new JSONObject(); stage.put(X_KEY, sp.x); stage.put(Y_KEY, sp.y); stage.put(Z_KEY, sp.z); stage.put(NUMAXES_KEY, sp.numAxes); stage.put(DEVICE_KEY, sp.stageName); devicePosData.put(j, stage); } mspData.put(DEVARRAY_KEY, devicePosData); // insert properties JSONObject props = new JSONObject(); String keys[] = msp.getPropertyNames(); for (int k=0; k<keys.length; k++) { String val = msp.getProperty(keys[k]); props.put(keys[k], val); } mspData.put(PROPERTIES_KEY, props); listOfPositions.put(i, mspData); } meta.put(POSARRAY_KEY, listOfPositions); return meta.toString(3); } catch (JSONException e) { throw new MMSerializationException("Unable to serialize XY positition data into formatted string."); } } /** * Restore object data from the JSON encoded stream. * @param stream * @throws MMSerializationException */ public void restore(String stream) throws MMSerializationException { try { JSONObject meta = new JSONObject(stream); JSONArray posArray = meta.getJSONArray(POSARRAY_KEY); int version = meta.getInt(VERSION_KEY); positions_.clear(); for (int i=0; i<posArray.length(); i++) { JSONObject mspData = posArray.getJSONObject(i); MultiStagePosition msp = new MultiStagePosition(); msp.setLabel(mspData.getString(LABEL_KEY)); if (version >= 2) msp.setGridCoordinates(mspData.getInt(GRID_ROW_KEY), mspData.getInt(GRID_COL_KEY)); if (version >= 3) { msp.setDefaultXYStage(mspData.getString(DEFAULT_XY_STAGE)); msp.setDefaultZStage(mspData.getString(DEFAULT_Z_STAGE)); } JSONArray devicePosData = mspData.getJSONArray(DEVARRAY_KEY); for (int j=0; j < devicePosData.length(); j++) { JSONObject stage = devicePosData.getJSONObject(j); StagePosition pos = new StagePosition(); pos.x = stage.getDouble(X_KEY); pos.y = stage.getDouble(Y_KEY); pos.z = stage.getDouble(Z_KEY); pos.stageName = stage.getString(DEVICE_KEY); pos.numAxes = stage.getInt(NUMAXES_KEY); msp.add(pos); } // get properties JSONObject props = mspData.getJSONObject(PROPERTIES_KEY); for (Iterator<String> it = (Iterator<String>)props.keys(); it.hasNext();) { String key = it.next(); msp.setProperty(key, props.getString(key)); } positions_.add(msp); } } catch (JSONException e) { throw new MMSerializationException("Invalid or corrupted serialization data."); } notifyChangeListeners(); } /** * Helper method to generate unique label when inserting a new position. * Not recommended for use - planned to become obsolete. * @return Unique label */ public String generateLabel() { return generateLabel("Pos"); } public String generateLabel(String proposal) { String label = proposal + positions_.size(); // verify the uniqueness int i = 1; while (!isLabelUnique(label)) { label = proposal + (positions_.size() + i++); } return label; } /** * Verify that the new label is unique * @param label - proposed label * @return true if label does not exist */ public boolean isLabelUnique(String label) { for (int i=0; i<positions_.size(); i++) { if (positions_.get(i).getLabel().compareTo(label) == 0) return false; } return true; } /** * Save list to a file. * @param path * @throws MMException */ public void save(String path) throws MMException { File f = new File(path); try { String serList = serialize(); FileWriter fw = new FileWriter(f); fw.write(serList); fw.close(); } catch (Exception e) { throw new MMException(e.getMessage()); } } /** * Load position list from a file. * @param path * @throws MMException */ public void load(String path) throws MMException { File f = new File(path); try { StringBuffer contents = new StringBuffer(); BufferedReader input = new BufferedReader(new FileReader(f)); String line = null; while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } restore(contents.toString()); } catch (Exception e) { throw new MMException(e.getMessage()); } notifyChangeListeners(); } }
package edu.wustl.catissuecore.action; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.cde.CDEManager; /** * This class initializes the fields in the User Add/Edit webpage. * @author gautam_shetty */ public class CollectionProtocolAction extends SpecimenProtocolAction { /** * Overrides the execute method of Action class. * Sets the various fields in User Add/Edit webpage. * */ public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.executeSecureAction(mapping, form, request, response); List clinicalStatusList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_CLINICAL_STATUS); request.setAttribute(Constants.CLINICAL_STATUS_LIST, clinicalStatusList); return mapping.findForward(Constants.SUCCESS); } }
package edu.wustl.query.bizlogic; import junit.framework.TestCase; import edu.wustl.cab2b.server.cache.EntityCache; import edu.wustl.cider.query.CiderQuery; import edu.wustl.cider.querymanager.CiderQueryManager; import edu.wustl.common.query.impl.PassOneXQueryGenerator; import edu.wustl.common.query.impl.QueryUtility; import edu.wustl.common.querysuite.queryobject.IQuery; import edu.wustl.common.util.logger.Logger; import edu.wustl.query.querymanager.Count; import edu.wustl.query.util.global.Constants; import edu.wustl.query.util.global.Variables; import edu.wustl.query.utility.Utility; /** * ASynchronous queries related test cases * @version 1.0 * @author ravindra_jain * */ public class ASynchronousQueriesTestCases extends TestCase { public static PassOneXQueryGenerator xQueryGenerator = new PassOneXQueryGenerator(); static { Logger.configure(); try { EntityCache.getInstance(); Utility.initTest(); /** * Indicating - Do not LOG XQueries */ Variables.isExecutingTestCase = true; Variables.queryGeneratorClassName = "edu.wustl.common.query.impl.PassOneXQueryGenerator"; } catch (Exception e) { e.printStackTrace(); } } /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() { try { super.setUp(); } catch (Exception e) { System.out.println(); e.printStackTrace(); fail("An Exception has occurred.... Please refer to 'System.err' link below for Details"); } } /* * (non-Javadoc) * * @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Fire a query * PersonUPI is NOT NULL * Get count * Initialize 'expectedNoOfRecords' to an appropriate value */ public void testExecuteQueryWithinXML1() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UPI NOT NULL and DEMOGRAPHICS DOB>10/10/1985"); query = QueryUtility.getQuery(23L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } } public void testExecuteQueryAcrossXML() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UPI NOT NULL and LABS, ACCESSION NUMBER CONTAINS 2008295007131"); query = QueryUtility.getQuery(24L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } } /** * Fire a query * Wait for some time (approximately 5 seconds) * Get count * Cancel Query (Thread corresponding to query) * Get count again */ public void testCancelQuery() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UPI NOT NULL"); query = QueryUtility.getQuery(21L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); for(int i=0; i<20000; i++) { for(int j=0; j<50000; j++) { // do nothing } } manager.cancel(queryExecId); System.out.println("After manager.cancel()...."); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { fail("QUERY COMPLETED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { System.out.println("QUERY CANCELLED...."); assertTrue("QUERY CANCELLED....", true); } else if(count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { System.out.println("QUERY COMPLETED....."); fail("QUERY COMPLETED....."); } else if(count.getStatus().equalsIgnoreCase(Constants.QUERY_IN_PROGRESS)) { System.out.println("QUERY IN PROGRESS....."); fail("QUERY IN PROGRESS....."); } } catch (Exception e) { fail("AN EXCEPTION HAS OCCURRED........"); System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } /** * Fire a Query which will return 0 records * Get Count * Should be zero */ /*public void testQueryWithZeroRecords() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UPI LESS THAN 1"); query = Utility.getQuery(fileName2); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); // IQuery query = QueryUtility.getQuery(1L); // ciderQueryObj.setQuery(query); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); if(noOfRecords > 0) { fail("NO OF RECORDS > 0"); } System.out.println("SUCCESSFULL...................................."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } }*/ /** * Fire 2 or more queries simultaneously */ /*public void testExecuteQueriesASynchronously() { int queryExecId1 = -1; int queryExecId2 = -1; int noOfRecords1 = 0; int noOfRecords2 = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UPI NOT NULL"); query = QueryUtility.getQuery(23L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId1 = manager.execute(ciderQueryObj); queryExecId2 = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID1 :::: "+queryExecId1); System.out.println("QUERY EXECUTION ID2 :::: "+queryExecId2); Count count1 = manager.getQueryCount(queryExecId1); Count count2 = manager.getQueryCount(queryExecId2); while(!count1.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count1.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count1 = manager.getQueryCount(queryExecId1); } while(!count2.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count2.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count2 = manager.getQueryCount(queryExecId2); } noOfRecords1 = count1.getCount(); noOfRecords2 = count2.getCount(); System.out.println("No of Records 1 :: "+noOfRecords1); System.out.println("No of Records 2 :: "+noOfRecords2); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } }*/ /** * Fire a query * PersonUPI is NOT NULL * Get count * Initialize 'expectedNoOfRecords' to an appropriate value */ public void testExecuteQueryWithinXML2() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UPI NOT NULL and DEMOGRAPHICS DOB>10/10/1980"); query = QueryUtility.getQuery(22L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } } public void testBetweenOperator() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - DEMOGRAPHICS DOB between 1940 and 1970"); query = QueryUtility.getQuery(41L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } } public void testStartsWithOperator() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UI STARTS WITH 000000000000000008690"); query = QueryUtility.getQuery(42L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } } public void testEndsWithOperator() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UI ENDS WITH 3"); query = QueryUtility.getQuery(43L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } } public void testINOperator() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UI IN 000000000000000008690923"); query = QueryUtility.getQuery(44L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } } /*public void testNOT_INOperator() { int queryExecId = -1; int noOfRecords = 0; CiderQueryManager manager = new CiderQueryManager(); IQuery query = null; try { System.out.println("QUERY - PERSON UI NOT IN 000000000000000008690923"); query = QueryUtility.getQuery(45L); CiderQuery ciderQueryObj = new CiderQuery(query, -1, "", -1L, null); queryExecId = manager.execute(ciderQueryObj); System.out.println("QUERY EXECUTION ID :::: "+queryExecId); Count count = manager.getQueryCount(queryExecId); while(!count.getStatus().equalsIgnoreCase(Constants.QUERY_COMPLETED)) { if(count.getStatus().equalsIgnoreCase(Constants.QUERY_CANCELLED)) { fail("QUERY CANCELLED......."); } count = manager.getQueryCount(queryExecId); } noOfRecords = count.getCount(); System.out.println("No of Records :: "+noOfRecords); System.out.println("TEST CASE EXECUTED....."); } catch (Exception e) { System.out.println("AN EXCEPTION HAS OCCURRED........"); e.printStackTrace(); } }*/ }
package org.bouncycastle.asn1.util; import java.io.FileInputStream; import org.bouncycastle.asn1.ASN1InputStream; /** * Command line ASN.1 Dump utility. * <p> * Usage: org.bouncycastle.asn1.util.Dump ber_encoded_file * </p> */ public class Dump { public static void main( String args[]) throws Exception { FileInputStream fIn = new FileInputStream(args[0]); try { ASN1InputStream bIn = new ASN1InputStream(fIn); Object obj = null; while ((obj = bIn.readObject()) != null) { System.out.println(ASN1Dump.dumpAsString(obj)); } } finally { fIn.close(); } } }
package org.kohsuke.stapler; import javax.servlet.http.HttpSession; import java.util.UUID; /** * Generates a nonce value that allows us to protect against cross-site request forgery (CSRF) attacks. * * <p> * We send this with each JavaScript proxy and verify them when we receive a request. * * @author Kohsuke Kawaguchi * @see WebApp#getCrumbIssuer() * @see WebApp#setCrumbIssuer(CrumbIssuer) */ public abstract class CrumbIssuer { /** * Issues a crumb for the given request. */ public abstract String issueCrumb(StaplerRequest request); public final String issueCrumb() { return issueCrumb(Stapler.getCurrentRequest()); } /** * Sends the crumb value in plain text, enabling retrieval through XmlHttpRequest. */ public HttpResponse doCrumb() { return HttpResponses.plainText(issueCrumb()); } /** * Validates a crumb that was submitted along with the request. * * @param request * The request that submitted the crumb * @param submittedCrumb * The submitted crumb value to be validated. * * @throws Exception * If the crumb doesn't match and the request processing should abort. */ public void validateCrumb(StaplerRequest request, String submittedCrumb) { if (!issueCrumb(request).equals(submittedCrumb)) { throw new SecurityException("Request failed to pass the crumb test"); } } /** * Default crumb issuer. */ public static final CrumbIssuer DEFAULT = new CrumbIssuer() { @Override public String issueCrumb(StaplerRequest request) { HttpSession s = request.getSession(); String v = (String)s.getAttribute(ATTRIBUTE_NAME); if (v!=null) return v; v = UUID.randomUUID().toString(); s.setAttribute(ATTRIBUTE_NAME,v); return v; } }; private static final String ATTRIBUTE_NAME = CrumbIssuer.class.getName(); }
package ti.modules.titanium.ui.widget; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.titanium.TiBlob; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.TiContext.OnLifecycleEvent; import org.appcelerator.titanium.TiDimension; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.AsyncResult; import org.appcelerator.titanium.util.Log; import org.appcelerator.titanium.util.TiBackgroundImageLoadTask; import org.appcelerator.titanium.util.TiConfig; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiDownloadListener; import org.appcelerator.titanium.util.TiResponseCache; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiDrawableReference; import org.appcelerator.titanium.view.TiUIView; import ti.modules.titanium.filesystem.FileProxy; import ti.modules.titanium.ui.ImageViewProxy; import ti.modules.titanium.ui.widget.TiImageView.OnSizeChangeListener; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.view.ViewParent; import android.webkit.URLUtil; public class TiUIImageView extends TiUIView implements OnLifecycleEvent, Handler.Callback { private static final String LCAT = "TiUIImageView"; private static final boolean DBG = TiConfig.LOGD; private static final AtomicInteger imageTokenGenerator = new AtomicInteger(0); private static final int FRAME_QUEUE_SIZE = 5; public static final int INFINITE = 0; // TIMOB-3599: A bug in Gingerbread forces us to retry decoding bitmaps when they initially fail private static final String PROPERTY_DECODE_RETRIES = "decodeRetries"; private static final int DEFAULT_DECODE_RETRIES = 5; private Timer timer; private Animator animator; private Object[] images; private Loader loader; private Thread loaderThread; private AtomicBoolean animating = new AtomicBoolean(false); private boolean reverse = false; private boolean paused = false; private int token; private boolean firedLoad; private ImageViewProxy imageViewProxy; private TiDimension requestedWidth; private TiDimension requestedHeight; private ArrayList<TiDrawableReference> imageSources; private TiDrawableReference defaultImageSource; private TiDownloadListener downloadListener; private int decodeRetries = 0; private class BgImageLoader extends TiBackgroundImageLoadTask { private int token; public BgImageLoader(TiContext tiContext, TiDimension imageWidth, TiDimension imageHeight, int token) { super(tiContext, getParentView(), imageWidth, imageHeight); this.token = token; } @Override protected void onPostExecute(Drawable d) { super.onPostExecute(d); if (d != null) { setImageDrawable(d, token); } else { if (DBG) { String traceMsg = "Background image load returned null"; if (proxy.hasProperty(TiC.PROPERTY_IMAGE)) { Object image = proxy.getProperty(TiC.PROPERTY_IMAGE); if (image instanceof String) { traceMsg += " (" + TiConvert.toString(image) + ")"; } } Log.d(LCAT, traceMsg); } } } } public TiUIImageView(TiViewProxy proxy) { super(proxy); imageViewProxy = (ImageViewProxy) proxy; if (DBG) { Log.d(LCAT, "Creating an ImageView"); } TiImageView view = new TiImageView(proxy.getContext()); view.setOnSizeChangeListener(new OnSizeChangeListener() { @Override public void sizeChanged(int w, int h, int oldWidth, int oldHeight) { // By the time this hits, we've already set the drawable in the view. // And this runs even the first time the view is drawn (in which // case oldWidth and oldHeight are 0.) This was leading to // setImage running twice unnecessarily, so the if block here // will avoid a second, unnecessary call to setImage. if (oldWidth == 0 && oldHeight == 0) { TiImageView view = getView(); if (view != null) { Drawable drawable = view.getImageDrawable(); if (drawable != null && drawable.getIntrinsicHeight() == h && drawable.getIntrinsicWidth() == w) { return; } } } setImage(true); } }); downloadListener = new TiDownloadListener() { @Override public void downloadFinished(URI uri) { if (!TiResponseCache.peek(uri)) { // The requested image did not make it into our TiResponseCache, // possibly because it had a header forbidding that. Now get it // via the "old way" (not relying on cache). synchronized (imageTokenGenerator) { token = imageTokenGenerator.incrementAndGet(); imageSources.get(0).getBitmapAsync(new BgImageLoader(getProxy().getTiContext(), requestedWidth, requestedHeight, token)); } } else { firedLoad = false; setImage(true); } } }; setNativeView(view); proxy.getTiContext().addOnLifecycleEventListener(this); } @Override public void setProxy(TiViewProxy proxy) { super.setProxy(proxy); imageViewProxy = (ImageViewProxy) proxy; } private TiImageView getView() { return (TiImageView) nativeView; } protected View getParentView() { if (nativeView == null) return null; ViewParent parent = nativeView.getParent(); if (parent instanceof View) { return (View)parent; } if (parent == null) { TiViewProxy parentProxy = proxy.getParent(); if (parentProxy != null) { TiUIView parentTiUi = parentProxy.peekView(); if (parentTiUi != null) { return parentTiUi.getNativeView(); } } } return null; } // This method is intended to only be use from the background task, it's basically // an optimistic commit. private void setImageDrawable(Drawable d, int token) { TiImageView view = getView(); if (view != null) { synchronized(imageTokenGenerator) { if (this.token == token) { view.setImageDrawable(d, false); this.token = -1; } } } } private Handler handler = new Handler(Looper.getMainLooper(), this); private static final int SET_IMAGE = 10001; @Override public boolean handleMessage(Message msg) { if (msg.what == SET_IMAGE) { AsyncResult result = (AsyncResult)msg.obj; TiImageView view = getView(); if (view != null) { view.setImageBitmap((Bitmap)result.getArg()); result.setResult(null); } } return false; } private void setImage(final Bitmap bitmap) { if (bitmap != null) { if (!proxy.getTiContext().isUIThread()) { AsyncResult result = new AsyncResult(bitmap); proxy.sendBlockingUiMessage(handler.obtainMessage(SET_IMAGE, result), result); } else { TiImageView view = getView(); if (view != null) { view.setImageBitmap(bitmap); } } imageViewProxy.onBitmapChanged(this, bitmap); } } private class BitmapWithIndex { public BitmapWithIndex(Bitmap b, int i) { this.bitmap = b; this.index = i; } public Bitmap bitmap; public int index; } private class Loader implements Runnable { private ArrayBlockingQueue<BitmapWithIndex> bitmapQueue; private int repeatIndex = 0; public Loader() { bitmapQueue = new ArrayBlockingQueue<BitmapWithIndex>(FRAME_QUEUE_SIZE); } private boolean isRepeating() { int repeatCount = getRepeatCount(); if (repeatCount <= INFINITE) { return true; } return repeatIndex < repeatCount; } private int getStart() { if (imageSources == null) { return 0; } if (reverse) { return imageSources.size()-1; } return 0; } private boolean isNotFinalFrame(int frame) { if (imageSources == null) { return false; } if (reverse) { return frame >= 0; } return frame < imageSources.size(); } private int getCounter() { if (reverse) { return -1; } return 1; } public void run() { if (getProxy() == null) { Log.d(LCAT, "Multi-image loader exiting early because proxy has been gc'd"); return; } TiContext context = getProxy().getTiContext(); if (context == null) { Log.d(LCAT, "Multi-image loader exiting early because context has been gc'd"); return; } repeatIndex = 0; animating.set(true); firedLoad = false; topLoop: while (isRepeating()) { if (imageSources == null) { break; } long time = System.currentTimeMillis(); for (int j = getStart(); imageSources != null && isNotFinalFrame(j); j+=getCounter()) { if (bitmapQueue.size() == FRAME_QUEUE_SIZE && !firedLoad) { fireLoad(TiC.PROPERTY_IMAGES); firedLoad = true; } if (paused && !Thread.currentThread().isInterrupted()) { try { Log.i(LCAT, "Pausing"); if (loader == null) { break; } // User backed-out while animation running synchronized (loader) { loader.wait(); } Log.i(LCAT, "Waking from pause."); } catch (InterruptedException e) { Log.w(LCAT, "Interrupted from paused state."); } } if (!animating.get()) { break topLoop; } Bitmap b = imageSources.get(j).getBitmap(); try { bitmapQueue.offer(new BitmapWithIndex(b, j), (int)getDuration() * imageSources.size(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } repeatIndex++; } if (DBG) { Log.d(LCAT, "TIME TO LOAD FRAMES: "+(System.currentTimeMillis()-time)+"ms"); } } animating.set(false); } public ArrayBlockingQueue<BitmapWithIndex> getBitmapQueue() { return bitmapQueue; } } private void setImages() { if (imageSources == null || imageSources.size() == 0) { return; } if (loader == null) { paused = false; firedLoad = false; loader = new Loader(); Thread loaderThread = new Thread(loader); if (DBG) { Log.d(LCAT, "STARTING LOADER THREAD "+loaderThread +" for "+this); } loaderThread.start(); } } public double getDuration() { if (proxy.getProperty(TiC.PROPERTY_DURATION) != null) { return TiConvert.toDouble(proxy.getProperty(TiC.PROPERTY_DURATION)); } if (images != null) { return images.length * 33; } return 100; } public int getRepeatCount() { if (proxy.hasProperty(TiC.PROPERTY_REPEAT_COUNT)) { return TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_REPEAT_COUNT)); } return INFINITE; } private void fireLoad(String state) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_STATE, state); proxy.fireEvent(TiC.EVENT_LOAD, data); } private void fireStart() { KrollDict data = new KrollDict(); proxy.fireEvent(TiC.EVENT_START, data); } private void fireChange(int index) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_INDEX, index); proxy.fireEvent(TiC.EVENT_CHANGE, data); } private void fireStop() { KrollDict data = new KrollDict(); proxy.fireEvent(TiC.EVENT_STOP, data); } private class Animator extends TimerTask { private Loader loader; public Animator(Loader loader) { this.loader = loader; } public void run() { try { BitmapWithIndex b = loader.getBitmapQueue().take(); if (DBG) { Log.d(LCAT, "set image: "+b.index); } setImage(b.bitmap); fireChange(b.index); } catch (InterruptedException e) { e.printStackTrace(); } } } public void start() { if (!proxy.getTiContext().isUIThread()) { proxy.getTiContext().getActivity().runOnUiThread(new Runnable() { public void run() { handleStart(); } }); } else { handleStart(); } } public void handleStart() { if (animator == null) { timer = new Timer(); if (loader == null) { loader = new Loader(); loaderThread = new Thread(loader); if (DBG) { Log.d(LCAT, "STARTING LOADER THREAD "+loaderThread +" for "+this); } } animator = new Animator(loader); if (!animating.get()) { new Thread(loader).start(); } int duration = (int) getDuration(); if (duration == 0) { duration = 1; } fireStart(); timer.schedule(animator, duration, duration); } else { resume(); } } public void pause() { paused = true; } public void resume() { paused = false; if (loader != null) { synchronized (loader) { loader.notify(); } } } public void stop() { if (timer != null) { timer.cancel(); } animating.set(false); if (loaderThread != null) { loaderThread.interrupt(); loaderThread = null; } if (loader != null) { synchronized (loader) { loader.notify(); } } loader = null; timer = null; animator = null; paused = false; fireStop(); } private void setImageSource(Object object) { if (imageViewProxy.inTableView()) { ArrayList<TiDrawableReference> currentSources = imageViewProxy.getImageSources(); if (currentSources != null) { imageSources = currentSources; return; } } imageSources = new ArrayList<TiDrawableReference>(); if (object instanceof Object[]) { for(Object o : (Object[])object) { imageSources.add(makeImageSource(o)); } } else { imageSources.add( makeImageSource(object) ); } imageViewProxy.onImageSourcesChanged(this, imageSources); } private void setImageSource(TiDrawableReference source) { imageSources = new ArrayList<TiDrawableReference>(); imageSources.add(source); } private TiDrawableReference makeImageSource(Object object) { if (object instanceof FileProxy) { return TiDrawableReference.fromFile(getProxy().getTiContext(), ((FileProxy)object).getBaseFile()); } else { return TiDrawableReference.fromObject(getProxy().getTiContext(), object); } } private void setDefaultImageSource(Object object) { if (object instanceof FileProxy) { defaultImageSource = TiDrawableReference.fromFile(getProxy().getTiContext(), ((FileProxy)object).getBaseFile()); } else { defaultImageSource = TiDrawableReference.fromObject(getProxy().getTiContext(), object); } } private void setImage(boolean recycle) { if (imageSources == null || imageSources.size() == 0) { setImage(null); return; } if (imageSources.size() == 1) { if (imageViewProxy.inTableView()) { Bitmap currentBitmap = imageViewProxy.getBitmap(); if (currentBitmap != null) { // If the image proxy has the default image currently cached, we need to // load the downloaded URL instead. TIMOB-4814 ArrayList<TiDrawableReference> proxySources = imageViewProxy.getImageSources(); if (proxySources != null && !proxySources.contains(defaultImageSource)) { setImage(currentBitmap); return; } } } TiDrawableReference imageref = imageSources.get(0); if (imageref.isNetworkUrl()) { if (defaultImageSource != null) { setDefaultImage(); } else { TiImageView view = getView(); if (view != null) { view.setImageDrawable(null, recycle); } } boolean getAsync = true; try { URI uri = new URI(imageref.getUrl()); getAsync = !TiResponseCache.peek(uri); } catch (URISyntaxException e) { Log.e(LCAT, "URISyntaxException for url " + imageref.getUrl(), e); getAsync = false; } if (getAsync) { imageref.getBitmapAsync(downloadListener); } else { Bitmap bitmap = imageref.getBitmap(getParentView(), requestedWidth, requestedHeight); if (bitmap != null) { setImage(bitmap); if (!firedLoad) { fireLoad(TiC.PROPERTY_IMAGE); firedLoad = true; } } else { retryDecode(recycle); } } } else { setImage(imageref.getBitmap(getParentView(), requestedWidth, requestedHeight)); if (!firedLoad) { fireLoad(TiC.PROPERTY_IMAGE); firedLoad = true; } } } else { setImages(); } } private void setDefaultImage() { if (defaultImageSource == null) { setImage(null); return; } setImage(defaultImageSource.getBitmap(getParentView(), requestedWidth, requestedHeight)); } private void retryDecode(final boolean recycle) { // Really odd Android 2.3/Gingerbread behavior -- BitmapFactory.decode* Skia functions // fail randomly and seemingly without a cause. Retry 5 times by default w/ 250ms between each try, // Usually the 2nd or 3rd try succeeds, but the "decodeRetries" property // will allow users to tweak this if needed final int maxRetries = proxy.getProperties().optInt(PROPERTY_DECODE_RETRIES, DEFAULT_DECODE_RETRIES); if (decodeRetries < maxRetries) { decodeRetries++; proxy.getUIHandler().postDelayed(new Runnable() { public void run() { Log.d(LCAT, "Retrying bitmap decode: " + decodeRetries + "/" + maxRetries); setImage(recycle); } }, 250); } else { String url = null; if (imageSources != null && imageSources.size() == 1) { url = imageSources.get(0).getUrl(); } Log.e(LCAT, "Max retries reached, giving up decoding image source: " + url); } } @Override public void processProperties(KrollDict d) { TiImageView view = getView(); if (view == null) { return; } if (d.containsKey(TiC.PROPERTY_WIDTH)) { requestedWidth = TiConvert.toTiDimension(d, TiC.PROPERTY_WIDTH, TiDimension.TYPE_WIDTH); } if (d.containsKey(TiC.PROPERTY_HEIGHT)) { requestedHeight = TiConvert.toTiDimension(d, TiC.PROPERTY_HEIGHT, TiDimension.TYPE_HEIGHT); } if (d.containsKey(TiC.PROPERTY_IMAGES)) { setImageSource(d.get(TiC.PROPERTY_IMAGES)); setImages(); } else if (d.containsKey(TiC.PROPERTY_URL)) { Log.w(LCAT, "The url property of ImageView is deprecated, use image instead."); if (!d.containsKey(TiC.PROPERTY_IMAGE)) { d.put(TiC.PROPERTY_IMAGE, d.get(TiC.PROPERTY_URL)); } } if (d.containsKey(TiC.PROPERTY_CAN_SCALE)) { view.setCanScaleImage(TiConvert.toBoolean(d, TiC.PROPERTY_CAN_SCALE)); } if (d.containsKey(TiC.PROPERTY_ENABLE_ZOOM_CONTROLS)) { view.setEnableZoomControls(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLE_ZOOM_CONTROLS)); } if (d.containsKey(TiC.PROPERTY_DEFAULT_IMAGE)) { try { if (!d.containsKey(TiC.PROPERTY_IMAGE) || (URLUtil.isNetworkUrl(d.getString(TiC.PROPERTY_IMAGE)) && !TiResponseCache.peek(new URI(d.getString(TiC.PROPERTY_IMAGE))))) setDefaultImageSource(d.get(TiC.PROPERTY_DEFAULT_IMAGE)); } catch (URISyntaxException e) { setDefaultImageSource(d.get(TiC.PROPERTY_DEFAULT_IMAGE)); } } if (d.containsKey(TiC.PROPERTY_IMAGE)) { // processProperties is also called from TableView, we need check if we changed before re-creating the bitmap boolean changeImage = true; Object newImage = d.get(TiC.PROPERTY_IMAGE); TiDrawableReference source = makeImageSource(newImage); if (imageSources != null && imageSources.size() == 1) { if (imageSources.get(0).equals(source)) { changeImage = false; } } if (changeImage) { setImageSource(source); firedLoad = false; setImage(false); } } else { if (!d.containsKey(TiC.PROPERTY_IMAGES)) { getProxy().setProperty(TiC.PROPERTY_IMAGE, null); if (defaultImageSource != null) { setDefaultImage(); } } } super.processProperties(d); } @Override public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { TiImageView view = getView(); if (view == null) { return; } if (key.equals(TiC.PROPERTY_CAN_SCALE)) { view.setCanScaleImage(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_ENABLE_ZOOM_CONTROLS)) { view.setEnableZoomControls(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_URL)) { setImageSource(newValue); firedLoad = false; setImage(true); } else if (key.equals(TiC.PROPERTY_IMAGE)) { setImageSource(newValue); firedLoad = false; setImage(true); } else if (key.equals(TiC.PROPERTY_IMAGES)) { if (newValue instanceof Object[]) { setImageSource(newValue); setImages(); } } else { super.propertyChanged(key, oldValue, newValue, proxy); } } public void onDestroy(Activity activity) { } public void onPause(Activity activity) { pause(); } public void onResume(Activity activity) { resume(); } public void onStart(Activity activity) { } public void onStop(Activity activity) { stop(); } public boolean isAnimating() { return animating.get() && !paused; } public boolean isReverse() { return reverse; } public void setReverse(boolean reverse) { this.reverse = reverse; } public TiBlob toBlob () { TiImageView view = getView(); if (view != null) { Drawable drawable = view.getImageDrawable(); if (drawable != null && drawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); return TiBlob.blobFromImage(proxy.getTiContext(), bitmap); } } return null; } @Override public void setOpacity(float opacity) { TiImageView view = getView(); if (view != null) { view.setColorFilter(TiUIHelper.createColorFilterForOpacity(opacity)); super.setOpacity(opacity); } } @Override public void clearOpacity(View view) { super.clearOpacity(view); TiImageView iview = getView(); if (iview != null) { iview.setColorFilter(null); } } @Override public void release() { super.release(); if (loader != null) { synchronized (loader) { loader.notify(); } loader = null; } if (imageSources != null) { imageSources.clear(); } imageSources = null; defaultImageSource = null; } }
package mobi.semparar.cordova.mixpanel; import android.content.Context; import android.text.TextUtils; import com.mixpanel.android.mpmetrics.MixpanelAPI; import java.util.Map;; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.apache.cordova.LOG; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; class JSONHelper { public static Map<String, Integer> jsonToMap(JSONObject json) throws JSONException { Map<String, Integer> retMap = new HashMap<String, Integer>(); if(json != JSONObject.NULL) { retMap = toMap(json); } return retMap; } public static Map<String, Integer> toMap(JSONObject object) throws JSONException { Map<String, Integer> map = new HashMap<String, Integer>(); Iterator<String> keysItr = object.keys(); while(keysItr.hasNext()) { String key = keysItr.next(); Integer value = object.optInt(key); map.put(key, value); } return map; } public static List<Object> toList(JSONArray array) throws JSONException { List<Object> list = new ArrayList<Object>(); for(int i = 0; i < array.length(); i++) { Object value = array.get(i); if(value instanceof JSONArray) { value = toList((JSONArray) value); } else if(value instanceof JSONObject) { value = toMap((JSONObject) value); } list.add(value); } return list; } } public class MixpanelPlugin extends CordovaPlugin { private static String LOG_TAG = "MIXPANEL PLUGIN"; private static MixpanelAPI mixpanel; private enum Action { // MIXPANEL API ALIAS("alias"), FLUSH("flush"), IDENTIFY("identify"), INIT("init"), RESET("reset"), TRACK("track"), // PEOPLE API PEOPLE_SET("people_set"), PEOPLE_IDENTIFY("people_identify"), PEOPLE_INCREMENT("people_increment"), PEOPLE_TRACK_CHARGE("people_track_charge"), SET_PUSH_REGISTRATION_ID("set_push_registration_id"), INITIALIZE_HANDLE_PUSH("initialize_handle_push"); private final String name; private static final Map<String, Action> lookup = new HashMap<String, Action>(); static { for (Action a : Action.values()) lookup.put(a.getName(), a); } private Action(String name) { this.name = name; } public String getName() { return name; } public static Action get(String name) { return lookup.get(name); } } /** * helper fn that logs the err and then calls the err callback */ private void error(CallbackContext cbCtx, String message) { LOG.e(LOG_TAG, message); cbCtx.error(message); } @Override public boolean execute(String action, JSONArray args, final CallbackContext cbCtx) { // throws JSONException Action act = Action.get(action); if (act == null){ this.error(cbCtx, "unknown action"); return false; } if (mixpanel == null && Action.INIT != act) { this.error(cbCtx, "you must initialize mixpanel first using \"init\" action"); return false; } switch (act) { case ALIAS: return handleAlias(args, cbCtx); case FLUSH: return handleFlush(args, cbCtx); case IDENTIFY: return handleIdentify(args, cbCtx); case INIT: return handleInit(args, cbCtx); case RESET: return handleReset(args, cbCtx); case TRACK: return handleTrack(args, cbCtx); case PEOPLE_SET: return handlePeopleSet(args, cbCtx); case PEOPLE_IDENTIFY: return handlePeopleIdentify(args, cbCtx); case PEOPLE_INCREMENT: return handlePeopleIncrement(args, cbCtx); case PEOPLE_TRACK_CHARGE: return handlePeopleTrackCharge(args, cbCtx); case INITIALIZE_HANDLE_PUSH: return handleInitializePushHandling(args, cbCtx); case SET_PUSH_REGISTRATION_ID: return handleSetPushRegistrationId(args, cbCtx); default: this.error(cbCtx, "unknown action"); return false; } } @Override public void onDestroy() { if (mixpanel != null) { mixpanel.flush(); } super.onDestroy(); }
package org.ihtsdo.buildcloud.controller; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.ihtsdo.buildcloud.controller.helper.HypermediaGenerator; import org.ihtsdo.buildcloud.entity.Build; import org.ihtsdo.buildcloud.entity.BuildConfiguration; import org.ihtsdo.buildcloud.entity.QATestConfig; import org.ihtsdo.buildcloud.service.BuildService; import org.ihtsdo.buildcloud.service.PublishService; import org.ihtsdo.otf.rest.exception.BusinessServiceException; import org.ihtsdo.otf.rest.exception.ResourceNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.mangofactory.swagger.annotations.ApiIgnore; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; @Controller @RequestMapping("/centers/{releaseCenterKey}/products/{productKey}/builds") @Api(value = "Build", position = 1) public class BuildController { private final Logger logger = LoggerFactory.getLogger(BuildController.class); @Autowired private BuildService buildService; @Autowired private HypermediaGenerator hypermediaGenerator; @Autowired private PublishService publishService; private static final String[] BUILD_LINKS = {"configuration","qaTestConfig", "inputfiles", "outputfiles","buildReport","logs" }; @RequestMapping( method = RequestMethod.POST ) @ApiOperation( value = "Create a build", notes = "Create a build for given product key and release center key and returns build id" ) @ResponseBody public ResponseEntity<Map<String, Object>> createBuild(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, final HttpServletRequest request) throws BusinessServiceException { final Build build = buildService.createBuildFromProduct(releaseCenterKey, productKey); final boolean currentResource = false; return new ResponseEntity<>(hypermediaGenerator.getEntityHypermedia(build, currentResource, request, BUILD_LINKS), HttpStatus.CREATED); } @RequestMapping(value = "/", method = RequestMethod.GET ) @ApiOperation( value = "Returns a list all builds for a logged in user", notes = "Returns a list all builds visible to the currently logged in user, " + "so this could potentially span across Release Centres" ) @ResponseBody public List<Map<String, Object>> getBuilds(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, final HttpServletRequest request) throws ResourceNotFoundException { final List<Build> builds = buildService.findAllDesc(releaseCenterKey, productKey); return hypermediaGenerator.getEntityCollectionHypermedia(builds, request, BUILD_LINKS); } @RequestMapping(value = "/{buildId}", method = RequestMethod.GET ) @ResponseBody @ApiOperation( value = "Get a build id", notes = "Returns a single build object for given key" ) public Map<String, Object> getBuild(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, final HttpServletRequest request) throws ResourceNotFoundException { final Build build = buildService.find(releaseCenterKey, productKey, buildId); ifBuildIsNullThrow(productKey, buildId, build); final boolean currentResource = true; return hypermediaGenerator.getEntityHypermedia(build, currentResource, request, BUILD_LINKS); } @RequestMapping(value = "/{buildId}/configuration", produces = "application/json", method = RequestMethod.GET) @ResponseBody @ApiOperation( value = "Retrieves configuration details", notes = "Retrieves configuration details for given product key, release center key, and build id" ) public Map<String, Object> getConfiguration(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, final HttpServletRequest request) throws IOException, BusinessServiceException { final BuildConfiguration buildConfiguration = buildService.loadBuildConfiguration(releaseCenterKey, productKey, buildId); final Map<String,Object> result = new HashMap<>(); if (buildConfiguration != null ) { result.putAll(hypermediaGenerator.getEntityHypermedia(buildConfiguration, false, request)); } final QATestConfig qaTestConfig = buildService.loadQATestConfig(releaseCenterKey, productKey, buildId); if( qaTestConfig != null) { result.putAll(hypermediaGenerator.getEntityHypermedia(qaTestConfig, true, request)); } return result; } @RequestMapping(value = "/{buildId}/qaTestConfig", produces = "application/json", method = RequestMethod.GET) @ResponseBody @ApiOperation( value = "Retrieves QA test configuration details", notes = "Retrieves configuration details for given product key, release center key, and build id" ) public Map<String, Object> getQqTestConfig(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, final HttpServletRequest request) throws IOException, BusinessServiceException { final Map<String,Object> result = new HashMap<>(); final QATestConfig qaTestConfig = buildService.loadQATestConfig(releaseCenterKey, productKey, buildId); if( qaTestConfig != null) { result.putAll(hypermediaGenerator.getEntityHypermedia(qaTestConfig, false, request)); } return result; } @RequestMapping(value = "/{buildId}/buildReport", produces = "application/json", method = RequestMethod.GET) @ResponseBody @ApiOperation( value = "Retrieves build report details", notes = "Retrieves buildReport details for given product key, release center key, and build id" ) public void getBuildReport(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, final HttpServletRequest request, final HttpServletResponse response) throws IOException, BusinessServiceException { try (InputStream outputFileStream = buildService.getBuildReportFile(releaseCenterKey, productKey, buildId)) { if (outputFileStream != null) { StreamUtils.copy(outputFileStream, response.getOutputStream()); } else { throw new ResourceNotFoundException("No build_report json file found for build: " + productKey + "/" + buildId + "/"); } } } @RequestMapping(value = "/{buildId}/inputfiles", method = RequestMethod.GET) @ResponseBody @ApiOperation( value = "Retrieves list of input file names", notes = "Retrieves list of input file names for given release center, product key and build id" ) public List<Map<String, Object>> listPackageInputFiles(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, final HttpServletRequest request) throws IOException, ResourceNotFoundException { final List<String> relativeFilePaths = buildService.getInputFilePaths(releaseCenterKey, productKey, buildId); return convertFileListToEntities(request, relativeFilePaths); } @RequestMapping(value = "/{buildId}/inputfiles/{inputFileName:.*}", method = RequestMethod.GET) @ApiOperation( value = "Download a specific file", notes = "Download a specific file content for given release center, product key, build id and given input file name combination" ) public void getPackageInputFile(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, @PathVariable final String inputFileName, final HttpServletResponse response) throws IOException, ResourceNotFoundException { try (InputStream outputFileStream = buildService.getInputFile(releaseCenterKey, productKey, buildId, inputFileName)) { StreamUtils.copy(outputFileStream, response.getOutputStream()); } } @RequestMapping(value = "/{buildId}/outputfiles", method = RequestMethod.GET) @ResponseBody @ApiOperation( value = "Retrieves a list of file names from output directory", notes = "Retrieves a list of file names from output directory for given release center, " + "product key, build id combination" ) public List<Map<String, Object>> listPackageOutputFiles(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, final HttpServletRequest request) throws BusinessServiceException { final List<String> relativeFilePaths = buildService.getOutputFilePaths(releaseCenterKey, productKey, buildId); return convertFileListToEntities(request, relativeFilePaths); } @RequestMapping(value = "/{buildId}/outputfiles/{outputFileName:.*}", method = RequestMethod.GET) @ApiOperation( value = "Download a specific file from output directory", notes = "Download a specific file from output directory for given release center, " + "product key, build id and file name combination" ) public void getPackageOutputFile(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, @PathVariable final String outputFileName, final HttpServletResponse response) throws IOException, ResourceNotFoundException { try (InputStream outputFileStream = buildService.getOutputFile(releaseCenterKey, productKey, buildId, outputFileName)) { StreamUtils.copy(outputFileStream, response.getOutputStream()); } } @RequestMapping(value = "/{buildId}/trigger", method = RequestMethod.POST) @ResponseBody @ApiIgnore public Map<String, Object> triggerProduct(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, @RequestParam(value = "failureExportMax", required = false) final Integer failureExportMax, final HttpServletRequest request) throws BusinessServiceException { //when failureExportMax is set to less than zero means exporting all results. The default value is 10 when not set final Build build = buildService.triggerBuild(releaseCenterKey, productKey, buildId, failureExportMax); return hypermediaGenerator.getEntityHypermediaOfAction(build, request, BUILD_LINKS); } @RequestMapping(value = "/{buildId}/publish", method = RequestMethod.POST) @ResponseBody @ApiOperation( value = "Publish a release for given build id", notes = "Publish release for given build id to make it available in repository for wider usages" ) public void publishBuild(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId) throws BusinessServiceException { final Build build = buildService.find(releaseCenterKey, productKey, buildId); ifBuildIsNullThrow(productKey, buildId, build); publishService.publishBuild(build, true); } @RequestMapping(value = "/{buildId}/logs" , method = RequestMethod.GET) @ResponseBody @ApiOperation( value = "Retrieves a list of build log file names", notes = "Retrieves a list of build log file names for given release center, product key, and build id" ) public List<Map<String, Object>> getBuildLogs(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, final HttpServletRequest request) throws ResourceNotFoundException { return convertFileListToEntities(request, buildService.getLogFilePaths(releaseCenterKey, productKey, buildId)); } @RequestMapping(value = "/{buildId}/logs/{logFileName:.*}", method = RequestMethod.GET) @ApiOperation( value = "Download a specific build log file", notes = "Download a specific log file for given release center, " + "product key, build id and file name combination" ) public void getBuildLog(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, @PathVariable final String logFileName, final HttpServletResponse response) throws ResourceNotFoundException, IOException { try (InputStream outputFileStream = buildService.getLogFile(releaseCenterKey, productKey, buildId, logFileName)) { if (outputFileStream != null) { StreamUtils.copy(outputFileStream, response.getOutputStream()); } else { throw new ResourceNotFoundException("Did not find requested log file: " + productKey + "/" + buildId + "/" + logFileName); } } } @RequestMapping(value = "/{buildId}/logs/{logFileName:.*}", method = RequestMethod.HEAD) @ApiOperation(value = "Download a specific build log file", notes = "Download a specific log file for given release center, " + "product key, build id and file name combination") public void getBuildLogHead(@PathVariable final String releaseCenterKey, @PathVariable final String productKey, @PathVariable final String buildId, @PathVariable final String logFileName, final HttpServletResponse response) throws ResourceNotFoundException, IOException { try (InputStream outputFileStream = buildService.getLogFile(releaseCenterKey, productKey, buildId, logFileName)) { // This will blow up with 404 if the file isn't found. HTTP HEAD demands that no body is returned, so nothing to do here logger.debug("HTTP 200 response to head request for {}/{}/{}", productKey, buildId, logFileName); } } private void ifBuildIsNullThrow(final String productKey, final String buildId, final Build build) throws ResourceNotFoundException { if (build == null) { throw new ResourceNotFoundException("Unable to find build, productKey: " + productKey + ", buildId:" + buildId); } } private List<Map<String, Object>> convertFileListToEntities(final HttpServletRequest request, final List<String> relativeFilePaths) { final List<Map<String, String>> files = new ArrayList<>(); for (final String relativeFilePath : relativeFilePaths) { final Map<String, String> file = new HashMap<>(); file.put(ControllerConstants.ID, relativeFilePath); files.add(file); } return hypermediaGenerator.getEntityCollectionHypermedia(files, request); } }
package com.biotronisis.pettplant.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; //import android.support.v7.appcompat.BuildConfig; import com.biotronisis.pettplant.BuildConfig; import com.biotronisis.pettplant.R; //import com.biotronisis.pettplant.plant.processor.PlantState; public class AboutActivity extends AbstractBaseActivity { private static final String TAG = "AboutActivity"; private TextView versionNumberTV; @Override public String getActivityName() { return TAG; } @Override public String getHelpKey() { return "about"; } public static Intent createIntent(Context context) { Intent intent = new Intent(context, AboutActivity.class); // intent.putExtra(EXTRA_PLANT_STATE, plantState); return intent; } @Override protected void onCreate(Bundle savedInstanceSate) { super.onCreate(savedInstanceSate); setContentView(R.layout.activity_about); versionNumberTV = (TextView) findViewById(R.id.versionNumber); // int versionCode = BuildConfig.VERSION_CODE; String versionName = BuildConfig.VERSION_NAME; // Get the version number from the system versionNumberTV.setText(versionName); // versionNumberTV.setText("test"); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } }
package com.gmail.brian.broll.taxidash.app; import android.app.AlertDialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.radiusnetworks.ibeacon.IBeacon; import com.radiusnetworks.ibeacon.IBeaconConsumer; import com.radiusnetworks.ibeacon.IBeaconManager; import com.radiusnetworks.ibeacon.RangeNotifier; import com.radiusnetworks.ibeacon.Region; import it.gmariotti.cardslib.library.internal.Card; import it.gmariotti.cardslib.library.internal.CardArrayAdapter; import it.gmariotti.cardslib.library.view.CardListView; public class NearbyCabList extends NavigationActivity implements IBeaconConsumer{ /* * A couple big things will be going on here: * + Populating the nearby cab list * + Getting beacon ids of nearby beacons * + Sending beacon ids to server for driver info * + Displaying the driver info of each driver in a list * * + Clicking a cab for more info * + Send intent to another activity * * + If no cabs... * + Alert user that no cabs are nearby * + Offer to call top cab companies * + Get cab companies and phone numbers from the server * + Pass intent to phone calling functionality */ /* * TODO: * + Listen for changes to bluetooth after app is running * + Warn the user that bluetooth must be enabled to get nearby cabs * + Alert the user that the app will not be able to get nearby cabs if BT not supported */ Map<Integer, Driver> driverCache = new HashMap<Integer, Driver>(); Map<Integer, Company> companyCache = new HashMap<Integer, Company>(); Map<Integer, DriverCard> beaconId2driverCard = new HashMap<Integer, DriverCard>(); ArrayList<Integer> nearbyDrivers = new ArrayList<Integer>(); ArrayList<Integer> displayedDrivers = new ArrayList<Integer>(); List<Card> displayedCards = new ArrayList<Card>(); //iBeacon Stuff String BEACON_TAG = "iBEACON MSG:"; private final int TOTAL_ATTEMPTS = 10; private int ATTEMPTS_LEFT = TOTAL_ATTEMPTS; private IBeaconManager iBM = IBeaconManager.getInstanceForApplication(this); BluetoothAdapter bAdaptor; private final int REQUEST_ENABLE_BT = 1; Card.OnCardClickListener viewDriver; ProgressDialog progress; TextView noneFoundMsg = null; public NearbyCabList() { final IBeaconConsumer self; self = this; viewDriver = new Card.OnCardClickListener() { @Override public void onClick(Card c, View v) { //What should happen when driver panel is pressed iBM.unBind(self); Driver driver; driver = ((DriverCard) c).getDriver(); Log.i("NEARBY CABS", "Driver clicked has rating of " + driver.getRating()); Intent viewDriverIntent = new Intent(v.getContext(), DriverProfile.class); viewDriverIntent.putExtra("Driver", (android.os.Parcelable) driver); startActivity(viewDriverIntent); } }; } private void setFonts(){ //Set all textview objects to use font-awesome //TODO Typeface fontAwesome = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View contentView = inflater.inflate(R.layout.activity_taxi__list, null, false); content.addView(contentView, 0); //Get temp dir if(CONSTANTS.TEMP == null) { CONSTANTS.TEMP = getFilesDir() + "/tmp"; new File(CONSTANTS.TEMP).mkdir(); } //Set noneFoundMsg noneFoundMsg = new TextView(this); noneFoundMsg.setText("Searching for nearby taxis..."); noneFoundMsg.setTextSize(24); noneFoundMsg.setTextColor(getResources().getColor(R.color.lightText)); noneFoundMsg.setGravity(Gravity.CENTER); FrameLayout container = (FrameLayout) findViewById(R.id.containerq); container.addView(noneFoundMsg); bAdaptor = BluetoothAdapter.getDefaultAdapter(); if(bAdaptor == null){//bluetooth not supported on device //Alert the user that the app will not be able to get nearby //cab info offerToCallCompany("Your device does not have bluetooth and " + "will not be able to detect nearby cabs. "); }else{ startBlueTooth(); } } private void startBlueTooth(){ //Make sure the user has bluetooth if(!bAdaptor.isEnabled()){ Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }else{ iBM.bind(this); //Write this to the background... //TODO progress = new ProgressDialog(this); progress.setTitle("Searching..."); progress.setMessage("Please wait while we find nearby cabs..."); progress.show(); } } protected void onDestroy(){ super.onDestroy(); iBM.unBind(this); } @Override public void onPause(){ //Don't scan while suspended iBM.unBind(this); super.onPause(); } @Override public void onResume(){ super.onResume(); //if((bAdaptor = BluetoothAdapter.getDefaultAdapter()) != null) { //startBlueTooth(); } private void offerToCallCompany(String reason){ //Ask the user if he/she wants to call a local cab company AlertDialog.Builder alert = new AlertDialog.Builder(this); //alert.setTitle("Compan"); alert.setMessage(reason + "\n\nWould you like to call a local cab company?"); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do something with value! //Go to LocalCompanyList Activity //TODO Intent callCompanyIntent = new Intent(getBaseContext(), LocalCompanyList.class); startActivity(callCompanyIntent); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); } //After Bluetooth is turned on/off... protected void onActivityResult(int requestCode, int resultCode, Intent data){ switch(requestCode){//This switch case may be unnecessary but should be easily extended case REQUEST_ENABLE_BT://Bluetooth if(resultCode == RESULT_OK) { //Start discovering nearby cabs iBM.bind(this); progress = new ProgressDialog(this); progress.setTitle("Searching..."); progress.setMessage("Please wait while we find nearby cabs..."); progress.show(); }else{ //Add warning message offerToCallCompany("Without bluetooth you " + "will not be able to detect nearby cabs. "); } break; } } protected void displayDriverInfo(){ //Stop the waiting bar if(nearbyDrivers.size() > 0){ if(progress != null) { progress.dismiss(); } ATTEMPTS_LEFT = TOTAL_ATTEMPTS; }else if(ATTEMPTS_LEFT == 0) { //Ask to keep searching ATTEMPTS_LEFT--;//Make sure we only ask with one box askToKeepSearching(); }else{ ATTEMPTS_LEFT } //Clear the current list ArrayList<Integer> nearbyDriversClone = (ArrayList<Integer>) nearbyDrivers.clone();//Snapshot of nearby drivers CardListView list = (CardListView) findViewById(R.id.taxi_list); for(int i = displayedDrivers.size()-1; i >= 0; i Integer displayedDriverId = displayedDrivers.get(i); if(nearbyDriversClone.indexOf(displayedDriverId) != -1){//If not nearby, remove from screen displayedDrivers.remove(displayedDriverId); displayedCards.remove(beaconId2driverCard.get(displayedDriverId)); } } Collections.sort(nearbyDriversClone); Context context = this.getApplicationContext(); for(Integer nearbyDriverId : nearbyDriversClone){ //Create the driver's card FrameLayout container = (FrameLayout) findViewById(R.id.containerq); container.removeView(noneFoundMsg); if(displayedDrivers.indexOf(nearbyDriverId) == -1) { //Add the driver DriverCard driverCard; if (CONSTANTS.DEMO_MODE) { driverCard = new DriverCard(context); } else { driverCard = new DriverCard(context, driverCache.get(nearbyDriverId)); } driverCard.setClickListener(viewDriver); driverCard.setBackgroundResource(new ColorDrawable(getResources().getColor(R.color.cardColor))); //Adding the driver displayedDrivers.add(nearbyDriverId); displayedCards.add(driverCard); beaconId2driverCard.put(nearbyDriverId, driverCard); } } //TODO Find out how to remove cards from view CardArrayAdapter adapter; adapter = new CardArrayAdapter(context, displayedCards); list.setAdapter(adapter); } private void askToKeepSearching(){ //Ask the user if he/she wants to call a local cab company AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("No cabs found yet"); alert.setMessage("Would you like to search a little longer?"); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //if yes... ATTEMPTS_LEFT = TOTAL_ATTEMPTS; } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //if no... progress.dismiss(); } }); alert.show(); } @Override public void onIBeaconServiceConnect() { iBM.setRangeNotifier(new RangeNotifier() { @Override public void didRangeBeaconsInRegion(Collection<IBeacon> iBeacons, Region region) { //For each beacon in range, get the driver info //Sort the driver info by distance Log.i(BEACON_TAG, "FOUND " + iBeacons.size() + " BEACON(S)"); Iterator<IBeacon> itr = iBeacons.iterator(); Integer beaconId; ArrayList<Integer> beaconIds = new ArrayList<Integer>(); while(itr.hasNext()){ IBeacon b = itr.next(); beaconId = b.getMinor();//Make sure we are using the minor and not the major... if(driverCache.containsKey(beaconId)){ driverCache.get(beaconId).setDistance(b.getAccuracy()); nearbyDrivers.add(beaconId); }else{ beaconIds.add(b.getMinor()); //Request driver info from the server Log.i(BEACON_TAG, "Gonna request info for driver with beacon id: " + beaconId); } } Integer[] bIds = new Integer[beaconIds.size()]; for(int i = 0; i < bIds.length; i++){ bIds[i] = beaconIds.get(i); } //DEMO PURPOSES ONLY if(CONSTANTS.DEMO_MODE){ Log.i(BEACON_TAG, "DEMO MODE ACTIVE"); bIds = new Integer[3]; bIds[0] = 37; bIds[1] = 1661; bIds[2] = 1662; } Log.i(BEACON_TAG, "ABOUT TO REQUEST DRIVER INFO"); new getNearbyCabInfo().execute(bIds); } }); try { iBM.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); } catch (RemoteException e) { } } private class getNearbyCabInfo extends AsyncTask<Integer[], Void, JSONObject[]>{ @Override protected JSONObject[] doInBackground(Integer[]... params) { //Given the beaconIds, get the driver info Integer[] beaconIds = params[0];//Only grab the first one FIXME Log.i("NETWORK STUFF", "FOUND " + beaconIds.length + " BEACONS IN NETWORK SECTION"); String driverInfo; Integer beaconId; JSONObject[] result = new JSONObject[beaconIds.length]; for(int i = 0; i < beaconIds.length; i++) { beaconId = beaconIds[i]; String endpoint = CONSTANTS.CURRENT_SERVER.getAddress() + "/mobile/" + beaconId + ".json"; Log.i("REQUESTING CAB", "AT " + endpoint); try { HttpClient http = new DefaultHttpClient(); http.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpGet req = new HttpGet(endpoint); HttpResponse response = http.execute(req); HttpEntity entity = response.getEntity(); driverInfo = EntityUtils.toString(entity); result[i] = new JSONObject(driverInfo); Log.i("JSON RECEIVED: ", result[i].toString()); JSONObject company = result[i].getJSONObject("company"); Integer companyId = company.getInt("id"); if(companyCache.get(companyId) == null){ Company newCompany = new Company(company.getInt("id"), company.getString("name"), (float) company.getDouble("average_rating"), company.getString("phone_number")); companyCache.put(companyId, newCompany); //Get the company's logo newCompany.setLogo(getCompanyLogo(companyId)); } driverCache.put(beaconId, new Driver(result[i].getInt("id"), beaconId, result[i].getString("first_name")+ " " +result[i].getString("last_name"), companyCache.get(companyId), (float) result[i].getDouble("average_rating"), result[i].getString("phone_number"), result[i].getBoolean("valid"))); nearbyDrivers.add(beaconId); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { Log.e("NO DRIVER ERROR", "No driver with beacon id " + beaconId); e.printStackTrace(); } //Get the image for the driver /* try { HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Log.i(BEACON_TAG, "SET IMAGE FOR " + driverCache.get(beaconId).getName()); Bitmap img = BitmapFactory.decodeStream(input); File path = new File(getFilesDir(), beaconId + ".png"); saveImageToCache(path.getAbsolutePath(), img); driverCache.get(beaconId).setImage(path.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); Log.e("getBmpFromUrl error: ", e.getMessage().toString()); return null; } */ } return result; } protected void onPostExecute(JSONObject[] result){ displayDriverInfo(); } private void saveImageToCache(String filename, Bitmap image) { Log.i("IMAGE SAVING", "GONNA SAVE IMAGE TO " + filename); FileOutputStream out = null; try { out = new FileOutputStream(filename); image.compress(Bitmap.CompressFormat.PNG, 90, out); } catch (Exception e) { e.printStackTrace(); } finally { try{ out.close(); Log.i("IMAGE SAVING", "SAVED IMAGE TO " + filename); } catch(Throwable ignore) {} } } private String getCompanyLogo(Integer companyId){ try { URL url = new URL(CONSTANTS.CURRENT_SERVER.getAddress() + "/mobile/images/companies/" + companyId + ".json"); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(input); File path = new File(CONSTANTS.TEMP, "COMPANY_" + companyId + ".png"); Log.i("SAVING COMPANY IMAGE", "FILE PATH IS " + CONSTANTS.TEMP); saveImageToCache(path.getAbsolutePath(), img); //Log.i("Company IMAGE", "SAVING IMAGE TO " + path.getAbsolutePath()); return path.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); Log.e("getBmpFromUrl error: ", e.getMessage().toString()); return null; } } } }
package tv.rocketbeans.rbcgj.core; import aurelienribon.tweenengine.BaseTween; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenEquation; import aurelienribon.tweenengine.TweenEquations; import aurelienribon.tweenengine.TweenManager; import tv.rocketbeans.rbcgj.GameConfig; import tv.rocketbeans.rbcgj.tweens.GameObjectTween; import tv.rocketbeans.rbcgj.tweens.SharedTweenManager; import tv.rocketbeans.rbcgj.util.DeltaTimer; public class GameObjectMover { static { Tween.registerAccessor(GameObject.class, new GameObjectTween()); } private GameObject object; private CollisionDetector collisions; private TweenManager tweenManager = SharedTweenManager.getInstance(); private DeltaTimer timer = new DeltaTimer(); public GameObjectMover(GameObject object, CollisionDetector collisions) { this.object = object; this.collisions = collisions; timer.update(GameConfig.MOVEMENT_TIME); } public void update(float delta) { timer.update(delta); } public void moveLeft() { if (isReadyToMove() && canMoveLeft()) { timer.reset(); object.move(-GameConfig.CELL_SCALE, 0f); object.setOffset(GameConfig.CELL_SCALE, 0f); object.setDirection(Direction.LEFT); Tween.to(object, GameObjectTween.OFFSET_X, GameConfig.MOVEMENT_TIME) .ease(TweenEquations.easeNone) .target(0f).start(tweenManager); animateMovement(object); } } public void moveRight() { if (isReadyToMove() && canMoveRight()) { timer.reset(); object.move(GameConfig.CELL_SCALE, 0f); object.setOffset(-GameConfig.CELL_SCALE, 0f); object.setDirection(Direction.RIGHT); Tween.to(object, GameObjectTween.OFFSET_X, GameConfig.MOVEMENT_TIME) .ease(TweenEquations.easeNone) .target(0f).start(tweenManager); animateMovement(object); } } public void moveUp() { if (isReadyToMove() && canMoveUp()) { timer.reset(); object.move(0f, GameConfig.CELL_SCALE); object.setOffset(0f, -GameConfig.CELL_SCALE); object.setDirection(Direction.UP); Tween.to(object, GameObjectTween.OFFSET_Y, GameConfig.MOVEMENT_TIME) .ease(TweenEquations.easeNone) .target(0f).start(tweenManager); animateMovement(object); } } public void moveDown() { if (isReadyToMove() && canMoveDown()) { timer.reset(); object.move(0f, -GameConfig.CELL_SCALE); object.setOffset(0f, GameConfig.CELL_SCALE); object.setDirection(Direction.DOWN); Tween.to(object, GameObjectTween.OFFSET_Y, GameConfig.MOVEMENT_TIME) .ease(TweenEquations.easeNone) .target(0f).start(tweenManager); animateMovement(object); } } private boolean isReadyToMove() { return timer.reached(GameConfig.MOVEMENT_TIME); } private boolean canMoveLeft() { return !collisions.isCollision(object.getLeft() - GameConfig.CELL_SCALE, object.getTop()); } private boolean canMoveRight() { return !collisions.isCollision(object.getLeft() + GameConfig.CELL_SCALE, object.getTop()); } private boolean canMoveDown() { return !collisions.isCollision(object.getLeft(), object.getTop() - GameConfig.CELL_SCALE); } private boolean canMoveUp() { return !collisions.isCollision(object.getLeft(), object.getTop() + GameConfig.CELL_SCALE); } private void animateMovement(final GameObject object) { Tween.to(object, GameObjectTween.SCALE_X, GameConfig.MOVEMENT_TIME / 2f) .ease(TweenEquations.easeInOutQuad) .target(0.9f) .repeatYoyo(1, 0f) .setCallbackTriggers(TweenCallback.COMPLETE) .setCallback(new TweenCallback() { @Override public void onEvent(int type, BaseTween<?> source) { Tween.to(object, GameObjectTween.SCALE_X, GameConfig.MOVEMENT_TIME / 2f) .target(1.15f) .repeatYoyo(1, 0f) .ease(TweenEquations.easeInOutQuad) .start(tweenManager); } }) .start(tweenManager); Tween.to(object, GameObjectTween.SCALE_Y, GameConfig.MOVEMENT_TIME / 2f) .ease(TweenEquations.easeInOutQuad) .target(0.95f) .repeatYoyo(1, 0f) .setCallbackTriggers(TweenCallback.COMPLETE) .setCallback(new TweenCallback() { @Override public void onEvent(int type, BaseTween<?> source) { Tween.to(object, GameObjectTween.SCALE_Y, GameConfig.MOVEMENT_TIME / 2f) .target(1.05f) .repeatYoyo(1, 0f) .ease(TweenEquations.easeInOutQuad) .start(tweenManager); } }) .start(tweenManager); } }
package de.ironjan.mensaupb.menus_ui; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.View; import android.widget.ProgressBar; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.androidannotations.annotations.sharedpreferences.Pref; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Locale; import arrow.core.Either; import de.ironjan.mensaupb.BuildConfig; import de.ironjan.mensaupb.R; import de.ironjan.mensaupb.api.ClientV2; import de.ironjan.mensaupb.api.model.Menu; import de.ironjan.mensaupb.model.LocalizedMenu; import de.ironjan.mensaupb.prefs.InternalKeyValueStore_; import se.emilsjolander.stickylistheaders.StickyListHeadersListView; @SuppressWarnings("WeakerAccess") @EFragment(R.layout.fragment_menu_listing) public class MenuListingFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { public static final String ARG_DATE = "date"; public static final String ARG_LOCATION = "restaurant"; public static final int TIMEOUT_30_SECONDS = 30000; private final Logger LOGGER = LoggerFactory.getLogger(MenuListingFragment.class.getSimpleName()); @ViewById(R.id.emptyExplanation) View mLoadingView; @ViewById(R.id.could_not_load_view) View mcouldNotLoadView; @ViewById(android.R.id.empty) View empty; @ViewById(android.R.id.list) StickyListHeadersListView list; @ViewById(R.id.progressBar) ProgressBar mProgressBar; @Pref InternalKeyValueStore_ mInternalKeyValueStore; private ArrayBasedMenuListingAdapter adapter; private MenusNavigationCallback navigationCallback; private long startedAt = Long.MAX_VALUE; public static MenuListingFragment getInstance(String dateAsKey, String restaurant) { MenuListingFragment fragment = new MenuListingFragment_(); Bundle arguments = new Bundle(); arguments.putString(MenuListingFragment.ARG_DATE, dateAsKey); arguments.putString(MenuListingFragment.ARG_LOCATION, restaurant); fragment.setArguments(arguments); return fragment; } @AfterViews void rememberStartupTime() { this.startedAt = System.currentTimeMillis(); } @Override public void onAttach(Context context) { if (!(context instanceof MenusNavigationCallback)) { throw new IllegalArgumentException("MenuListingFragment can only be attached to an Activity implementing MenusNavigationCallback."); } super.onAttach(context); this.navigationCallback = (MenusNavigationCallback) context; } private String getArgLocation() { String location = getArguments().getString(ARG_LOCATION); return location.replaceAll("\\*", "%"); } private String getArgDate() { return getArguments().getString(ARG_DATE); } @AfterViews void afterViews() { bindListAdapter(); loadContent(); /* TODO is this useful? yes - but not in this form. new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(TIMEOUT_30_SECONDS); updateLoadingMessage(); } catch (InterruptedException e) { // ignored } } }).start();*/ } @Background void loadContent() { final Either<String, Menu[]> either = ClientV2.Companion.getClient().getMenus(getArgLocation(), getArgDate()); if (either.isLeft()) { either.mapLeft(s -> { showError(s); return s; }); } else { either.map(menus1 -> { showMenusV2(menus1); return menus1; }); } } @UiThread void bindListAdapter() { adapter = new ArrayBasedMenuListingAdapter(getActivity(), new ArrayList<>(0)); list.setAdapter(adapter); list.setAreHeadersSticky(false); list.setOnItemClickListener((parent, view, position, id) -> listItemClicked(position)); list.setEmptyView(empty); } @UiThread void showMenusV2(Menu[] menus) { List<LocalizedMenu> localizedMenus = new ArrayList<>(menus.length); for (Menu m : menus) { localizedMenus.add(new LocalizedMenu(m, isEnglish())); } adapter.clear(); adapter.addAll(localizedMenus); } @UiThread void showError(String msg) { updateLoadingMessage(); } private boolean isEnglish() { return Locale.getDefault().getLanguage().startsWith(Locale.ENGLISH.toString()); } @UiThread void updateLoadingMessage() { if (list != null) { mLoadingView.setVisibility(View.GONE); mcouldNotLoadView.setVisibility(View.VISIBLE); } } void listItemClicked(int pos) { if (BuildConfig.DEBUG) LOGGER.debug("listItemClicked({})", pos); navigationCallback.showMenu(adapter.getKey(pos)); if (BuildConfig.DEBUG) LOGGER.debug("listItemClicked({}) done", pos); } @Override public void onRefresh() { afterViews(); } }
package sword.langbook3.android; import android.os.Parcel; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import sword.collections.Function; import sword.collections.ImmutableHashSet; import sword.collections.ImmutableIntKeyMap; import sword.collections.ImmutableIntList; import sword.collections.ImmutableIntPairMap; import sword.collections.ImmutableIntRange; import sword.collections.ImmutableIntSet; import sword.collections.ImmutableIntSetBuilder; import sword.collections.ImmutableIntValueHashMap; import sword.collections.ImmutableIntValueMap; import sword.collections.ImmutableList; import sword.collections.ImmutablePair; import sword.collections.ImmutableSet; import sword.collections.IntKeyMap; import sword.collections.IntList; import sword.collections.IntPairMap; import sword.collections.IntSet; import sword.collections.List; import sword.collections.MutableIntKeyMap; import sword.collections.MutableIntList; import sword.collections.MutableIntPairMap; import sword.collections.MutableIntSet; import sword.collections.SortUtils; import sword.database.DbExporter; import sword.database.DbImporter; import sword.database.DbQuery; import sword.database.DbResult; import sword.database.DbStringValue; import sword.database.DbTable; import sword.database.DbValue; import sword.langbook3.android.sdb.StreamedDatabaseConstants; import static sword.langbook3.android.LangbookDatabaseUtils.convertText; import static sword.langbook3.android.LangbookDbSchema.NO_BUNCH; public final class LangbookReadableDatabase { private final DbExporter.Database db; public LangbookReadableDatabase(DbExporter.Database db) { this.db = db; } public static List<DbValue> selectSingleRow(DbExporter.Database db, DbQuery query) { try (DbResult result = db.select(query)) { if (!result.hasNext()) { throw new AssertionError("Nothing found matching the given criteria"); } final List<DbValue> row = result.next(); if (result.hasNext()) { throw new AssertionError("Multiple rows found matching the given criteria"); } return row; } } public Integer findSymbolArray(String str) { return findSymbolArray(db, str); } public Integer findCorrelation(IntPairMap correlation) { return findCorrelation(db, correlation); } public static Integer findSymbolArray(DbExporter.Database db, String str) { final LangbookDbSchema.SymbolArraysTable table = LangbookDbSchema.Tables.symbolArrays; final DbQuery query = new DbQuery.Builder(table) .where(table.getStrColumnIndex(), str) .select(table.getIdColumnIndex()); final DbResult result = db.select(query); try { final Integer value = result.hasNext()? result.next().get(0).toInt() : null; if (result.hasNext()) { throw new AssertionError(); } return value; } finally { result.close(); } } public static Integer findCorrelation(DbExporter.Database db, IntKeyMap<String> correlation) { if (correlation.size() == 0) { return StreamedDatabaseConstants.nullCorrelationId; } final ImmutableIntKeyMap<String> corr = correlation.toImmutable(); final LangbookDbSchema.CorrelationsTable table = LangbookDbSchema.Tables.correlations; final LangbookDbSchema.SymbolArraysTable symbolArrays = LangbookDbSchema.Tables.symbolArrays; final int offset = table.columns().size(); final int offset2 = offset + symbolArrays.columns().size(); final int offset3 = offset2 + table.columns().size(); final DbQuery query = new DbQuery.Builder(table) .join(symbolArrays, table.getSymbolArrayColumnIndex(), symbolArrays.getIdColumnIndex()) .where(table.getAlphabetColumnIndex(), corr.keyAt(0)) .where(offset + symbolArrays.getStrColumnIndex(), corr.valueAt(0)) .join(table, table.getCorrelationIdColumnIndex(), table.getCorrelationIdColumnIndex()) .join(symbolArrays, offset2 + table.getSymbolArrayColumnIndex(), symbolArrays.getIdColumnIndex()) .select( table.getCorrelationIdColumnIndex(), offset2 + table.getAlphabetColumnIndex(), offset3 + symbolArrays.getStrColumnIndex()); final DbResult result = db.select(query); try { if (result.hasNext()) { List<DbValue> row = result.next(); int correlationId = row.get(0).toInt(); ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); builder.put(row.get(1).toInt(), row.get(2).toText()); while (result.hasNext()) { row = result.next(); int newCorrelationId = row.get(0).toInt(); if (newCorrelationId != correlationId) { if (builder.build().equals(corr)) { return correlationId; } correlationId = newCorrelationId; builder = new ImmutableIntKeyMap.Builder<>(); } builder.put(row.get(1).toInt(), row.get(2).toText()); } if (builder.build().equals(corr)) { return correlationId; } } } finally { result.close(); } return null; } public static Integer findCorrelation(DbExporter.Database db, IntPairMap correlation) { if (correlation.size() == 0) { return StreamedDatabaseConstants.nullCorrelationId; } final ImmutableIntPairMap corr = correlation.toImmutable(); final LangbookDbSchema.CorrelationsTable table = LangbookDbSchema.Tables.correlations; final int offset = table.columns().size(); final DbQuery query = new DbQuery.Builder(table) .join(table, table.getCorrelationIdColumnIndex(), table.getCorrelationIdColumnIndex()) .where(table.getAlphabetColumnIndex(), corr.keyAt(0)) .where(table.getSymbolArrayColumnIndex(), corr.valueAt(0)) .select( table.getCorrelationIdColumnIndex(), offset + table.getAlphabetColumnIndex(), offset + table.getSymbolArrayColumnIndex()); final DbResult result = db.select(query); try { if (result.hasNext()) { List<DbValue> row = result.next(); int correlationId = row.get(0).toInt(); ImmutableIntPairMap.Builder builder = new ImmutableIntPairMap.Builder(); builder.put(row.get(1).toInt(), row.get(2).toInt()); while (result.hasNext()) { row = result.next(); int newCorrelationId = row.get(0).toInt(); if (newCorrelationId != correlationId) { if (builder.build().equals(corr)) { return correlationId; } correlationId = newCorrelationId; builder = new ImmutableIntPairMap.Builder(); } builder.put(row.get(1).toInt(), row.get(2).toInt()); } if (builder.build().equals(corr)) { return correlationId; } } } finally { result.close(); } return null; } public static Integer findCorrelationArray(DbImporter.Database db, IntList array) { final LangbookDbSchema.CorrelationArraysTable table = LangbookDbSchema.Tables.correlationArrays; final DbQuery query = new DbQuery.Builder(table) .join(table, table.getArrayIdColumnIndex(), table.getArrayIdColumnIndex()) .where(table.getArrayPositionColumnIndex(), 0) .where(table.getCorrelationColumnIndex(), array.get(0)) .select(table.getArrayIdColumnIndex(), table.columns().size() + table.getCorrelationColumnIndex()); final DbResult result = db.select(query); try { if (result.hasNext()) { List<DbValue> row = result.next(); int arrayId = row.get(0).toInt(); ImmutableIntList.Builder builder = new ImmutableIntList.Builder(); builder.add(row.get(1).toInt()); while (result.hasNext()) { row = result.next(); int newArrayId = row.get(0).toInt(); if (arrayId != newArrayId) { if (builder.build().equals(array)) { return arrayId; } arrayId = newArrayId; builder = new ImmutableIntList.Builder(); } builder.add(row.get(1).toInt()); } if (builder.build().equals(array)) { return arrayId; } } } finally { result.close(); } return null; } public static Integer findCorrelationArray(DbExporter.Database db, int... correlations) { if (correlations.length == 0) { return StreamedDatabaseConstants.nullCorrelationArrayId; } LangbookDbSchema.CorrelationArraysTable table = LangbookDbSchema.Tables.correlationArrays; final DbQuery query = new DbQuery.Builder(table) .where(table.getArrayPositionColumnIndex(), 0) .where(table.getCorrelationColumnIndex(), correlations[0]) .select(table.getArrayIdColumnIndex()); final DbResult result = db.select(query); try { while (result.hasNext()) { final int arrayId = result.next().get(0).toInt(); final int[] array = getCorrelationArray(db, arrayId); if (Arrays.equals(correlations, array)) { return arrayId; } } } finally { result.close(); } return null; } public static ImmutableSet<ImmutableIntPair> findConversions(DbExporter.Database db) { final LangbookDbSchema.ConversionsTable conversions = LangbookDbSchema.Tables.conversions; final DbQuery query = new DbQuery.Builder(conversions) .groupBy(conversions.getSourceAlphabetColumnIndex(), conversions.getTargetAlphabetColumnIndex()) .select( conversions.getSourceAlphabetColumnIndex(), conversions.getTargetAlphabetColumnIndex()); final ImmutableSet.Builder<ImmutableIntPair> builder = new ImmutableHashSet.Builder<>(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); final int source = row.get(0).toInt(); final int target = row.get(1).toInt(); builder.add(new ImmutableIntPair(source, target)); } } return builder.build(); } public static Integer findRuledAcceptationByRuleAndMainAcceptation(DbExporter.Database db, int rule, int mainAcceptation) { final LangbookDbSchema.RuledAcceptationsTable ruledAccs = LangbookDbSchema.Tables.ruledAcceptations; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(ruledAccs) .join(agents, ruledAccs.getAgentColumnIndex(), agents.getIdColumnIndex()) .where(ruledAccs.getAcceptationColumnIndex(), mainAcceptation) .where(ruledAccs.columns().size() + agents.getRuleColumnIndex(), rule) .select(ruledAccs.getIdColumnIndex()); final DbResult dbResult = db.select(query); final Integer result = dbResult.hasNext()? dbResult.next().get(0).toInt() : null; if (dbResult.hasNext()) { throw new AssertionError(); } return result; } public static ImmutableList<SearchResult> findAcceptationFromText(DbExporter.Database db, String queryText, int restrictionStringType) { final LangbookDbSchema.StringQueriesTable table = LangbookDbSchema.Tables.stringQueries; final DbQuery query = new DbQuery.Builder(table) .where(table.getStringColumnIndex(), new DbQuery.Restriction(new DbStringValue(queryText), restrictionStringType)) .select( table.getStringColumnIndex(), table.getMainStringColumnIndex(), table.getMainAcceptationColumnIndex(), table.getDynamicAcceptationColumnIndex()); final MutableIntKeyMap<SearchResult> map = MutableIntKeyMap.empty(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); final String str = row.get(0).toText(); final String mainStr = row.get(1).toText(); final int acc = row.get(2).toInt(); final int dynAcc = row.get(3).toInt(); map.put(dynAcc, new SearchResult(str, mainStr, SearchResult.Types.ACCEPTATION, acc, dynAcc)); } } return map.valueList().toImmutable().sort((a, b) -> !a.isDynamic() && b.isDynamic() || a.isDynamic() == b.isDynamic() && SortUtils.compareCharSequenceByUnicode(a.getStr(), b.getStr())); } public static boolean isAcceptationInBunch(DbExporter.Database db, int bunch, int acceptation) { final LangbookDbSchema.BunchAcceptationsTable table = LangbookDbSchema.Tables.bunchAcceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getBunchColumnIndex(), bunch) .where(table.getAcceptationColumnIndex(), acceptation) .select(table.getIdColumnIndex()); try (DbResult result = db.select(query)) { return result.hasNext(); } } public static ImmutableList<ImmutablePair<String, String>> getConversion(DbExporter.Database db, ImmutableIntPair pair) { final LangbookDbSchema.ConversionsTable conversions = LangbookDbSchema.Tables.conversions; final LangbookDbSchema.SymbolArraysTable symbols = LangbookDbSchema.Tables.symbolArrays; final int off1Symbols = conversions.columns().size(); final int off2Symbols = off1Symbols + symbols.columns().size(); final DbQuery query = new DbQuery.Builder(conversions) .join(symbols, conversions.getSourceColumnIndex(), symbols.getIdColumnIndex()) .join(symbols, conversions.getTargetColumnIndex(), symbols.getIdColumnIndex()) .where(conversions.getSourceAlphabetColumnIndex(), pair.left) .where(conversions.getTargetAlphabetColumnIndex(), pair.right) .select( off1Symbols + symbols.getStrColumnIndex(), off2Symbols + symbols.getStrColumnIndex()); final ImmutableList.Builder<ImmutablePair<String, String>> builder = new ImmutableList.Builder<>(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); final String sourceText = row.get(0).toText(); final String targetText = row.get(1).toText(); builder.add(new ImmutablePair<>(sourceText, targetText)); } } return builder.build(); } public static Integer findBunchSet(DbExporter.Database db, IntSet bunches) { final LangbookDbSchema.BunchSetsTable table = LangbookDbSchema.Tables.bunchSets; if (bunches.isEmpty()) { return table.nullReference(); } final DbQuery query = new DbQuery.Builder(table) .join(table, table.getSetIdColumnIndex(), table.getSetIdColumnIndex()) .where(table.getBunchColumnIndex(), bunches.valueAt(0)) .select(table.getSetIdColumnIndex(), table.columns().size() + table.getBunchColumnIndex()); final DbResult result = db.select(query); try { if (result.hasNext()) { List<DbValue> row = result.next(); final HashSet<Integer> set = new HashSet<>(); int setId = row.get(0).toInt(); set.add(row.get(1).toInt()); while (result.hasNext()) { row = result.next(); if (row.get(0).toInt() != setId) { if (set.equals(bunches)) { return setId; } setId = row.get(0).toInt(); set.clear(); set.add(row.get(1).toInt()); } } if (set.equals(bunches)) { return setId; } } } finally { result.close(); } return null; } public static Integer findAgentSet(DbExporter.Database db, IntSet agentSet) { if (agentSet.isEmpty()) { return 0; } final ImmutableIntSet set = agentSet.toImmutable(); final LangbookDbSchema.AgentSetsTable table = LangbookDbSchema.Tables.agentSets; final DbQuery query = new DbQuery.Builder(table) .join(table, table.getSetIdColumnIndex(), table.getSetIdColumnIndex()) .where(table.getAgentColumnIndex(), set.valueAt(0)) .select(table.getSetIdColumnIndex(), table.columns().size() + table.getAgentColumnIndex()); final DbResult result = db.select(query); try { if (result.hasNext()) { List<DbValue> row = result.next(); int setId = row.get(0).toInt(); ImmutableIntSetBuilder builder = new ImmutableIntSetBuilder(); builder.add(row.get(1).toInt()); while (result.hasNext()) { row = result.next(); int newSetId = row.get(0).toInt(); if (newSetId != setId) { if (set.equals(builder.build())) { return setId; } setId = newSetId; builder = new ImmutableIntSetBuilder(); } builder.add(row.get(1).toInt()); } if (set.equals(builder.build())) { return setId; } } } finally { result.close(); } return null; } public static Integer findRuledConcept(DbExporter.Database db, int rule, int concept) { final LangbookDbSchema.RuledConceptsTable table = LangbookDbSchema.Tables.ruledConcepts; final DbQuery query = new DbQuery.Builder(table) .where(table.getRuleColumnIndex(), rule) .where(table.getConceptColumnIndex(), concept) .select(table.getIdColumnIndex()); try (DbResult result = db.select(query)) { final Integer id = result.hasNext()? result.next().get(0).toInt() : null; if (result.hasNext()) { throw new AssertionError("There should not be repeated ruled concepts"); } return id; } } public static Integer findQuizDefinition(DbExporter.Database db, int bunch, int setId) { final LangbookDbSchema.QuizDefinitionsTable table = LangbookDbSchema.Tables.quizDefinitions; final DbQuery query = new DbQuery.Builder(table) .where(table.getBunchColumnIndex(), bunch) .where(table.getQuestionFieldsColumnIndex(), setId) .select(table.getIdColumnIndex()); try (DbResult result = db.select(query)) { final Integer value = result.hasNext()? result.next().get(0).toInt() : null; if (result.hasNext()) { throw new AssertionError("Only one quiz definition expected"); } return value; } } public static ImmutableIntSet findAffectedAgentsByItsSource(DbExporter.Database db, int bunch) { if (bunch == 0) { return new ImmutableIntSetBuilder().build(); } final LangbookDbSchema.BunchSetsTable bunchSets = LangbookDbSchema.Tables.bunchSets; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(bunchSets) .join(agents, bunchSets.getSetIdColumnIndex(), agents.getSourceBunchSetColumnIndex()) .where(bunchSets.getBunchColumnIndex(), bunch) .select(bunchSets.columns().size() + agents.getIdColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntPairMap findAffectedAgentsByItsSourceWithTarget(DbExporter.Database db, int bunch) { if (bunch == 0) { return ImmutableIntPairMap.empty(); } final LangbookDbSchema.BunchSetsTable bunchSets = LangbookDbSchema.Tables.bunchSets; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final int offset = bunchSets.columns().size(); final DbQuery query = new DbQuery.Builder(bunchSets) .join(agents, bunchSets.getSetIdColumnIndex(), agents.getSourceBunchSetColumnIndex()) .where(bunchSets.getBunchColumnIndex(), bunch) .select(offset + agents.getIdColumnIndex(), offset + agents.getTargetBunchColumnIndex()); final ImmutableIntPairMap.Builder builder = new ImmutableIntPairMap.Builder(); try (DbResult result = db.select(query)) { while (result.hasNext()) { List<DbValue> row = result.next(); builder.put(row.get(0).toInt(), row.get(1).toInt()); } } return builder.build(); } public static ImmutableIntSet findAffectedAgentsByItsDiff(DbExporter.Database db, int bunch) { if (bunch == 0) { return new ImmutableIntSetBuilder().build(); } final LangbookDbSchema.BunchSetsTable bunchSets = LangbookDbSchema.Tables.bunchSets; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(bunchSets) .join(agents, bunchSets.getSetIdColumnIndex(), agents.getDiffBunchSetColumnIndex()) .where(bunchSets.getBunchColumnIndex(), bunch) .select(bunchSets.columns().size() + agents.getIdColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntPairMap findAffectedAgentsByItsDiffWithTarget(DbExporter.Database db, int bunch) { if (bunch == 0) { return ImmutableIntPairMap.empty(); } final LangbookDbSchema.BunchSetsTable bunchSets = LangbookDbSchema.Tables.bunchSets; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final int offset = bunchSets.columns().size(); final DbQuery query = new DbQuery.Builder(bunchSets) .join(agents, bunchSets.getSetIdColumnIndex(), agents.getDiffBunchSetColumnIndex()) .where(bunchSets.getBunchColumnIndex(), bunch) .select(offset + agents.getIdColumnIndex(), offset + agents.getTargetBunchColumnIndex()); final ImmutableIntPairMap.Builder builder = new ImmutableIntPairMap.Builder(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); builder.put(row.get(0).toInt(), row.get(1).toInt()); } } return builder.build(); } public static ImmutableIntSet findAgentsWithoutSourceBunches(DbExporter.Database db) { final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(agents) .where(agents.getSourceBunchSetColumnIndex(), 0) .select(agents.getIdColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntPairMap findAgentsWithoutSourceBunchesWithTarget(DbExporter.Database db) { final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(agents) .where(agents.getSourceBunchSetColumnIndex(), 0) .select(agents.getIdColumnIndex(), agents.getTargetBunchColumnIndex()); final ImmutableIntPairMap.Builder builder = new ImmutableIntPairMap.Builder(); try (DbResult result = db.select(query)) { while (result.hasNext()) { List<DbValue> row = result.next(); builder.put(row.get(0).toInt(), row.get(1).toInt()); } } return builder.build(); } public static ImmutableIntSet findAffectedAgentsByAcceptationCorrelationModification(DbExporter.Database db, int acceptation) { final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final LangbookDbSchema.BunchSetsTable bunchSets = LangbookDbSchema.Tables.bunchSets; final LangbookDbSchema.BunchAcceptationsTable bunchAcceptations = LangbookDbSchema.Tables.bunchAcceptations; final int bunchSetOffset = agents.columns().size(); final int bunchAccOffset = bunchSetOffset + bunchSets.columns().size(); final DbQuery query = new DbQuery.Builder(agents) .join(bunchSets, agents.getSourceBunchSetColumnIndex(), bunchSets.getSetIdColumnIndex()) .join(bunchAcceptations, bunchSetOffset + bunchSets.getBunchColumnIndex(), bunchAcceptations.getBunchColumnIndex()) .where(bunchAccOffset + bunchAcceptations.getAgentSetColumnIndex(), 0) .where(bunchAccOffset + bunchAcceptations.getAcceptationColumnIndex(), acceptation) .select(agents.getIdColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntSet findQuizzesByBunch(DbExporter.Database db, int bunch) { final LangbookDbSchema.QuizDefinitionsTable quizzes = LangbookDbSchema.Tables.quizDefinitions; final DbQuery query = new DbQuery.Builder(quizzes) .where(quizzes.getBunchColumnIndex(), bunch) .select(quizzes.getIdColumnIndex()); return intSetQuery(db, query); } public static Integer findQuestionFieldSet(DbExporter.Database db, Iterable<QuestionFieldDetails> collection) { final Set<QuestionFieldDetails> set = new HashSet<>(); if (collection == null) { return null; } for (QuestionFieldDetails field : collection) { set.add(field); } if (set.size() == 0) { return null; } final QuestionFieldDetails firstField = set.iterator().next(); final LangbookDbSchema.QuestionFieldSets fieldSets = LangbookDbSchema.Tables.questionFieldSets; final int columnCount = fieldSets.columns().size(); final DbQuery query = new DbQuery.Builder(fieldSets) .join(fieldSets, fieldSets.getSetIdColumnIndex(), fieldSets.getSetIdColumnIndex()) .where(fieldSets.getAlphabetColumnIndex(), firstField.alphabet) .where(fieldSets.getRuleColumnIndex(), firstField.rule) .where(fieldSets.getFlagsColumnIndex(), firstField.flags) .select( fieldSets.getSetIdColumnIndex(), columnCount + fieldSets.getAlphabetColumnIndex(), columnCount + fieldSets.getRuleColumnIndex(), columnCount + fieldSets.getFlagsColumnIndex()); try (DbResult result = db.select(query)) { if (result.hasNext()) { List<DbValue> row = result.next(); int setId = row.get(0).toInt(); final Set<QuestionFieldDetails> foundSet = new HashSet<>(); foundSet.add(new QuestionFieldDetails(row.get(1).toInt(), row.get(2).toInt(), row.get(3).toInt())); while (result.hasNext()) { row = result.next(); if (setId != row.get(0).toInt()) { if (foundSet.equals(set)) { return setId; } else { foundSet.clear(); setId = row.get(0).toInt(); } } foundSet.add(new QuestionFieldDetails(row.get(1).toInt(), row.get(2).toInt(), row.get(3).toInt())); } if (foundSet.equals(set)) { return setId; } } } return null; } public static Integer findSearchHistoryEntry(DbExporter.Database db, int acceptation) { final LangbookDbSchema.SearchHistoryTable table = LangbookDbSchema.Tables.searchHistory; final DbQuery query = new DbQuery.Builder(table) .where(table.getAcceptation(), acceptation) .select(table.getIdColumnIndex()); try (DbResult result = db.select(query)) { final Integer id = result.hasNext()? result.next().get(0).toInt() : null; if (result.hasNext()) { throw new AssertionError(); } return id; } } public static ImmutableIntPairMap findConversions(DbExporter.Database db, IntSet alphabets) { final LangbookDbSchema.ConversionsTable conversions = LangbookDbSchema.Tables.conversions; final DbQuery query = new DbQuery.Builder(conversions) .groupBy(conversions.getSourceAlphabetColumnIndex(), conversions.getTargetAlphabetColumnIndex()) .select( conversions.getSourceAlphabetColumnIndex(), conversions.getTargetAlphabetColumnIndex()); final MutableIntSet foundAlphabets = MutableIntSet.empty(); final ImmutableIntPairMap.Builder builder = new ImmutableIntPairMap.Builder(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int source = row.get(0).toInt(); final int target = row.get(1).toInt(); if (foundAlphabets.contains(target)) { throw new AssertionError(); } foundAlphabets.add(target); if (alphabets.contains(target)) { if (!alphabets.contains(source)) { throw new AssertionError(); } builder.put(target, source); } } } return builder.build(); } public static ImmutableIntSet findSentenceIdsMatchingMeaning(DbExporter.Database db, int symbolArrayId) { final LangbookDbSchema.SentenceMeaningTable table = LangbookDbSchema.Tables.sentenceMeaning; final int offset = table.columns().size(); final DbQuery query = new DbQuery.Builder(table) .join(table, table.getMeaning(), table.getMeaning()) .where(table.getIdColumnIndex(), symbolArrayId) .whereColumnValueDiffer(table.getIdColumnIndex(), offset + table.getIdColumnIndex()) .select(offset + table.getIdColumnIndex()); return db.select(query).mapToInt(row -> row.get(0).toInt()).toSet().toImmutable(); } public static int getColumnMax(DbExporter.Database db, DbTable table, int columnIndex) { final DbQuery query = new DbQuery.Builder(table) .select(DbQuery.max(columnIndex)); final DbResult result = db.select(query); try { return result.hasNext()? result.next().get(0).toInt() : 0; } finally { result.close(); } } public static int getMaxCorrelationId(DbExporter.Database db) { final LangbookDbSchema.CorrelationsTable table = LangbookDbSchema.Tables.correlations; return getColumnMax(db, table, table.getCorrelationIdColumnIndex()); } public static int getMaxCorrelationArrayId(DbExporter.Database db) { final LangbookDbSchema.CorrelationArraysTable table = LangbookDbSchema.Tables.correlationArrays; return getColumnMax(db, table, table.getArrayIdColumnIndex()); } public static int getMaxConceptInAcceptations(DbExporter.Database db) { LangbookDbSchema.AcceptationsTable table = LangbookDbSchema.Tables.acceptations; return getColumnMax(db, table, table.getConceptColumnIndex()); } public static int getMaxConceptInRuledConcepts(DbExporter.Database db) { LangbookDbSchema.RuledConceptsTable table = LangbookDbSchema.Tables.ruledConcepts; return getColumnMax(db, table, table.getIdColumnIndex()); } public static int getMaxConcept(DbExporter.Database db) { int max = getMaxConceptInAcceptations(db); int temp = getMaxConceptInRuledConcepts(db); if (temp > max) { max = temp; } return max; } public static int getMaxBunchSetId(DbExporter.Database db) { final LangbookDbSchema.BunchSetsTable table = LangbookDbSchema.Tables.bunchSets; return getColumnMax(db, table, table.getSetIdColumnIndex()); } public static int getMaxAgentSetId(DbExporter.Database db) { final LangbookDbSchema.AgentSetsTable table = LangbookDbSchema.Tables.agentSets; return getColumnMax(db, table, table.getSetIdColumnIndex()); } public static int getMaxQuestionFieldSetId(DbExporter.Database db) { LangbookDbSchema.QuestionFieldSets table = LangbookDbSchema.Tables.questionFieldSets; return getColumnMax(db, table, table.getSetIdColumnIndex()); } public static int getMaxSentenceMeaning(DbExporter.Database db) { LangbookDbSchema.SentenceMeaningTable table = LangbookDbSchema.Tables.sentenceMeaning; return getColumnMax(db, table, table.getMeaning()); } public static String getSymbolArray(DbExporter.Database db, int id) { final LangbookDbSchema.SymbolArraysTable table = LangbookDbSchema.Tables.symbolArrays; final DbQuery query = new DbQuery.Builder(table) .where(table.getIdColumnIndex(), id) .select(table.getStrColumnIndex()); final DbResult result = db.select(query); try { final String str = result.hasNext()? result.next().get(0).toText() : null; if (result.hasNext()) { throw new AssertionError("There should not be repeated identifiers"); } return str; } finally { result.close(); } } public static ImmutableIntPairMap getCorrelation(DbExporter.Database db, int id) { LangbookDbSchema.CorrelationsTable table = LangbookDbSchema.Tables.correlations; final DbQuery query = new DbQuery.Builder(table) .where(table.getCorrelationIdColumnIndex(), id) .select(table.getAlphabetColumnIndex(), table.getSymbolArrayColumnIndex()); ImmutableIntPairMap.Builder corrBuilder = new ImmutableIntPairMap.Builder(); final DbResult result = db.select(query); try { while (result.hasNext()) { final List<DbValue> row = result.next(); corrBuilder.put(row.get(0).toInt(), row.get(1).toInt()); } } finally { result.close(); } return corrBuilder.build(); } public static ImmutableIntKeyMap<String> getCorrelationWithText(DbExporter.Database db, int correlationId) { final LangbookDbSchema.CorrelationsTable correlations = LangbookDbSchema.Tables.correlations; final LangbookDbSchema.SymbolArraysTable symbolArrays = LangbookDbSchema.Tables.symbolArrays; final DbQuery query = new DbQuery.Builder(correlations) .join(symbolArrays, correlations.getSymbolArrayColumnIndex(), symbolArrays.getIdColumnIndex()) .where(correlations.getCorrelationIdColumnIndex(), correlationId) .select(correlations.getAlphabetColumnIndex(), correlations.columns().size() + symbolArrays.getStrColumnIndex()); final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); builder.put(row.get(0).toInt(), row.get(1).toText()); } } return builder.build(); } public static int[] getCorrelationArray(DbExporter.Database db, int id) { if (id == StreamedDatabaseConstants.nullCorrelationArrayId) { return new int[0]; } LangbookDbSchema.CorrelationArraysTable table = LangbookDbSchema.Tables.correlationArrays; final DbQuery query = new DbQuery.Builder(table) .where(table.getArrayIdColumnIndex(), id) .select(table.getArrayPositionColumnIndex(), table.getCorrelationColumnIndex()); final DbResult dbResult = db.select(query); final int[] result = new int[dbResult.getRemainingRows()]; try { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int pos = row.get(0).toInt(); final int corr = row.get(1).toInt(); if (result[pos] != 0) { throw new AssertionError("Malformed correlation array with id " + id); } result[pos] = corr; } } finally { dbResult.close(); } return result; } public static ImmutableIntPairMap getAcceptationsAndAgentSetsInBunch(DbExporter.Database db, int bunch) { final LangbookDbSchema.BunchAcceptationsTable table = LangbookDbSchema.Tables.bunchAcceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getBunchColumnIndex(), bunch) .select(table.getAcceptationColumnIndex(), table.getAgentSetColumnIndex()); final ImmutableIntPairMap.Builder builder = new ImmutableIntPairMap.Builder(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); builder.put(row.get(0).toInt(), row.get(1).toInt()); } } return builder.build(); } public static ImmutablePair<ImmutableIntList, ImmutableIntKeyMap<ImmutableIntKeyMap<String>>> getAcceptationCorrelations(DbExporter.Database db, int acceptation) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.CorrelationArraysTable correlationArrays = LangbookDbSchema.Tables.correlationArrays; final LangbookDbSchema.CorrelationsTable correlations = LangbookDbSchema.Tables.correlations; final LangbookDbSchema.SymbolArraysTable symbols = LangbookDbSchema.Tables.symbolArrays; final int corrArraysOffset = acceptations.columns().size(); final int corrOffset = corrArraysOffset + correlationArrays.columns().size(); final int symbolsOffset = corrOffset + correlations.columns().size(); final DbQuery query = new DbQuery.Builder(acceptations) .join(correlationArrays, acceptations.getCorrelationArrayColumnIndex(), correlationArrays.getArrayIdColumnIndex()) .join(correlations, corrArraysOffset + correlationArrays.getCorrelationColumnIndex(), correlations.getCorrelationIdColumnIndex()) .join(symbols, corrOffset + correlations.getSymbolArrayColumnIndex(), symbols.getIdColumnIndex()) .where(acceptations.getIdColumnIndex(), acceptation) .orderBy( corrArraysOffset + correlationArrays.getArrayPositionColumnIndex(), corrOffset + correlations.getAlphabetColumnIndex()) .select( corrArraysOffset + correlationArrays.getArrayPositionColumnIndex(), corrOffset + correlations.getCorrelationIdColumnIndex(), corrOffset + correlations.getAlphabetColumnIndex(), symbolsOffset + symbols.getStrColumnIndex() ); final MutableIntList correlationIds = MutableIntList.empty(); final MutableIntKeyMap<ImmutableIntKeyMap<String>> correlationMap = MutableIntKeyMap.empty(); try (DbResult dbResult = db.select(query)) { if (dbResult.hasNext()) { List<DbValue> row = dbResult.next(); ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); int pos = row.get(0).toInt(); int correlationId = row.get(1).toInt(); if (pos != correlationIds.size()) { throw new AssertionError("Expected position " + correlationIds.size() + ", but it was " + pos); } builder.put(row.get(2).toInt(), row.get(3).toText()); while (dbResult.hasNext()) { row = dbResult.next(); int newPos = row.get(0).toInt(); if (newPos != pos) { correlationMap.put(correlationId, builder.build()); correlationIds.append(correlationId); correlationId = row.get(1).toInt(); builder = new ImmutableIntKeyMap.Builder<>(); pos = newPos; } if (newPos != correlationIds.size()) { throw new AssertionError("Expected position " + correlationIds.size() + ", but it was " + pos); } builder.put(row.get(2).toInt(), row.get(3).toText()); } correlationMap.put(correlationId, builder.build()); correlationIds.append(correlationId); } } return new ImmutablePair<>(correlationIds.toImmutable(), correlationMap.toImmutable()); } public static ImmutableIntSet getBunchSet(DbExporter.Database db, int setId) { final LangbookDbSchema.BunchSetsTable table = LangbookDbSchema.Tables.bunchSets; final DbQuery query = new DbQuery.Builder(table) .where(table.getSetIdColumnIndex(), setId) .select(table.getBunchColumnIndex()); return intSetQuery(db, query); } public static ImmutableList<SearchResult> getSearchHistory(DbExporter.Database db) { final LangbookDbSchema.SearchHistoryTable history = LangbookDbSchema.Tables.searchHistory; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int offset = history.columns().size(); final DbQuery query = new DbQuery.Builder(history) .join(strings, history.getAcceptation(), strings.getDynamicAcceptationColumnIndex()) .orderBy(new DbQuery.Ordered(history.getIdColumnIndex(), true)) .select(history.getAcceptation(), offset + strings.getMainAcceptationColumnIndex(), offset + strings.getStringColumnIndex(), offset + strings.getMainStringColumnIndex()); final MutableIntSet acceptations = MutableIntSet.empty(); final ImmutableList.Builder<SearchResult> builder = new ImmutableList.Builder<>(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); final int acceptation = row.get(0).toInt(); if (!acceptations.contains(acceptation)) { acceptations.add(acceptation); builder.add(new SearchResult(row.get(2).toText(), row.get(3).toText(), SearchResult.Types.ACCEPTATION, row.get(1).toInt(), acceptation)); } } } return builder.build(); } public static Integer getSentenceMeaning(DbExporter.Database db, int symbolArrayId) { final LangbookDbSchema.SentenceMeaningTable table = LangbookDbSchema.Tables.sentenceMeaning; final DbQuery query = new DbQuery.Builder(table) .where(table.getIdColumnIndex(), symbolArrayId) .select(table.getMeaning()); Integer result = null; try (DbResult dbResult = db.select(query)) { if (dbResult.hasNext()) { result = dbResult.next().get(0).toInt(); } if (dbResult.hasNext()) { throw new AssertionError(); } } return result; } private static ImmutableIntKeyMap<String> readAcceptationsIncludingCorrelation(DbExporter.Database db, int correlation, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.CorrelationArraysTable correlationArrays = LangbookDbSchema.Tables.correlationArrays; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int accOffset = correlationArrays.columns().size(); final int strOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(correlationArrays) .join(acceptations, correlationArrays.getArrayIdColumnIndex(), acceptations.getCorrelationArrayColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(correlationArrays.getCorrelationColumnIndex(), correlation) .select(accOffset + acceptations.getIdColumnIndex(), strOffset + strings.getStringAlphabetColumnIndex(), strOffset + strings.getStringColumnIndex()); final MutableIntKeyMap<String> result = MutableIntKeyMap.empty(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int accId = row.get(0).toInt(); if (row.get(1).toInt() == preferredAlphabet || result.get(accId, null) == null) { result.put(accId, row.get(2).toText()); } } } return result.toImmutable(); } private static ImmutableIntKeyMap<ImmutableIntKeyMap<String>> readCorrelationsWithSameSymbolArray(DbExporter.Database db, int correlation, int alphabet) { final LangbookDbSchema.CorrelationsTable correlations = LangbookDbSchema.Tables.correlations; final LangbookDbSchema.SymbolArraysTable symbolArrays = LangbookDbSchema.Tables.symbolArrays; final int corrOffset2 = correlations.columns().size(); final int corrOffset3 = corrOffset2 + corrOffset2; final int strOffset = corrOffset3 + corrOffset2; final DbQuery query = new DbQuery.Builder(correlations) .join(correlations, correlations.getSymbolArrayColumnIndex(), correlations.getSymbolArrayColumnIndex()) .join(correlations, corrOffset2 + correlations.getCorrelationIdColumnIndex(), correlations.getCorrelationIdColumnIndex()) .join(symbolArrays, corrOffset3 + correlations.getSymbolArrayColumnIndex(), symbolArrays.getIdColumnIndex()) .where(correlations.getCorrelationIdColumnIndex(), correlation) .where(correlations.getAlphabetColumnIndex(), alphabet) .whereColumnValueMatch(correlations.getAlphabetColumnIndex(), corrOffset2 + correlations.getAlphabetColumnIndex()) .whereColumnValueDiffer(correlations.getCorrelationIdColumnIndex(), corrOffset2 + correlations.getCorrelationIdColumnIndex()) .select(corrOffset2 + correlations.getCorrelationIdColumnIndex(), corrOffset3 + correlations.getAlphabetColumnIndex(), strOffset + symbolArrays.getStrColumnIndex()); final MutableIntKeyMap<ImmutableIntKeyMap<String>> result = MutableIntKeyMap.empty(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int corrId = row.get(0).toInt(); final int textAlphabet = row.get(1).toInt(); final String text = row.get(2).toText(); final ImmutableIntKeyMap<String> currentCorr = result.get(corrId, ImmutableIntKeyMap.empty()); result.put(corrId, currentCorr.put(textAlphabet, text)); } } return result.toImmutable(); } public static int conceptFromAcceptation(DbExporter.Database db, int accId) { final LangbookDbSchema.AcceptationsTable table = LangbookDbSchema.Tables.acceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getIdColumnIndex(), accId) .select(table.getConceptColumnIndex()); return selectSingleRow(db, query).get(0).toInt(); } static MutableIntKeyMap<String> readCorrelationArrayTexts(DbExporter.Database db, int correlationArrayId) { MutableIntKeyMap<String> texts = MutableIntKeyMap.empty(); for (int correlationId : getCorrelationArray(db, correlationArrayId)) { for (IntKeyMap.Entry<String> entry : getCorrelationWithText(db, correlationId).entries()) { final String currentValue = texts.get(entry.key(), ""); texts.put(entry.key(), currentValue + entry.value()); } } return texts; } static IntKeyMap<String> readCorrelationArrayTextAndItsAppliedConversions(DbExporter.Database db, int correlationArrayId) { final MutableIntKeyMap<String> texts = readCorrelationArrayTexts(db, correlationArrayId); if (texts.isEmpty()) { return null; } final ImmutableSet<ImmutableIntPair> conversions = findConversions(db); for (IntKeyMap.Entry<String> entry : texts.entries().toImmutable()) { for (ImmutableIntPair pair : conversions) { if (pair.left == entry.key()) { final ImmutableList<ImmutablePair<String, String>> conversion = getConversion(db, pair); final String convertedText = convertText(conversion, entry.value()); if (convertedText == null) { return null; } texts.put(pair.right, convertedText); } } } return texts; } public static final class IdentifiableResult { final int id; final String text; IdentifiableResult(int id, String text) { this.id = id; this.text = text; } } public static final class DynamizableResult { final int id; final boolean dynamic; final String text; DynamizableResult(int id, boolean dynamic, String text) { this.id = id; this.dynamic = dynamic; this.text = text; } } public static final class MorphologyResult { final int agent; final int dynamicAcceptation; final int rule; final String ruleText; final String text; MorphologyResult(int agent, int dynamicAcceptation, int rule, String ruleText, String text) { this.agent = agent; this.dynamicAcceptation = dynamicAcceptation; this.rule = rule; this.ruleText = ruleText; this.text = text; } } public static final class SynonymTranslationResult { final int language; final String text; SynonymTranslationResult(int language, String text) { if (text == null) { throw new IllegalArgumentException(); } this.language = language; this.text = text; } } private static ImmutableIntKeyMap<SynonymTranslationResult> readAcceptationSynonymsAndTranslations(DbExporter.Database db, int acceptation) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.AlphabetsTable alphabets = LangbookDbSchema.Tables.alphabets; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final LangbookDbSchema.LanguagesTable languages = LangbookDbSchema.Tables.languages; final int accOffset = acceptations.columns().size(); final int stringsOffset = accOffset * 2; final int alphabetsOffset = stringsOffset + strings.columns().size(); final int languagesOffset = alphabetsOffset + alphabets.columns().size(); final DbQuery query = new DbQuery.Builder(acceptations) .join(acceptations, acceptations.getConceptColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .join(alphabets, stringsOffset + strings.getStringAlphabetColumnIndex(), alphabets.getIdColumnIndex()) .join(languages, alphabetsOffset + alphabets.getLanguageColumnIndex(), languages.getIdColumnIndex()) .where(acceptations.getIdColumnIndex(), acceptation) .whereColumnValueMatch(alphabetsOffset + alphabets.getIdColumnIndex(), languagesOffset + languages.getMainAlphabetColumnIndex()) .select(accOffset + acceptations.getIdColumnIndex(), languagesOffset + languages.getIdColumnIndex(), stringsOffset + strings.getStringColumnIndex()); final ImmutableIntKeyMap.Builder<SynonymTranslationResult> builder = new ImmutableIntKeyMap.Builder<>(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); final int accId = row.get(0).toInt(); if (accId != acceptation) { builder.put(accId, new SynonymTranslationResult(row.get(1).toInt(), row.get(2).toText())); } } } return builder.build(); } private static IdentifiableResult readSupertypeFromAcceptation(DbExporter.Database db, int acceptation, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.BunchConceptsTable bunchConcepts = LangbookDbSchema.Tables.bunchConcepts; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int bunchOffset = acceptations.columns().size(); final int accOffset = bunchOffset + bunchConcepts.columns().size(); final int strOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(acceptations) .join(bunchConcepts, acceptations.getConceptColumnIndex(), bunchConcepts.getConceptColumnIndex()) .join(acceptations, bunchOffset + bunchConcepts.getBunchColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(acceptations.getIdColumnIndex(), acceptation) .select(accOffset + acceptations.getIdColumnIndex(), strOffset + strings.getStringAlphabetColumnIndex(), strOffset + strings.getStringColumnIndex()); IdentifiableResult result = null; try (DbResult dbResult = db.select(query)) { if (dbResult.hasNext()) { List<DbValue> row = dbResult.next(); int acc = row.get(0).toInt(); int firstAlphabet = row.get(1).toInt(); String text = row.get(2).toText(); while (firstAlphabet != preferredAlphabet && dbResult.hasNext()) { row = dbResult.next(); if (row.get(1).toInt() == preferredAlphabet) { acc = row.get(0).toInt(); text = row.get(2).toText(); break; } } result = new IdentifiableResult(acc, text); } } return result; } private static ImmutableIntKeyMap<String> readSubtypesFromAcceptation(DbExporter.Database db, int acceptation, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.BunchConceptsTable bunchConcepts = LangbookDbSchema.Tables.bunchConcepts; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int bunchOffset = acceptations.columns().size(); final int accOffset = bunchOffset + bunchConcepts.columns().size(); final int strOffset = accOffset + bunchOffset; final DbQuery query = new DbQuery.Builder(acceptations) .join(bunchConcepts, acceptations.getConceptColumnIndex(), bunchConcepts.getBunchColumnIndex()) .join(acceptations, bunchOffset + bunchConcepts.getConceptColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(acceptations.getIdColumnIndex(), acceptation) .select(bunchOffset + bunchConcepts.getConceptColumnIndex(), accOffset + acceptations.getIdColumnIndex(), strOffset + strings.getStringAlphabetColumnIndex(), strOffset + strings.getStringColumnIndex()); final MutableIntKeyMap<String> conceptText = MutableIntKeyMap.empty(); final MutableIntPairMap conceptAccs = MutableIntPairMap.empty(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int concept = row.get(0).toInt(); final int alphabet = row.get(2).toInt(); if (alphabet == preferredAlphabet || !conceptAccs.keySet().contains(concept)) { conceptAccs.put(concept, row.get(1).toInt()); conceptText.put(concept, row.get(3).toText()); } } } final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); final int length = conceptAccs.size(); for (int i = 0; i < length; i++) { builder.put(conceptAccs.valueAt(i), conceptText.valueAt(i)); } return builder.build(); } private static ImmutableList<MorphologyResult> readMorphologiesFromAcceptation(DbExporter.Database db, int acceptation, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final LangbookDbSchema.RuledAcceptationsTable ruledAcceptations = LangbookDbSchema.Tables.ruledAcceptations; final int strOffset1 = ruledAcceptations.columns().size(); final int agentsOffset = strOffset1 + strings.columns().size(); final int accOffset = agentsOffset + agents.columns().size(); final int strOffset2 = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(ruledAcceptations) .join(strings, ruledAcceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .join(agents, ruledAcceptations.getAgentColumnIndex(), agents.getIdColumnIndex()) .join(acceptations, agentsOffset + agents.getRuleColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(ruledAcceptations.getAcceptationColumnIndex(), acceptation) .select(ruledAcceptations.getIdColumnIndex(), accOffset + acceptations.getConceptColumnIndex(), strOffset1 + strings.getStringAlphabetColumnIndex(), strOffset1 + strings.getStringColumnIndex(), strOffset2 + strings.getStringAlphabetColumnIndex(), strOffset2 + strings.getStringColumnIndex(), agentsOffset + agents.getIdColumnIndex()); final MutableIntKeyMap<String> texts = MutableIntKeyMap.empty(); final MutableIntKeyMap<String> ruleTexts = MutableIntKeyMap.empty(); final MutableIntPairMap ruleAgents = MutableIntPairMap.empty(); final MutableIntPairMap ruledAccs = MutableIntPairMap.empty(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int acc = row.get(0).toInt(); final int rule = row.get(1).toInt(); final int alphabet = row.get(2).toInt(); final String text = row.get(3).toText(); final int ruleAlphabet = row.get(4).toInt(); final String ruleText = row.get(5).toText(); final int agent = row.get(6).toInt(); if (!ruleTexts.keySet().contains(rule)) { ruleTexts.put(rule, ruleText); texts.put(rule, text); ruleAgents.put(rule, agent); ruledAccs.put(rule, acc); } else { if (ruleAlphabet == preferredAlphabet) { ruleTexts.put(rule, ruleText); } if (alphabet == preferredAlphabet) { texts.put(rule, text); } } } } final ImmutableList.Builder<MorphologyResult> builder = new ImmutableList.Builder<>(); final int length = ruleAgents.size(); for (int i = 0; i < length; i++) { builder.add(new MorphologyResult(ruleAgents.valueAt(i), ruledAccs.valueAt(i), ruleAgents.keyAt(i), ruleTexts.valueAt(i), texts.valueAt(i))); } return builder.build(); } private static ImmutableIntSet intSetQuery(DbExporter.Database db, DbQuery query) { final ImmutableIntSetBuilder builder = new ImmutableIntSetBuilder(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { builder.add(dbResult.next().get(0).toInt()); } } return builder.build(); } private static ImmutableIntSet readAgentsWhereAcceptationIsTarget(DbExporter.Database db, int staticAcceptation) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(acceptations) .join(agents, acceptations.getConceptColumnIndex(), agents.getTargetBunchColumnIndex()) .where(acceptations.getIdColumnIndex(), staticAcceptation) .select(acceptations.columns().size() + agents.getIdColumnIndex()); return intSetQuery(db, query); } private static ImmutableIntSet readAgentsWhereAcceptationIsSource(DbExporter.Database db, int staticAcceptation) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final LangbookDbSchema.BunchSetsTable bunchSets = LangbookDbSchema.Tables.bunchSets; final int bunchSetsOffset = acceptations.columns().size(); final int agentsOffset = bunchSetsOffset + bunchSets.getSetIdColumnIndex(); final DbQuery query = new DbQuery.Builder(acceptations) .join(bunchSets, acceptations.getConceptColumnIndex(), bunchSets.getBunchColumnIndex()) .join(agents, bunchSetsOffset + bunchSets.getSetIdColumnIndex(), agents.getSourceBunchSetColumnIndex()) .where(acceptations.getIdColumnIndex(), staticAcceptation) .select(agentsOffset + agents.getIdColumnIndex()); return intSetQuery(db, query); } private static ImmutableIntSet readAgentsWhereAcceptationIsRule(DbExporter.Database db, int staticAcceptation) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(acceptations) .join(agents, acceptations.getConceptColumnIndex(), agents.getRuleColumnIndex()) .where(acceptations.getIdColumnIndex(), staticAcceptation) .select(acceptations.columns().size() + agents.getIdColumnIndex()); return intSetQuery(db, query); } private static ImmutableIntSet readAgentsWhereAcceptationIsProcessed(DbExporter.Database db, int staticAcceptation) { final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final LangbookDbSchema.BunchAcceptationsTable bunchAcceptations = LangbookDbSchema.Tables.bunchAcceptations; final LangbookDbSchema.AgentSetsTable agentSets = LangbookDbSchema.Tables.agentSets; final DbQuery query = new DbQuery.Builder(bunchAcceptations) .join(agentSets, bunchAcceptations.getAgentSetColumnIndex(), agentSets.getSetIdColumnIndex()) .where(bunchAcceptations.getAcceptationColumnIndex(), staticAcceptation) .select(bunchAcceptations.columns().size() + agentSets.getAgentColumnIndex()); return intSetQuery(db, query).remove(agents.nullReference()); } public interface InvolvedAgentResultFlags { int target = 1; int source = 2; int diff = 4; int rule = 8; int processed = 16; } /** * Return information about all agents involved with the given acceptation. * @param db Readable database to be used * @param staticAcceptation Identifier for the acceptation to analyze. * @return a map whose keys are agent identifier and values are flags. Flags should match the values at {@link InvolvedAgentResultFlags} */ private static ImmutableIntPairMap readAcceptationInvolvedAgents(DbExporter.Database db, int staticAcceptation) { final MutableIntPairMap flags = MutableIntPairMap.empty(); for (int agentId : readAgentsWhereAcceptationIsTarget(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId, 0) | InvolvedAgentResultFlags.target); } for (int agentId : readAgentsWhereAcceptationIsSource(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId, 0) | InvolvedAgentResultFlags.source); } // TODO: Diff not implemented as right now it is impossible for (int agentId : readAgentsWhereAcceptationIsRule(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId, 0) | InvolvedAgentResultFlags.rule); } for (int agentId : readAgentsWhereAcceptationIsProcessed(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId, 0) | InvolvedAgentResultFlags.processed); } return flags.toImmutable(); } public static IdentifiableResult readLanguageFromAlphabet(DbExporter.Database db, int alphabet, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.AlphabetsTable alphabets = LangbookDbSchema.Tables.alphabets; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int accOffset = alphabets.columns().size(); final int strOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(alphabets) .join(acceptations, alphabets.getLanguageColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(alphabets.getIdColumnIndex(), alphabet) .select( accOffset + acceptations.getConceptColumnIndex(), strOffset + strings.getStringAlphabetColumnIndex(), strOffset + strings.getStringColumnIndex() ); try (DbResult dbResult = db.select(query)) { if (dbResult.hasNext()) { List<DbValue> row = dbResult.next(); int lang = row.get(0).toInt(); int firstAlphabet = row.get(1).toInt(); String text = row.get(2).toText(); while (firstAlphabet != preferredAlphabet && dbResult.hasNext()) { row = dbResult.next(); if (row.get(1).toInt() == preferredAlphabet) { lang = row.get(0).toInt(); firstAlphabet = preferredAlphabet; text = row.get(2).toText(); } } return new IdentifiableResult(lang, text); } } throw new IllegalArgumentException("alphabet " + alphabet + " not found"); } public static ImmutablePair<ImmutableIntKeyMap<String>, Integer> readAcceptationTextsAndLanguage(DbExporter.Database db, int acceptation) { final LangbookDbSchema.StringQueriesTable table = LangbookDbSchema.Tables.stringQueries; final LangbookDbSchema.AlphabetsTable alphabetsTable = LangbookDbSchema.Tables.alphabets; final DbQuery query = new DbQuery.Builder(table) .join(alphabetsTable, table.getStringAlphabetColumnIndex(), alphabetsTable.getIdColumnIndex()) .where(table.getDynamicAcceptationColumnIndex(), acceptation) .select( table.getStringAlphabetColumnIndex(), table.getStringColumnIndex(), table.columns().size() + alphabetsTable.getLanguageColumnIndex()); final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); boolean languageSet = false; int language = 0; try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); final int alphabet = row.get(0).toInt(); final String text = row.get(1).toText(); if (!languageSet) { language = row.get(2).toInt(); languageSet = true; } else if (row.get(2).toInt() != language) { throw new AssertionError(); } builder.put(alphabet, text); } } return new ImmutablePair<>(builder.build(), language); } public static ImmutablePair<ImmutableIntKeyMap<String>, Integer> readAcceptationTextsAndMain(DbExporter.Database db, int acceptation) { final LangbookDbSchema.StringQueriesTable table = LangbookDbSchema.Tables.stringQueries; final DbQuery query = new DbQuery.Builder(table) .where(table.getDynamicAcceptationColumnIndex(), acceptation) .select( table.getStringAlphabetColumnIndex(), table.getStringColumnIndex(), table.getMainAcceptationColumnIndex()); final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); boolean mainAccSet = false; int mainAcc = 0; try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); final int alphabet = row.get(0).toInt(); final String text = row.get(1).toText(); if (!mainAccSet) { mainAcc = row.get(2).toInt(); mainAccSet = true; } else if (row.get(2).toInt() != mainAcc) { throw new AssertionError(); } builder.put(alphabet, text); } } return new ImmutablePair<>(builder.build(), mainAcc); } public static String readConceptText(DbExporter.Database db, int concept, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int j1Offset = acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(acceptations) .join(strings, acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(acceptations.getConceptColumnIndex(), concept) .select(j1Offset + strings.getStringAlphabetColumnIndex(), j1Offset + strings.getStringColumnIndex()); String text; try (DbResult result = db.select(query)) { List<DbValue> row = result.next(); int firstAlphabet = row.get(0).toInt(); text = row.get(1).toText(); while (firstAlphabet != preferredAlphabet && result.hasNext()) { row = result.next(); if (row.get(0).toInt() == preferredAlphabet) { firstAlphabet = preferredAlphabet; text = row.get(1).toText(); } } } return text; } public static DisplayableItem readConceptAcceptationAndText(DbExporter.Database db, int concept, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int j1Offset = acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(acceptations) .join(strings, acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(acceptations.getConceptColumnIndex(), concept) .select(j1Offset + strings.getStringAlphabetColumnIndex(), acceptations.getIdColumnIndex(), j1Offset + strings.getStringColumnIndex()); int acceptation; String text; try (DbResult result = db.select(query)) { List<DbValue> row = result.next(); int firstAlphabet = row.get(0).toInt(); acceptation = row.get(1).toInt(); text = row.get(2).toText(); while (firstAlphabet != preferredAlphabet && result.hasNext()) { row = result.next(); if (row.get(0).toInt() == preferredAlphabet) { firstAlphabet = preferredAlphabet; acceptation = row.get(1).toInt(); text = row.get(2).toText(); } } } return new DisplayableItem(acceptation, text); } public static ImmutableList<DisplayableItem> readBunchSetAcceptationsAndTexts(DbExporter.Database db, int bunchSet, int preferredAlphabet) { final LangbookDbSchema.BunchSetsTable bunchSets = LangbookDbSchema.Tables.bunchSets; final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int accOffset = bunchSets.columns().size(); final int stringsOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(bunchSets) .join(acceptations, bunchSets.getBunchColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(bunchSets.getSetIdColumnIndex(), bunchSet) .select( bunchSets.getBunchColumnIndex(), accOffset + acceptations.getIdColumnIndex(), stringsOffset + strings.getStringAlphabetColumnIndex(), stringsOffset + strings.getStringColumnIndex() ); ImmutableList.Builder<DisplayableItem> builder = new ImmutableList.Builder<>(); try (DbResult cursor = db.select(query)) { if (cursor.hasNext()) { List<DbValue> row = cursor.next(); int bunch = row.get(0).toInt(); int acc = row.get(1).toInt(); int alphabet = row.get(2).toInt(); String text = row.get(3).toText(); while (cursor.hasNext()) { row = cursor.next(); if (bunch == row.get(0).toInt()) { if (alphabet != preferredAlphabet && row.get(2).toInt() == preferredAlphabet) { acc = row.get(1).toInt(); text = row.get(3).toText(); alphabet = preferredAlphabet; } } else { builder.add(new DisplayableItem(acc, text)); bunch = row.get(0).toInt(); acc = row.get(1).toInt(); alphabet = row.get(2).toInt(); text = row.get(3).toText(); } } builder.add(new DisplayableItem(acc, text)); } } return builder.build(); } private static ImmutableList<DynamizableResult> readBunchesWhereAcceptationIsIncluded(DbExporter.Database db, int acceptation, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.BunchAcceptationsTable bunchAcceptations = LangbookDbSchema.Tables.bunchAcceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int accOffset = bunchAcceptations.columns().size(); final int strOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(bunchAcceptations) .join(acceptations, bunchAcceptations.getBunchColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(bunchAcceptations.getAcceptationColumnIndex(), acceptation) .select(bunchAcceptations.getBunchColumnIndex(), accOffset + acceptations.getIdColumnIndex(), strOffset + strings.getStringAlphabetColumnIndex(), strOffset + strings.getStringColumnIndex(), bunchAcceptations.getAgentSetColumnIndex()); final MutableIntKeyMap<DynamizableResult> resultMap = MutableIntKeyMap.empty(); try (DbResult dbResult = db.select(query)) { final int nullAgentSet = LangbookDbSchema.Tables.agentSets.nullReference(); while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int bunch = row.get(0).toInt(); final int alphabet = row.get(2).toInt(); if (alphabet == preferredAlphabet || !resultMap.keySet().contains(bunch)) { final int acc = row.get(1).toInt(); final String text = row.get(3).toText(); final int agentSet = row.get(4).toInt(); final boolean dynamic = agentSet != nullAgentSet; resultMap.put(bunch, new DynamizableResult(acc, dynamic, text)); } } } final ImmutableList.Builder<DynamizableResult> builder = new ImmutableList.Builder<>(); for (DynamizableResult r : resultMap) { builder.add(r); } return builder.build(); } private static ImmutableList<DynamizableResult> readAcceptationBunchChildren(DbExporter.Database db, int acceptation, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.BunchAcceptationsTable bunchAcceptations = LangbookDbSchema.Tables.bunchAcceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int bunchAccOffset = acceptations.columns().size(); final int strOffset = bunchAccOffset + bunchAcceptations.columns().size(); final DbQuery query = new DbQuery.Builder(acceptations) .join(bunchAcceptations, acceptations.getConceptColumnIndex(), bunchAcceptations.getBunchColumnIndex()) .join(strings, bunchAccOffset + bunchAcceptations.getAcceptationColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(acceptations.getIdColumnIndex(), acceptation) .select(bunchAccOffset + bunchAcceptations.getAcceptationColumnIndex(), strOffset + strings.getStringAlphabetColumnIndex(), strOffset + strings.getStringColumnIndex(), bunchAccOffset + bunchAcceptations.getAgentSetColumnIndex()); final MutableIntKeyMap<DynamizableResult> resultMap = MutableIntKeyMap.empty(); try (DbResult dbResult = db.select(query)) { final int nullAgentSet = LangbookDbSchema.Tables.agentSets.nullReference(); while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int acc = row.get(0).toInt(); final int alphabet = row.get(1).toInt(); if (alphabet == preferredAlphabet || resultMap.get(acc, null) == null) { final String text = row.get(2).toText(); final int agentSet = row.get(3).toInt(); final boolean dynamic = agentSet != nullAgentSet; resultMap.put(acc, new DynamizableResult(acc, dynamic, text)); } } } return resultMap.valueList().toImmutable(); } public static ImmutableIntKeyMap<String> readAllAlphabets(DbExporter.Database db, int preferredAlphabet) { final LangbookDbSchema.AlphabetsTable alphabets = LangbookDbSchema.Tables.alphabets; final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int accOffset = alphabets.columns().size(); final int strOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(alphabets) .join(acceptations, alphabets.getIdColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .orderBy(alphabets.getIdColumnIndex()) // I do not understand why, but it seems to be required to ensure order .select(alphabets.getIdColumnIndex(), strOffset + strings.getStringAlphabetColumnIndex(), strOffset + strings.getStringColumnIndex()); final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); try (DbResult result = db.select(query)) { if (result.hasNext()) { List<DbValue> row = result.next(); int alphabet = row.get(0).toInt(); String text = row.get(2).toText(); while (result.hasNext()) { row = result.next(); if (alphabet == row.get(0).toInt()) { if (row.get(1).toInt() == preferredAlphabet) { text = row.get(2).toText(); } } else { builder.put(alphabet, text); alphabet = row.get(0).toInt(); text = row.get(2).toText(); } } builder.put(alphabet, text); } } return builder.build(); } public static ImmutableIntKeyMap<String> readAlphabetsForLanguage(DbExporter.Database db, int language, int preferredAlphabet) { final LangbookDbSchema.AlphabetsTable alphabets = LangbookDbSchema.Tables.alphabets; final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.StringQueriesTable stringQueries = LangbookDbSchema.Tables.stringQueries; final int accOffset = alphabets.columns().size(); final int strOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(alphabets) .join(acceptations, alphabets.getIdColumnIndex(), acceptations.getConceptColumnIndex()) .join(stringQueries, accOffset + acceptations.getIdColumnIndex(), stringQueries.getDynamicAcceptationColumnIndex()) .where(alphabets.getLanguageColumnIndex(), language) .select( alphabets.getIdColumnIndex(), strOffset + stringQueries.getStringAlphabetColumnIndex(), strOffset + stringQueries.getStringColumnIndex()); final MutableIntSet foundAlphabets = MutableIntSet.empty(); final MutableIntKeyMap<String> result = MutableIntKeyMap.empty(); try (DbResult r = db.select(query)) { while (r.hasNext()) { final List<DbValue> row = r.next(); final int id = row.get(0).toInt(); final int strAlphabet = row.get(1).toInt(); if (strAlphabet == preferredAlphabet || !foundAlphabets.contains(id)) { foundAlphabets.add(id); result.put(id, row.get(2).toText()); } } } return result.toImmutable(); } public static int readMainAlphabetFromAlphabet(DbExporter.Database db, int alphabet) { final LangbookDbSchema.AlphabetsTable alpTable = LangbookDbSchema.Tables.alphabets; final LangbookDbSchema.LanguagesTable langTable = LangbookDbSchema.Tables.languages; final DbQuery mainAlphableQuery = new DbQuery.Builder(alpTable) .join(langTable, alpTable.getLanguageColumnIndex(), langTable.getIdColumnIndex()) .where(alpTable.getIdColumnIndex(), alphabet) .select(alpTable.columns().size() + langTable.getMainAlphabetColumnIndex()); return selectSingleRow(db, mainAlphableQuery).get(0).toInt(); } public static ImmutableIntKeyMap<String> readAllLanguages(DbExporter.Database db, int preferredAlphabet) { final LangbookDbSchema.LanguagesTable languages = LangbookDbSchema.Tables.languages; final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.StringQueriesTable stringQueries = LangbookDbSchema.Tables.stringQueries; final int accOffset = languages.columns().size(); final int strOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(languages) .join(acceptations, languages.getIdColumnIndex(), acceptations.getConceptColumnIndex()) .join(stringQueries, accOffset + acceptations.getIdColumnIndex(), stringQueries.getDynamicAcceptationColumnIndex()) .select( languages.getIdColumnIndex(), strOffset + stringQueries.getStringAlphabetColumnIndex(), strOffset + stringQueries.getStringColumnIndex() ); MutableIntSet foundLanguages = MutableIntSet.empty(); MutableIntKeyMap<String> result = MutableIntKeyMap.empty(); try (DbResult r = db.select(query)) { while (r.hasNext()) { List<DbValue> row = r.next(); final int lang = row.get(0).toInt(); final int alphabet = row.get(1).toInt(); if (alphabet == preferredAlphabet || !foundLanguages.contains(lang)) { foundLanguages.add(lang); result.put(lang, row.get(2).toText()); } } } return result.toImmutable(); } public static ImmutableIntSet readAllAcceptations(DbExporter.Database db, int alphabet) { final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final DbQuery query = new DbQuery.Builder(strings) .where(strings.getStringAlphabetColumnIndex(), alphabet) .whereColumnValueMatch(strings.getMainAcceptationColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .select(strings.getDynamicAcceptationColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntSet readAllAcceptationsInBunch(DbExporter.Database db, int alphabet, int bunch) { final LangbookDbSchema.BunchAcceptationsTable bunchAcceptations = LangbookDbSchema.Tables.bunchAcceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final DbQuery query = new DbQuery.Builder(bunchAcceptations) .join(strings, bunchAcceptations.getAcceptationColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(bunchAcceptations.getBunchColumnIndex(), bunch) .where(bunchAcceptations.columns().size() + strings.getStringAlphabetColumnIndex(), alphabet) .select(bunchAcceptations.getAcceptationColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntKeyMap<String> readAllRules(DbExporter.Database db, int preferredAlphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.RuledConceptsTable ruledConcepts = LangbookDbSchema.Tables.ruledConcepts; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int accOffset = ruledConcepts.columns().size(); final int strOffset = accOffset + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(ruledConcepts) .join(acceptations, ruledConcepts.getRuleColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .orderBy(ruledConcepts.getRuleColumnIndex()) .select(ruledConcepts.getRuleColumnIndex(), strOffset + strings.getStringAlphabetColumnIndex(), strOffset + strings.getStringColumnIndex()); final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); try (DbResult result = db.select(query)) { if (result.hasNext()) { List<DbValue> row = result.next(); int rule = row.get(0).toInt(); int textAlphabet = row.get(1).toInt(); String text = row.get(2).toText(); while (result.hasNext()) { row = result.next(); if (rule == row.get(0).toInt()) { if (textAlphabet != preferredAlphabet && row.get(1).toInt() == preferredAlphabet) { textAlphabet = preferredAlphabet; text = row.get(2).toText(); } } else { builder.put(rule, text); rule = row.get(0).toInt(); textAlphabet = row.get(1).toInt(); text = row.get(2).toText(); } } builder.put(rule, text); } } return builder.build(); } private static boolean checkMatching(ImmutableIntKeyMap<String> startMatcher, ImmutableIntKeyMap<String> endMatcher, ImmutableIntKeyMap<String> texts) { for (IntKeyMap.Entry<String> entry : startMatcher.entries()) { final String text = texts.get(entry.key(), null); if (text == null || !text.startsWith(entry.value())) { return false; } } for (IntKeyMap.Entry<String> entry : endMatcher.entries()) { final String text = texts.get(entry.key(), null); if (text == null || !text.endsWith(entry.value())) { return false; } } return !startMatcher.isEmpty() || !endMatcher.isEmpty(); } public static ImmutableIntSet readBunchesFromSetOfBunchSets(DbExporter.Database db, ImmutableIntSet bunchSets) { final ImmutableIntSetBuilder builder = new ImmutableIntSetBuilder(); for (int bunchSet : bunchSets) { for (int bunch : getBunchSet(db, bunchSet)) { builder.add(bunch); } } return builder.build(); } /** * Check all bunches including agents that may match the given texts. * * For simplicity, this will only pick bunches declared as source bunches * in agents that are applying a rule and has no diff bunches nor target bunch. * * Required conditions are: * <li>The agent's matchers must match the given string</li> * <li>Start or end matcher must not be empty</li> * <li>There must be an adder different from the matcher</li> * * @param db Database to be used * @param texts Map containing the word to be matched. Keys in the map are alphabets and values are the text on those alphabets. * @param preferredAlphabet User's defined alphabet. * @return A map whose keys are bunches (concepts) and value are the suitable way to represent that bunch, according to the given preferred alphabet. */ public static ImmutableIntKeyMap<String> readAllMatchingBunches(DbExporter.Database db, ImmutableIntKeyMap<String> texts, int preferredAlphabet) { final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(agents) .where(agents.getTargetBunchColumnIndex(), NO_BUNCH) .where(agents.getDiffBunchSetColumnIndex(), 0) .select(agents.getSourceBunchSetColumnIndex(), agents.getStartMatcherColumnIndex(), agents.getEndMatcherColumnIndex()); final SyncCacheIntKeyNonNullValueMap<ImmutableIntKeyMap<String>> cachedCorrelations = new SyncCacheIntKeyNonNullValueMap<>(id -> getCorrelationWithText(db, id)); final ImmutableIntSetBuilder validBunchSetsBuilder = new ImmutableIntSetBuilder(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); int bunchSet = row.get(0).toInt(); int startMatcherId = row.get(1).toInt(); int endMatcherId = row.get(2).toInt(); final ImmutableIntKeyMap<String> startMatcher = cachedCorrelations.get(startMatcherId); final ImmutableIntKeyMap<String> endMatcher = cachedCorrelations.get(endMatcherId); if (checkMatching(startMatcher, endMatcher, texts)) { validBunchSetsBuilder.add(bunchSet); } } } final ImmutableIntSet bunches = readBunchesFromSetOfBunchSets(db, validBunchSetsBuilder.build()); final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); for (int bunch : bunches) { builder.put(bunch, readConceptText(db, bunch, preferredAlphabet)); } return builder.build(); } public static ImmutableIntSet readAllPossibleSynonymOrTranslationAcceptations(DbExporter.Database db, int alphabet) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int strOffset = acceptations.columns().size() * 2; final DbQuery query = new DbQuery.Builder(acceptations) .join(acceptations, acceptations.getConceptColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, acceptations.columns().size() + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(strOffset + strings.getStringAlphabetColumnIndex(), alphabet) .whereColumnValueDiffer(acceptations.getIdColumnIndex(), acceptations.columns().size() + acceptations.getIdColumnIndex()) .select(acceptations.getIdColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntSet readAllPossibleSynonymOrTranslationAcceptationsInBunch(DbExporter.Database db, int alphabet, int bunch) { final LangbookDbSchema.AcceptationsTable acceptations = LangbookDbSchema.Tables.acceptations; final LangbookDbSchema.BunchAcceptationsTable bunchAcceptations = LangbookDbSchema.Tables.bunchAcceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final int accOffset1 = bunchAcceptations.columns().size(); final int accOffset2 = accOffset1 + acceptations.columns().size(); final int strOffset = accOffset2 + acceptations.columns().size(); final DbQuery query = new DbQuery.Builder(bunchAcceptations) .join(acceptations, bunchAcceptations.getAcceptationColumnIndex(), acceptations.getIdColumnIndex()) .join(acceptations, accOffset1 + acceptations.getConceptColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, accOffset2 + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(bunchAcceptations.getBunchColumnIndex(), bunch) .where(strOffset + strings.getStringAlphabetColumnIndex(), alphabet) .whereColumnValueDiffer(accOffset1 + acceptations.getIdColumnIndex(), accOffset2 + acceptations.getIdColumnIndex()) .select(accOffset1 + acceptations.getIdColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntSet readAllRulableAcceptations(DbExporter.Database db, int alphabet, int rule) { final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final LangbookDbSchema.RuledAcceptationsTable ruledAcceptations = LangbookDbSchema.Tables.ruledAcceptations; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final int agentOffset = ruledAcceptations.columns().size(); final int strOffset = agentOffset + agents.columns().size(); final DbQuery query = new DbQuery.Builder(ruledAcceptations) .join(agents, ruledAcceptations.getAgentColumnIndex(), agents.getIdColumnIndex()) .join(strings, ruledAcceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(strOffset + strings.getStringAlphabetColumnIndex(), alphabet) .where(agentOffset + agents.getRuleColumnIndex(), rule) .select(ruledAcceptations.getAcceptationColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntSet readAllRulableAcceptationsInBunch(DbExporter.Database db, int alphabet, int rule, int bunch) { final LangbookDbSchema.BunchAcceptationsTable bunchAcceptations = LangbookDbSchema.Tables.bunchAcceptations; final LangbookDbSchema.StringQueriesTable strings = LangbookDbSchema.Tables.stringQueries; final LangbookDbSchema.RuledAcceptationsTable ruledAcceptations = LangbookDbSchema.Tables.ruledAcceptations; final LangbookDbSchema.AgentsTable agents = LangbookDbSchema.Tables.agents; final int ruledAccOffset = bunchAcceptations.columns().size(); final int agentOffset = ruledAccOffset + ruledAcceptations.columns().size(); final int strOffset = agentOffset + agents.columns().size(); final DbQuery query = new DbQuery.Builder(bunchAcceptations) .join(ruledAcceptations, bunchAcceptations.getAcceptationColumnIndex(), ruledAcceptations. getAcceptationColumnIndex()) .join(agents, ruledAccOffset + ruledAcceptations.getAgentColumnIndex(), agents.getIdColumnIndex()) .join(strings, ruledAccOffset + ruledAcceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .where(bunchAcceptations.getBunchColumnIndex(), bunch) .where(strOffset + strings.getStringAlphabetColumnIndex(), alphabet) .where(agentOffset + agents.getRuleColumnIndex(), rule) .select(bunchAcceptations.getAcceptationColumnIndex()); return intSetQuery(db, query); } private static ImmutableIntSet readAllPossibleAcceptationForField(DbExporter.Database db, int bunch, QuestionFieldDetails field) { switch (field.getType()) { case LangbookDbSchema.QuestionFieldFlags.TYPE_SAME_ACC: return (bunch == NO_BUNCH)? readAllAcceptations(db, field.alphabet) : readAllAcceptationsInBunch(db, field.alphabet, bunch); case LangbookDbSchema.QuestionFieldFlags.TYPE_SAME_CONCEPT: return (bunch == NO_BUNCH)? readAllPossibleSynonymOrTranslationAcceptations(db, field.alphabet) : readAllPossibleSynonymOrTranslationAcceptationsInBunch(db, field.alphabet, bunch); case LangbookDbSchema.QuestionFieldFlags.TYPE_APPLY_RULE: return (bunch == NO_BUNCH)? readAllRulableAcceptations(db, field.alphabet, field.rule) : readAllRulableAcceptationsInBunch(db, field.alphabet, field.rule, bunch); default: throw new AssertionError(); } } public static ImmutableIntSet readAllPossibleAcceptations(DbExporter.Database db, int bunch, ImmutableSet<QuestionFieldDetails> fields) { final Function<QuestionFieldDetails, ImmutableIntSet> mapFunc = field -> readAllPossibleAcceptationForField(db, bunch, field); return fields.map(mapFunc).reduce((a,b) -> a.filter(b::contains)); } public static ImmutableIntSet getAllRuledAcceptationsForAgent(DbExporter.Database db, int agentId) { final LangbookDbSchema.RuledAcceptationsTable table = LangbookDbSchema.Tables.ruledAcceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getAgentColumnIndex(), agentId) .select(table.getIdColumnIndex()); return intSetQuery(db, query); } public static ImmutableIntPairMap getAgentProcessedMap(DbExporter.Database db, int agentId) { final LangbookDbSchema.RuledAcceptationsTable table = LangbookDbSchema.Tables.ruledAcceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getAgentColumnIndex(), agentId) .select(table.getAcceptationColumnIndex(), table.getIdColumnIndex()); final ImmutableIntPairMap.Builder builder = new ImmutableIntPairMap.Builder(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); builder.put(row.get(0).toInt(), row.get(1).toInt()); } } return builder.build(); } public static ImmutableIntKeyMap<ImmutableIntSet> getAllAgentSetsContaining(DbExporter.Database db, int agentId) { final LangbookDbSchema.AgentSetsTable table = LangbookDbSchema.Tables.agentSets; final DbQuery query = new DbQuery.Builder(table) .join(table, table.getSetIdColumnIndex(), table.getSetIdColumnIndex()) .where(table.getAgentColumnIndex(), agentId) .select(table.getSetIdColumnIndex(), table.columns().size() + table.getAgentColumnIndex()); final ImmutableIntKeyMap.Builder<ImmutableIntSet> mapBuilder = new ImmutableIntKeyMap.Builder<>(); try (DbResult result = db.select(query)) { if (result.hasNext()) { List<DbValue> row = result.next(); int setId = row.get(0).toInt(); ImmutableIntSetBuilder setBuilder = new ImmutableIntSetBuilder(); setBuilder.add(row.get(1).toInt()); while (result.hasNext()) { row = result.next(); int newSetId = row.get(0).toInt(); if (newSetId != setId) { mapBuilder.put(setId, setBuilder.build()); setId = newSetId; setBuilder = new ImmutableIntSetBuilder(); } setBuilder.add(row.get(1).toInt()); } mapBuilder.put(setId, setBuilder.build()); } } return mapBuilder.build(); } public static final class AgentRegister { public final int targetBunch; public final int sourceBunchSetId; public final int diffBunchSetId; public final int startMatcherId; public final int startAdderId; public final int endMatcherId; public final int endAdderId; public final int rule; public AgentRegister(int targetBunch, int sourceBunchSetId, int diffBunchSetId, int startMatcherId, int startAdderId, int endMatcherId, int endAdderId, int rule) { if (startMatcherId == startAdderId && endMatcherId == endAdderId) { if (targetBunch == 0 || rule != 0) { throw new IllegalArgumentException(); } } else if (rule == 0) { throw new IllegalArgumentException(); } this.targetBunch = targetBunch; this.sourceBunchSetId = sourceBunchSetId; this.diffBunchSetId = diffBunchSetId; this.startMatcherId = startMatcherId; this.startAdderId = startAdderId; this.endMatcherId = endMatcherId; this.endAdderId = endAdderId; this.rule = rule; } } public static AgentRegister getAgentRegister(DbExporter.Database db, int agentId) { final LangbookDbSchema.AgentsTable table = LangbookDbSchema.Tables.agents; final DbQuery query = new DbQuery.Builder(table) .where(table.getIdColumnIndex(), agentId) .select(table.getTargetBunchColumnIndex(), table.getSourceBunchSetColumnIndex(), table.getDiffBunchSetColumnIndex(), table.getStartMatcherColumnIndex(), table.getStartAdderColumnIndex(), table.getEndMatcherColumnIndex(), table.getEndAdderColumnIndex(), table.getRuleColumnIndex()); final List<DbValue> agentRow = selectSingleRow(db, query); final int sourceBunchSetId = agentRow.get(1).toInt(); final int diffBunchSetId = agentRow.get(2).toInt(); final int startMatcherId = agentRow.get(3).toInt(); final int startAdderId = agentRow.get(4).toInt(); final int endMatcherId = agentRow.get(5).toInt(); final int endAdderId = agentRow.get(6).toInt(); return new AgentRegister(agentRow.get(0).toInt(), sourceBunchSetId, diffBunchSetId, startMatcherId, startAdderId, endMatcherId, endAdderId, agentRow.get(7).toInt()); } public static final class AgentDetails { public final int targetBunch; public final ImmutableIntSet sourceBunches; public final ImmutableIntSet diffBunches; public final ImmutableIntKeyMap<String> startMatcher; public final ImmutableIntKeyMap<String> startAdder; public final ImmutableIntKeyMap<String> endMatcher; public final ImmutableIntKeyMap<String> endAdder; public final int rule; public AgentDetails(int targetBunch, ImmutableIntSet sourceBunches, ImmutableIntSet diffBunches, ImmutableIntKeyMap<String> startMatcher, ImmutableIntKeyMap<String> startAdder, ImmutableIntKeyMap<String> endMatcher, ImmutableIntKeyMap<String> endAdder, int rule) { if (startMatcher == null) { startMatcher = ImmutableIntKeyMap.empty(); } if (startAdder == null) { startAdder = ImmutableIntKeyMap.empty(); } if (endMatcher == null) { endMatcher = ImmutableIntKeyMap.empty(); } if (endAdder == null) { endAdder = ImmutableIntKeyMap.empty(); } if (startMatcher.equals(startAdder) && endMatcher.equals(endAdder)) { if (targetBunch == 0) { throw new IllegalArgumentException(); } rule = 0; } else if (rule == 0) { throw new IllegalArgumentException(); } if (sourceBunches == null) { sourceBunches = new ImmutableIntSetBuilder().build(); } if (diffBunches == null) { diffBunches = new ImmutableIntSetBuilder().build(); } if (!sourceBunches.filter(diffBunches::contains).isEmpty()) { throw new IllegalArgumentException(); } if (sourceBunches.contains(0)) { throw new IllegalArgumentException(); } if (diffBunches.contains(0)) { throw new IllegalArgumentException(); } this.targetBunch = targetBunch; this.sourceBunches = sourceBunches; this.diffBunches = diffBunches; this.startMatcher = startMatcher; this.startAdder = startAdder; this.endMatcher = endMatcher; this.endAdder = endAdder; this.rule = rule; } public boolean modifyCorrelations() { return !startMatcher.equals(startAdder) || !endMatcher.equals(endAdder); } } public static AgentDetails getAgentDetails(DbExporter.Database db, int agentId) { final AgentRegister register = getAgentRegister(db, agentId); final ImmutableIntSet sourceBunches = getBunchSet(db, register.sourceBunchSetId); final ImmutableIntSet diffBunches = (register.sourceBunchSetId != register.diffBunchSetId)? getBunchSet(db, register.diffBunchSetId) : sourceBunches; final SyncCacheIntKeyNonNullValueMap<ImmutableIntKeyMap<String>> correlationCache = new SyncCacheIntKeyNonNullValueMap<>(id -> getCorrelationWithText(db, id)); final ImmutableIntKeyMap<String> startMatcher = correlationCache.get(register.startMatcherId); final ImmutableIntKeyMap<String> startAdder = correlationCache.get(register.startAdderId); final ImmutableIntKeyMap<String> endMatcher = correlationCache.get(register.endMatcherId); final ImmutableIntKeyMap<String> endAdder = correlationCache.get(register.endAdderId); return new AgentDetails(register.targetBunch, sourceBunches, diffBunches, startMatcher, startAdder, endMatcher, endAdder, register.rule); } public static final class QuestionFieldDetails { public final int alphabet; public final int rule; public final int flags; public QuestionFieldDetails(int alphabet, int rule, int flags) { this.alphabet = alphabet; this.rule = rule; this.flags = flags; } public int getType() { return flags & LangbookDbSchema.QuestionFieldFlags.TYPE_MASK; } public boolean isAnswer() { return (flags & LangbookDbSchema.QuestionFieldFlags.IS_ANSWER) != 0; } @Override public int hashCode() { return (flags * 37 + rule) * 37 + alphabet; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof QuestionFieldDetails)) { return false; } final QuestionFieldDetails that = (QuestionFieldDetails) other; return alphabet == that.alphabet && rule == that.rule && flags == that.flags; } @Override public String toString() { return getClass().getSimpleName() + '(' + alphabet + ',' + rule + ',' + flags + ')'; } } public static final class QuizDetails { public final int bunch; public final ImmutableList<QuestionFieldDetails> fields; public QuizDetails(int bunch, ImmutableList<QuestionFieldDetails> fields) { if (fields == null || fields.size() < 2 || !fields.anyMatch(field -> !field.isAnswer()) || !fields.anyMatch(QuestionFieldDetails::isAnswer)) { throw new IllegalArgumentException(); } this.bunch = bunch; this.fields = fields; } @Override public int hashCode() { return fields.hashCode() * 41 + bunch; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof QuizDetails)) { return false; } final QuizDetails that = (QuizDetails) other; return bunch == that.bunch && fields.equals(that.fields); } @Override public String toString() { return getClass().getSimpleName() + '(' + bunch + ',' + fields.toString() + ')'; } } public static QuizDetails getQuizDetails(DbExporter.Database db, int quizId) { final LangbookDbSchema.QuizDefinitionsTable quizzes = LangbookDbSchema.Tables.quizDefinitions; final LangbookDbSchema.QuestionFieldSets questions = LangbookDbSchema.Tables.questionFieldSets; final int offset = quizzes.columns().size(); final DbQuery query = new DbQuery.Builder(quizzes) .join(questions, quizzes.getQuestionFieldsColumnIndex(), questions.getSetIdColumnIndex()) .where(quizzes.getIdColumnIndex(), quizId) .select(quizzes.getBunchColumnIndex(), offset + questions.getAlphabetColumnIndex(), offset + questions.getRuleColumnIndex(), offset + questions.getFlagsColumnIndex()); final ImmutableList.Builder<QuestionFieldDetails> builder = new ImmutableList.Builder<>(); int bunch = 0; try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); bunch = row.get(0).toInt(); builder.add(new QuestionFieldDetails(row.get(1).toInt(), row.get(2).toInt(), row.get(3).toInt())); } } final ImmutableList<QuestionFieldDetails> fields = builder.build(); return fields.isEmpty()? null : new QuizDetails(bunch, fields); } public static ImmutableIntPairMap getCurrentKnowledge(DbExporter.Database db, int quizId) { final LangbookDbSchema.KnowledgeTable table = LangbookDbSchema.Tables.knowledge; final DbQuery query = new DbQuery.Builder(table) .where(table.getQuizDefinitionColumnIndex(), quizId) .select(table.getAcceptationColumnIndex(), table.getScoreColumnIndex()); final ImmutableIntPairMap.Builder builder = new ImmutableIntPairMap.Builder(); try (DbResult result = db.select(query)) { while (result.hasNext()) { final List<DbValue> row = result.next(); builder.put(row.get(0).toInt(), row.get(1).toInt()); } } return builder.build(); } private static ImmutableIntKeyMap<String> getSampleSentences(DbExporter.Database db, int staticAcceptation) { final LangbookDbSchema.SpanTable spans = LangbookDbSchema.Tables.spans; final DbQuery query = new DbQuery.Builder(spans) .where(spans.getAcceptation(), staticAcceptation) .select(spans.getSymbolArray()); final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final int symbolArrayId = dbResult.next().get(0).toInt(); builder.put(symbolArrayId, getSymbolArray(db, symbolArrayId)); } } return builder.build(); } public static AcceptationDetailsModel getAcceptationsDetails( DbExporter.Database db, int staticAcceptation, int preferredAlphabet) { final int concept = conceptFromAcceptation(db, staticAcceptation); if (concept == 0) { return null; } ImmutablePair<ImmutableIntList, ImmutableIntKeyMap<ImmutableIntKeyMap<String>>> correlationResultPair = getAcceptationCorrelations(db, staticAcceptation); final int givenAlphabet = correlationResultPair.right.get(correlationResultPair.left.get(0)).keyAt(0); final IdentifiableResult languageResult = readLanguageFromAlphabet(db, givenAlphabet, preferredAlphabet); final MutableIntKeyMap<String> languageStrs = MutableIntKeyMap.empty(); languageStrs.put(languageResult.id, languageResult.text); final IdentifiableResult definition = readSupertypeFromAcceptation(db, staticAcceptation, preferredAlphabet); final ImmutableIntKeyMap<String> subtypes = readSubtypesFromAcceptation(db, staticAcceptation, preferredAlphabet); final ImmutableIntKeyMap<SynonymTranslationResult> synonymTranslationResults = readAcceptationSynonymsAndTranslations(db, staticAcceptation); for (IntKeyMap.Entry<SynonymTranslationResult> entry : synonymTranslationResults.entries()) { final int language = entry.value().language; if (languageStrs.get(language, null) == null) { languageStrs.put(language, readConceptText(db, language, preferredAlphabet)); } } final ImmutableList<DynamizableResult> bunchesWhereAcceptationIsIncluded = readBunchesWhereAcceptationIsIncluded(db, staticAcceptation, preferredAlphabet); final ImmutableList<MorphologyResult> morphologyResults = readMorphologiesFromAcceptation(db, staticAcceptation, preferredAlphabet); final ImmutableList<DynamizableResult> bunchChildren = readAcceptationBunchChildren(db, staticAcceptation, preferredAlphabet); final ImmutableIntPairMap involvedAgents = readAcceptationInvolvedAgents(db, staticAcceptation); final ImmutableIntKeyMap.Builder<String> supertypesBuilder = new ImmutableIntKeyMap.Builder<>(); if (definition != null) { supertypesBuilder.put(definition.id, definition.text); } final ImmutableIntKeyMap<String> sampleSentences = getSampleSentences(db, staticAcceptation); return new AcceptationDetailsModel(concept, languageResult, correlationResultPair.left, correlationResultPair.right, supertypesBuilder.build(), subtypes, synonymTranslationResults, bunchChildren, bunchesWhereAcceptationIsIncluded, morphologyResults, involvedAgents, languageStrs.toImmutable(), sampleSentences); } public static CorrelationDetailsModel getCorrelationDetails(DbExporter.Database db, int correlationId, int preferredAlphabet) { final ImmutableIntKeyMap<String> correlation = getCorrelationWithText(db, correlationId); if (correlation.isEmpty()) { return null; } final ImmutableIntKeyMap<String> alphabets = readAllAlphabets(db, preferredAlphabet); final ImmutableIntKeyMap<String> acceptations = readAcceptationsIncludingCorrelation(db, correlationId, preferredAlphabet); final int entryCount = correlation.size(); final MutableIntKeyMap<ImmutableIntSet> relatedCorrelationsByAlphabet = MutableIntKeyMap.empty(); final MutableIntKeyMap<ImmutableIntKeyMap<String>> relatedCorrelations = MutableIntKeyMap.empty(); for (int i = 0; i < entryCount; i++) { final int matchingAlphabet = correlation.keyAt(i); final ImmutableIntKeyMap<ImmutableIntKeyMap<String>> correlations = readCorrelationsWithSameSymbolArray(db, correlationId, matchingAlphabet); final int amount = correlations.size(); final ImmutableIntSetBuilder setBuilder = new ImmutableIntSetBuilder(); for (int j = 0; j < amount; j++) { final int corrId = correlations.keyAt(j); if (relatedCorrelations.get(corrId, null) == null) { relatedCorrelations.put(corrId, correlations.valueAt(j)); } setBuilder.add(corrId); } relatedCorrelationsByAlphabet.put(matchingAlphabet, setBuilder.build()); } return new CorrelationDetailsModel(alphabets, correlation, acceptations, relatedCorrelationsByAlphabet.toImmutable(), relatedCorrelations.toImmutable()); } public static class SentenceSpan { final ImmutableIntRange range; final int acceptation; SentenceSpan(ImmutableIntRange range, int acceptation) { if (range == null || range.min() < 0 || acceptation == 0) { throw new IllegalArgumentException(); } this.range = range; this.acceptation = acceptation; } @Override public int hashCode() { return ((range.min() * 37) + range.size() * 37) + acceptation; } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other == null || !(other instanceof SentenceSpan)) { return false; } final SentenceSpan that = (SentenceSpan) other; return acceptation == that.acceptation && range.equals(that.range); } @Override public String toString() { return getClass().getSimpleName() + '(' + range + ", " + acceptation + ')'; } void writeToParcel(Parcel dest) { dest.writeInt(range.min()); dest.writeInt(range.max()); dest.writeInt(acceptation); } static SentenceSpan fromParcel(Parcel in) { final int start = in.readInt(); final int end = in.readInt(); final int acc = in.readInt(); return new SentenceSpan(new ImmutableIntRange(start, end), acc); } } public static ImmutableSet<SentenceSpan> getSentenceSpans(DbExporter.Database db, int symbolArray) { final LangbookDbSchema.SpanTable table = LangbookDbSchema.Tables.spans; final DbQuery query = new DbQuery.Builder(table) .where(table.getSymbolArray(), symbolArray) .select(table.getStart(), table.getLength(), table.getAcceptation()); final ImmutableHashSet.Builder<SentenceSpan> builder = new ImmutableHashSet.Builder<>(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int start = row.get(0).toInt(); final int length = row.get(1).toInt(); final int acc = row.get(2).toInt(); final ImmutableIntRange range = new ImmutableIntRange(start, start + length - 1); builder.add(new SentenceSpan(range, acc)); } } return builder.build(); } public static ImmutableIntValueMap<SentenceSpan> getSentenceSpansWithIds(DbExporter.Database db, int symbolArray) { final LangbookDbSchema.SpanTable table = LangbookDbSchema.Tables.spans; final DbQuery query = new DbQuery.Builder(table) .where(table.getSymbolArray(), symbolArray) .select(table.getIdColumnIndex(), table.getStart(), table.getLength(), table.getAcceptation()); final ImmutableIntValueHashMap.Builder<SentenceSpan> builder = new ImmutableIntValueHashMap.Builder<>(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); final int id = row.get(0).toInt(); final int start = row.get(1).toInt(); final int length = row.get(2).toInt(); final int acc = row.get(3).toInt(); final ImmutableIntRange range = new ImmutableIntRange(start, start + length - 1); builder.put(new SentenceSpan(range, acc), id); } } return builder.build(); } public static Integer getStaticAcceptationFromDynamic(DbExporter.Database db, int dynamicAcceptation) { final LangbookDbSchema.StringQueriesTable table = LangbookDbSchema.Tables.stringQueries; final DbQuery query = new DbQuery.Builder(table) .where(table.getDynamicAcceptationColumnIndex(), dynamicAcceptation) .select(table.getMainAcceptationColumnIndex()); boolean found = false; int value = 0; try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final int newValue = dbResult.next().get(0).toInt(); if (!found) { found = true; value = newValue; } else if (value != newValue) { throw new AssertionError(); } } } return found? value : null; } public static ImmutableIntKeyMap<String> getAcceptationTexts(DbExporter.Database db, int acceptations) { final LangbookDbSchema.StringQueriesTable table = LangbookDbSchema.Tables.stringQueries; final DbQuery query = new DbQuery.Builder(table) .where(table.getDynamicAcceptationColumnIndex(), acceptations) .select(table.getStringAlphabetColumnIndex(), table.getStringColumnIndex()); final ImmutableIntKeyMap.Builder<String> builder = new ImmutableIntKeyMap.Builder<>(); try (DbResult dbResult = db.select(query)) { while (dbResult.hasNext()) { final List<DbValue> row = dbResult.next(); builder.put(row.get(0).toInt(), row.get(1).toText()); } } return builder.build(); } /** * Checks if the given symbolArray is not used neither as a correlation nor as a conversion, * and then it is merely a sentence. */ public static boolean isSymbolArrayMerelyASentence(DbExporter.Database db, int symbolArrayId) { final LangbookDbSchema.CorrelationsTable corrTable = LangbookDbSchema.Tables.correlations; DbQuery query = new DbQuery.Builder(corrTable) .where(corrTable.getSymbolArrayColumnIndex(), symbolArrayId) .select(corrTable.getIdColumnIndex()); try (DbResult dbResult = db.select(query)) { if (dbResult.hasNext()) { return false; } } final LangbookDbSchema.ConversionsTable convTable = LangbookDbSchema.Tables.conversions; query = new DbQuery.Builder(convTable) .where(convTable.getSourceColumnIndex(), symbolArrayId) .select(convTable.getIdColumnIndex()); try (DbResult dbResult = db.select(query)) { if (dbResult.hasNext()) { return false; } } query = new DbQuery.Builder(convTable) .where(convTable.getTargetColumnIndex(), symbolArrayId) .select(convTable.getIdColumnIndex()); try (DbResult dbResult = db.select(query)) { if (dbResult.hasNext()) { return false; } } return true; } }
package org.biojava.bio.structure; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Element is an enumeration of the elements of the periodic table. In addition, * several attributes of each element are accessible. * <B>Note:</B> Deuterium and Tritium are treated as separate elements D and T, * respectively. Sometimes part of a molecule is represented as an R-group, which * is represented as the element R. * * * @author Peter Rose * @version %I% %G% * @since 3.0 * */ public enum Element implements Serializable { // most frequently used elements first H(1, 1, 39, 1.10f, 0.32f, 1, 1, 1, 1, 1, 1.008f, 0, 1, 2.20f, ElementType.OTHER_NONMETAL), C(6, 2, 0, 1.55f, 0.77f, 4, 4, 4, 4, 4, 12.011f, 2, -4, 2.55f, ElementType.OTHER_NONMETAL), N(7, 2, 57, 1.40f, 0.75f, 5, 2, 5, 3, 4, 14.007f, 2, -3, 3.04f, ElementType.OTHER_NONMETAL), O(8, 2, 65, 1.35f, 0.73f, 6, 1, 2, 2, 2, 16.000f, 2, -2, 3.44f, ElementType.OTHER_NONMETAL), /** * Deuterim */ D(1, 1, 27, 1.10f, 0.32f, 1, 1, 1, 1, 1, 1.008f, 0, 1, 2.20f, ElementType.OTHER_NONMETAL), // need to edit properties! /** * Tritium */ T(1, 1, 90, 1.10f, 0.32f, 1, 1, 1, 1, 1, 1.008f, 0, 1, 2.20f, ElementType.OTHER_NONMETAL), // need to edit properties! He(2, 1, 40, 2.20f, 1.60f, 2, 0, 12, 0, 0, 4.003f, 2, 0, 0.0f, ElementType.NOBLE_GAS), // electroneg not reported Li(3, 2, 50, 1.22f, 1.34f, 1, 0, 12, 0, 1, 6.940f, 2, 1, 0.98f, ElementType.ALKALI_METAL), Be(4, 2, 12, 0.63f, 0.90f, 2, 0, 12, 2, 2, 9.012f, 2, 2, 1.57f, ElementType.TRANSITION_METAL), B(5, 2, 10, 1.55f, 0.82f, 3, 3, 5, 3, 4, 10.810f, 2, 3, 2.04f, ElementType.METALLOID), F(9, 2, 32, 1.30f, 0.72f, 7, 0, 1, 1, 1, 18.998f, 2, -1, 3.98f, ElementType.HALOGEN), Ne(10, 2, 61, 2.02f, 1.12f, 8, 0, 12, 0, 0, 20.170f, 10, 0, 0.00f, ElementType.NOBLE_GAS), // electroneg not reported Na(11, 3, 58, 2.20f, 1.54f, 1, 0, 1, 0, 0, 22.990f, 10, 1, 0.93f, ElementType.ALKALI_METAL), Mg(12, 3, 54, 1.50f, 1.30f, 2, 0, 2, 0, 2, 24.305f, 10, 2, 1.31f, ElementType.ALKALINE_EARTH_METAL), Al(13, 3, 4, 1.50f, 1.18f, 3, 0, 5, 0, 4, 26.982f, 10, 3, 1.61f, ElementType.POST_TRANSITION_METAL), Si(14, 3, 86, 2.20f, 1.11f, 4, 4, 4, 4, 4, 28.086f, 10, 4, 1.90f, ElementType.METALLOID), P(15, 3, 67, 1.88f, 1.06f, 5, 3, 5, 3, 5, 30.974f, 10, 5, 2.19f, ElementType.OTHER_NONMETAL), S(16, 3, 82, 1.81f, 1.02f, 6, 2, 6, 2, 6, 32.060f, 10, -2, 2.58f, ElementType.OTHER_NONMETAL), Cl(17, 3, 21, 1.75f, 0.99f, 7, 0, 1, 1, 1, 35.453f, 10, -1, 3.16f, ElementType.HALOGEN), Ar(18, 4, 6, 2.77f, 1.54f, 8, 0, 12, 0, 0, 39.948f, 18, 0, 0.00f, ElementType.NOBLE_GAS), // electroneg not reported K(19, 4, 47, 2.39f, 1.96f, 1, 0, 12, 0, 0, 39.102f, 18, 1, 0.82f, ElementType.ALKALI_METAL), Ca(20, 4, 17, 1.95f, 1.74f, 2, 0, 2, 0, 0, 40.080f, 18, 2, 1.00f, ElementType.ALKALINE_EARTH_METAL), Sc(21, 4, 84, 1.32f, 1.44f, 3, 0, 12, 3, 0, 44.956f, 18, 3, 1.36f, ElementType.TRANSITION_METAL), Ti(22, 4, 96, 1.95f, 1.36f, 4, 2, 4, 3, 4, 47.880f, 18, 4, 1.54f, ElementType.TRANSITION_METAL), V(23, 4, 100, 1.06f, 1.25f, 5, 0, 12, 3, 0, 50.040f, 18, 5, 1.63f, ElementType.TRANSITION_METAL), Cr(24, 4, 24, 1.13f, 1.27f, 6, 0, 12, 2, 0, 51.996f, 18, 3, 1.66f, ElementType.TRANSITION_METAL), Mn(25, 4, 55, 1.19f, 1.39f, 7, 0, 12, 0, 0, 54.938f, 18, 2, 1.55f, ElementType.TRANSITION_METAL), Fe(26, 4, 33, 1.95f, 1.25f, 3, 0, 8, 0, 0, 55.847f, 18, 3, 1.83f, ElementType.TRANSITION_METAL), Co(27, 4, 23, 1.13f, 1.26f, 3, 0, 12, 0, 0, 58.933f, 18, 2, 1.88f, ElementType.TRANSITION_METAL), Ni(28, 4, 62, 1.24f, 1.21f, 3, 0, 12, 0, 0, 58.710f, 18, 2, 1.91f, ElementType.TRANSITION_METAL), Cu(29, 4, 26, 1.15f, 1.38f, 2, 0, 4, 0, 0, 63.546f, 18, 2, 1.90f, ElementType.TRANSITION_METAL), Zn(30, 4, 106, 1.15f, 1.31f, 2, 0, 2, 0, 0, 65.380f, 18, 2, 1.65f, ElementType.TRANSITION_METAL), Ga(31, 4, 36, 1.55f, 1.26f, 3, 1, 4, 2, 4, 69.720f, 28, 3, 1.81f, ElementType.POST_TRANSITION_METAL), Ge(32, 4, 38, 2.72f, 1.22f, 4, 0, 12, 4, 4, 72.590f, 28, 4, 2.01f, ElementType.METALLOID), As(33, 4, 7, 0.83f, 1.19f, 5, 0, 12, 3, 5, 74.922f, 28, -3, 2.18f, ElementType.METALLOID), Se(34, 4, 85, 0.90f, 1.16f, 6, 0, 12, 2, 6, 78.960f, 28, 4, 2.55f, ElementType.OTHER_NONMETAL), Br(35, 4, 15, 1.95f, 1.14f, 7, 0, 1, 1, 1, 79.904f, 28, -1, 2.96f, ElementType.HALOGEN), Kr(36, 4, 48, 1.90f, 1.60f, 8, 0, 12, 0, 0, 83.800f, 28, 0, 3.00f, ElementType.NOBLE_GAS), Rb(37, 5, 77, 2.65f, 2.11f, 1, 0, 12, 0, 0, 85.467f, 36, 1, 0.82f, ElementType.ALKALI_METAL), Sr(38, 5, 89, 2.02f, 1.92f, 2, 0, 12, 2, 0, 87.620f, 36, 2, 0.95f, ElementType.ALKALINE_EARTH_METAL), Y(39, 5, 103, 1.61f, 1.62f, 3, 0, 12, 3, 0, 88.806f, 36, 3, 1.22f, ElementType.TRANSITION_METAL), Zr(40, 5, 105, 1.42f, 1.48f, 4, 0, 12, 4, 0, 91.220f, 36, 4, 1.33f, ElementType.TRANSITION_METAL), Nb(41, 5, 59, 1.33f, 1.37f, 5, 0, 12, 3, 0, 92.906f, 36, 5, 1.60f, ElementType.TRANSITION_METAL), Mo(42, 5, 56, 1.75f, 1.45f, 6, 1, 6, 3, 0, 95.940f, 36, 6, 2.16f, ElementType.TRANSITION_METAL), Tc(43, 5, 93, 1.80f, 1.56f, 7, 0, 12, 6, 0, 98.910f, 36, 7, 1.90f, ElementType.TRANSITION_METAL), Ru(44, 5, 81, 1.20f, 1.26f, 8, 0, 12, 3, 0, 101.070f, 36, 4, 2.20f, ElementType.TRANSITION_METAL), Rh(45, 5, 79, 1.22f, 1.35f, 4, 0, 12, 3, 0, 102.906f, 36, 3, 2.28f, ElementType.TRANSITION_METAL), Pd(46, 5, 70, 1.44f, 1.31f, 4, 0, 12, 2, 0, 106.400f, 36, 2, 2.20f, ElementType.TRANSITION_METAL), Ag(47, 5, 3, 1.55f, 1.53f, 1, 0, 6, 0, 0, 107.868f, 36, 1, 1.93f, ElementType.TRANSITION_METAL), Cd(48, 5, 18, 1.75f, 1.48f, 2, 0, 12, 0, 0, 112.400f, 36, 2, 1.69f, ElementType.TRANSITION_METAL), In(49, 5, 45, 1.46f, 1.44f, 3, 0, 12, 3, 0, 114.820f, 46, 3, 1.78f, ElementType.POST_TRANSITION_METAL), Sn(50, 5, 88, 1.67f, 1.41f, 4, 0, 12, 2, 4, 118.690f, 46, 4, 1.96f, ElementType.POST_TRANSITION_METAL), Sb(51, 5, 83, 1.12f, 1.38f, 5, 0, 12, 4, 5, 121.750f, 46, -3, 2.05f, ElementType.METALLOID), Te(52, 5, 94, 1.26f, 1.35f, 6, 0, 12, 2, 6, 127.600f, 46, 4, 2.10f, ElementType.METALLOID), I(53, 5, 44, 2.15f, 1.33f, 7, 1, 1, 1, 1, 126.905f, 46, -1, 2.66f, ElementType.HALOGEN), Xe(54, 5, 102, 2.10f, 1.70f, 8, 0, 12, 0, 0, 131.300f, 46, 0, 2.60f, ElementType.NOBLE_GAS), Cs(55, 6, 25, 3.01f, 2.25f, 1, 0, 12, 0, 0, 132.905f, 54, 1, 0.79f, ElementType.ALKALI_METAL), Ba(56, 6, 11, 2.41f, 1.98f, 2, 0, 12, 0, 0, 137.340f, 54, 2, 0.89f, ElementType.ALKALINE_EARTH_METAL), La(57, 6, 49, 1.83f, 1.95f, 3, 0, 12, 3, 0, 138.905f, 54, 3, 1.10f, ElementType.LANTHANOID), Ce(58, 6, 19, 1.86f, 1.03f, 4, 0, 12, 3, 0, 140.120f, 54, 3, 1.12f, ElementType.LANTHANOID), Pr(59, 6, 73, 1.62f, 0.90f, 4, 0, 12, 3, 0, 140.908f, 55, 3, 1.13f, ElementType.LANTHANOID), Nd(60, 6, 60, 1.79f, 0.99f, 3, 0, 12, 3, 0, 144.240f, 56, 3, 1.14f, ElementType.LANTHANOID), Pm(61, 6, 71, 1.76f, 0.98f, 3, 0, 12, 3, 0, 145.000f, 58, 3, 1.13f, ElementType.LANTHANOID), Sm(62, 6, 87, 1.74f, 0.96f, 3, 0, 12, 2, 0, 150.400f, 59, 3, 1.17f, ElementType.LANTHANOID), Eu(63, 6, 31, 1.96f, 1.09f, 3, 0, 12, 2, 0, 151.960f, 60, 3, 1.20f, ElementType.LANTHANOID), Gd(64, 6, 37, 1.69f, 0.94f, 3, 0, 12, 3, 0, 157.250f, 61, 3, 1.20f, ElementType.LANTHANOID), Tb(65, 6, 92, 1.66f, 0.92f, 4, 0, 12, 3, 0, 158.925f, 61, 3, 1.10f, ElementType.LANTHANOID), Dy(66, 6, 28, 1.63f, 0.91f, 3, 0, 12, 3, 0, 162.500f, 62, 3, 1.22f, ElementType.LANTHANOID), Ho(67, 6, 43, 1.61f, 0.89f, 3, 0, 12, 3, 0, 164.930f, 64, 3, 1.23f, ElementType.LANTHANOID), Er(68, 6, 29, 1.59f, 0.88f, 3, 0, 12, 3, 0, 167.260f, 65, 3, 1.24f, ElementType.LANTHANOID), Tm(69, 6, 98, 1.57f, 0.87f, 3, 0, 12, 3, 0, 168.934f, 66, 3, 1.25f, ElementType.LANTHANOID), Yb(70, 6, 104, 1.54f, 0.86f, 3, 0, 12, 2, 0, 173.040f, 67, 3, 1.10f, ElementType.LANTHANOID), Lu(71, 6, 52, 1.53f, 0.85f, 3, 0, 12, 3, 0, 174.970f, 68, 3, 1.27f, ElementType.LANTHANOID), Hf(72, 6, 41, 1.40f, 1.58f, 4, 0, 12, 4, 0, 178.490f, 68, 4, 1.30f, ElementType.TRANSITION_METAL), Ta(73, 6, 91, 1.22f, 1.38f, 5, 0, 12, 5, 0, 180.850f, 68, 5, 1.50f, ElementType.TRANSITION_METAL), W(74, 6, 101, 1.26f, 1.46f, 6, 0, 12, 6, 0, 183.850f, 68, 6, 2.36f, ElementType.TRANSITION_METAL), Re(75, 6, 78, 1.30f, 1.59f, 7, 0, 12, 4, 0, 186.200f, 68, 7, 1.90f, ElementType.TRANSITION_METAL), Os(76, 6, 66, 1.58f, 1.28f, 8, 0, 12, 2, 0, 190.200f, 68, 4, 2.20f, ElementType.TRANSITION_METAL), Ir(77, 6, 46, 1.22f, 1.37f, 6, 0, 12, 3, 0, 192.220f, 68, 4, 2.20f, ElementType.TRANSITION_METAL), Pt(78, 6, 74, 1.55f, 1.28f, 4, 0, 6, 0, 0, 195.090f, 68, 4, 2.28f, ElementType.TRANSITION_METAL), Au(79, 6, 9, 1.45f, 1.44f, 3, 0, 6, 0, 0, 196.967f, 68, 3, 2.54f, ElementType.TRANSITION_METAL), Hg(80, 6, 42, 1.55f, 1.32f, 2, 0, 12, 1, 2, 200.59f, 78, 1, 2.00f, ElementType.TRANSITION_METAL), Tl(81, 6, 97, 1.96f, 1.45f, 3, 0, 12, 1, 3, 204.3833f, 78, 1, 1.62f, ElementType.POST_TRANSITION_METAL), Pb(82, 6, 69, 2.16f, 1.47f, 4, 0, 12, 2, 4, 207.200f, 78, 2, 2.33f, ElementType.POST_TRANSITION_METAL), Bi(83, 6, 13, 1.73f, 1.46f, 5, 0, 12, 3, 3, 208.981f, 78, 3, 2.20f, ElementType.POST_TRANSITION_METAL), Po(84, 6, 72, 1.21f, 0.67f, 6, 0, 12, 4, 2, 209.000f, 78, 4, 2.0f, ElementType.METALLOID), At(85, 6, 8, 1.12f, 0.62f, 7, 0, 12, 1, 1, 210.000f, 78, -1, 2.20f, ElementType.HALOGEN), Rn(86, 6, 80, 2.30f, 1.90f, 8, 0, 12, 0, 0, 222.000f, 78, 0, 0.0f, ElementType.NOBLE_GAS), // electroneg not reported Fr(87, 7, 35, 3.24f, 1.80f, 1, 0, 12, 0, 0, 223.000f, -1, 1, 0.70f, ElementType.ALKALI_METAL), Ra(88, 7, 76, 2.57f, 1.43f, 2, 0, 12, 2, 0, 226.000f, -1, 2, 0.9f, ElementType.ALKALINE_EARTH_METAL), Ac(89, 7, 2, 2.12f, 1.18f, 3, 0, 12, 4, 0, 227.000f, -1, 3, 1.1f, ElementType.ACTINOID), Th(90, 7, 95, 1.84f, 1.02f, 4, 0, 12, 1, 0, 232.038f, -1, 4, 1.30f, ElementType.ACTINOID), Pa(91, 7, 68, 1.60f, 0.89f, 5, 0, 12, 4, 0, 231.036f, -1, 5, 1.50f, ElementType.ACTINOID), U(92, 7, 99, 1.75f, 0.97f, 6, 0, 12, 4, 0, 238.029f, -1, 6, 1.38f, ElementType.ACTINOID), Np(93, 7, 64, 1.71f, 0.95f, 6, 0, 12, 4, 0, 237.048f, -1, 5, 1.36f, ElementType.ACTINOID), Pu(94, 7, 75, 1.67f, 0.93f, 6, 0, 12, 3, 0, 244.000f, -1, 4, 1.28f, ElementType.ACTINOID), Am(95, 7, 5, 1.66f, 0.92f, 6, 0, 12, 3, 0, 243.000f, -1, 3, 1.13f, ElementType.ACTINOID), Cm(96, 7, 22, 1.65f, 0.91f, 3, 0, 12, 3, 0, 248.000f, -1, 3, 1.28f, ElementType.ACTINOID), Bk(97, 7, 14, 1.64f, 0.90f, 4, 0, 12, 3, 0, 247.000f, -1, 3, 1.30f, ElementType.ACTINOID), Cf(98, 7, 20, 1.63f, 0.89f, 3, 0, 12, 4, 0, 251.000f, -1, 3, 1.30f, ElementType.ACTINOID), Es(99, 7, 30, 1.62f, 0.88f, -1, 0, 12, 4, 0, 254.000f, -1, 3, 1.30f, ElementType.ACTINOID), Fm(100, 7, 34, 1.61f, 0.87f, -1, 0, 12, 4, 0, 257.000f, -1, 3, 1.30f, ElementType.ACTINOID), Md(101, 7, 53, 1.60f, 0.86f, -1, 0, 12, 4, 0, 256.000f, -1, 3, 1.30f, ElementType.ACTINOID), No(102, 7, 63, 1.59f, 0.85f, -1, 0, 12, 4, 0, 254.000f, -1, 3, 1.30f, ElementType.ACTINOID), Lr(103, 7, 51, 1.58f, 0.84f, -1, 0, 12, 4, 0, 257.000f, -1, 3, 0.00f, ElementType.ACTINOID), // electroneg not reported /** * R-group to represent generic groups that are sometimes present in MDL .sdf * files. */ R(104, 0, 105, 0.0f, 0.0f, 0, 0, 4, 1, 0, 0.000f, -1, 3, 0.00f, ElementType.UNKNOWN); // this is an R-group // should these be declared final? private int atomicNumber; private int period; private int hillOrder; private float VDWRadius; // in Angstroms private float covalentRadius; // in Angstroms private int valenceElectronCount; private int minimumValence; private int maximumValence; private int commonValence; private int maximumCovalentValence; private float atomicMass; private int coreElectronCount; private int oxidationState; private float paulingElectronegativity; private ElementType elementType; //private static final Element[] hillOrderIndex; // static { // hillOrderIndex = new Element[Element.values().length + 1]; // for (Element e : Element.values()) { // hillOrderIndex[e.getHillOrder()] = e; // hillOrderIndex[Element.H.getHillOrder()] = Element.H; // special case for hydrogen private static final Map<String,Element> allElements ; static { allElements = new HashMap<String,Element>(); for (Element e : Element.values()){ allElements.put(e.toString().toLowerCase(), e); } } private Element(int atomicNumber, int period, int hillOrder, float VDWRadius, float covalentRadius, int valenceElectronCount, int minimumValence, int maximumValence, int commonValence, int maximumCovalentValence, float atomicMass, int coreElectronCount, int oxidationState, float paulingElectronegativity, ElementType elementType) { this.atomicNumber = atomicNumber; this.period = period; this.hillOrder = hillOrder; this.VDWRadius = VDWRadius; this.covalentRadius = covalentRadius; this.valenceElectronCount = valenceElectronCount; this.minimumValence = minimumValence; this.maximumValence = maximumValence; this.commonValence = commonValence; this.maximumCovalentValence = maximumCovalentValence; this.atomicMass = atomicMass; this.coreElectronCount = coreElectronCount; this.oxidationState = oxidationState; this.paulingElectronegativity = paulingElectronegativity; this.elementType = elementType; } /** * Returns the atomic number of this Element. * @return the atomic number of this Element. */ public int getAtomicNumber() { return atomicNumber; } /** * Returns the period in the periodic table of this Element. * @return the period in the periodic table of this Element. */ public int getPeriod() { return period; } public int getHillOrder() { throw new RuntimeException("Not implemented, yet!"); //throw new NotImplementedYetException(); //return hillOrder; } /** * Returns the van der Waals radius of this Element. * @return the van der Waals radius of this Element, measured in Angstroms. */ public float getVDWRadius() { return VDWRadius; } /** * Returns the covalent radius of this Element. * @return covalent radius, measured in Angstroms. */ public float getCovalentRadius() { return covalentRadius; } /** * Returns the number of valence electrons for this Element. * @return the number of valence electrons for this Element. */ public int getValenceElectronCount() { return valenceElectronCount; } /** * Returns the minimum valence for this Element. * @return the minimum valence of this atom. */ public int getMinimumValence() { return minimumValence; } /** * Returns the maximum valence for this Element. * @return the maximum valence for this Element. */ public int getMaximumValence() { return maximumValence; } /** * Returns the common valence for this Element. * @return the common valence for this Element. */ public int getCommonValence() { return commonValence; } /** * Returns the maximum valence for this Element. * @return the maximum valence of this element. */ public int getMaximumCovalentValence() { return maximumCovalentValence; } /** * Returns the atomic mass for this Element. * @return the atomic mass for this Element, measured in g/mol. */ public float getAtomicMass() { return atomicMass; } /** * Returns the number of core electrons for this Element. * @return number of core electrons for this Element. */ public int getCoreElectronCount() { return coreElectronCount; } /** * Returns a typical oxidation state for this Element. This information is mostly * useful for metals. * @return a typical oxidation state for this Element. */ public int getOxidationState() { return oxidationState; } /** * Returns the Pauling electronegativity for this Element. * @return the Pauling electronegativity for this Element. */ public float getPaulingElectronegativity() { return paulingElectronegativity; } /** * Returns the Element Type for this Element. * @return the Element Type for this Element. */ public ElementType getElementType() { return elementType; } /** * Returns the Element that corresponds to the specified element symbol. The case * of the element symbol is ignored. Example: FE, fe, Fe represent iron. * @param elementSymbol element symbol to specify Element. * @return the Element specified by the element symbol. */ public static Element valueOfIgnoreCase(String elementSymbol) throws IllegalArgumentException { Element e = allElements.get(elementSymbol.toLowerCase()); if ( e != null) return e; throw new IllegalArgumentException("Invalid element symbol: " + elementSymbol); } /** * Returns true if this Element is Hydrogen. <B>Note:</B> currently Deuterium (D) * and Tritium (T) are not considered Hydrogen. * @return <CODE>true</CODE> if the Element is Hydrogen. */ public boolean isHydrogen() { return (this == H); } /** * Returns <CODE>true</CODE> is the Element is an not Hydrogen. * @return <CODE>true</CODE> is Element is not Hydrogen. */ public boolean isHeavyAtom() { return (this != H); } /** * Returns <CODE>true</CODE> if Element is not Hydrogen and not Carbon. * @return <CODE>true</CODE> if Element is not Hydrogen and not Carbon. */ public boolean isHeteroAtom() { return !(this == C || this == H); } /** * Returns <CODE>true</CODE> if ElementType is a metal. * @return <CODE>true</CODE> if ElementType is a metal. */ public boolean isMetal() { return elementType.isMetal(); } /** * Returns <CODE>true</CODE> if ElementType is a metalloid. * @return <CODE>true</CODE> if ElementType is a metalloid. */ public boolean isMetalloid() { return elementType.isMetalloid(); } /** * Returns <CODE>true</CODE> if ElementType is a non-metal. * @return <CODE>true</CODE> if ElementType is a non-metal. */ public boolean isNonMetal() { return elementType.isNonMetal(); } /** * Returns <CODE>true</CODE> if Element is a halogen (F, Cl, Br, I, At). * @return <CODE>true</CODE> if Element is a halogen. */ public boolean isHalogen() { return elementType.equals(ElementType.HALOGEN); } /** * Returns <CODE>true</CODE> if Element is a chalcogen (O, S, Se, Te, Po). * @return <CODE>true</CODE> if Element is a chalcogen. */ public boolean isChalcogen() { return (this == O || this == S || this == Se || this == Te || this == Po); } /** * Returns the Element that corresponds to the specified Hill Order. * @param index the Hill Order. * @return the Element that corresponds to the specified Hill Order. * @see #getHillOrder() */ public static Element getElementFromHillIndex(int index) { throw new RuntimeException("Not implemented, yet!"); //return hillOrderIndex[index]; } }
package com.alvazan.test; import java.util.List; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.alvazan.orm.api.base.NoSqlEntityManager; import com.alvazan.orm.api.base.NoSqlEntityManagerFactory; import com.alvazan.test.db.Account; import com.alvazan.test.db.Activity; public class TestIndexAndOrParens { private static NoSqlEntityManagerFactory factory; private NoSqlEntityManager mgr; @BeforeClass public static void setup() { factory = FactorySingleton.createFactoryOnce(); } @Before public void createEntityManager() { mgr = factory.createEntityManager(); setupRecords(); } @After public void clearDatabase() { NoSqlEntityManager other = factory.createEntityManager(); other.clearDatabase(true); } @Test public void testSimpleAnd() { List<Activity> findByName = Activity.findWithAnd(mgr, "hello", 5); Assert.assertEquals(1, findByName.size()); List<Activity> list = Activity.findWithAnd(mgr, "hello", 6); Assert.assertEquals(2, list.size()); } @Test public void testBooleanWithAndClause() { Account acc = new Account(); acc.setName("abc"); acc.setIsActive(true); mgr.put(acc); Account acc2 = new Account(); acc2.setName("dean"); acc2.setIsActive(false); mgr.put(acc2); Account acc3 = new Account(); acc3.setName("dean"); acc3.setIsActive(true); mgr.put(acc3); Account acc4 = new Account(); acc4.setName("dean"); acc4.setIsActive(true); mgr.put(acc4); Account acc5 = new Account(); acc5.setName("dean"); acc5.setIsActive(null); mgr.put(acc5); mgr.flush(); List<Account> activeList = Account.findAnd(mgr, "dean", true); Assert.assertEquals(2, activeList.size()); List<Account> nullList = Account.findAnd(mgr, "dean", null); Assert.assertEquals(1, nullList.size()); List<Account> orList = Account.findOr(mgr, "dean", true); Assert.assertEquals(5, orList.size()); } @Test public void testSimpleOr() { List<Activity> findByName = Activity.findWithOr(mgr, "hello", 6); Assert.assertEquals(4, findByName.size()); List<Activity> list = Activity.findWithOr(mgr, "nothaveThe5OrHellohere", 20); Assert.assertEquals(1, list.size()); } @Test public void testParensVsNoParens() { //@NoSqlQuery(name="findWithParens", query="select * FROM TABLE e WHERE" + // " e.name=:name and (e.numTimes = :numTimes or e.isCool = :isCool)"), //@NoSqlQuery(name="findWithoutParens", query="select * FROM TABLE e WHERE" + // " e.name=:name and e.numTimes = :numTimes or e.isCool = :isCool"), //We have a truth table of this where the result of A named query and B named query are on right side //We need to test #2 (A=F, B=T) to make sure results differ //1 F, F, F : A=F, B=F //2 F, F, T : A=F, B=T //3 F, T, F : A=F, B=F //4 F, T, T : A=F, B=T //5 T, F, F : A=F, B=F //6 T, F, T : A=T, B=T //7 T, T, F : A=T, B=T //8 T, T, T : A=T, B=T //First query should not be found....(A) List<Activity> withParens = Activity.findWithParens(mgr, "notfound", 99, 5.55f); Assert.assertEquals(0, withParens.size()); //Second query should be found....(B) List<Activity> list = Activity.findWithoutParens(mgr, "notfound", 99, 5.55f); Assert.assertEquals(1, list.size()); } private void setupRecords() { Activity act1 = new Activity(); act1.setName("hello"); act1.setMyFloat(5.65f); act1.setUniqueColumn("notunique"); act1.setNumTimes(5); act1.setIsCool(true); mgr.put(act1); Activity act2 = new Activity(); act2.setName("notelloBUTHas5ForNumTimes"); act2.setMyFloat(5.65f); act2.setUniqueColumn("notunique"); act2.setNumTimes(5); act2.setIsCool(true); mgr.put(act2); Activity act4 = new Activity(); act4.setName("hello"); act4.setMyFloat(5.65f); act4.setUniqueColumn("notunique"); act4.setNumTimes(6); act4.setIsCool(true); mgr.put(act4); Activity act5 = new Activity(); act5.setName("nothaveThe5OrHellohere"); act5.setMyFloat(5.65f); act5.setUniqueColumn("notunique"); act5.setNumTimes(6); act5.setIsCool(true); mgr.put(act5); Activity act6 = new Activity(); act6.setName("somethingtttt"); act6.setMyFloat(5.55f); act6.setUniqueColumn("notunique"); act6.setNumTimes(9); act6.setIsCool(true); mgr.put(act6); Activity act7 = new Activity(); act7.setName("hello"); act7.setNumTimes(6); mgr.put(act7); mgr.flush(); } }
package com.exedio.cope.instrument; import static java.lang.reflect.Modifier.FINAL; import static java.lang.reflect.Modifier.PRIVATE; import static java.lang.reflect.Modifier.PROTECTED; import static java.lang.reflect.Modifier.PUBLIC; import static java.lang.reflect.Modifier.STATIC; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import com.exedio.cope.BooleanField; import com.exedio.cope.Feature; import com.exedio.cope.Item; import com.exedio.cope.LengthViolationException; import com.exedio.cope.MandatoryViolationException; import com.exedio.cope.RangeViolationException; import com.exedio.cope.SetValue; import com.exedio.cope.Settable; import com.exedio.cope.Type; import com.exedio.cope.UniqueViolationException; import com.exedio.cope.Wrapper; import com.exedio.cope.util.ReactivationConstructorDummy; final class Generator { private static final String STRING = String.class.getName(); private static final String COLLECTION = Collection.class.getName(); private static final String LIST = List.class.getName(); private static final String IO_EXCEPTION = IOException.class.getName(); private static final String SET_VALUE = SetValue.class.getName(); private static final String ITEM = Item.class.getName(); private static final String TYPE_NAME = Type.class.getName(); private static final String REACTIVATION = ReactivationConstructorDummy.class.getName(); private static final String THROWS_MANDATORY = "if {0} is null."; private static final String THROWS_UNIQUE = "if {0} is not unique."; private static final String THROWS_RANGE = "if {0} violates its range constraint."; private static final String THROWS_LENGTH = "if {0} violates its length constraint."; private static final String CONSTRUCTOR_INITIAL = "Creates a new {0} with all the fields initially needed."; private static final String CONSTRUCTOR_INITIAL_PARAMETER = "the initial value for field {0}."; private static final String CONSTRUCTOR_INITIAL_CUSTOMIZE = "It can be customized with the tags " + "<tt>@" + CopeType.TAG_INITIAL_CONSTRUCTOR + ' ' + Option.TEXT_VISIBILITY_PUBLIC + '|' + Option.TEXT_VISIBILITY_PACKAGE + '|' + Option.TEXT_VISIBILITY_PROTECTED + '|' + Option.TEXT_VISIBILITY_PRIVATE + '|' + Option.TEXT_NONE + "</tt> " + "in the class comment and " + "<tt>@" + CopeFeature.TAG_INITIAL + "</tt> in the comment of fields."; private static final String CONSTRUCTOR_GENERIC = "Creates a new {0} and sets the given fields initially."; private static final String CONSTRUCTOR_GENERIC_CALLED = "This constructor is called by {0}."; private static final String CONSTRUCTOR_GENERIC_CUSTOMIZE = "It can be customized with the tag " + "<tt>@" + CopeType.TAG_GENERIC_CONSTRUCTOR + ' ' + Option.TEXT_VISIBILITY_PUBLIC + '|' + Option.TEXT_VISIBILITY_PACKAGE + '|' + Option.TEXT_VISIBILITY_PROTECTED + '|' + Option.TEXT_VISIBILITY_PRIVATE + '|' + Option.TEXT_NONE + "</tt> " + "in the class comment."; private static final String CONSTRUCTOR_REACTIVATION = "Reactivation constructor. Used for internal purposes only."; private static final String FINDER_UNIQUE = "Finds a {0} by it''s unique fields."; private static final String FINDER_UNIQUE_PARAMETER = "shall be equal to field {0}."; private static final String FINDER_UNIQUE_RETURN = "null if there is no matching item."; private static final String QUALIFIER = "Returns the qualifier."; private static final String QUALIFIER_GETTER = "Returns the qualifier."; private static final String QUALIFIER_SETTER = "Sets the qualifier."; private static final String RELATION_GETTER = "Returns the items associated to this item by the relation."; private static final String RELATION_ADDER = "Adds an item to the items associated to this item by the relation."; private static final String RELATION_REMOVER = "Removes an item from the items associated to this item by the relation."; private static final String RELATION_SETTER = "Sets the items associated to this item by the relation."; private static final String TYPE = "The persistent type information for {0}."; private static final String TYPE_CUSTOMIZE = "It can be customized with the tag " + "<tt>@" + CopeType.TAG_TYPE + ' ' + Option.TEXT_VISIBILITY_PUBLIC + '|' + Option.TEXT_VISIBILITY_PACKAGE + '|' + Option.TEXT_VISIBILITY_PROTECTED + '|' + Option.TEXT_VISIBILITY_PRIVATE + '|' + Option.TEXT_NONE + "</tt> " + "in the class comment."; private static final String GENERATED = "This feature has been generated by the cope instrumentor and will be overwritten by the build process."; /** * All generated class features get this doccomment tag. */ static final String TAG_GENERATED = CopeFeature.TAG_PREFIX + "generated"; private final JavaFile javaFile; private final Writer o; private final CRC32 outputCRC = new CRC32(); private final String lineSeparator; private final boolean longJavadoc; private static final String localFinal = "final "; // TODO make switchable from ant target Generator(final JavaFile javaFile, final ByteArrayOutputStream outputStream, final boolean longJavadoc) { this.javaFile = javaFile; this.o = new OutputStreamWriter(new CheckedOutputStream(outputStream, outputCRC)); final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; this.longJavadoc = longJavadoc; } void close() throws IOException { if(o!=null) o.close(); } long getCRC() { return outputCRC.getValue(); } private static final String toCamelCase(final String name) { final char first = name.charAt(0); if (Character.isUpperCase(first)) return name; else return Character.toUpperCase(first) + name.substring(1); } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private void writeThrowsClause(final Collection<Class> exceptions) throws IOException { if(!exceptions.isEmpty()) { o.write("\t\t\tthrows"); boolean first = true; for(final Class e : exceptions) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\t"); o.write(e.getName()); } o.write(lineSeparator); } } private void writeCommentHeader() throws IOException { o.write("/**"); o.write(lineSeparator); if(longJavadoc) { o.write(lineSeparator); o.write("\t **"); o.write(lineSeparator); } } private void writeCommentFooter() throws IOException { writeCommentFooter(null); } private void writeCommentFooter(final String extraComment) throws IOException { o.write("\t * @" + TAG_GENERATED + ' '); o.write(GENERATED); o.write(lineSeparator); if(extraComment!=null) { o.write("\t * "); o.write(extraComment); o.write(lineSeparator); } o.write("\t */"); o.write(lineSeparator); o.write('\t'); // TODO put this into calling methods } private static final String link(final String target) { return "{@link #" + target + '}'; } private static final String link(final String target, final String name) { return "{@link #" + target + ' ' + name + '}'; } private static final String format(final String pattern, final Object... arguments) { return MessageFormat.format(pattern, arguments); } private void writeInitialConstructor(final CopeType type) throws IOException { if(!type.hasInitialConstructor()) return; final List<CopeFeature> initialFeatures = type.getInitialFeatures(); final SortedSet<Class> constructorExceptions = type.getConstructorExceptions(); writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_INITIAL, type.name)); o.write(lineSeparator); for(final CopeFeature feature : initialFeatures) { o.write("\t * @param "); o.write(feature.name); o.write(' '); o.write(format(CONSTRUCTOR_INITIAL_PARAMETER, link(feature.name))); o.write(lineSeparator); } for(final Class constructorException : constructorExceptions) { o.write("\t * @throws "); o.write(constructorException.getName()); o.write(' '); boolean first = true; final StringBuffer initialAttributesBuf = new StringBuffer(); for(final CopeFeature feature : initialFeatures) { if(!feature.getSetterExceptions().contains(constructorException)) continue; if(first) first = false; else initialAttributesBuf.append(", "); initialAttributesBuf.append(feature.name); } final String pattern; if(MandatoryViolationException.class.equals(constructorException)) pattern = THROWS_MANDATORY; else if(UniqueViolationException.class.equals(constructorException)) pattern = THROWS_UNIQUE; else if(RangeViolationException.class.equals(constructorException)) pattern = THROWS_RANGE; else if(LengthViolationException.class.equals(constructorException)) pattern = THROWS_LENGTH; else throw new RuntimeException(constructorException.getName()); o.write(format(pattern, initialAttributesBuf.toString())); o.write(lineSeparator); } writeCommentFooter(CONSTRUCTOR_INITIAL_CUSTOMIZE); writeModifier(type.getInitialConstructorModifier()); o.write(type.name); o.write('('); boolean first = true; for(final CopeFeature feature : initialFeatures) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\tfinal "); o.write(toString(((Settable<?>)feature.getInstance()).getWrapperSetterType(), feature)); o.write(' '); o.write(feature.name); } o.write(')'); o.write(lineSeparator); writeThrowsClause(constructorExceptions); o.write("\t{"); o.write(lineSeparator); o.write("\t\tthis(new " + SET_VALUE + "[]{"); o.write(lineSeparator); for(final CopeFeature feature : initialFeatures) { o.write("\t\t\t"); o.write(type.name); o.write('.'); o.write(feature.name); o.write(".map("); o.write(feature.name); o.write("),"); o.write(lineSeparator); } o.write("\t\t});"); o.write(lineSeparator); o.write("\t}"); } private void writeGenericConstructor(final CopeType type) throws IOException { final Option option = type.genericConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC, type.name)); o.write(lineSeparator); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC_CALLED, "{@link " + TYPE_NAME + "#newItem Type.newItem}")); o.write(lineSeparator); writeCommentFooter(CONSTRUCTOR_GENERIC_CUSTOMIZE); writeModifier(option.getModifier(type.allowSubTypes() ? PROTECTED : PRIVATE)); o.write(type.name); o.write('('); o.write(localFinal); o.write(SET_VALUE + "... setValues)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(setValues);"); o.write(lineSeparator); o.write("\t}"); } private void writeReactivationConstructor(final CopeType type) throws IOException { final Option option = type.reactivationConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(CONSTRUCTOR_REACTIVATION); o.write(lineSeparator); o.write("\t * @see " + ITEM + "#Item(" + REACTIVATION + ",int)"); o.write(lineSeparator); writeCommentFooter(); writeModifier(option.getModifier(type.allowSubTypes() ? PROTECTED : PRIVATE)); o.write(type.name); o.write('('); o.write(localFinal); o.write(REACTIVATION + " d,"); o.write(localFinal); o.write("int pk)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(d,pk);"); o.write(lineSeparator); o.write("\t}"); } private void writeFeature(final CopeFeature feature) throws InjectorParseException, IOException { final Feature instance = feature.getInstance(); for(final Wrapper wrapper : instance.getWrappers()) { final String modifierTag = wrapper.getModifier(); final Option option = modifierTag!=null ? new Option(Injector.findDocTagLine( feature.docComment, CopeFeature.TAG_PREFIX + modifierTag), true) : null; if(option!=null && !option.exists) continue; final String methodName = wrapper.getMethodName(); final java.lang.reflect.Type methodReturnType = wrapper.getMethodReturnType(); final List<java.lang.reflect.Type> parameterTypes = wrapper.getParameterTypes(); final List<String> parameterNames = wrapper.getParameterNames(); final String featureNameCamelCase = toCamelCase(feature.name); final boolean isStatic = wrapper.isStatic(); final int modifier = feature.modifier; final boolean useIs = instance instanceof BooleanField && methodName.startsWith("get"); { writeCommentHeader(); final Object[] arguments = new String[]{ link(feature.name), feature.name, lowerCamelCase(feature.parent.name)}; o.write("\t * "); o.write(format(wrapper.getComment(), arguments)); o.write(lineSeparator); for(final String comment : wrapper.getComments()) { o.write("\t * "); o.write(format(comment, arguments)); o.write(lineSeparator); } writeCommentFooter( modifierTag!=null ? "It can be customized with the tag " + "<tt>@" + CopeFeature.TAG_PREFIX + modifierTag + ' ' + Option.TEXT_VISIBILITY_PUBLIC + '|' + Option.TEXT_VISIBILITY_PACKAGE + '|' + Option.TEXT_VISIBILITY_PROTECTED + '|' + Option.TEXT_VISIBILITY_PRIVATE + '|' + Option.TEXT_NONE + '|' + Option.TEXT_NON_FINAL + (useIs ? '|' + Option.TEXT_BOOLEAN_AS_IS : "") + "</tt> " + "in the comment of the field." : null); } writeModifier( ( option!=null ? option.getModifier(modifier) : ((modifier & (PUBLIC|PROTECTED|PRIVATE)) | FINAL) ) | (isStatic ? STATIC : 0) ); o.write(toString(methodReturnType, feature)); if(option!=null && useIs && option.booleanAsIs) { o.write(" is"); o.write(featureNameCamelCase); } else { o.write(' '); final String pattern = wrapper.getMethodWrapperPattern(); if(pattern!=null) o.write(MessageFormat.format(pattern, featureNameCamelCase, feature.name)); else writeName(methodName, featureNameCamelCase); } if(option!=null) o.write(option.suffix); o.write('('); boolean first = true; final Iterator<String> parameterNameIter = parameterNames.iterator(); for(final java.lang.reflect.Type parameter : parameterTypes) { if(first) first = false; else o.write(','); o.write(localFinal); o.write(toString(parameter, feature)); o.write(' '); final String name = parameterNameIter.next(); o.write(name!=null ? name : feature.name); } o.write(')'); o.write(lineSeparator); { final SortedSet<Class> exceptions = new TreeSet<Class>(CopeType.CLASS_COMPARATOR); exceptions.addAll(wrapper.getThrowsClause()); writeThrowsClause(exceptions); } o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); if(!methodReturnType.equals(void.class)) o.write("return "); o.write(feature.parent.name); o.write('.'); o.write(feature.name); o.write('.'); o.write(methodName); o.write('('); first = true; if(isStatic) { if(first) first = false; else o.write(','); o.write(feature.parent.name); o.write(".class"); } else { first = false; o.write("this"); } for(final String name : parameterNames) { if(first) first = false; else o.write(','); o.write(name!=null ? name : feature.name); } o.write(')'); o.write(';'); o.write(lineSeparator); o.write("\t}"); } } private void writeName(final String methodName, final String featureName) throws IOException { for(int i = 0; i<methodName.length(); i++) if(Character.isUpperCase(methodName.charAt(i))) { o.write(methodName.substring(0, i)); o.write(featureName); o.write(methodName.substring(i)); return; } o.write(methodName); o.write(featureName); } private static final String toString(final Class c, final CopeFeature feature) { if(Wrapper.ClassVariable.class.equals(c)) return feature.parent.name; else if(Wrapper.TypeVariable0.class.equals(c)) return Injector.getGenerics(feature.javaAttribute.type).get(0); else if(Wrapper.TypeVariable1.class.equals(c)) return Injector.getGenerics(feature.javaAttribute.type).get(1); else return c.getCanonicalName(); } private static final String toString(final ParameterizedType t, final CopeFeature feature) { final StringBuffer bf = new StringBuffer(toString(t.getRawType(), feature)); bf.append('<'); boolean first = true; for(final java.lang.reflect.Type a : t.getActualTypeArguments()) { bf.append(toString(a, feature)); if(first) first = false; else bf.append(','); } bf.append('>'); return bf.toString(); } private static final String toString(final Wrapper.ExtendsType t, final CopeFeature feature) { final StringBuffer bf = new StringBuffer(toString(t.getRawType(), feature)); bf.append('<'); boolean first = true; for(final java.lang.reflect.Type a : t.getActualTypeArguments()) { bf.append("? extends "); bf.append(toString(a, feature)); if(first) first = false; else bf.append(','); } bf.append('>'); return bf.toString(); } private static final String toString(final java.lang.reflect.Type t, final CopeFeature feature) { if(t instanceof Class) return toString((Class)t, feature); else if(t instanceof ParameterizedType) return toString((ParameterizedType)t, feature); else if(t instanceof Wrapper.ExtendsType) return toString((Wrapper.ExtendsType)t, feature); else throw new RuntimeException(t.toString()); } private void writeUniqueFinder(final CopeUniqueConstraint constraint) throws IOException, InjectorParseException { final CopeAttribute[] attributes = constraint.getAttributes(); final String className = attributes[0].getParent().name; writeCommentHeader(); o.write("\t * "); o.write(format(FINDER_UNIQUE, lowerCamelCase(className))); o.write(lineSeparator); for(int i=0; i<attributes.length; i++) { o.write("\t * @param "); o.write(attributes[i].name); o.write(' '); o.write(format(FINDER_UNIQUE_PARAMETER, link(attributes[i].name))); o.write(lineSeparator); } o.write("\t * @return "); o.write(FINDER_UNIQUE_RETURN); o.write(lineSeparator); writeCommentFooter(); writeModifier((constraint.modifier & (PRIVATE|PROTECTED|PUBLIC)) | (STATIC|FINAL) ); o.write(className); o.write(" findBy"); o.write(toCamelCase(constraint.name)); o.write('('); for(int i=0; i<attributes.length; i++) { if(i>0) o.write(','); final CopeAttribute attribute = attributes[i]; o.write(localFinal); o.write(getBoxedType(attribute)); o.write(' '); o.write(attribute.name); } o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(attributes[0].parent.name); o.write('.'); o.write(constraint.name); o.write(".searchUnique("); o.write(className); o.write(".class,"); o.write(attributes[0].name); for(int i = 1; i<attributes.length; i++) { o.write(','); o.write(attributes[i].name); } o.write(");"); o.write(lineSeparator); o.write("\t}"); } @SuppressWarnings("deprecation") private String getBoxedType(final CopeAttribute a) { return a.getBoxedType(); } private void writeSerialVersionUID() throws IOException { // TODO make disableable { writeCommentHeader(); writeCommentFooter(null); writeModifier(PRIVATE|STATIC|FINAL); o.write("long serialVersionUID = 1l;"); } } private void writeType(final CopeType type) throws IOException { final Option option = type.typeOption; if(option.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(TYPE, lowerCamelCase(type.name))); o.write(lineSeparator); writeCommentFooter(TYPE_CUSTOMIZE); writeModifier(option.getModifier(PUBLIC) | STATIC|FINAL); // TODO obey class visibility o.write(TYPE_NAME + '<'); o.write(type.name); o.write("> TYPE = newType("); o.write(type.name); o.write(".class)"); o.write(lineSeparator); o.write(';'); } } void write() throws IOException, InjectorParseException { final String buffer = javaFile.buffer.toString(); int previousClassEndPosition = 0; for(final JavaClass javaClass : javaFile.getClasses()) { final CopeType type = CopeType.getCopeType(javaClass); final int classEndPosition = javaClass.getClassEndPosition(); if(type!=null) { assert previousClassEndPosition<=classEndPosition; if(previousClassEndPosition<classEndPosition) o.write(buffer, previousClassEndPosition, classEndPosition-previousClassEndPosition); writeClassFeatures(type); previousClassEndPosition = classEndPosition; } } o.write(buffer, previousClassEndPosition, buffer.length()-previousClassEndPosition); } private void writeClassFeatures(final CopeType type) throws IOException, InjectorParseException { if(!type.isInterface()) { writeInitialConstructor(type); writeGenericConstructor(type); writeReactivationConstructor(type); for(final CopeFeature feature : type.getFeatures()) { writeFeature(feature); if(feature instanceof CopeUniqueConstraint) writeUniqueFinder((CopeUniqueConstraint)feature); } for(final CopeQualifier qualifier : sort(type.getQualifiers())) writeQualifier(qualifier); for(final CopeRelation relation : sort(type.getRelations(true))) writeRelation(relation, false); for(final CopeRelation relation : sort(type.getRelations(false))) writeRelation(relation, true); writeSerialVersionUID(); writeType(type); } } private static final <X extends CopeFeature> List<X> sort(final List<X> l) { final ArrayList<X> result = new ArrayList<X>(l); Collections.sort(result, new Comparator<X>() { public int compare(final X a, final X b) { return a.parent.javaClass.getFullName().compareTo(b.parent.javaClass.getFullName()); } }); return result; } private void writeModifier(final int modifier) throws IOException { final String modifierString = Modifier.toString(modifier); if(modifierString.length()>0) { o.write(modifierString); o.write(' '); } } @Deprecated private void writeQualifierParameters(final CopeQualifier qualifier) throws IOException, InjectorParseException { final CopeAttribute[] keys = qualifier.getKeyAttributes(); for(int i = 0; i<keys.length; i++) { if(i>0) o.write(','); o.write(localFinal); o.write(keys[i].persistentType); o.write(' '); o.write(keys[i].name); } } @Deprecated private void writeQualifierCall(final CopeQualifier qualifier) throws IOException, InjectorParseException { final CopeAttribute[] keys = qualifier.getKeyAttributes(); for(int i = 0; i<keys.length; i++) { o.write(','); o.write(keys[i].name); } } @Deprecated private void writeQualifier(final CopeQualifier qualifier) throws IOException, InjectorParseException { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER); o.write(lineSeparator); writeCommentFooter(); o.write("public final "); // TODO: obey attribute visibility o.write(qualifierClassName); o.write(" get"); o.write(toCamelCase(qualifier.name)); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(qualifierClassName); o.write(')'); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".getQualifier(this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); final List<CopeAttribute> qualifierAttributes = Arrays.asList(qualifier.getAttributes()); for(final CopeFeature feature : qualifier.parent.getFeatures()) { if(feature instanceof CopeAttribute) { final CopeAttribute attribute = (CopeAttribute)feature; if(qualifierAttributes.contains(attribute)) continue; writeQualifierGetter(qualifier, attribute); writeQualifierSetter(qualifier, attribute); } } } @Deprecated private void writeQualifierGetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException, InjectorParseException { if(attribute.getterOption.exists) { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_GETTER); o.write(lineSeparator); writeCommentFooter(); writeModifier(attribute.getGeneratedGetterModifier()); o.write(attribute.persistentType); o.write(" get"); o.write(toCamelCase(attribute.name)); o.write(attribute.getterOption.suffix); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".get("); o.write(qualifierClassName); o.write('.'); o.write(attribute.name); o.write(",this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } @Deprecated private void writeQualifierSetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException, InjectorParseException { if(attribute.setterOption.exists) { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_SETTER); o.write(lineSeparator); writeCommentFooter(); writeModifier(attribute.getGeneratedSetterModifier()); o.write("void set"); o.write(toCamelCase(attribute.name)); o.write(attribute.setterOption.suffix); o.write('('); writeQualifierParameters(qualifier); o.write(','); o.write(localFinal); o.write(attribute.getBoxedType()); o.write(' '); o.write(attribute.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(attribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".set("); o.write(qualifierClassName); o.write('.'); o.write(attribute.name); o.write(','); o.write(attribute.name); o.write(",this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } @Deprecated private void writeRelation(final CopeRelation relation, final boolean source) throws IOException { final boolean vector = relation.vector; final String endType = relation.getEndType(source); final String endName = relation.getEndName(source); final String endNameCamel = toCamelCase(endName); final String methodName = source ? "Sources" : "Targets"; final String className = relation.parent.javaClass.getFullName(); // getter if(!vector || !source) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_GETTER); o.write(lineSeparator); writeCommentFooter(); o.write("public final " + LIST + '<'); // TODO: obey attribute visibility o.write(endType); o.write("> get"); o.write(endNameCamel); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".get"); o.write(methodName); o.write("(this);"); o.write(lineSeparator); o.write("\t}"); } // adder if(!vector) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_ADDER); o.write(lineSeparator); writeCommentFooter(); o.write("public final boolean addTo"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(endType); o.write(' '); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".addTo"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } // remover if(!vector) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_REMOVER); o.write(lineSeparator); writeCommentFooter(); o.write("public final boolean removeFrom"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(endType); o.write(' '); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".removeFrom"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } // setter if(!vector || !source) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_SETTER); o.write(lineSeparator); writeCommentFooter(); o.write("public final void set"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(COLLECTION + "<? extends "); o.write(endType); o.write("> "); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(className); o.write('.'); o.write(relation.name); o.write(".set"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } }
package demo; import com.jayway.restassured.RestAssured; import com.palantir.docker.compose.DockerComposeRule; import com.palantir.docker.compose.connection.DockerPort; import org.junit.*; import java.util.function.Function; import static com.jayway.restassured.RestAssured.get; import static com.palantir.docker.compose.connection.waiting.HealthChecks.toRespondOverHttp; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isA; public class IntegrationTest { private static final int INTERNAL_PORT = 8080; private static final Function<DockerPort, String> TO_EXTERNAL_URI = (port) -> port.inFormat("http://$HOST:$EXTERNAL_PORT"); @Rule public DockerComposeRule docker = DockerComposeRule.builder() .file("../docker-compose.yml") .waitingForService("greeting-service", toRespondOverHttp(INTERNAL_PORT, TO_EXTERNAL_URI)) .waitingForService("counter-service", toRespondOverHttp(INTERNAL_PORT, TO_EXTERNAL_URI)) .waitingForService("master-service", toRespondOverHttp(INTERNAL_PORT, TO_EXTERNAL_URI)) .saveLogsTo("build/docker-logs") .build(); @Before public void setUp() throws Exception { docker.dockerCompose().up(); DockerPort masterService = docker.containers().container("master-service").port(INTERNAL_PORT); RestAssured.baseURI = TO_EXTERNAL_URI.apply(masterService); } @After public void tearDown() throws Exception { docker.dockerCompose().down(); } @Test public void shouldReturnData() throws Exception { get("/info") .then().assertThat() .body("counter", isA(Number.class)) .body("greeting", is("Hello World")); } @Test public void shouldReturnDefaultGreetingWhenGreetingServiceDown() throws Exception { docker.dockerCompose().container("greeting-service").stop(); get("/info") .then().assertThat() .body("greeting", is("Hola!")); } @Test public void shouldReturnDefaultCountWhenCounterServiceDown() throws Exception { docker.dockerCompose().container("counter-service").stop(); get("/info") .then().assertThat() .body("counter", is(42)); } }
//Human = player 1 Alien = player 2 import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import java.net.*; import javax.swing.*; import javax.imageio.*; import java.util.Random; import java.util.ArrayList; import java.util.Scanner; import java.util.Date; import java.text.DateFormat; import javax.sound.sampled.*; public class BattleGround extends JPanel implements ActionListener{ Timer tm = new Timer(5, this); int humanX = 100, velHumanX = 0, humanY = 100, velHumanY = 0, humanHeight = 0, humanWidth = 0, humanDeathSequence = 0; BufferedImage humanImage; BufferedImage alienImage; int width = width(); int height = height(); int alienX = 500, velAlienX = 0, alienY = 500, velAlienY = 0, alienHeight = 0, alienWidth = 0, alienDeathSequence = 0; boolean fieldReady = false; ArrayList<Integer> starX = new ArrayList<>(); ArrayList<Integer> starY = new ArrayList<>(); ArrayList<Integer> bulletX = new ArrayList<>(); ArrayList<Integer> bulletY = new ArrayList<>(); ArrayList<Integer> bulletVelX = new ArrayList<>(); ArrayList<Integer> bulletVelY = new ArrayList<>(); ArrayList<Integer> bulletDuration = new ArrayList<>(); ArrayList<Integer> asteroidX = new ArrayList<>(); ArrayList<Integer> asteroidY = new ArrayList<>(); boolean bulletsActive = false, humanDied = false, alienDied = false; int asteroids = 0; public BattleGround(){ URL resource = getClass().getResource("HumanShip.png");//get human fighter try{ humanImage = ImageIO.read(resource); }catch(IOException e){ System.out.println("This file was improperly installed.\nResource \'" + resource + "\' not found."); } URL resource2 = getClass().getResource("AlienShip.png");//get alien fighter try{ alienImage = ImageIO.read(resource2); }catch(IOException e){ System.out.println("This file was improperly installed.\nResource \'" + resource2 + "\' not found."); } try { // Open an audio input stream. URL url = this.getClass().getClassLoader().getResource("237089__foolboymedia__race-track.wav"); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); // Get a sound clip resource. Clip clip = AudioSystem.getClip(); // Open audio clip and load samples from the audio input stream. clip.open(audioIn); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.out.println("The music files for this game were improperly installed"); } catch (LineUnavailableException e) { e.printStackTrace(); } humanHeight = humanImage.getHeight(); humanWidth = humanImage.getWidth(); alienHeight = alienImage.getHeight(); alienWidth = alienImage.getWidth(); Random cow = new Random(); humanX = cow.nextInt(width-humanWidth); humanY = cow.nextInt(height-humanHeight); do{ alienX = cow.nextInt(width-alienWidth); alienY = cow.nextInt(height-alienHeight); }while((alienX+alienWidth >= humanX && alienX <= humanX+humanWidth && alienY+alienHeight >= humanY && alienY <= humanY+humanHeight)); //Human Input getInputMap().put(KeyStroke.getKeyStroke("released ENTER"), "enter without modifiers"); getActionMap().put("enter without modifiers", new AbstractAction(){public void actionPerformed(ActionEvent a){fire(1);}}); getInputMap().put(KeyStroke.getKeyStroke("pressed UP"), "up arrow"); getActionMap().put("up arrow", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!humanDied){velHumanY = -4;}}}); getInputMap().put(KeyStroke.getKeyStroke("released UP"), "up arrow released"); getActionMap().put("up arrow released", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!humanDied){velHumanY = 0;}}}); getInputMap().put(KeyStroke.getKeyStroke("pressed LEFT"), "left arrow"); getActionMap().put("left arrow", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!humanDied){velHumanX = -4;}}}); getInputMap().put(KeyStroke.getKeyStroke("released LEFT"), "left arrow released"); getActionMap().put("left arrow released", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!humanDied){velHumanX = 0;}}}); getInputMap().put(KeyStroke.getKeyStroke("pressed DOWN"), "down arrow"); getActionMap().put("down arrow", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!humanDied){velHumanY = 4;}}}); getInputMap().put(KeyStroke.getKeyStroke("released DOWN"), "down arrow released"); getActionMap().put("down arrow released", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!humanDied){velHumanY = 0;}}}); getInputMap().put(KeyStroke.getKeyStroke("pressed RIGHT"), "right arrow"); getActionMap().put("right arrow", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!humanDied){velHumanX = 4;}}}); getInputMap().put(KeyStroke.getKeyStroke("released RIGHT"), "right arrow released"); getActionMap().put("right arrow released", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!humanDied){velHumanX = 0;}}}); //Alien Input getInputMap().put(KeyStroke.getKeyStroke("released SPACE"), "space without modifiers"); getActionMap().put("space without modifiers", new AbstractAction(){public void actionPerformed(ActionEvent a){fire(2);}}); getInputMap().put(KeyStroke.getKeyStroke("pressed W"), "up"); getActionMap().put("up", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!alienDied){velAlienY = -4;}}}); getInputMap().put(KeyStroke.getKeyStroke("released W"), "up released"); getActionMap().put("up released", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!alienDied){velAlienY = 0;}}}); getInputMap().put(KeyStroke.getKeyStroke("pressed A"), "left"); getActionMap().put("left", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!alienDied){velAlienX = -4;}}}); getInputMap().put(KeyStroke.getKeyStroke("released A"), "left released"); getActionMap().put("left released", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!alienDied){velAlienX = 0;}}}); getInputMap().put(KeyStroke.getKeyStroke("pressed S"), "down"); getActionMap().put("down", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!alienDied){velAlienY = 4;}}}); getInputMap().put(KeyStroke.getKeyStroke("released S"), "down released"); getActionMap().put("down released", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!alienDied){velAlienY = 0;}}}); getInputMap().put(KeyStroke.getKeyStroke("pressed D"), "right"); getActionMap().put("right", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!alienDied){velAlienX = 4;}}}); getInputMap().put(KeyStroke.getKeyStroke("released D"), "right released"); getActionMap().put("right released", new AbstractAction(){public void actionPerformed(ActionEvent a){if(!alienDied){velAlienX = 0;}}}); tm.start(); } public void actionPerformed(ActionEvent e){ humanX += velHumanX; humanY += velHumanY; alienX += velAlienX; alienY += velAlienY; if(humanX < -humanWidth){//wrap screen for human player humanX = width - humanWidth; }else if(humanX > width - humanWidth){//test humanX = -humanWidth; }else if(humanY < -humanHeight){ humanY = height - humanHeight; }else if(humanY > height - humanHeight){ humanY = -humanHeight; } if(alienX < -alienWidth){//wrap screen for human player alienX = width - alienWidth; }else if(alienX > width - alienWidth){ alienX = -alienWidth; }else if(alienY < -alienHeight){ alienY = height - alienHeight; }else if(alienY > height - alienHeight){ alienY = -alienHeight; } theEnd(); repaint(); } public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(0, 0, width, height); if(!fieldReady){//generate stars and asteroids g.setColor(Color.WHITE); Random fromage = new Random(); for(int i = 0; i <= (width/3); i++){//randomly generate stars starX.add(fromage.nextInt(width)); starY.add(fromage.nextInt(height)); g.fillOval(starX.get(i), starY.get(i), 5, 5); } asteroids = fromage.nextInt(5) + 2;//randomly generate asteroids int rockX, rockY, rockA, rockB; do{ rockX = fromage.nextInt(width)- 180; rockY = fromage.nextInt(height) - 180; } while((rockX > humanX - 181 && rockX < humanX + humanWidth && rockY < humanY + humanHeight && rockY > humanY - 181) || (rockX > alienX - 181 && rockX < alienX + alienWidth && rockY < alienY + alienHeight && rockY > alienY - 181) || (rockX < 0 || rockY <0)); asteroidX.add(rockX);//pt 0 asteroidX.add(rockX - fromage.nextInt(41)+20); asteroidX.add(rockX - fromage.nextInt(31)+40); asteroidX.add(rockX + fromage.nextInt(4)-2); asteroidX.add(rockX + fromage.nextInt(31)+40); asteroidX.add(rockX + fromage.nextInt(31)+150); asteroidX.add(rockX + fromage.nextInt(31)+130); asteroidX.add(rockX + fromage.nextInt(31)+80); asteroidX.add(rockX + fromage.nextInt(31)+40); asteroidX.add(rockX); asteroidY.add(rockY);//pt 1 asteroidY.add(rockY + fromage.nextInt(31)+40); asteroidY.add(rockY + fromage.nextInt(31)+80); asteroidY.add(rockY + fromage.nextInt(31)+150); asteroidY.add(rockY + fromage.nextInt(31)+150); asteroidY.add(rockY + fromage.nextInt(31)+80); asteroidY.add(rockY + fromage.nextInt(31)+60); asteroidY.add(rockY + fromage.nextInt(31)+60); asteroidY.add(rockY + fromage.nextInt(31)+40); asteroidY.add(rockY); do{ rockA = fromage.nextInt(width) - 180; rockB = fromage.nextInt(height) - 180; }while((rockA > humanX - 181 && rockA < humanX + humanWidth && rockB < humanY + humanHeight && rockB > humanY - 181) || (rockA > alienX - 181 && rockA < alienX + alienWidth && rockB < alienY + alienHeight && rockB > alienY - 181) || (rockA < 0 || rockB <0)); asteroidX.add(rockA); asteroidX.add(rockA-(fromage.nextInt(21) + 20)); asteroidX.add(rockA-(fromage.nextInt(31) + 20)); asteroidX.add(rockA-fromage.nextInt(4) - 2); asteroidX.add(rockA+fromage.nextInt(31) + 30); asteroidX.add(rockA+fromage.nextInt(31) + 150); asteroidX.add(rockA+fromage.nextInt(31) + 130); asteroidX.add(rockA+fromage.nextInt(31) + 80); asteroidX.add(rockA+fromage.nextInt(31) + 40); asteroidX.add(rockA); asteroidY.add(rockB); asteroidY.add(rockB+fromage.nextInt(31) + 40); asteroidY.add(rockB+fromage.nextInt(31) + 80); asteroidY.add(rockB+ fromage.nextInt(31) + 150); asteroidY.add(rockB+ fromage.nextInt(31) + 150); asteroidY.add(rockB+ fromage.nextInt(31) + 80); asteroidY.add(rockB+ fromage.nextInt(31) + 20); asteroidY.add(rockB+ fromage.nextInt(31) + 5); asteroidY.add(rockB+ fromage.nextInt(31)); asteroidY.add(rockB); Polygon asteroid = new Polygon(); for(int i = 0; i < 10; i++) { asteroid.addPoint(asteroidX.get(i), asteroidY.get(i)); } g.setColor(Color.GRAY); g.fillPolygon(asteroid); Polygon asteroid1 = new Polygon(); for(int i=10;i<20;i++) asteroid1.addPoint(asteroidX.get(i), asteroidY.get(i)); g.fillPolygon(asteroid1); fieldReady = true; }else{ g.setColor(Color.WHITE); for(int i = 0; i < starX.size(); i++){ g.fillOval(starX.get(i), starY.get(i), 5, 5); } Polygon asteroid = new Polygon(); for(int i = 0; i < 10; i++) { asteroid.addPoint(asteroidX.get(i), asteroidY.get(i)); } g.setColor(Color.GRAY); g.fillPolygon(asteroid); Polygon asteroid1 = new Polygon(); for(int i=10;i<20;i++) asteroid1.addPoint(asteroidX.get(i), asteroidY.get(i)); g.fillPolygon(asteroid1); } if(humanDied && humanDeathSequence <= 400) { g.setColor(Color.RED); g.fillOval((humanX + (humanWidth + humanX)) / 2 - humanDeathSequence, (humanY + (humanHeight + humanY)) / 2 - humanDeathSequence, 10, 10); g.fillOval((humanX + (humanWidth + humanX)) / 2, (humanY + (humanHeight + humanY)) / 2 - humanDeathSequence, 10, 10); g.fillOval((humanX + (humanWidth + humanX)) / 2 + humanDeathSequence, (humanY + (humanHeight + humanY)) / 2 - humanDeathSequence, 10, 10); g.fillOval((humanX + (humanWidth + humanX)) / 2 + humanDeathSequence, (humanY + (humanHeight + humanY)) / 2, 10, 10); g.fillOval((humanX + (humanWidth + humanX)) / 2 + humanDeathSequence, (humanY + (humanHeight + humanY)) / 2 + humanDeathSequence, 10, 10); g.fillOval((humanX + (humanWidth + humanX)) / 2, (humanY + (humanHeight + humanY)) / 2 + humanDeathSequence, 10, 10); g.fillOval((humanX + (humanWidth + humanX)) / 2 - humanDeathSequence, (humanY + (humanHeight + humanY)) / 2 + humanDeathSequence, 10, 10); g.fillOval((humanX + (humanWidth + humanX)) / 2 - humanDeathSequence, (humanY + (humanHeight + humanY)) / 2, 10, 10); humanDeathSequence+=8; } if(alienDied && alienDeathSequence <= 400) { g.setColor(Color.RED); g.fillOval((alienX + (alienWidth + alienX)) / 2 - alienDeathSequence, (alienY + (alienHeight + alienY)) / 2 - alienDeathSequence, 10, 10); g.fillOval((alienX + (alienWidth + alienX)) / 2, (alienY + (alienHeight + alienY)) / 2 - alienDeathSequence, 10, 10); g.fillOval((alienX + (alienWidth + alienX)) / 2 + alienDeathSequence, (alienY + (alienHeight + alienY)) / 2 - alienDeathSequence, 10, 10); g.fillOval((alienX + (alienWidth + alienX)) / 2 + alienDeathSequence, (alienY + (alienHeight + alienY)) / 2, 10, 10); g.fillOval((alienX + (alienWidth + alienX)) / 2 + alienDeathSequence, (alienY + (alienHeight + alienY)) / 2 + alienDeathSequence, 10, 10); g.fillOval((alienX + (alienWidth + alienX)) / 2, (alienY + (alienHeight + alienY)) / 2 + alienDeathSequence, 10, 10); g.fillOval((alienX + (alienWidth + alienX)) / 2 - alienDeathSequence, (alienY + (alienHeight + alienY)) / 2 + alienDeathSequence, 10, 10); g.fillOval((alienX + (alienWidth + alienX)) / 2 - alienDeathSequence, (alienY + (alienHeight + alienY)) / 2, 10, 10); alienDeathSequence+=8; } if(!humanDied) g.drawImage(humanImage, humanX, humanY, null);//draw human ship if(!alienDied) g.drawImage(alienImage, alienX, alienY, null);//draw alien ship if(bulletsActive){ for(int i = 0; i < bulletX.size(); i++){ g.setColor(Color.WHITE); g.drawOval(bulletX.get(i), bulletY.get(i), 15, 15); g.setColor(Color.WHITE); g.fillOval(bulletX.get(i), bulletY.get(i), 15, 15); bulletX.set(i, bulletX.get(i) + bulletVelX.get(i)); bulletY.set(i, bulletY.get(i) + bulletVelY.get(i)); if((bulletX.get(i) > humanX + 15 && bulletX.get(i) < (humanX + humanWidth - 15)) && (bulletY.get(i) > humanY + 15 && bulletY.get(i) < (humanY + humanHeight - 15)) && !humanDied){ humanDied = true; bulletDuration.set(i, 100);//erase bullet } if((bulletX.get(i) > alienX + 15 && bulletX.get(i) < (alienX + alienWidth - 15)) && (bulletY.get(i) > alienY + 8 && bulletY.get(i) < (alienY + alienHeight - 15)) && !alienDied){ alienDied = true; bulletDuration.set(i, 100);//erase bullet } if(bulletX.get(i) < -15) //wrap bullets around screen bulletX.set(i,width-15); if(bulletX.get(i) > width) bulletX.set(i, -15); if(bulletY.get(i) < -15) bulletY.set(i,height-15); if(bulletY.get(i) > height) bulletY.set(i, -15); if((bulletX.get(i) > asteroidX.get(0) && bulletX.get(i) < asteroidX.get(0) + 181 && bulletY.get(i) > asteroidY.get(0) && bulletY.get(i) < asteroidY.get(0) + 181)||(bulletX.get(i) > asteroidX.get(10) && bulletX.get(i) < asteroidX.get(10) + 150 && bulletY.get(i) > asteroidY.get(10)+20 && bulletY.get(i) < asteroidY.get(10) + 150)) {//bullet explodes on asteroid bulletDuration.set(i, 500); } if(bulletDuration.get(i) >= 100){ bulletX.remove(i); bulletY.remove(i); bulletVelX.remove(i); bulletVelY.remove(i); bulletDuration.remove(i); }else{ bulletDuration.set(i, bulletDuration.get(i) + 1); } } if(bulletDuration.size() == 0) bulletsActive = false; } if(((humanX+humanWidth) > asteroidX.get(0) && humanX < (asteroidX.get(0)+120) && (humanY+humanHeight) > asteroidY.get(0)+50 && humanY<(asteroidY.get(0)+130))||((humanX+humanWidth) > asteroidX.get(10) && humanX < (asteroidX.get(10)+160) && (humanY+humanHeight) > asteroidY.get(10)-20 && humanY<(asteroidY.get(10)+120))){//Did player1 hit asteroid? humanDied = true; } if(((alienX+alienWidth) > asteroidX.get(0) && alienX < (asteroidX.get(0)+120) && (alienY+alienHeight) > asteroidY.get(0)+50 && alienY<(asteroidY.get(0)+130))||((alienX+alienWidth) > asteroidX.get(10) && alienX < (asteroidX.get(10)+160) && (alienY+alienHeight) > asteroidY.get(10)-20 && alienY<(asteroidY.get(10)+120))){//Did player1 hit asteroid? alienDied = true; } } public static void main(String[] args){ try{ PrintWriter out = new PrintWriter(new FileWriter("score.txt", true), true); Date now = new Date(); out.write(DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now)); out.close(); }catch(IOException e){ System.out.println(e); } BattleGround battlescreen = new BattleGround(); JFrame frame = new JFrame("MiniInvaders 0.0"); frame.setSize(new Dimension(200, 200)); frame.setExtendedState(Frame.MAXIMIZED_BOTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(battlescreen); frame.setVisible(true); } public int width(){ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); return (int)screenSize.getWidth() + 1; } public int height(){ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); return (int)screenSize.getHeight() + 1; } public void fire(int whoShot){ bulletsActive = true; bulletDuration.add(0); switch(whoShot){ case 1: if(!(velHumanX == 0 && velHumanY == 0)) { bulletVelX.add(velHumanX*2); bulletVelY.add(velHumanY*2); bulletX.add((humanX + humanWidth / 2) + (velHumanX * 40)); bulletY.add((humanY + humanHeight / 2) + (velHumanY * 40)); } break; case 2: if(!(velAlienX == 0 && velAlienY == 0)) { bulletVelX.add(velAlienX*2); bulletVelY.add(velAlienY*2); bulletX.add((alienX + alienWidth / 2) + (velAlienX * 40)); bulletY.add((alienY + alienHeight / 2) + (velAlienY * 40)); } break; } } public void theEnd(){ if((alienDeathSequence > 400 && !humanDied) || (humanDeathSequence > 400 && !alienDied) || (alienDeathSequence > 400 && humanDeathSequence > 400)){ tm.stop(); File score = new File("score.txt"); try{ Scanner input = new Scanner(score); System.out.println(input.nextLine()); }catch(IOException e){ System.out.println("Score file improperly installed"); } System.exit(0); } } }
package com.sims.topaz; import java.sql.Date; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.graphics.drawable.TransitionDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.sims.topaz.adapter.CommentAdapter; import com.sims.topaz.modele.CommentItem; import com.sims.topaz.network.NetworkRestModule; import com.sims.topaz.network.interfaces.CommentDelegate; import com.sims.topaz.network.interfaces.ErreurDelegate; import com.sims.topaz.network.interfaces.LikeStatusDelegate; import com.sims.topaz.network.interfaces.MessageDelegate; import com.sims.topaz.network.modele.ApiError; import com.sims.topaz.network.modele.Comment; import com.sims.topaz.network.modele.Message; import com.sims.topaz.network.modele.Preview; import com.sims.topaz.utils.MyTypefaceSingleton; import com.sims.topaz.utils.SimsContext; public class CommentFragment extends Fragment implements MessageDelegate,LikeStatusDelegate,CommentDelegate,ErreurDelegate{ private TextView mFirstComment; private TextView mFirstCommentNameUser; private TextView mFirstCommentTimestamp; private EditText mNewComment; private ListView mListComments; private ImageButton mShareButton; private ImageButton mLikeButton; private ImageButton mDislikeButton; // The main message private Message mMessage=null; //intelligence private NetworkRestModule restModule = new NetworkRestModule(this); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_comment, container, false); mFirstComment = (TextView) v.findViewById(R.id.comment_first_comment_text); mFirstComment.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace()); mFirstCommentNameUser = (TextView) v.findViewById(R.id.comment_person_name); mFirstCommentNameUser.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace()); mFirstCommentTimestamp = (TextView) v.findViewById(R.id.comment_time); mFirstCommentTimestamp.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace()); mNewComment = (EditText)v.findViewById(R.id.write_comment_text); mNewComment.setTypeface(MyTypefaceSingleton.getInstance().getTypeFace()); mListComments = (ListView)v.findViewById(R.id.comment_list); //Set Like, Dislike and Share Buttons setButtons(v); //get the main message from the preview id loadMessage(); return v; } private void displayComments() { List<CommentItem> lci = new ArrayList<CommentItem>(); for (Comment co : mMessage.getComments()) { lci.add(new CommentItem(co)); } mListComments.setAdapter(new CommentAdapter(SimsContext.getContext(), R.layout.fragment_comment_item, lci)); } //Set Like, Dislike and Share Buttons private void setButtons(View v) { mShareButton = (ImageButton)v.findViewById(R.id.comment_share); mLikeButton = (ImageButton)v.findViewById(R.id.comment_like); mDislikeButton = (ImageButton)v.findViewById(R.id.comment_dislike); mShareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {shareMessage();} }); mLikeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {likeMessage();} }); mDislikeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {dislikeMessage();} }); } private void loadMessage() { //get the main message from the preview id if(getArguments()!=null && getArguments().containsKey("id_preview")){ Long id = getArguments().getLong("id_preview"); restModule.getMessage(id); } } protected void likeMessage() { if(mMessage!=null) { switch(mMessage.likeStatus) { case LIKED: mMessage.unlike(); ((TransitionDrawable) mLikeButton.getDrawable()) .reverseTransition(0); break; case NONE: mMessage.like(); ((TransitionDrawable) mLikeButton.getDrawable()) .startTransition(0); break; case DISLIKED: mMessage.undislike();mMessage.like(); ((TransitionDrawable) mDislikeButton.getDrawable()) .reverseTransition(0); ((TransitionDrawable) mLikeButton.getDrawable()) .startTransition(0); break; } //REST method call restModule.postLikeStatus(mMessage); //Update view updateLikes(); } } protected void dislikeMessage() { if(mMessage!=null) { switch(mMessage.likeStatus) { case LIKED: mMessage.unlike(); mMessage.dislike(); ((TransitionDrawable) mLikeButton.getDrawable()) .reverseTransition(0); ((TransitionDrawable) mDislikeButton.getDrawable()) .startTransition(0); break; case NONE: mMessage.dislike(); ((TransitionDrawable) mDislikeButton.getDrawable()) .startTransition(0); break; case DISLIKED: mMessage.undislike(); ((TransitionDrawable) mDislikeButton.getDrawable()) .reverseTransition(0); break; } // REST method call restModule.postLikeStatus(mMessage); //update view updateLikes(); } } // public void onDoneButton(){ // getFragmentManager().beginTransaction().remove(this).commit(); @Override public void afterPostMessage(Message message) {} @Override public void afterGetMessage(Message message) { if(message!=null) { mMessage=message; mFirstComment.setText(message.getText()); mFirstCommentTimestamp.setText(DateFormat.format (getString(R.string.date_format), new Date( message.getTimestamp() ) ) ); initLikeButtons(); updateLikes(); displayComments(); } } private void initLikeButtons() { if(mMessage==null) return; switch(mMessage.likeStatus) { case NONE: //nothing break; case LIKED: ((TransitionDrawable) mLikeButton.getDrawable()) .startTransition(0); break; case DISLIKED: ((TransitionDrawable) mDislikeButton.getDrawable()) .startTransition(0); break; } } protected void updateLikes() { if(mMessage!=null) { TextView likes = (TextView) getView().findViewById(R.id.textViewLikes); likes.setText(Integer.toString(mMessage.getLikes())); TextView dislikes = (TextView) getView().findViewById(R.id.textViewDislikes); dislikes.setText(Integer.toString(mMessage.getDislikes())); } } @Override public void afterGetPreviews(List<Preview> list) {} @Override public void networkError() { Toast.makeText(SimsContext.getContext(),SimsContext.getString(R.string.network_error), Toast.LENGTH_SHORT).show(); } @Override public void apiError(ApiError error) { // TODO Auto-generated method stub } public void clearMessage(){ mNewComment.setText(""); } public void shareMessage(){ Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, mFirstComment.getText()); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "Share Comment")); } @Override public void afterPostLikeStatus(Message message) { if(message != null && mMessage != null) { if(message.getLikeStatus()==mMessage.getLikeStatus()) { //Rafraichir les informations //Le nombre de like a pu changer mMessage = message; mFirstComment.setText(message.getText()); mFirstCommentTimestamp.setText(DateFormat.format (getString(R.string.date_format), new Date( message.getTimestamp() ) ) ); updateLikes(); } } } @Override public void afterPostComment(Comment comment) { CommentItem ci = new CommentItem(comment); ((CommentAdapter) mListComments.getAdapter()).add(ci); } }
package be.ibridge.kettle.job.entry.getpop; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import javax.mail.*; import javax.mail.internet.*; import org.apache.commons.vfs.FileObject; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.vfs.KettleVFS; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.job.entry.JobEntryBase; import be.ibridge.kettle.job.entry.JobEntryDialogInterface; import be.ibridge.kettle.job.entry.JobEntryInterface; import be.ibridge.kettle.repository.Repository; import com.sun.mail.pop3.POP3SSLStore; /** * This defines an SQL job entry. * * @author Samatar * @since 01-03-2007 * */ public class JobEntryGetPOP extends JobEntryBase implements Cloneable, JobEntryInterface { private String servername; private String username; private String password; private boolean usessl; private String sslport; private String outputdirectory; private String filenamepattern; private String firstmails; public int retrievemails; private boolean delete; public JobEntryGetPOP(String n) { super(n, ""); servername=null; username=null; password=null; usessl=false; sslport="995"; outputdirectory=null; filenamepattern=null; retrievemails=0; firstmails=null; delete=false; setID(-1L); setType(JobEntryInterface.TYPE_JOBENTRY_GET_POP); } public JobEntryGetPOP() { this(""); } public JobEntryGetPOP(JobEntryBase jeb) { super(jeb); } public Object clone() { JobEntryGetPOP je = (JobEntryGetPOP) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("servername", servername)); retval.append(" ").append(XMLHandler.addTagValue("username", username)); retval.append(" ").append(XMLHandler.addTagValue("password", password)); retval.append(" ").append(XMLHandler.addTagValue("usessl", usessl)); retval.append(" ").append(XMLHandler.addTagValue("sslport", sslport)); retval.append(" ").append(XMLHandler.addTagValue("outputdirectory", outputdirectory)); retval.append(" ").append(XMLHandler.addTagValue("filenamepattern", filenamepattern)); retval.append(" ").append(XMLHandler.addTagValue("retrievemails", retrievemails)); retval.append(" ").append(XMLHandler.addTagValue("firstmails", firstmails)); retval.append(" ").append(XMLHandler.addTagValue("delete", delete)); return retval.toString(); } public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases); servername = XMLHandler.getTagValue(entrynode, "servername"); username = XMLHandler.getTagValue(entrynode, "username"); password = XMLHandler.getTagValue(entrynode, "password"); usessl = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "usessl") ); sslport = XMLHandler.getTagValue(entrynode, "sslport"); outputdirectory = XMLHandler.getTagValue(entrynode, "outputdirectory"); filenamepattern = XMLHandler.getTagValue(entrynode, "filenamepattern"); retrievemails = Const.toInt(XMLHandler.getTagValue(entrynode, "retrievemails"), -1); firstmails = XMLHandler.getTagValue(entrynode, "firstmails"); delete = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "delete") ); } catch(KettleXMLException xe) { throw new KettleXMLException("Unable to load job entry of type 'get pop' from XML node", xe); } } public void loadRep(Repository rep, long id_jobentry, ArrayList databases) throws KettleException { try { super.loadRep(rep, id_jobentry, databases); servername = rep.getJobEntryAttributeString(id_jobentry, "servername"); username = rep.getJobEntryAttributeString(id_jobentry, "username"); password = rep.getJobEntryAttributeString(id_jobentry, "password"); usessl = rep.getJobEntryAttributeBoolean(id_jobentry, "usessl"); int intSSLPort = (int)rep.getJobEntryAttributeInteger(id_jobentry, "sslport"); sslport = rep.getJobEntryAttributeString(id_jobentry, "sslport"); // backward compatible. if (intSSLPort>0 && Const.isEmpty(sslport)) sslport = Integer.toString(intSSLPort); outputdirectory = rep.getJobEntryAttributeString(id_jobentry, "outputdirectory"); filenamepattern = rep.getJobEntryAttributeString(id_jobentry, "filenamepattern"); retrievemails=(int) rep.getJobEntryAttributeInteger(id_jobentry, "retrievemails"); firstmails= rep.getJobEntryAttributeString(id_jobentry, "firstmails"); delete = rep.getJobEntryAttributeBoolean(id_jobentry, "delete"); } catch(KettleException dbe) { throw new KettleException("Unable to load job entry of type 'get pop' exists from the repository for id_jobentry="+id_jobentry, dbe); } } public void saveRep(Repository rep, long id_job) throws KettleException { try { super.saveRep(rep, id_job); rep.saveJobEntryAttribute(id_job, getID(), "servername", servername); rep.saveJobEntryAttribute(id_job, getID(), "username", username); rep.saveJobEntryAttribute(id_job, getID(), "password", password); rep.saveJobEntryAttribute(id_job, getID(), "usessl", usessl); rep.saveJobEntryAttribute(id_job, getID(), "sslport", sslport); rep.saveJobEntryAttribute(id_job, getID(), "outputdirectory", outputdirectory); rep.saveJobEntryAttribute(id_job, getID(), "filenamepattern", filenamepattern); rep.saveJobEntryAttribute(id_job, getID(), "retrievemails", retrievemails); rep.saveJobEntryAttribute(id_job, getID(), "firstmails", firstmails); rep.saveJobEntryAttribute(id_job, getID(), "delete", delete); } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to save job entry of type 'get pop' to the repository for id_job="+id_job, dbe); } } public String getSSLPort() { return sslport; } public String getRealSSLPort() { return StringUtil.environmentSubstitute(getSSLPort()); } public void setSSLPort(String sslport) { this.sslport = sslport; } public void setFirstMails(String firstmails) { this.firstmails = firstmails; } public String getFirstMails() { return firstmails; } public String getRealFirstMails() { return StringUtil.environmentSubstitute(getFirstMails()); } public void setServerName(String servername) { this.servername = servername; } public String getServerName() { return servername; } public void setUserName(String username) { this.username = username; } public String getUserName() { return username; } public void setOutputDirectory(String outputdirectory) { this.outputdirectory = outputdirectory; } public void setFilenamePattern(String filenamepattern) { this.filenamepattern = filenamepattern; } public String getFilenamePattern() { return filenamepattern; } public String getOutputDirectory() { return outputdirectory; } public String getRealOutputDirectory() { return StringUtil.environmentSubstitute(getOutputDirectory()); } public String getRealFilenamePattern() { return StringUtil.environmentSubstitute(getFilenamePattern()); } public String getRealUsername() { return StringUtil.environmentSubstitute(getUserName()); } public String getRealServername() { return StringUtil.environmentSubstitute(getServerName()); } /** * @return Returns the password. */ public String getPassword() { return password; } public String getRealPassword() { return StringUtil.environmentSubstitute(getPassword()); } /** * @param delete The delete to set. */ public void setDelete(boolean delete) { this.delete = delete; } /** * @return Returns the delete. */ public boolean getDelete() { return delete; } /** * @param usessl The usessl to set. */ public void setUseSSL(boolean usessl) { this.usessl = usessl; } /** * @return Returns the usessl. */ public boolean getUseSSL() { return usessl; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult( false ); result.setNrErrors(1); FileObject fileObject = null; //Get system properties //Properties prop = System.getProperties(); Properties prop = new Properties(); prop.setProperty("mail.pop3s.rsetbeforequit","true"); prop.setProperty("mail.pop3.rsetbeforequit","true"); //Create session object //Session sess = Session.getInstance(prop, null); Session sess = Session.getDefaultInstance( prop, null ); sess.setDebug(true); try { int nbrmailtoretrieve=Const.toInt(firstmails, 0); fileObject = KettleVFS.getFileObject(getRealOutputDirectory()); // Check if output folder exists if ( !fileObject.exists() ) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory() + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label")); } else { String host=getRealServername(); String user=getRealUsername(); String pwd=getRealPassword(); Store st=null; if (!getUseSSL()) { //Create POP3 object st=sess.getStore("pop3"); // Try to connect to the server st.connect(host,user,pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //Properties pop3Props = new Properties(); prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); prop.setProperty("mail.pop3.socketFactory.fallback", "false"); prop.setProperty("mail.pop3.port", getRealSSLPort()); prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(),995), "", user, pwd); st = new POP3SSLStore(sess, url); st.connect(); } log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //Open the INBOX FOLDER // For POP3, the only folder available is the INBOX. Folder f = st.getFolder("INBOX"); if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); } else { // Open folder if (delete) { f.open(Folder.READ_WRITE); } else { f.open(Folder.READ_ONLY); } Message messageList[] = f.getMessages(); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label") + messageList.length); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder2.Label") + f.getUnreadMessageCount()); // Get emails Message msg_list[]=getPOPMessages(f, retrievemails); if (msg_list.length>0) { List current_file_POP = new ArrayList(); List current_filepath_POP = new ArrayList(); int nb_email_POP=1; DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy"); String startpattern="name"; if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for(int i=0;i<msg_list.length;i++) { /*if(msg[i].isMimeType("text/plain")) { log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]); log.logDetailed(toString(), "Sujet: "+msg[i].getSubject()); log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent()); }*/ if ((nb_email_POP<=nbrmailtoretrieve && retrievemails==2)||(retrievemails!=2)) { Message msg_POP = msg_list[i]; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label") + msg_list[i].getFrom()[0]); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailSubject.Label") + msg_list[i].getSubject()); String localfilename_message = startpattern + "_" + dateFormat.format(new Date()) + "_" +(i + 1) + ".mail"; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label") + localfilename_message + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label")); File filename_message = new File(getRealOutputDirectory(), localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = (Header) enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()) .append(": ").append(header_POP.getValue()) .append("\r\n").toString().getBytes()); } os_filename.write("\r\n".getBytes()); InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP= 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); // Check attachments Object content = msg_POP.getContent(); if (content instanceof Multipart) { handleMultipart(getRealOutputDirectory(),(Multipart)content); } // Check if mail has to be deleted if (delete) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } //close the folder, passing in a true value to expunge the deleted message if(f != null) f.close(true); if (st != null) st.close(); f = null; st = null; sess = null; result.setNrErrors(0); result.setResult( true ); } } } catch(NoSuchProviderException e) { log.logError(toString(), "provider error: "+e.getMessage()); } catch(MessagingException e) { log.logError(toString(), "Message error: "+e.getMessage()); } catch(Exception e) { log.logError(toString(), "Inexpected error: "+e.getMessage()); } finally { if ( fileObject != null ) { try { fileObject.close(); } catch ( IOException ex ) {}; } sess = null; } return result; } public static void handleMultipart(String foldername,Multipart multipart) throws MessagingException, IOException { for (int i=0, n=multipart.getCount(); i<n; i++) { handlePart(foldername,multipart.getBodyPart(i)); } } public static void handlePart(String foldername,Part part) throws MessagingException, IOException { String disposition = part.getDisposition(); // String contentType = part.getContentType(); if ((disposition != null) && ( disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE) ) ) { saveFile(foldername,MimeUtility.decodeText(part.getFileName()), part.getInputStream()); } } public static void saveFile(String foldername,String filename, InputStream input) throws IOException { // LogWriter log = LogWriter.getInstance(); if (filename == null) { filename = File.createTempFile("xx", ".out").getName(); } // Do no overwrite existing file File file = new File(foldername,filename); for (int i=0; file.exists(); i++) { file = new File(foldername,filename+i); } FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedInputStream bis = new BufferedInputStream(input); int aByte; while ((aByte = bis.read()) != -1) { bos.write(aByte); } bos.flush(); bos.close(); bis.close(); } public boolean evaluates() { return true; } public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) { return new JobEntryGetPOPDialog(shell,this,jobMeta); } public Message[] getPOPMessages(Folder folder, int retrievemails) throws Exception { // Get messages .. try { int unreadMsgs = folder.getUnreadMessageCount(); Message msgsAll[] = folder.getMessages(); int msgCount = msgsAll.length; if (retrievemails ==1) { Message msgsUnread[] = folder.getMessages(msgCount - unreadMsgs + 1, msgCount); return(msgsUnread); } else { return(msgsAll); } } catch (Exception e) { return null; } } }
package com.backendless.transaction; import com.backendless.Persistence; import com.backendless.exceptions.ExceptionMessage; import com.backendless.persistence.BackendlessSerializer; import com.backendless.transaction.operations.Operation; import com.backendless.transaction.operations.OperationAddRelation; import com.backendless.transaction.operations.OperationDeleteRelation; import com.backendless.transaction.operations.OperationSetRelation; import com.backendless.transaction.payload.Relation; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class RelationOperationImpl implements RelationOperation { AtomicInteger countAddRelation = new AtomicInteger( 1 ); AtomicInteger countSetRelation = new AtomicInteger( 1 ); AtomicInteger countDeleteRelation = new AtomicInteger( 1 ); private final List<Operation> operations; public RelationOperationImpl( List<Operation> operations ) { this.operations = operations; } @Override public <E> OpResult addOperation( OperationType operationType, String parentTable, Map<String, Object> parentObject, String columnName, List<E> children ) { String parentObjectId = (String) parentObject.get( Persistence.DEFAULT_OBJECT_ID_FIELD ); return addOperation( operationType, parentTable, parentObjectId, columnName, children ); } @Override public OpResult addOperation( OperationType operationType, String parentTable, Map<String, Object> parentObject, String columnName, OpResult children ) { String parentObjectId = (String) parentObject.get( Persistence.DEFAULT_OBJECT_ID_FIELD ); return addOperation( operationType, parentTable, parentObjectId, columnName, children ); } @Override public OpResult addOperation( OperationType operationType, String parentTable, Map<String, Object> parentObject, String columnName, String whereClauseForChildren ) { String parentObjectId = (String) parentObject.get( Persistence.DEFAULT_OBJECT_ID_FIELD ); return addOperation( operationType, parentTable, parentObjectId, columnName, whereClauseForChildren ); } @Override public <E> OpResult addOperation( OperationType operationType, String parentTable, String parentObjectId, String columnName, List<E> children ) { if( children == null || children.isEmpty() ) throw new IllegalArgumentException( ExceptionMessage.NULL_EMPTY_BULK ); List<String> childrenIds = TransactionHelper.getObjectIdsFromUnknownList( children ); return addOperation( operationType, parentTable, parentObjectId, columnName, null, childrenIds ); } @Override public OpResult addOperation( OperationType operationType, String parentTable, String parentObjectId, String columnName, OpResult children ) { if( children == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_OP_RESULT ); if( !OperationType.supportResultIndexType.contains( children.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); return addOperation( operationType, parentTable, parentObjectId, columnName, null, children.getReference() ); } @Override public OpResult addOperation( OperationType operationType, String parentTable, String parentObjectId, String columnName, String whereClauseForChildren ) { return addOperation( operationType, parentTable, parentObjectId, columnName, whereClauseForChildren, null ); } @Override public <E, U> OpResult addOperation( OperationType operationType, E parentObject, String columnName, List<U> children ) { String parentObjectId = Persistence.getEntityId( parentObject ); String parentTable = BackendlessSerializer.getSimpleName( parentObject.getClass() ); List<String> childrenIds = TransactionHelper.getObjectIdsFromUnknownList( children ); return addOperation( operationType, parentTable, parentObjectId, columnName, null, childrenIds ); } @Override public <E> OpResult addOperation( OperationType operationType, E parentObject, String columnName, OpResult children ) { if( children == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_OP_RESULT ); String parentObjectId = Persistence.getEntityId( parentObject ); String parentTable = BackendlessSerializer.getSimpleName( parentObject.getClass() ); if( !OperationType.supportResultIndexType.contains( children.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); return addOperation( operationType, parentTable, parentObjectId, columnName, null, children.getReference() ); } @Override public <E> OpResult addOperation( OperationType operationType, E parentObject, String columnName, String whereClauseForChildren ) { String parentObjectId = Persistence.getEntityId( parentObject ); String parentTable = BackendlessSerializer.getSimpleName( parentObject.getClass() ); return addOperation( operationType, parentTable, parentObjectId, columnName, whereClauseForChildren, null ); } @Override public <E> OpResult addOperation( OperationType operationType, String parentTable, OpResult parentObject, String columnName, List<E> children ) { if( parentObject == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_OP_RESULT ); if( children == null || children.isEmpty() ) throw new IllegalArgumentException( ExceptionMessage.NULL_EMPTY_BULK ); List<String> childrenIds = TransactionHelper.getObjectIdsFromUnknownList( children ); if( !OperationType.supportEntityDescriptionResultType.contains( parentObject.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); return addOperation( operationType, parentTable, parentObject.resolveTo( Persistence.DEFAULT_OBJECT_ID_FIELD ), columnName, null, childrenIds ); } @Override public OpResult addOperation( OperationType operationType, String parentTable, OpResult parentObject, String columnName, OpResult children ) { if( parentObject == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_OP_RESULT ); if( !OperationType.supportEntityDescriptionResultType.contains( parentObject.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); if( !OperationType.supportResultIndexType.contains( children.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); return addOperation( operationType, parentTable, parentObject.resolveTo( Persistence.DEFAULT_OBJECT_ID_FIELD ), columnName, null, children.getReference() ); } @Override public OpResult addOperation( OperationType operationType, String parentTable, OpResult parentObject, String columnName, String whereClauseForChildren ) { if( parentObject == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_OP_RESULT ); if( !OperationType.supportEntityDescriptionResultType.contains( parentObject.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); return addOperation( operationType, parentTable, parentObject.resolveTo( Persistence.DEFAULT_OBJECT_ID_FIELD ), columnName, whereClauseForChildren, null ); } @Override public <E> OpResult addOperation( OperationType operationType, String parentTable, OpResultIndex parentObject, String columnName, List<E> children ) { if( parentObject == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_OP_RESULT_INDEX ); if( children == null || children.isEmpty() ) throw new IllegalArgumentException( ExceptionMessage.NULL_EMPTY_BULK ); List<String> childrenIds = TransactionHelper.getObjectIdsFromUnknownList( children ); if( !OperationType.supportResultIndexType.contains( parentObject.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); return addOperation( operationType, parentTable, parentObject.getReference(), columnName, null, childrenIds ); } @Override public OpResult addOperation( OperationType operationType, String parentTable, OpResultIndex parentObject, String columnName, OpResult children ) { if( parentObject == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_OP_RESULT_INDEX ); if( !OperationType.supportEntityDescriptionResultType.contains( parentObject.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); if( !OperationType.supportResultIndexType.contains( children.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); return addOperation( operationType, parentTable, parentObject, null, columnName, children.getReference() ); } @Override public OpResult addOperation( OperationType operationType, String parentTable, OpResultIndex parentObject, String columnName, String whereClauseForChildren ) { if( parentObject == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_OP_RESULT_INDEX ); if( !OperationType.supportResultIndexType.contains( parentObject.getOperationType() ) ) throw new IllegalArgumentException( ExceptionMessage.REF_TYPE_NOT_SUPPORT ); return addOperation( operationType, parentTable, parentObject, columnName, whereClauseForChildren, null ); } private OpResult addOperation( OperationType operationType, String parentTable, Object parentObject, String columnName, String whereClauseForChildren, Object children ) { String operationResultId = null; Relation relation = new Relation(); relation.setParentObject( parentObject ); relation.setRelationColumn( columnName ); relation.setConditional( whereClauseForChildren ); relation.setUnconditional( children ); switch( operationType ) { case ADD_RELATION: operationResultId = operationType + "_" + countAddRelation.getAndIncrement(); operations.add( new OperationAddRelation( operationType, parentTable, operationResultId, relation ) ); break; case SET_RELATION: operationResultId = operationType + "_" + countSetRelation.getAndIncrement(); operations.add( new OperationSetRelation( operationType, parentTable, operationResultId, relation ) ); break; case DELETE_RELATION: operationResultId = operationType + "_" + countDeleteRelation.getAndIncrement(); operations.add( new OperationDeleteRelation( operationType, parentTable, operationResultId, relation ) ); break; } return TransactionHelper.makeOpResult( parentTable, operationResultId, operationType ); } }
package com.dmdirc.addons.ui_swing.framemanager.tree; import com.dmdirc.addons.ui_swing.SwingController; import com.dmdirc.addons.ui_swing.UIUtilities; import com.dmdirc.addons.ui_swing.actions.CloseFrameContainerAction; import com.dmdirc.addons.ui_swing.components.frames.TextFrame; import com.dmdirc.config.ConfigManager; import com.dmdirc.interfaces.ConfigChangeListener; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import net.miginfocom.layout.PlatformDefaults; /** * Specialised JTree for the frame manager. */ public class Tree extends JTree implements MouseMotionListener, ConfigChangeListener, MouseListener, ActionListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** Tree frame manager. */ private final TreeFrameManager manager; /** UI Controller. */ private final SwingController controller; /** Config manager. */ private final ConfigManager config; /** Drag selection enabled? */ private boolean dragSelect; /** Drag button 1? */ private boolean dragButton; /** Show handles. */ private boolean showHandles; /** * Specialised JTree for frame manager. * * @param manager Frame manager * @param model tree model. * @param controller Swing controller */ public Tree(final TreeFrameManager manager, final TreeModel model, final SwingController controller) { super(model); this.manager = manager; this.controller = controller; this.config = controller.getGlobalConfig(); putClientProperty("JTree.lineStyle", "Angled"); getInputMap().setParent(null); getInputMap(JComponent.WHEN_FOCUSED).clear(); getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).clear(); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).clear(); getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); setRootVisible(false); setRowHeight(16); setOpaque(true); setBorder(BorderFactory.createEmptyBorder( (int) PlatformDefaults.getUnitValueX("related").getValue(), (int) PlatformDefaults.getUnitValueX("related").getValue(), (int) PlatformDefaults.getUnitValueX("related").getValue(), (int) PlatformDefaults.getUnitValueX("related").getValue())); setFocusable(false); dragSelect = config.getOptionBool("treeview", "dragSelection"); showHandles = config.getOptionBool(controller.getDomain(), "showtreeexpands"); config.addChangeListener(controller.getDomain(), "showtreeexpands", this); config.addChangeListener("treeview", this); setShowsRootHandles(showHandles); putClientProperty("showHandles", showHandles); addMouseListener(this); addMouseMotionListener(this); } /** {@inheritDoc} */ @Override public void scrollRectToVisible(final Rectangle aRect) { final Rectangle rect = new Rectangle(0, aRect.y, aRect.width, aRect.height); super.scrollRectToVisible(rect); } /** * Set path. * * @param path Path */ public void setTreePath(final TreePath path) { UIUtilities.invokeLater(new Runnable() { @Override public void run() { setSelectionPath(path); } }); } /** * Returns the node for the specified location, returning null if rollover * is disabled or there is no node at the specified location. * * @param x x coordiantes * @param y y coordiantes * * @return node or null */ public TreeViewNode getNodeForLocation(final int x, final int y) { TreeViewNode node = null; final TreePath selectedPath = getPathForLocation(x, y); if (selectedPath != null) { node = (TreeViewNode) selectedPath.getLastPathComponent(); } return node; } /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { if ("dragSelection".equals(key)) { dragSelect = config.getOptionBool("treeview", "dragSelection"); } else if ("showtreeexpands".equals(key)) { config.getOptionBool(controller.getDomain(), "showtreeexpands"); setShowsRootHandles(showHandles); putClientProperty("showHandles", showHandles); } } /** * {@inheritDoc} * * @param e Mouse event */ @Override public void mouseDragged(final MouseEvent e) { if (dragSelect && dragButton) { final TreeViewNode node = getNodeForLocation(e.getX(), e.getY()); if (node != null) { controller.requestWindowFocus(controller.getWindowFactory() .getSwingWindow(((TreeViewNode) new TreePath(node.getPath()). getLastPathComponent()).getWindow())); } } manager.checkRollover(e); } /** * {@inheritDoc} * * @param e Mouse event */ @Override public void mouseMoved(final MouseEvent e) { manager.checkRollover(e); } /** * {@inheritDoc} * * @param e Mouse event */ @Override public void mouseClicked(final MouseEvent e) { processMouseEvents(e); } /** * {@inheritDoc} * * @param e Mouse event */ @Override public void mousePressed(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { dragButton = true; final TreePath selectedPath = getPathForLocation(e.getX(), e.getY()); if (selectedPath != null) { controller.requestWindowFocus(controller.getWindowFactory() .getSwingWindow(((TreeViewNode) selectedPath .getLastPathComponent()).getWindow())); } } processMouseEvents(e); } /** * {@inheritDoc} * * @param e Mouse event */ @Override public void mouseReleased(final MouseEvent e) { dragButton = false; processMouseEvents(e); } /** * {@inheritDoc} * * @param e Mouse event */ @Override public void mouseEntered(final MouseEvent e) { //Ignore } /** * {@inheritDoc} * * @param e Mouse event */ @Override public void mouseExited(final MouseEvent e) { manager.checkRollover(null); } /** * Processes every mouse button event to check for a popup trigger. * @param e mouse event */ public void processMouseEvents(final MouseEvent e) { final TreePath localPath = getPathForLocation(e.getX(), e.getY()); if (localPath != null && e.isPopupTrigger()) { final TextFrame frame = controller.getWindowFactory() .getSwingWindow(((TreeViewNode) localPath.getLastPathComponent()) .getWindow()); if (frame == null) { return; } final JPopupMenu popupMenu = frame.getPopupMenu(null, new Object[][] {new Object[]{""}}); frame.addCustomPopupItems(popupMenu); if (popupMenu.getComponentCount() > 0) { popupMenu.addSeparator(); } final TreeViewNodeMenuItem popoutMenuItem; if (frame.getPopoutFrame() == null) { popoutMenuItem = new TreeViewNodeMenuItem("Pop Out", "popout", (TreeViewNode) localPath.getLastPathComponent()); } else { popoutMenuItem = new TreeViewNodeMenuItem("Pop In", "popin", (TreeViewNode) localPath.getLastPathComponent()); } popupMenu.add(popoutMenuItem); popupMenu.addSeparator(); popoutMenuItem.addActionListener(this); final TreeViewNodeMenuItem moveUp = new TreeViewNodeMenuItem("Move Up", "Up", (TreeViewNode) localPath.getLastPathComponent()); final TreeViewNodeMenuItem moveDown = new TreeViewNodeMenuItem("Move Down", "Down", (TreeViewNode) localPath.getLastPathComponent()); moveUp.addActionListener(this); moveDown.addActionListener(this); popupMenu.add(moveUp); popupMenu.add(moveDown); popupMenu.add(new JMenuItem(new CloseFrameContainerAction(frame. getContainer()))); popupMenu.show(this, e.getX(), e.getY()); } } /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { final TreeViewNode node = ((TreeViewNodeMenuItem) e.getSource()). getTreeNode(); int index = getModel().getIndexOfChild(node.getParent(), node); if ("Up".equals(e.getActionCommand())) { if (index == 0) { index = node.getSiblingCount() - 1; } else { index } } else if ("Down".equals(e.getActionCommand())) { if (index == (node.getSiblingCount() - 1)) { index = 0; } else { index++; } } else if ("popout".equals(e.getActionCommand())) { controller.getWindowFactory().getSwingWindow(node.getWindow()) .setPopout(true); } else if ("popin".equals(e.getActionCommand())) { controller.getWindowFactory().getSwingWindow(node.getWindow()) .setPopout(false); } final TreeViewNode parentNode = (TreeViewNode) node.getParent(); final TreePath nodePath = new TreePath(node.getPath()); final boolean isExpanded = isExpanded(nodePath); ((TreeViewModel) getModel()).removeNodeFromParent(node); ((TreeViewModel) getModel()).insertNodeInto(node, parentNode, index); setExpandedState(nodePath, isExpanded); } }
package com.googlecode.totallylazy.records.sql; import com.googlecode.totallylazy.*; import com.googlecode.totallylazy.numbers.Numbers; import com.googlecode.totallylazy.records.AbstractRecords; import com.googlecode.totallylazy.records.Keyword; import com.googlecode.totallylazy.records.Queryable; import com.googlecode.totallylazy.records.Record; import com.googlecode.totallylazy.records.sql.expressions.Expression; import com.googlecode.totallylazy.records.sql.expressions.Expressions; import com.googlecode.totallylazy.records.sql.mappings.Mappings; import java.io.PrintStream; import java.sql.Connection; import java.util.Iterator; import java.util.List; import static com.googlecode.totallylazy.Closeables.using; import static com.googlecode.totallylazy.Predicates.is; import static com.googlecode.totallylazy.Predicates.where; import static com.googlecode.totallylazy.Sequences.sequence; import static com.googlecode.totallylazy.Streams.nullOutputStream; import static com.googlecode.totallylazy.records.Keywords.keyword; import static com.googlecode.totallylazy.records.sql.expressions.DeleteStatement.deleteStatement; import static com.googlecode.totallylazy.records.sql.expressions.InsertStatement.insertStatement; import static com.googlecode.totallylazy.records.sql.expressions.SelectBuilder.from; import static com.googlecode.totallylazy.records.sql.expressions.TableDefinition.dropTable; import static com.googlecode.totallylazy.records.sql.expressions.TableDefinition.tableDefinition; import static com.googlecode.totallylazy.records.sql.expressions.UpdateStatement.updateStatement; import static java.lang.String.format; public class SqlRecords extends AbstractRecords implements Queryable<Expression> { private final Connection connection; private final PrintStream logger; private final Mappings mappings; private final CreateTable createTable; public SqlRecords(final Connection connection, CreateTable createTable, Mappings mappings, PrintStream logger) { this.connection = connection; this.createTable = createTable; this.mappings = mappings; this.logger = logger; } public SqlRecords(final Connection connection) { this(connection, CreateTable.Enabled, new Mappings(), new PrintStream(nullOutputStream())); } public RecordSequence get(Keyword recordName) { return new RecordSequence(this, from(recordName).select(definitions(recordName)), logger); } public Sequence<Record> query(final Expression expression, final Sequence<Keyword> definitions) { return new Sequence<Record>() { public Iterator<Record> iterator() { return SqlRecords.this.iterator(expression, definitions); } }; } public RecordIterator iterator(Expression expression, Sequence<Keyword> definitions) { return new RecordIterator(connection, mappings, expression, definitions, logger); } public void define(Keyword recordName, Keyword<?>... fields) { super.define(recordName, fields); if(createTable.equals(CreateTable.Disabled)){ return; } if (exists(recordName)) { return; } update(tableDefinition(recordName, fields)); } @Override public List<Keyword<?>> undefine(Keyword recordName) { if(exists(recordName)){ update(dropTable(recordName)); } return super.undefine(recordName); } private static final Keyword<Integer> one = keyword("1", Integer.class); public boolean exists(Keyword recordName) { try { query(from(recordName).select(one).where(Predicates.where(one, is(2))).build(), Sequences.<Keyword>empty()).realise(); return true; } catch (Exception e) { return false; } } public Number add(final Keyword recordName, final Sequence<Record> records) { if (records.isEmpty()) { return 0; } return update(records.map(insertStatement(recordName))); } @Override public Number set(Keyword recordName, Sequence<Pair<? extends Predicate<? super Record>, Record>> records) { return update(records.map(updateStatement(recordName))); } public Number update(final Expression... expressions) { return update(sequence(expressions)); } public Number update(final Sequence<Expression> expressions) { return expressions.groupBy(Expressions.text()).map(new Callable1<Group<String, Expression>, Number>() { public Number call(Group<String, Expression> group) throws Exception { logger.print(format("SQL: %s", group.key())); Number rowCount = using(connection.prepareStatement(group.key()), mappings.addValuesInBatch(group.map(Expressions.parameters()))); logger.println(format(" Count:%s", rowCount)); return rowCount; } }).reduce(Numbers.<Number>sum()); } public Number remove(Keyword recordName, Predicate<? super Record> predicate) { return update(deleteStatement(recordName, predicate)); } public Number remove(Keyword recordName) { if (!exists(recordName)) { return 0; } return update(deleteStatement(recordName)); } }
package com.idunnololz.widgets; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.view.animation.Transformation; /** * This class defines an ExpandableListView which supports animations for * collapsing and expanding groups. */ public class AnimatedExpandableListView extends ExpandableListView { /* * A detailed explanation for how this class works: * * Animating the ExpandableListView was no easy task. The way that this * class does it is by exploiting how an ExpandableListView works. * * Normally when {@link ExpandableListView#collapseGroup(int)} or * {@link ExpandableListView#expandGroup(int)} is called, the view toggles * the flag for a group and calls notifyDataSetChanged to cause the ListView * to refresh all of it's view. This time however, depending on whether a * group is expanded or collapsed, certain childViews will either be ignored * or added to the list. * * Knowing this, we can come up with a way to animate our views. For * instance for group expansion, we tell the adapter to animate the * children of a certain group. We then expand the group which causes the * ExpandableListView to refresh all views on screen. The way that * ExpandableListView does this is by calling getView() in the adapter. * However since the adapter knows that we are animating a certain group, * instead of returning the real views for the children of the group being * animated, it will return a fake dummy view. This dummy view will then * draw the real child views within it's dispatchDraw function. The reason * we do this is so that we can animate all of it's children by simply * animating the dummy view. After we complete the animation, we tell the * adapter to stop animating the group and call notifyDataSetChanged. Now * the ExpandableListView is forced to refresh it's views again, except this * time, it will get the real views for the expanded group. * * So, to list it all out, when {@link #expandGroupWithAnimation(int)} is * called the following happens: * * 1. The ExpandableListView tells the adapter to animate a certain group. * 2. The ExpandableListView calls expandGroup. * 3. ExpandGroup calls notifyDataSetChanged. * 4. As an result, getChildView is called for expanding group. * 5. Since the adapter is in "animating mode", it will return a dummy view. * 6. This dummy view draws the actual children of the expanding group. * 7. This dummy view's height is animated from 0 to it's expanded height. * 8. Once the animation completes, the adapter is notified to stop * animating the group and notifyDataSetChanged is called again. * 9. This forces the ExpandableListView to refresh all of it's views again. * 10.This time when getChildView is called, it will return the actual * child views. * * For animating the collapse of a group is a bit more difficult since we * can't call collapseGroup from the start as it would just ignore the * child items, giving up no chance to do any sort of animation. Instead * what we have to do is play the animation first and call collapseGroup * after the animation is done. * * So, to list it all out, when {@link #collapseGroupWithAnimation(int)} is * called the following happens: * * 1. The ExpandableListView tells the adapter to animate a certain group. * 2. The ExpandableListView calls notifyDataSetChanged. * 3. As an result, getChildView is called for expanding group. * 4. Since the adapter is in "animating mode", it will return a dummy view. * 5. This dummy view draws the actual children of the expanding group. * 6. This dummy view's height is animated from it's current height to 0. * 7. Once the animation completes, the adapter is notified to stop * animating the group and notifyDataSetChanged is called again. * 8. collapseGroup is finally called. * 9. This forces the ExpandableListView to refresh all of it's views again. * 10.This time when the ListView will not get any of the child views for * the collapsed group. */ /** * The duration of the expand/collapse animations */ private static final int ANIMATION_DURATION = 300; private AnimatedExpandableListAdapter adapter; public AnimatedExpandableListView(Context context) { super(context); } public AnimatedExpandableListView(Context context, AttributeSet attrs) { super(context, attrs); } public AnimatedExpandableListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * @see ExpandableListView#setAdapter(ExpandableListAdapter) */ public void setAdapter(ExpandableListAdapter adapter) { super.setAdapter(adapter); // Make sure that the adapter extends AnimatedExpandableListAdapter if(adapter instanceof AnimatedExpandableListAdapter) { this.adapter = (AnimatedExpandableListAdapter) adapter; this.adapter.setParent(this); } else { throw new ClassCastException(adapter.toString() + " must implement AnimatedExpandableListAdapter"); } } /** * Expands the given group with an animation. * @param groupPos The position of the group to expand * @return Returns true if the group was expanded. False if the group was * already expanded. */ public boolean expandGroupWithAnimation(int groupPos) { int groupFlatPos = getFlatListPosition(getPackedPositionForGroup(groupPos)); if (groupFlatPos != -1) { int childIndex = groupFlatPos - getFirstVisiblePosition(); if (childIndex < getChildCount()) { // Get the view for the group is it is on screen... View v = getChildAt(childIndex); if (v.getBottom() >= getBottom()) { // If the user is not going to be able to see the animation // we just expand the group without an animation. // This resolves the case where getChildView will not be // called if the children of the group is not on screen return expandGroup(groupPos); } } } // Let the adapter know that we are starting the animation... adapter.startExpandAnimation(groupPos, 0); // Finally call expandGroup (note that expandGroup will call // notifyDataSetChanged so we don't need to) return expandGroup(groupPos); } /** * Collapses the given group with an animation. * @param groupPos The position of the group to collapse * @return Returns true if the group was collapsed. False if the group was * already collapsed. */ public boolean collapseGroupWithAnimation(int groupPos) { int groupFlatPos = getFlatListPosition(getPackedPositionForGroup(groupPos)); if (groupFlatPos != -1) { int childIndex = groupFlatPos - getFirstVisiblePosition(); if (childIndex < getChildCount()) { // Get the view for the group is it is on screen... View v = getChildAt(childIndex); if (v.getBottom() >= getBottom()) { // If the user is not going to be able to see the animation // we just collapse the group without an animation. // This resolves the case where getChildView will not be // called if the children of the group is not on screen return collapseGroup(groupPos); } } } // Get the position of the firstChild visible from the top of the screen long packedPos = getExpandableListPosition(getFirstVisiblePosition()); int firstChildPos = getPackedPositionChild(packedPos); int firstGroupPos = getPackedPositionGroup(packedPos); // If the first visible view on the screen is a child view AND it's a // child of the group we are trying to collapse, then set that // as the first child position of the group... see // {@link #startCollapseAnimation(int, int)} for why this is necessary firstChildPos = firstChildPos == -1 || firstGroupPos != groupPos ? 0 : firstChildPos; // Let the adapter know that we are going to start animating the // collapse animation. adapter.startCollapseAnimation(groupPos, firstChildPos); // Force the listview to refresh it's views adapter.notifyDataSetChanged(); return isGroupExpanded(groupPos); } private int getAnimationDuration() { return ANIMATION_DURATION; } /** * Used for holding information regarding the group. */ private static class GroupInfo { boolean animating = false; boolean expanding = false; int firstChildPosition; /** * This variable contains the last known height value of the dummy view. * We save this information so that if the user collapses a group * before it fully expands, the collapse animation will start from the * CURRENT height of the dummy view and not from the full expanded * height. */ int dummyHeight = -1; } /** * A specialized adapter for use with the AnimatedExpandableListView. All * adapters used with AnimatedExpandableListView MUST extend this class. */ public static abstract class AnimatedExpandableListAdapter extends BaseExpandableListAdapter { private SparseArray<GroupInfo> groupInfo = new SparseArray<GroupInfo>(); private AnimatedExpandableListView parent; private void setParent(AnimatedExpandableListView parent) { this.parent = parent; } public int getRealChildType(int groupPosition, int childPosition) { return 0; } public int getRealChildTypeCount() { return 1; } public abstract View getRealChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent); public abstract int getRealChildrenCount(int groupPosition); private GroupInfo getGroupInfo(int groupPosition) { GroupInfo info = groupInfo.get(groupPosition); if (info == null) { info = new GroupInfo(); groupInfo.put(groupPosition, info); } return info; } private void startExpandAnimation(int groupPosition, int firstChildPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = true; info.firstChildPosition = firstChildPosition; info.expanding = true; } private void startCollapseAnimation(int groupPosition, int firstChildPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = true; info.firstChildPosition = firstChildPosition; info.expanding = false; } private void stopAnimation(int groupPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = false; } /** * Override {@link #getRealChildType(int, int)} instead. */ @Override public final int getChildType(int groupPosition, int childPosition) { GroupInfo info = getGroupInfo(groupPosition); if (info.animating) { // If we are animating this group, then all of it's children // are going to be dummy views which we will say is type 0. return 0; } else { // If we are not animating this group, then we will add 1 to // the type it has so that no type id conflicts will occur // unless getRealChildType() returns MAX_INT return getRealChildType(groupPosition, childPosition) + 1; } } /** * Override {@link #getRealChildTypeCount()} instead. */ @Override public final int getChildTypeCount() { // Return 1 more than the childTypeCount to account for DummyView return getRealChildTypeCount() + 1; } /** * Override {@link #getChildView(int, int, boolean, View, ViewGroup)} instead. */ @Override public final View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) { GroupInfo info = getGroupInfo(groupPosition); if (info.animating) { if (convertView == null) { convertView = new DummyView(parent.getContext()); convertView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, 0)); } if (childPosition < info.firstChildPosition) { convertView.getLayoutParams().height = 0; return convertView; } final ExpandableListView listView = (ExpandableListView) parent; DummyView dummyView = (DummyView) convertView; dummyView.clearViews(); dummyView.setDivider(listView.getDivider(), parent.getMeasuredWidth(), listView.getDividerHeight()); final int measureSpecW = MeasureSpec.makeMeasureSpec(parent.getWidth(), MeasureSpec.EXACTLY); final int measureSpecH = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); int totalHeight = 0; int clipHeight = parent.getHeight(); final int len = getRealChildrenCount(groupPosition); for (int i = info.firstChildPosition; i < len; i++) { View childView = getRealChildView(groupPosition, i, (i == len - 1), null, parent); childView.measure(measureSpecW, measureSpecH); totalHeight += childView.getMeasuredHeight(); if (totalHeight < clipHeight) { // we only need to draw enough views to fool the user... dummyView.addFakeView(childView); } else { // if this group has too many views, we don't want to calculate the height // of everything... just do a light approximation... int averageHeight = totalHeight / (i + 1); totalHeight += (len - i - 1) * averageHeight; break; } } if (info.expanding) { ExpandAnimation ani = new ExpandAnimation(dummyView, 0, totalHeight, info); ani.setDuration(this.parent.getAnimationDuration()); ani.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { stopAnimation(groupPosition); notifyDataSetChanged(); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); dummyView.startAnimation(ani); } else { if (info.dummyHeight == -1) { info.dummyHeight = totalHeight; } ExpandAnimation ani = new ExpandAnimation(dummyView, info.dummyHeight, 0, info); ani.setDuration(this.parent.getAnimationDuration()); ani.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { stopAnimation(groupPosition); listView.collapseGroup(groupPosition); notifyDataSetChanged(); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); dummyView.startAnimation(ani); } return convertView; } else { return getRealChildView(groupPosition, childPosition, isLastChild, convertView, parent); } } @Override public final int getChildrenCount(int groupPosition) { GroupInfo info = getGroupInfo(groupPosition); if (info.animating) { return info.firstChildPosition + 1; } else { return getRealChildrenCount(groupPosition); } } } private static class DummyView extends View { private List<View> views = new ArrayList<View>(); private Drawable divider; private int dividerWidth; private int dividerHeight; public DummyView(Context context) { super(context); } public void setDivider(Drawable divider, int dividerWidth, int dividerHeight) { this.divider = divider; this.dividerWidth = dividerWidth; this.dividerHeight = dividerHeight; divider.setBounds(0, 0, dividerWidth, dividerHeight); } public void addFakeView(View childView) { childView.layout(0, 0, getWidth(), getHeight()); views.add(childView); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); final int len = views.size(); for(int i = 0; i < len; i++) { View v = views.get(i); v.layout(left, top, right, bottom); } } public void clearViews() { views.clear(); } @Override public void dispatchDraw(Canvas canvas) { canvas.save(); divider.setBounds(0, 0, dividerWidth, dividerHeight); final int len = views.size(); for(int i = 0; i < len; i++) { View v = views.get(i); v.draw(canvas); canvas.translate(0, v.getMeasuredHeight()); divider.draw(canvas); canvas.translate(0, dividerHeight); } canvas.restore(); } } private static class ExpandAnimation extends Animation { private int baseHeight; private int delta; private View view; private GroupInfo groupInfo; private ExpandAnimation(View v, int startHeight, int endHeight, GroupInfo info) { baseHeight = startHeight; delta = endHeight - startHeight; view = v; groupInfo = info; view.getLayoutParams().height = startHeight; view.requestLayout(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); if (interpolatedTime < 1.0f) { int val = baseHeight + (int) (delta * interpolatedTime); view.getLayoutParams().height = val; groupInfo.dummyHeight = val; view.requestLayout(); } else { int val = baseHeight + delta; view.getLayoutParams().height = val; groupInfo.dummyHeight = val; view.requestLayout(); } } } }
package com.itmill.toolkit.terminal.gwt.client.ui; import java.util.Iterator; import java.util.Vector; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.DeferredCommand; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Frame; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.ScrollListener; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.Widget; import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; import com.itmill.toolkit.terminal.gwt.client.BrowserInfo; import com.itmill.toolkit.terminal.gwt.client.Paintable; import com.itmill.toolkit.terminal.gwt.client.UIDL; import com.itmill.toolkit.terminal.gwt.client.Util; /** * "Sub window" component. * * TODO update position / scrollposition / size to client * * @author IT Mill Ltd */ public class IWindow extends PopupPanel implements Paintable, ScrollListener { private static final int MIN_HEIGHT = 60; private static final int MIN_WIDTH = 80; private static Vector windowOrder = new Vector(); public static final String CLASSNAME = "i-window"; /** pixels used by inner borders and paddings horizontally */ protected static final int BORDER_WIDTH_HORIZONTAL = 41; /** pixels used by headers, footers, inner borders and paddings vertically */ protected static final int BORDER_WIDTH_VERTICAL = 58; private static final int STACKING_OFFSET_PIXELS = 15; private static final int Z_INDEX_BASE = 10000; private Paintable layout; private Element contents; private Element header; private Element footer; private Element resizeBox; private final ScrollPanel contentPanel = new ScrollPanel(); private boolean dragging; private int startX; private int startY; private int origX; private int origY; private boolean resizing; private int origW; private int origH; private Element closeBox; protected ApplicationConnection client; private String id; ShortcutActionHandler shortcutHandler; /** Last known positionx read from UIDL or updated to application connection */ private int uidlPositionX = -1; /** Last known positiony read from UIDL or updated to application connection */ private int uidlPositionY = -1; private boolean modal = false; private Element modalityCurtain; private Element draggingCurtain; private Element headerText; public IWindow() { super(); final int order = windowOrder.size(); setWindowOrder(order); windowOrder.add(this); constructDOM(); setPopupPosition(order * STACKING_OFFSET_PIXELS, order * STACKING_OFFSET_PIXELS); contentPanel.addScrollListener(this); } private void bringToFront() { int curIndex = windowOrder.indexOf(this); if (curIndex + 1 < windowOrder.size()) { windowOrder.remove(this); windowOrder.add(this); for (; curIndex < windowOrder.size(); curIndex++) { ((IWindow) windowOrder.get(curIndex)).setWindowOrder(curIndex); } } } /** * Returns true if window is the topmost window * * @return */ private boolean isActive() { return windowOrder.lastElement().equals(this); } public void setWindowOrder(int order) { int zIndex = (order + Z_INDEX_BASE); if (modal) { zIndex += 1000; DOM.setStyleAttribute(modalityCurtain, "zIndex", "" + zIndex); } DOM.setStyleAttribute(getElement(), "zIndex", "" + zIndex); } protected void constructDOM() { header = DOM.createDiv(); DOM.setElementProperty(header, "className", CLASSNAME + "-outerheader"); headerText = DOM.createDiv(); DOM.setElementProperty(headerText, "className", CLASSNAME + "-header"); contents = DOM.createDiv(); DOM.setElementProperty(contents, "className", CLASSNAME + "-contents"); footer = DOM.createDiv(); DOM.setElementProperty(footer, "className", CLASSNAME + "-footer"); resizeBox = DOM.createDiv(); DOM .setElementProperty(resizeBox, "className", CLASSNAME + "-resizebox"); closeBox = DOM.createDiv(); DOM.setElementProperty(closeBox, "className", CLASSNAME + "-closebox"); DOM.appendChild(footer, resizeBox); DOM.sinkEvents(getElement(), Event.ONLOSECAPTURE); DOM.sinkEvents(closeBox, Event.ONCLICK); DOM.sinkEvents(contents, Event.ONCLICK); final Element wrapper = DOM.createDiv(); DOM.setElementProperty(wrapper, "className", CLASSNAME + "-wrap"); final Element wrapper2 = DOM.createDiv(); DOM.setElementProperty(wrapper2, "className", CLASSNAME + "-wrap2"); DOM.sinkEvents(wrapper, Event.ONKEYDOWN); DOM.appendChild(wrapper2, closeBox); DOM.appendChild(wrapper2, header); DOM.appendChild(header, headerText); DOM.appendChild(wrapper2, contents); DOM.appendChild(wrapper2, footer); DOM.appendChild(wrapper, wrapper2); DOM.appendChild(super.getContainerElement(), wrapper); DOM.setElementProperty(getElement(), "className", CLASSNAME); sinkEvents(Event.MOUSEEVENTS); setWidget(contentPanel); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { id = uidl.getId(); this.client = client; // Workaround needed for Testing Tools (GWT generates window DOM // slightly different in different browsers). DOM.setElementProperty(closeBox, "id", id + "_window_close"); if (uidl.hasAttribute("invisible")) { this.hide(); return; } if (client.updateComponent(this, uidl, false)) { return; } if (uidl.getBooleanAttribute("modal") != modal) { setModal(!modal); } // Initialize the size from UIDL // FIXME relational size is for outer size, others are applied for // content if (uidl.hasVariable("width")) { final String width = uidl.getStringVariable("width"); if (width.indexOf("px") < 0) { DOM.setStyleAttribute(getElement(), "width", width); } else { setWidth(width); } } // Initialize the position form UIDL try { final int positionx = uidl.getIntVariable("positionx"); final int positiony = uidl.getIntVariable("positiony"); if (positionx >= 0 && positiony >= 0) { setPopupPosition(positionx, positiony); } } catch (final IllegalArgumentException e) { // Silently ignored as positionx and positiony are not required // parameters } if (!isAttached()) { show(); } // Height set after show so we can detect space used by decorations if (uidl.hasVariable("height")) { final String height = uidl.getStringVariable("height"); if (height.indexOf("%") > 0) { int winHeight = Window.getClientHeight(); float percent = Float.parseFloat(height.substring(0, height .indexOf("%"))) / 100.0f; int contentPixels = (int) (winHeight * percent); contentPixels -= (DOM.getElementPropertyInt(getElement(), "offsetHeight") - DOM.getElementPropertyInt(contents, "offsetHeight")); // FIXME hardcoded contents elements border size contentPixels -= 2; setHeight(contentPixels + "px"); } else { setHeight(height); } } if (uidl.hasAttribute("caption")) { setCaption(uidl.getStringAttribute("caption"), uidl .getStringAttribute("icon")); } boolean showingUrl = false; int childIndex = 0; UIDL childUidl = uidl.getChildUIDL(childIndex++); while ("open".equals(childUidl.getTag())) { // TODO multiple opens with the same target will in practice just // open the last one - should we fix that somehow? final String parsedUri = client.translateToolkitUri(childUidl .getStringAttribute("src")); if (!childUidl.hasAttribute("name")) { final Frame frame = new Frame(); DOM.setStyleAttribute(frame.getElement(), "width", "100%"); DOM.setStyleAttribute(frame.getElement(), "height", "100%"); DOM.setStyleAttribute(frame.getElement(), "border", "0px"); frame.setUrl(parsedUri); contentPanel.setWidget(frame); showingUrl = true; } else { final String target = childUidl.getStringAttribute("name"); Window.open(parsedUri, target, ""); } childUidl = uidl.getChildUIDL(childIndex++); } final Paintable lo = client.getPaintable(childUidl); if (layout != null) { if (layout != lo) { // remove old client.unregisterPaintable(layout); contentPanel.remove((Widget) layout); // add new if (!showingUrl) { contentPanel.setWidget((Widget) lo); } layout = lo; } } else if (!showingUrl) { contentPanel.setWidget((Widget) lo); } lo.updateFromUIDL(childUidl, client); // we may have actions and notifications if (uidl.getChildCount() > 1) { final int cnt = uidl.getChildCount(); for (int i = 1; i < cnt; i++) { childUidl = uidl.getChildUIDL(i); if (childUidl.getTag().equals("actions")) { if (shortcutHandler == null) { shortcutHandler = new ShortcutActionHandler(id, client); } shortcutHandler.updateActionMap(childUidl); } else if (childUidl.getTag().equals("notifications")) { // TODO needed? move -> for (final Iterator it = childUidl.getChildIterator(); it .hasNext();) { final UIDL notification = (UIDL) it.next(); String html = ""; if (notification.hasAttribute("icon")) { final String parsedUri = client .translateToolkitUri(notification .getStringAttribute("icon")); html += "<img src=\"" + parsedUri + "\" />"; } if (notification.hasAttribute("caption")) { html += "<h1>" + notification .getStringAttribute("caption") + "</h1>"; } if (notification.hasAttribute("message")) { html += "<p>" + notification .getStringAttribute("message") + "</p>"; } final String style = notification.hasAttribute("style") ? notification .getStringAttribute("style") : null; final int position = notification .getIntAttribute("position"); final int delay = notification.getIntAttribute("delay"); new Notification(delay).show(html, position, style); } } } } // setting scrollposition must happen after children is rendered contentPanel.setScrollPosition(uidl.getIntVariable("scrolltop")); contentPanel.setHorizontalScrollPosition(uidl .getIntVariable("scrollleft")); } public void show() { if (modal) { showModalityCurtain(); } super.show(); setFF2CaretFixEnabled(true); fixFF3OverflowBug(); } /** Disable overflow auto with FF3 to fix #1837. */ private void fixFF3OverflowBug() { if (BrowserInfo.get().isFF3()) { DeferredCommand.addCommand(new Command() { public void execute() { DOM.setStyleAttribute(getElement(), "overflow", ""); } }); } } /** * Fix "missing cursor" browser bug workaround for FF2 in Windows and Linux. * * Calling this method has no effect on other browsers than the ones based * on Gecko 1.8 * * @param enable */ private void setFF2CaretFixEnabled(boolean enable) { if (BrowserInfo.get().isFF2()) { if (enable) { DeferredCommand.addCommand(new Command() { public void execute() { DOM.setStyleAttribute(getElement(), "overflow", "auto"); } }); } else { DOM.setStyleAttribute(getElement(), "overflow", ""); } } } public void hide() { if (modal) { hideModalityCurtain(); } super.hide(); } private void setModal(boolean modality) { modal = modality; if (modal) { modalityCurtain = DOM.createDiv(); DOM.setElementProperty(modalityCurtain, "className", CLASSNAME + "-modalitycurtain"); if (isAttached()) { showModalityCurtain(); bringToFront(); } else { DeferredCommand.addCommand(new Command() { public void execute() { // modal window must on top of others bringToFront(); } }); } } else { if (modalityCurtain != null) { if (isAttached()) { hideModalityCurtain(); } modalityCurtain = null; } } } private void showModalityCurtain() { if (BrowserInfo.get().isFF2()) { DOM.setStyleAttribute(modalityCurtain, "height", DOM .getElementPropertyInt(RootPanel.getBodyElement(), "offsetHeight") + "px"); DOM.setStyleAttribute(modalityCurtain, "position", "absolute"); } DOM.appendChild(RootPanel.getBodyElement(), modalityCurtain); } private void hideModalityCurtain() { DOM.removeChild(RootPanel.getBodyElement(), modalityCurtain); } /* * Shows (or hides) an empty div on top of all other content; used when * resizing or moving, so that iframes (etc) do not steal event. */ private void showDraggingCurtain(boolean show) { if (show && draggingCurtain == null) { setFF2CaretFixEnabled(false); // makes FF2 slow draggingCurtain = DOM.createDiv(); DOM.setStyleAttribute(draggingCurtain, "position", "absolute"); DOM.setStyleAttribute(draggingCurtain, "top", "0px"); DOM.setStyleAttribute(draggingCurtain, "left", "0px"); DOM.setStyleAttribute(draggingCurtain, "width", "100%"); DOM.setStyleAttribute(draggingCurtain, "height", "100%"); DOM.setStyleAttribute(draggingCurtain, "zIndex", "" + ToolkitOverlay.Z_INDEX); DOM.appendChild(RootPanel.getBodyElement(), draggingCurtain); } else if (!show && draggingCurtain != null) { setFF2CaretFixEnabled(true); // makes FF2 slow DOM.removeChild(RootPanel.getBodyElement(), draggingCurtain); draggingCurtain = null; } } public void setPopupPosition(int left, int top) { super.setPopupPosition(left, top); if (left != uidlPositionX && client != null) { client.updateVariable(id, "positionx", left, false); uidlPositionX = left; } if (top != uidlPositionY && client != null) { client.updateVariable(id, "positiony", top, false); uidlPositionY = top; } } public void setCaption(String c) { setCaption(c, null); } public void setCaption(String c, String icon) { String html = Util.escapeHTML(c); if (icon != null) { icon = client.translateToolkitUri(icon); html = "<img src=\"" + icon + "\" class=\"i-icon\" />" + html; } DOM.setInnerHTML(headerText, html); } protected Element getContainerElement() { return contents; } public void onBrowserEvent(final Event event) { final int type = DOM.eventGetType(event); if (type == Event.ONKEYDOWN && shortcutHandler != null) { shortcutHandler.handleKeyboardEvent(event); return; } final Element target = DOM.eventGetTarget(event); // Handle window caption tooltips if (client != null && DOM.isOrHasChild(header, target)) { client.handleTooltipEvent(event, this); } if (resizing || DOM.compare(resizeBox, target)) { onResizeEvent(event); DOM.eventCancelBubble(event, true); } else if (DOM.compare(target, closeBox)) { if (type == Event.ONCLICK) { onCloseClick(); DOM.eventCancelBubble(event, true); } } else if (dragging || !DOM.isOrHasChild(contents, target)) { onDragEvent(event); DOM.eventCancelBubble(event, true); } else if (type == Event.ONCLICK) { // clicked inside window, ensure to be on top if (!isActive()) { bringToFront(); } } } private void onCloseClick() { client.updateVariable(id, "close", true, true); } private void onResizeEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONMOUSEDOWN: if (!isActive()) { bringToFront(); } showDraggingCurtain(true); resizing = true; startX = DOM.eventGetScreenX(event); startY = DOM.eventGetScreenY(event); origW = getWidget().getOffsetWidth(); origH = getWidget().getOffsetHeight(); DOM.setCapture(getElement()); DOM.eventPreventDefault(event); break; case Event.ONMOUSEUP: showDraggingCurtain(false); resizing = false; DOM.releaseCapture(getElement()); setSize(event, true); break; case Event.ONLOSECAPTURE: showDraggingCurtain(false); resizing = false; case Event.ONMOUSEMOVE: if (resizing) { setSize(event, false); DOM.eventPreventDefault(event); } break; default: DOM.eventPreventDefault(event); break; } } public void setSize(Event event, boolean updateVariables) { int w = DOM.eventGetScreenX(event) - startX + origW; if (w < MIN_WIDTH) { w = MIN_WIDTH; } int h = DOM.eventGetScreenY(event) - startY + origH; if (h < MIN_HEIGHT) { h = MIN_HEIGHT; } setWidth(w + "px"); setHeight(h + "px"); if (updateVariables) { // sending width back always as pixels, no need for unit client.updateVariable(id, "width", w, false); client.updateVariable(id, "height", h, false); } // Update child widget dimensions Util.runDescendentsLayout(this); } public void setWidth(String width) { if (!"".equals(width)) { DOM .setStyleAttribute( getElement(), "width", (Integer.parseInt(width.substring(0, width.length() - 2)) + BORDER_WIDTH_HORIZONTAL) + "px"); } } private void onDragEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONMOUSEDOWN: if (!isActive()) { bringToFront(); } showDraggingCurtain(true); dragging = true; startX = DOM.eventGetScreenX(event); startY = DOM.eventGetScreenY(event); origX = DOM.getAbsoluteLeft(getElement()); origY = DOM.getAbsoluteTop(getElement()); DOM.setCapture(getElement()); DOM.eventPreventDefault(event); break; case Event.ONMOUSEUP: dragging = false; showDraggingCurtain(false); DOM.releaseCapture(getElement()); break; case Event.ONLOSECAPTURE: showDraggingCurtain(false); dragging = false; break; case Event.ONMOUSEMOVE: if (dragging) { final int x = DOM.eventGetScreenX(event) - startX + origX; final int y = DOM.eventGetScreenY(event) - startY + origY; setPopupPosition(x, y); DOM.eventPreventDefault(event); } break; default: break; } } public boolean onEventPreview(Event event) { if (dragging) { onDragEvent(event); return false; } else if (resizing) { onResizeEvent(event); return false; } else if (modal) { // return false when modal and outside window final Element target = DOM.eventGetTarget(event); if (!DOM.isOrHasChild(getElement(), target)) { return false; } } return true; } public void onScroll(Widget widget, int scrollLeft, int scrollTop) { client.updateVariable(id, "scrolltop", scrollTop, false); client.updateVariable(id, "scrollleft", scrollLeft, false); } public void addStyleDependentName(String styleSuffix) { // IWindow's getStyleElement() does not return the same element as // getElement(), so we need to override this. setStyleName(getElement(), getStylePrimaryName() + "-" + styleSuffix, true); } }
package com.commit451.gitlab.model.api; import com.google.gson.annotations.SerializedName; import org.parceler.Parcel; import android.net.Uri; @Parcel public class Group { @SerializedName("id") long mId; @SerializedName("name") String mName; @SerializedName("path") String mPath; @SerializedName("description") String mDescription; @SerializedName("avatar_url") Uri mAvatarUrl; @SerializedName("web_url") Uri mWebUrl; public Group() {} public long getId() { return mId; } public String getName() { return mName; } public String getPath() { return mPath; } public String getDescription() { return mDescription; } public Uri getAvatarUrl() { return mAvatarUrl; } public Uri getWebUrl() { return mWebUrl; } public Uri getFeedUrl() { if (mWebUrl == null) { return null; } return Uri.parse(mWebUrl.toString() + ".atom"); } @Override public boolean equals(Object o) { if (!(o instanceof Group)) { return false; } Group group = (Group) o; return mId == group.mId; } @Override public int hashCode() { return (int) (mId ^ (mId >>> 32)); } }
package io.openkit.leaderboards; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import io.openkit.OKHTTPClient; import io.openkit.OKLog; import io.openkit.OKScore; import io.openkit.OKUser; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class OKScoreCache extends SQLiteOpenHelper{ private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "OKCACHEDB"; private static final String TABLE_SCORES = "OKCACHE"; private static final String KEY_ID = "id"; private static final String KEY_LEADERBOARD_ID = "leaderboardID"; private static final String KEY_SCOREVALUE = "scoreValue"; private static final String KEY_METADATA = "metadata"; private static final String KEY_DISPLAYSTRING = "displayString"; private static final String KEY_SUBMITTED = "submitted"; private int numOpenedConnections = 0; public OKScoreCache(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createCacheTable = "CREATE TABLE IF NOT EXISTS " + TABLE_SCORES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LEADERBOARD_ID + " INTEGER, "+ KEY_SCOREVALUE + " BIGINT, " + KEY_METADATA + " INTEGER, " + KEY_DISPLAYSTRING + " VARCHAR(255), " + KEY_SUBMITTED + " BOOLEAN);"; db.execSQL(createCacheTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES); onCreate(db); } public void insertScore(OKScore score) { ContentValues values = new ContentValues(); values.put(KEY_DISPLAYSTRING, score.getDisplayString()); values.put(KEY_LEADERBOARD_ID, score.getOKLeaderboardID()); values.put(KEY_METADATA, score.getMetadata()); values.put(KEY_SCOREVALUE, score.getScoreValue()); values.put(KEY_SUBMITTED, score.isSubmitted()); SQLiteDatabase db = getWritableDatabase(); long rowID = db.insert(TABLE_SCORES, null, values); score.setOKScoreID((int)rowID); close(); OKLog.v("Inserted score into db: " + score); } public void deleteScore(OKScore score) { if(score.getOKScoreID() <=0) { OKLog.v("Tried to delete a score from cache without an ID"); return; } SQLiteDatabase db = getWritableDatabase(); db.delete(TABLE_SCORES , KEY_ID + " = ?", new String[] { String.valueOf(score.getOKScoreID()) }); close(); } public void updateCachedScoreSubmitted(OKScore score) { if(score.getOKScoreID() <=0) { OKLog.v("Tried to update a score from cache without an ID"); return; } ContentValues values = new ContentValues(); values.put(KEY_SUBMITTED, score.isSubmitted()); SQLiteDatabase db = getWritableDatabase(); db.update(TABLE_SCORES , values, KEY_ID + " = ?", new String[] { String.valueOf(score.getOKScoreID()) }); close(); } public List<OKScore> getCachedScoresForLeaderboardID(int leaderboardID, boolean submittedScoresOnly) { String queryFormat; if(submittedScoresOnly) { queryFormat = "SELECT * FROM %s WHERE leaderboardID=%d AND submitted=1"; } else { queryFormat = "SELECT * FROM %s WHERE leaderboardID=%d"; } String selectQuery = String.format(queryFormat, TABLE_SCORES, leaderboardID); return getScoresWithQuerySQL(selectQuery); } public List<OKScore> getUnsubmittedCachedScores() { String queryFormat = "SELECT * FROM %s WHERE submitted=0"; String selectQuery = String.format(queryFormat, TABLE_SCORES); return getScoresWithQuerySQL(selectQuery); } public List<OKScore> getAllCachedScores() { String queryFormat = "SELECT * FROM %s"; String selectQuery = String.format(queryFormat, TABLE_SCORES); return getScoresWithQuerySQL(selectQuery); } private List<OKScore> getScoresWithQuerySQL(String querySQL) { List<OKScore> scoresList = new ArrayList<OKScore>(); SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery(querySQL, null); if(cursor.moveToFirst()) { do { OKScore score = new OKScore(); score.setOKScoreID(cursor.getInt(0)); score.setOKLeaderboardID(cursor.getInt(1)); score.setScoreValue(cursor.getLong(2)); score.setMetadata(cursor.getInt(3)); score.setDisplayString(cursor.getString(4)); int submitted = cursor.getInt(5); if(submitted == 0) { score.setSubmitted(false); } else { score.setSubmitted(true); } scoresList.add(score); } while (cursor.moveToNext()); } close(); return scoresList; } public void clearCachedSubmittedScores() { SQLiteDatabase db = getWritableDatabase(); db.execSQL("DELETE FROM " + TABLE_SCORES + " WHERE " + KEY_SUBMITTED + "=1"); close(); //logScoreCache(); } // Unused for now, use clearCachedSubmittedScores() instead. This drops the entire table, where as clearCachedSubmitted() is used to clear // out scores that have been submitted when a userID changes /* private void clearCache() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES); this.onCreate(db); }*/ /* private void logScoreCache() { List<OKScore> scoreList = getAllCachedScores(); OKLog.d("Score cache contains:"); for(int x =0; x < scoreList.size(); x++) { OKLog.d("1: " + scoreList.get(x)); } }*/ private void submitCachedScore(final OKScore score) { if(OKUser.getCurrentUser() != null) { score.setOKUser(OKUser.getCurrentUser()); score.cachedScoreSubmit(new OKScore.ScoreRequestResponseHandler() { @Override public void onSuccess() { OKLog.v("Submitted cached score successfully: " + score); updateCachedScoreSubmitted(score); } @Override public void onFailure(Throwable error) { // If the server responds with an error code in the 400s, delete the score from the cache if(OKHTTPClient.isErrorCodeInFourHundreds(error)) { OKLog.v("Deleting score from cache because server responded with error code in 400s"); deleteScore(score); } } }); } else { OKLog.v("Tried to submit cached score without having an OKUser logged in"); } } public void submitAllCachedScores() { if(OKUser.getCurrentUser() == null) { return; } List<OKScore> cachedScores = getUnsubmittedCachedScores(); for(int x = 0; x < cachedScores.size(); x++) { OKScore score = cachedScores.get(x); submitCachedScore(score); } } @Override public synchronized SQLiteDatabase getReadableDatabase() { numOpenedConnections++; return super.getReadableDatabase(); } @Override public synchronized SQLiteDatabase getWritableDatabase() { numOpenedConnections++; return super.getWritableDatabase(); } @Override public synchronized void close() { numOpenedConnections if(numOpenedConnections == 0) { super.close(); } } public boolean storeScoreInCacheIfBetterThanLocalCachedScores(OKScore score) { List<OKScore> cachedScores; // If there is a user logged in, we should compare against scores that have already been submitted to decide whether // to submit the new score, and not all scores. E.g. if there is an unsubmitted score for some reason that has a higher value than the // one to submit, we should still submit it. This is because for some reason there might be an unsubmitted score stored that will never // get submitted for some unknown reason. if(OKUser.getCurrentUser() != null) { cachedScores = getCachedScoresForLeaderboardID(score.getOKLeaderboardID(), true); } else { cachedScores = getCachedScoresForLeaderboardID(score.getOKLeaderboardID(), false); } if(cachedScores.size() <= 1) { insertScore(score); return true; } else { // Sort the scores in descending order Comparator<OKScore> descendingComparator = new Comparator<OKScore>() { @Override public int compare(OKScore s1, OKScore s2) { return (s1.getScoreValue()>s2.getScoreValue() ? -1 : (s1.getScoreValue()==s2.getScoreValue() ? 0 : 1)); } }; Collections.sort(cachedScores,descendingComparator); OKScore higestScore = cachedScores.get(0); OKScore lowestScore = cachedScores.get(cachedScores.size()-1); if(score.getScoreValue() > higestScore.getScoreValue()) { deleteScore(higestScore); insertScore(score); return true; } else if (score.getScoreValue() < lowestScore.getScoreValue()) { deleteScore(lowestScore); insertScore(score); return true; } } return false; } }
package com.konradjanica.amatch; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import com.andtinder.model.CardModel; import com.andtinder.view.CardContainer; import com.andtinder.view.SimpleCardStackAdapter; import com.facebook.drawee.backends.pipeline.Fresco; import com.konradjanica.Utils; import com.konradjanica.careercup.CareerCupAPI; import com.konradjanica.careercup.questions.Question; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import at.markushi.ui.CircleButton; import fr.castorflex.android.smoothprogressbar.SmoothProgressBar; public class MainActivity extends Activity { private final int maxCards = 5; private CardContainer mCardContainerMain; private CardContainer mCardContainerFavorites; private SimpleCardStackAdapter adapterMain; private SimpleCardStackAdapter adapterFavorites; private CareerCupAPI careerCupAPI; private LinkedList<Question> questionsList; private Queue<CardModel> questionsCardQueue; private LinkedList<CardModel> favouritesList; private Queue<CardModel> favoritesCardQueue; // Number of cards displayed private int cardCountMain; private int indexMain; private int cardCountFavorite; private int indexFavorite; // From preferences/settings private int pageRaw; private String company; private String job; private String topic; private boolean aMatchButtonState; private boolean isQuestionsLoading; private boolean isErrorLoading; private SmoothProgressBar progressBar; private TextView noQuestionsText; private boolean isFavoriteMode; // Favourites card file public final static String favoritesFile = "favourites.sav"; private static int settingsChangedIntent = 1; private void init() { careerCupAPI = new CareerCupAPI(); questionsList = new LinkedList<>(); questionsCardQueue = new LinkedList<>(); adapterMain = new SimpleCardStackAdapter(this); cardCountMain = 0; indexMain = 0; SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String page = preferences.getString("page_number", ""); company = preferences.getString("company_list", ""); job = preferences.getString("job_list", ""); topic = preferences.getString("topic_list", ""); pageRaw = Integer.parseInt(page); new DownloadInitialQuestions().execute(page, company, job, topic); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fresco.initialize(this); setContentView(R.layout.activity_main); mCardContainerMain = (CardContainer) findViewById(R.id.main_cards); mCardContainerFavorites = (CardContainer) findViewById(R.id.favorite_cards); progressBar = (SmoothProgressBar) findViewById(R.id.dl_progress); noQuestionsText = (TextView) findViewById(R.id.no_questions_found); aMatchButtonState = true; isQuestionsLoading = false; isErrorLoading = false; isFavoriteMode = false; favouritesList = Utils.readLinkedListFromFile(getApplicationContext(), favoritesFile); favoritesCardQueue = new LinkedList<>(favouritesList); adapterFavorites = new SimpleCardStackAdapter(this); cardCountFavorite = 0; indexFavorite = 0; ensureFavoritesFull(true); mCardContainerFavorites.setAdapter(adapterFavorites); init(); // Set aMatch button release final CircleButton aMatchButton = ((CircleButton) findViewById(R.id.amatchtoggle)); aMatchButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { if (aMatchButton.repeatCount < aMatchButton.ANIMATION_REPEATS) { if (mCardContainerMain.getTopCardView() == null && !isFavoriteMode) { final String page = Integer.toString(pageRaw); new DownloadRefillQuestions().execute(page, company, job, topic); } else { CardModel topCard = questionsCardQueue.peek(); View topCardView = mCardContainerMain.getTopCardView(); if (isFavoriteMode) { if (adapterFavorites.getCount() > indexFavorite) { topCard = adapterFavorites.getCardModel(indexFavorite); } topCardView = mCardContainerFavorites.getTopCardView(); } if (topCardView != null) { FrameLayout favView = ((FrameLayout) topCardView.findViewById(R.id.fav)); if (!topCard.isFavorite()) { favView.setVisibility(View.VISIBLE); favouritesList.add(topCard); Utils.writeLinkedListToFile(getApplicationContext(), favouritesList, favoritesFile); } else { favView.setVisibility(View.INVISIBLE); if (favouritesList.size() > 0) { Iterator<CardModel> itr = favouritesList.iterator(); do { CardModel cm = itr.next(); if (cm.getId().equals(topCard.getId())) { itr.remove(); break; } } while (itr.hasNext()); } Utils.writeLinkedListToFile(getApplicationContext(), favouritesList, favoritesFile); } topCard.toggleFavorite(); System.out.println(favouritesList.size()); } } } else { favouritesList = Utils.readLinkedListFromFile(getApplicationContext(), favoritesFile); if (!isFavoriteMode) { isFavoriteMode = true; adapterFavorites = new SimpleCardStackAdapter(getApplicationContext()); cardCountFavorite = 0; indexFavorite = 0; favoritesCardQueue = new LinkedList<>(favouritesList); ensureFavoritesFull(true); mCardContainerFavorites.setAdapter(adapterFavorites); findViewById(R.id.main_cards).setVisibility(View.GONE); findViewById(R.id.favorite_cards).setVisibility(View.VISIBLE); } else { isFavoriteMode = false; adapterMain = new SimpleCardStackAdapter(getApplicationContext()); ensureMainFull(); mCardContainerMain.setAdapter(adapterMain); findViewById(R.id.main_cards).setVisibility(View.VISIBLE); findViewById(R.id.favorite_cards).setVisibility(View.GONE); } System.out.println(favouritesList.size()); System.out.println("queue =" + favoritesCardQueue.size()); System.out.println("adapter =" + adapterMain.getCount()); } // Log.d("Released", "Button released"); } return false; } }); } /** * Sets up the adapterMain for first use and populates it with maxCards amount of cards */ private class DownloadInitialQuestions extends AsyncTask<String, Void, Void> { private Exception exception; protected void onPreExecute() { startProgressBar(); } protected Void doInBackground(String... filters) { try { questionsList.addAll(careerCupAPI.loadRecentQuestions(filters)); } catch (Exception e) { this.exception = e; } return null; } protected void onPostExecute(Void dummy) { if (exception != null) { errorProgressBar(); return; } if (questionsList.size() == 0) { mCardContainerMain.setAdapter(adapterMain); stopProgressBar(); return; } Iterator<Question> itr = questionsList.iterator(); // Add cards to adapterMain container addCardInitial(itr); while (itr.hasNext() && cardCountMain < maxCards) { addCardInitial(itr); } stopProgressBar(); mCardContainerMain.setAdapter(adapterMain); } } /** * Used to refill the cards upon pressing aMatch button on connection error */ private class DownloadRefillQuestions extends AsyncTask<String, Void, Void> { private Exception exception; protected void onPreExecute() { startProgressBar(); } protected Void doInBackground(String... filters) { try { questionsList.addAll(careerCupAPI.loadRecentQuestions(filters)); } catch (Exception e) { this.exception = e; } return null; } protected void onPostExecute(Void dummy) { if (exception != null) { errorProgressBar(); return; } ensureFull(); mCardContainerMain.refreshTopCard(); stopProgressBar(); } } /** * Normal download operation, next page is loaded into questionList */ private class DownloadQuestions extends AsyncTask<String, Void, Void> { private Exception exception; protected void onPreExecute() { startProgressBar(); } protected Void doInBackground(String... filters) { try { questionsList.addAll(careerCupAPI.loadRecentQuestions(filters)); } catch (Exception e) { this.exception = e; } return null; } protected void onPostExecute(Void dummy) { if (exception != null) { errorProgressBar(); return; } stopProgressBar(); } } /** * Display download error msg */ private void errorProgressBar() { isQuestionsLoading = false; isErrorLoading = true; progressBar.progressiveStop(); noQuestionsText.setText("Download Error has occurred!\nPlease Try Again."); } /** * Stop download progress bar and display question filter complete msg */ private void stopProgressBar() { isQuestionsLoading = false; isErrorLoading = false; progressBar.progressiveStop(); noQuestionsText.setText("Sorry - no more questions!\nTry new filters"); } /** * Start download progress bar and display loading msg */ private void startProgressBar() { isQuestionsLoading = true; progressBar.progressiveStart(); noQuestionsText.setText("Loading Questions..."); } /** * Add a card without notifying adapterMain * This is the normal procedure for adding files after initial * * @param itr an iterator to the questionsList */ private void addCard(Iterator<Question> itr) { addCard(itr, false); } /** * Add a card while notifying adapterMain * This is the initial procedure for adding files * * @param itr an iterator to the questionsList */ private void addCardInitial(Iterator<Question> itr) { addCard(itr, true); } /** * Add card to adapterMain and add it's listener for adding more cards */ private void addCard(Iterator<Question> itr, boolean isInitial) { Question q = itr.next(); CardModel cardModel = new CardModel(q.company, q.questionText, q.companyImgURL, q.pageNumber, q.dateText + q.location, q.id, q.questionTextLineCount); if (favouritesList.size() > 0) { Iterator<CardModel> iter = favouritesList.iterator(); do { CardModel cm = iter.next(); if (cm.getId().equals(cardModel.getId())) { cardModel.setFavorite(true); break; } } while (iter.hasNext()); } cardModel.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() { @Override public void onLike() { // Log.i("Swipeable Cards", "I like the card"); mainCardRemoval(); ensureFull(); } @Override public void onDislike() { // Log.i("Swipeable Cards", "I dislike the card"); mainCardRemoval(); ensureFull(); } }); cardModel.setOnClickListener(new CardModel.OnClickListener() { @Override public void OnClickListener() { // Log.i("Swipeable Cards", "I am pressing the card"); } }); if (isInitial) { adapterMain.addInitial(cardModel); } else { adapterMain.add(cardModel); } ++cardCountMain; itr.remove(); questionsCardQueue.add(cardModel); } /** * Add cards from queue to adapterMain * Used when changing from favourites to main */ private void addCardFromFav(Iterator<CardModel> itr) { CardModel cardModel = itr.next(); cardModel.setFavorite(false); if (favouritesList.size() > 0) { Iterator<CardModel> iter = favouritesList.iterator(); do { CardModel cm = iter.next(); if (cm.getId().equals(cardModel.getId())) { cardModel.setFavorite(true); break; } } while (iter.hasNext()); } cardModel.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() { @Override public void onLike() { // Log.i("Swipeable Cards", "I like the card"); mainCardRemoval(); ensureFull(); } @Override public void onDislike() { // Log.i("Swipeable Cards", "I dislike the card"); mainCardRemoval(); ensureFull(); } }); cardModel.setOnClickListener(new CardModel.OnClickListener() { @Override public void OnClickListener() { // Log.i("Swipeable Cards", "I am pressing the card"); } }); adapterMain.addInitial(cardModel); } private void mainCardRemoval() { --cardCountMain; ++indexMain; questionsCardQueue.remove(); } /** * Add card to adapterMain and add it's listener for adding more cards */ private void addCardFavorites(CardModel cardModel, boolean isInitial) { cardModel.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() { @Override public void onLike() { // Log.i("Swipeable Cards", "I like the card"); --cardCountFavorite; ++indexFavorite; ensureFavoritesFull(false); } @Override public void onDislike() { // Log.i("Swipeable Cards", "I dislike the card"); --cardCountFavorite; ++indexFavorite; ensureFavoritesFull(false); } }); cardModel.setOnClickListener(new CardModel.OnClickListener() { @Override public void OnClickListener() { // Log.i("Swipeable Cards", "I am pressing the card"); } }); if (isInitial) { adapterFavorites.addInitial(cardModel); } else { adapterFavorites.add(cardModel); } ++cardCountFavorite; } /** * Downloads next page if there's less than (maxCards * 2 - 1) in the list * Also fills 2 cards into adapterMain up to maxCards amount */ private void ensureFull() { if (questionsList.size() < maxCards * 2) { if (!isQuestionsLoading) { if (!isErrorLoading) { ++pageRaw; } final String page = Integer.toString(pageRaw); new DownloadQuestions().execute(page, company, job, topic); } } if (questionsList.size() > 0) { // Add cards until full Iterator<Question> itr = questionsList.iterator(); addCard(itr); if (itr.hasNext() && cardCountMain < maxCards) { addCard(itr); } } System.out.println("page = " + pageRaw + " questionsList size = " + questionsList.size()); } /** * Fills 2 cards into adapterFavourites up to maxCards amount */ private void ensureFavoritesFull(boolean isInitial) { if (favoritesCardQueue.size() > 0 && cardCountFavorite < maxCards) { // Add cards until full addCardFavorites(favoritesCardQueue.poll(), isInitial); if (favoritesCardQueue.size() > 0 && cardCountFavorite < maxCards) { addCardFavorites(favoritesCardQueue.poll(), isInitial); } } // System.out.println("page = " + pageRaw + " questionsList size = " + questionsList.size()); } /** * Fills cards into adapterMain from cardQueue */ private void ensureMainFull() { if (questionsCardQueue.size() > 0) { Iterator<CardModel> itr = questionsCardQueue.iterator(); do { addCardFromFav(itr); } while (itr.hasNext()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); // return true; return super.onCreateOptionsMenu(menu); } @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(); // Drawable gearup = getResources().getDrawable(R.drawable.gearup); // item.setIcon(gearup); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { // Drawable gearDown = getResources().getDrawable(R.drawable.ic_launcher); // item.setIcon(gearDown); SettingsActivity.applyPressed = false; Intent myIntent = new Intent(this, SettingsActivity.class); startActivityForResult(myIntent, settingsChangedIntent); return true; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (SettingsActivity.applyPressed) { init(); } } }
package me.nallar.patched; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.relauncher.IClassTransformer; import cpw.mods.fml.relauncher.RelaunchClassLoader; import me.nallar.tickthreading.Log; import sun.misc.URLClassPath; public abstract class PatchRelaunchClassLoader extends RelaunchClassLoader { private static volatile Map<String, byte[]> replacedClasses; private File minecraftdir; private File patchedModsFolder; private URLClassPath ucp; public PatchRelaunchClassLoader(URL[] sources) { super(sources); } private static File locationOf(Class clazz) { String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath(); path = path.contains("!") ? path.substring(0, path.lastIndexOf('!')) : path; if (!path.isEmpty() && path.charAt(0) == '/') { path = "file:" + path; } try { return new File(new URL(path).toURI()); } catch (Exception e) { Log.severe("", e); return new File(path); } } public void construct() { try { Field field = URLClassLoader.class.getDeclaredField("ucp"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, (field.getModifiers() & ~Modifier.FINAL) & ~Modifier.PRIVATE); ucp = (URLClassPath) field.get(this); minecraftdir = locationOf(net.minecraft.util.Tuple.class).getParentFile(); patchedModsFolder = new File(minecraftdir, "patchedMods"); boolean foundTT = false; for (File file : new File(minecraftdir, "mods").listFiles()) { if (file.getName().toLowerCase().contains("tickthreading") && file.getName().endsWith(".jar")) { URL toAdd = file.toURI().toURL(); if (!sources.contains(toAdd)) { sources.add(toAdd); ucp.addURL(toAdd); } foundTT = true; } } if (!foundTT) { System.err.println("Failed to find TT jar in mods folder - make sure it has 'tickthreading' in its name!"); } } catch (Throwable t) { t.printStackTrace(); } } @Override public void addURL(URL url) { if (sources.contains(url)) { FMLLog.warning("Added " + url.toString().replace("%", "%%") + " to classpath twice"); } ucp.addURL(url); sources.add(url); if (replacedClasses == null) { getReplacementClassBytes(""); } synchronized (RelaunchClassLoader.class) { loadPatchedClasses(url, replacedClasses); } } private void loadPatchedClasses(URL url_, Map<String, byte[]> replacedClasses) { if (replacedClasses == null) { return; } String url = url_.toString(); File patchedModFile; try { patchedModFile = new File(patchedModsFolder, url.substring(url.lastIndexOf('/') + 1, url.length())); } catch (Exception e) { return; } try { if (patchedModFile.exists()) { ZipFile zipFile = new ZipFile(patchedModFile); try { Enumeration<ZipEntry> zipEntryEnumeration = (Enumeration<ZipEntry>) zipFile.entries(); while (zipEntryEnumeration.hasMoreElements()) { ZipEntry zipEntry = zipEntryEnumeration.nextElement(); String name = zipEntry.getName(); if (!name.toLowerCase().endsWith(".class") || replacedClasses.containsKey(name)) { continue; } byte[] contents = readFully(zipFile.getInputStream(zipEntry)); replacedClasses.put(name, contents); } } finally { zipFile.close(); } } } catch (Exception e) { System.out.println("Failed to load patched classes for " + patchedModFile.getName()); e.printStackTrace(); } } private byte[] getReplacementClassBytes(String file) { try { Map<String, byte[]> replacedClasses = PatchRelaunchClassLoader.replacedClasses; if (replacedClasses == null) { synchronized (RelaunchClassLoader.class) { replacedClasses = PatchRelaunchClassLoader.replacedClasses; if (replacedClasses == null && minecraftdir != null) { replacedClasses = new ConcurrentHashMap<String, byte[]>(); for (URL url_ : sources) { loadPatchedClasses(url_, replacedClasses); } PatchRelaunchClassLoader.replacedClasses = replacedClasses; } } } return replacedClasses == null ? null : replacedClasses.get(file); } catch (Throwable t) { t.printStackTrace(); } return null; } @Override public byte[] getClassBytes(String name) throws IOException { byte[] data; if (name.indexOf('.') == -1) { for (String res : RESERVED) { if (name.toUpperCase(Locale.ENGLISH).startsWith(res)) { data = getClassBytes('_' + name); if (data != null) { return data; } } } } InputStream classStream = null; try { URL classResource = findResource(name.replace('.', '/') + ".class"); if (classResource == null) { if (DEBUG_CLASSLOADING) { FMLLog.finest("Failed to find class resource %s", name.replace('.', '/') + ".class"); } return null; } classStream = classResource.openStream(); if (DEBUG_CLASSLOADING) { FMLLog.finest("Loading class %s from resource %s", name, classResource.toString()); } data = readFully(classStream); byte[] data2 = getReplacementClassBytes(name.replace('.', '/') + ".class"); return data2 == null ? data : data2; } finally { if (classStream != null) { try { classStream.close(); } catch (IOException ignored) { } } } } @Override protected byte[] runTransformers(String name, byte[] basicClass) { if (basicClass == null) { if (DEBUG_CLASSLOADING) { FMLLog.log(DEBUG_CLASSLOADING ? Level.WARNING : Level.FINE, "Could not find the class " + name + ". This is not necessarily an issue."); } } for (IClassTransformer transformer : transformers) { try { byte[] oldClass = basicClass; basicClass = transformer.transform(name, basicClass); if (basicClass == null) { basicClass = oldClass; FMLLog.severe(transformer.getClass() + " returned a null class during transformation, ignoring."); } } catch (Throwable throwable) { String message = throwable.getMessage(); if ((message == null ? "" : message).contains("for invalid side")) { invalidClasses.add(name); throw (RuntimeException) throwable; } else if (basicClass != null || DEBUG_CLASSLOADING) { FMLLog.log((DEBUG_CLASSLOADING && basicClass != null) ? Level.WARNING : Level.FINE, throwable, "Failed to transform " + name); } } } return basicClass; } }
package com.mooo.ziggypop.candconline; import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.ListFragment; import android.support.v7.preference.PreferenceManager; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.transition.Scene; import android.transition.TransitionManager; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import static com.mooo.ziggypop.candconline.Player.PlayersAdapter.*; public class Player implements Comparable{ private static final String TAG = "Player"; private static int NOTIFICATION_VALUE = 1; private static int FRIEND_VALUE = 2; private static int YOURSELF_VALUE = 4; // Assemble the stats link: prefix + game_key + infix + player_name, MAYBE... private static String STATS_PREFIX = "http: private static String STATS_INFIX = "/index.php?g=kw&a=sp&name="; private static String PROFILE_PREFIX = "http://cnc-online.net/profiles/"; private static final int TYPE_SMALL = 0; private static final int TYPE_LARGE = 1; private String nickname; private int id; private int pid; private boolean isFriend; private boolean isReceiveNotifications; private boolean isYourself; private String game; private String userName; private boolean isExpanded; public Player(String nickname, int id, int pid){ this.nickname = nickname; this.id = id; this.pid = pid; this.isFriend = false; this.isReceiveNotifications = false; this.isYourself = false; this.game = ""; this.userName = ""; } public Player(String nickname, int id, int pid, boolean isFriend, boolean isReceiveNotifications, boolean isYourself, String userName) { this.nickname = nickname; this.id = id; this.pid = pid; this.isFriend = isFriend; this.isReceiveNotifications = isReceiveNotifications; this.isYourself = isYourself; this.userName = userName; } public String getNickname(){ return nickname; } public int getID(){return id;} public int getPID(){return pid;} public boolean getIsFriend(){return isFriend;} public boolean getIsRecieveNotifications(){return isReceiveNotifications;} public boolean getIsYourself(){return isYourself;} public String getUserName(){ return userName;} public void setIsFriend(boolean isFriend){ this.isFriend = isFriend; } public void setIsRecieveNotifications(boolean isRecieve){ this.isReceiveNotifications = isRecieve; } public void setIsYourself(boolean isYourself){ this.isYourself = isYourself; } public void setUserName(String userName) { this.userName = userName; } /** * Sorts the players by their case-insensitive nicknames. * @param another The other player to be compared against. * @return An int representing the comparison result. */ @Override public int compareTo(@NonNull Object another) { Player rightPlayer = (Player) another; // This logic slows the method significantly, but, with logging, it still took about .050 seconds // to sort 100 elements (.0002s per compare) on a Nexus 5x, so this is /acceptable/. This is // instead of the .011 seconds without the logic, or .040 seconds if the preference is disabled. Context context = CnCSpymaster.getAppContext(); if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean("sort_players_friendship_pref", true)){ Integer lPlayerValue = valueAdder(this); Integer rPlayerValue = valueAdder(rightPlayer); // we want the greater value of the two to be "Lesser", so this is opposite from normal. int returnValue = rPlayerValue.compareTo(lPlayerValue); if (returnValue != 0){ return returnValue; } } return this.nickname.compareToIgnoreCase(rightPlayer.nickname); } /** * Assigns a value based on the flags set for a player * @param player The player to be evaluated. * @return The player's "value". */ private int valueAdder(Player player){ int sum = 0; if (player.getIsYourself()) sum += YOURSELF_VALUE; if (player.getIsRecieveNotifications()) sum += NOTIFICATION_VALUE; if (player.getIsFriend()) sum += FRIEND_VALUE; return sum; } /** * Adapter used with the PlayersFragment */ public static class PlayersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public ArrayList<Player> myPlayers; private static PlayerDatabaseHandler db; public PlayersAdapter(Context context,ArrayList<Player> players){ myPlayers = players; db = new PlayerDatabaseHandler(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup cardView = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.player_card, null); RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); cardView.setLayoutParams(lp); View smallView = LayoutInflater.from(parent.getContext()).inflate(R.layout.player_small_layout, null); switch (viewType){ case TYPE_SMALL: cardView.addView(smallView); return new SmallViewHolder(cardView); case TYPE_LARGE: View largeView = LayoutInflater.from(parent.getContext()).inflate(R.layout.player_big_layout, null); cardView.addView(largeView); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cardView.setElevation(16); } return new LargeViewHolder(cardView); default: cardView.addView(smallView); return new SmallViewHolder(cardView); } } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) { final Player player = myPlayers.get(position); switch (holder.getItemViewType()){ //set up the view contents. case TYPE_SMALL: SmallViewHolder smallViewHolder = (SmallViewHolder) holder; smallViewHolder.nickname.setText(player.nickname); if (player.isFriend){ smallViewHolder.friendMarker.setVisibility(View.VISIBLE); } else { smallViewHolder.friendMarker.setVisibility(View.INVISIBLE); } if (player.isReceiveNotifications){ smallViewHolder.notificationMarker.setVisibility(View.VISIBLE); } else { smallViewHolder.notificationMarker.setVisibility(View.INVISIBLE); } if (player.isYourself){ smallViewHolder.yourselfMarker.setVisibility(View.VISIBLE); } else { smallViewHolder.yourselfMarker.setVisibility(View.INVISIBLE); } ((SmallViewHolder) holder).holderView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.v(TAG, "Small item clicked"); player.isExpanded = true; //TODO: animate a transformation. notifyItemChanged(position); notifyDataSetChanged(); } }); break; case TYPE_LARGE: final LargeViewHolder largeViewHolder = (LargeViewHolder) holder; largeViewHolder.nickname.setText(player.nickname); //Set the username to invisible to make the prog bar look nice when the view is recycled. largeViewHolder.username.setText(""); //Update the username if (player.getUserName().equals("")){ String cncOnlineLink = PROFILE_PREFIX + player.pid + "/"; Log.d(TAG, "Player IGN not found, getting from website"); LinearLayout progBarView = (LinearLayout) ((LargeViewHolder) holder).holderView.findViewById(R.id.name_loading_progress_bar); new RealUsernameHandler( cncOnlineLink, player, largeViewHolder.username, progBarView ).getUsername(); } else { largeViewHolder.username.setText(player.getUserName()); } largeViewHolder.friendsCheckbox.setChecked(player.isFriend); largeViewHolder.notificationsCheckbox.setChecked(player.isReceiveNotifications); largeViewHolder.yourselfCheckbox.setChecked(player.isYourself); largeViewHolder.friendsCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { expandedViewUpdateDB(player, (LargeViewHolder) holder); } }); largeViewHolder.notificationsCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { expandedViewUpdateDB(player, (LargeViewHolder) holder); } }); largeViewHolder.yourselfCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { expandedViewUpdateDB(player, (LargeViewHolder) holder); } }); ((LargeViewHolder) holder).holderView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.v(TAG, "Large item clicked"); player.isExpanded = false; //TODO: animate this transformation //prevent this viewHolder from having the onCheckedChanged() method called on other viewHolder instances. largeViewHolder.yourselfCheckbox.setOnCheckedChangeListener(null); largeViewHolder.notificationsCheckbox.setOnCheckedChangeListener(null); largeViewHolder.friendsCheckbox.setOnCheckedChangeListener(null); //Let the RecyclerView recognize that player is no longer expanded, and cause the row to be redrawn. notifyItemChanged(position); } }); break; } } @Override public int getItemViewType(int position){ if (myPlayers.get(position).isExpanded){ return TYPE_LARGE; } else{ return TYPE_SMALL; } } @Override public int getItemCount() { if (myPlayers != null){ return myPlayers.size(); } else return 0; } private static class SmallViewHolder extends RecyclerView.ViewHolder { TextView nickname; View friendMarker; View notificationMarker; View yourselfMarker; ViewGroup holderView; public SmallViewHolder(View itemView) { super(itemView); nickname = (TextView) itemView.findViewById(R.id.players_name); friendMarker = itemView.findViewById(R.id.friend_marker); notificationMarker = itemView.findViewById(R.id.notify_marker); yourselfMarker = itemView.findViewById(R.id.yourself_marker); holderView = (ViewGroup) itemView.findViewById(R.id.player_card); } } private static class LargeViewHolder extends RecyclerView.ViewHolder { TextView nickname; TextView username; CheckBox friendsCheckbox; CheckBox notificationsCheckbox; CheckBox yourselfCheckbox; ViewGroup holderView; public LargeViewHolder(final View itemView) { super(itemView); nickname = (TextView) itemView.findViewById(R.id.players_name); username = (TextView) itemView.findViewById(R.id.players_user_name); friendsCheckbox= (CheckBox) itemView.findViewById(R.id.friends_checkbox); notificationsCheckbox = (CheckBox) itemView.findViewById(R.id.notifications_checkbox); yourselfCheckbox = (CheckBox) itemView.findViewById(R.id.is_you_checkbox); holderView = (ViewGroup) itemView.findViewById(R.id.player_card); } } private void expandedViewUpdateDB(Player player, LargeViewHolder holder){ Log.v(TAG, "Updating the db for: " + player.nickname); CheckBox friendsCheckbox = (CheckBox) holder.holderView.findViewById(R.id.friends_checkbox); CheckBox notificationsCheckbox = (CheckBox) holder.holderView.findViewById(R.id.notifications_checkbox); CheckBox yourselfCheckbox = (CheckBox) holder.holderView.findViewById(R.id.is_you_checkbox); player.setIsFriend(friendsCheckbox.isChecked()); player.setIsRecieveNotifications(notificationsCheckbox.isChecked()); player.setIsYourself(yourselfCheckbox.isChecked()); player.setUserName(((TextView)holder.holderView.findViewById(R.id.players_user_name)).getText() + ""); // Commit the new player to the DB, or remove them if they are unchecked. if (!friendsCheckbox.isChecked() && !notificationsCheckbox.isChecked() && !yourselfCheckbox.isChecked()){ db.deletePlayer(player); } else { db.addPlayer(player); } } } /** * Demonstrates the use of {@link RecyclerView} with a {@link LinearLayoutManager} and a * {@link GridLayoutManager}. */ public static class PlayersFragment extends RecyclerViewFragment { private static final String TAG = "RecyclerViewFragment"; private static final String KEY_LAYOUT_MANAGER = "layoutManager"; private static final int SPAN_COUNT = 2; protected LayoutManagerType mCurrentLayoutManagerType; protected RecyclerView mRecyclerView; protected PlayersAdapter mAdapter; protected RecyclerView.LayoutManager mLayoutManager; protected ArrayList<Player> mDataset; @Override public void onCreate(Bundle bundle){ super.onCreate(bundle); Log.v(TAG, "onCreate called"); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); llm.setOrientation(LinearLayoutManager.VERTICAL); View rootView = getActivity().getLayoutInflater().inflate(R.layout.fragment_list_view, null, false); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(llm); mDataset = new ArrayList<>(); mAdapter = new PlayersAdapter(getActivity(), mDataset); Log.v(TAG, "setting the adapter for player"); mRecyclerView.setAdapter( mAdapter ); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater,container,savedInstanceState); Log.v(TAG, "onCreateView Called"); View rootView = inflater.inflate(R.layout.fragment_list_view, container, false); rootView.setTag(TAG); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view); // LinearLayoutManager is used here, this will layout the elements in a similar fashion // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how // elements are laid out. mLayoutManager = new LinearLayoutManager(getActivity()); mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER; mRecyclerView.setHasFixedSize(true); if (savedInstanceState != null) { // Restore saved layout manager type. mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState .getSerializable(KEY_LAYOUT_MANAGER); } setRecyclerViewLayoutManager(mCurrentLayoutManagerType); mRecyclerView.addItemDecoration(new RecyclerViewFragment.VerticalSpaceItemDecoration( (int) getResources().getDimension(R.dimen.recycle_spacing))); mAdapter = new PlayersAdapter(getContext(), mDataset); // Set CustomAdapter as the adapter for RecyclerView. Log.v(TAG, "setting the adapter for player"); mRecyclerView.setAdapter(mAdapter); return rootView; } /** * Set RecyclerView's LayoutManager to the one given. * * @param layoutManagerType Type of layout manager to switch to. */ public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) { int scrollPosition = 0; // If a layout manager has already been set, get current scroll position. if (mRecyclerView.getLayoutManager() != null) { scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()) .findFirstCompletelyVisibleItemPosition(); } switch (layoutManagerType) { case GRID_LAYOUT_MANAGER: mLayoutManager = new GridLayoutManager(getActivity(), SPAN_COUNT); mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER; break; case LINEAR_LAYOUT_MANAGER: mLayoutManager = new LinearLayoutManager(getActivity()); mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER; break; default: mLayoutManager = new LinearLayoutManager(getActivity()); mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER; } mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.scrollToPosition(scrollPosition); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save currently selected layout manager. savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, mCurrentLayoutManagerType); super.onSaveInstanceState(savedInstanceState); } public void refreshData(final ArrayList<Player> data, final Activity activity ){ if(!isAdded()) mAdapter = new PlayersAdapter(activity, mDataset); activity.runOnUiThread(new Runnable() { public void run() { Log.v(TAG, "Refreshing"); mDataset.clear(); mDataset.addAll(data); mAdapter.notifyDataSetChanged(); } }); } } }
package com.pilotcraftmc.health; import android.content.ContentUris; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.provider.CalendarContract; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; public class MainActivity extends ActionBarActivity { //These variables are used for the navigation bar private String[] mNavItems; private DrawerLayout mDrawerLayout; private LinearLayout mDrawerLinear; //for header pic private ListView mDrawerList; private CharSequence mTitle; private CharSequence mDrawerTitle; private ActionBarDrawerToggle mDrawerToggle; //v7 support version @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Navigation Bar Section// mNavItems = getResources().getStringArray(R.array.nav_items); mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); //activity_main.xml mDrawerLinear = (LinearLayout) findViewById(R.id.drawer_linear_layout); //activity_main.xml mDrawerList = (ListView) findViewById(R.id.left_drawer); //activity_main.xml // Set the adapter for the list view mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mNavItems)); //layout is a textview to style nav items mDrawerList.setItemChecked(0, true); //highlight the first item // Set the list's click listener mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); //inner class we create mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); getSupportActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getSupportActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; //For the hamburger menu mDrawerLayout.setDrawerListener(mDrawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } // //Navigation Bar Related Inner Class & Helper Methods// // private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { selectItem(position); } } /** * Swaps fragments in the main content view */ private void selectItem(int position) { Fragment fragment = null; switch (position) { case 0: fragment = new PlaceHolderFragment(); break; case 1: case 2: long startMillis = System.currentTimeMillis(); Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon(); builder.appendPath("time"); ContentUris.appendId(builder, startMillis); Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder.build()); startActivity(intent); fragment = new PlaceHolderFragment(); break; case 4: Intent bob = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345")); startActivity(bob); fragment = new PlaceHolderFragment(); break; default: fragment = new PlaceHolderFragment(); } // Insert the fragment by replacing any existing fragment FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment) .commit(); // Highlight the selected item, update the title, and close the drawer mDrawerList.setItemChecked(position, true); setTitle(mNavItems[position]); mDrawerLayout.closeDrawer(mDrawerLinear); //mDrawerList as the arg if no header pic } @Override public void setTitle(CharSequence title) { mTitle = title; getSupportActionBar().setTitle(mTitle); } /* Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerLinear); //mDrawerList arg if no pic //menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); //the thing to hide return super.onPrepareOptionsMenu(menu); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } // @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }
package com.proxima.fragments; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.location.Location; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.FrameLayout; import android.widget.Toast; import com.parse.ParseUser; import com.proxima.R; import com.proxima.activities.ConfirmationActivity; import com.proxima.activities.TabActivity; import com.proxima.utils.PhotoUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class CameraFragment extends Fragment { public static final String ARG_SECTION_NUMBER = "Cam"; private static final String TAG = CameraFragment.class.getName(); // Native camera. private Camera mCamera; // View to display the camera output. private CameraPreview mPreview; int mNumberOfCameras; // Camera ID currently chosen int mCurrentCamera; // Camera ID that's actually acquired int mCameraCurrentlyLocked; // The first rear facing camera int mDefaultCameraId; // Reference to the containing view. private View mCameraView; boolean pauseFlag = true; /** * Default empty constructor. */ public CameraFragment(){ super(); } /** * Static factory method * @param sectionNumber * @return */ public static CameraFragment newInstance(int sectionNumber) { CameraFragment fragment = new CameraFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } /** * OnCreateView fragment override * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Create our Preview view and set it as the content of our activity. View view = inflater.inflate(R.layout.camera_fragment, container, false); // Show the action bar options menu. setHasOptionsMenu(true); // Find the total number of cameras available mNumberOfCameras = Camera.getNumberOfCameras(); // Find the ID of the rear-facing ("default") camera CameraInfo cameraInfo = new CameraInfo(); for (int i = 0; i < mNumberOfCameras; i++) { Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { mCurrentCamera = mDefaultCameraId = i; } } //open the camera for use boolean opened = safeCameraOpenInView(view); if(opened == false){ Log.d("CameraGuide","Error, Camera failed to open"); return view; } // Trap the capture button. Button captureButton = (Button) view.findViewById(R.id.button_capture); captureButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // get an image from the camera mCamera.takePicture(null, null, mPicture); } } ); // Trap the camera flip button. Button flipButton = (Button) view.findViewById(R.id.button_flip); // Check if there is a front camera, if not make the flip button unaccessable if(Camera.getNumberOfCameras() == 1){ flipButton.setVisibility(View.INVISIBLE); } else { flipButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } // Acquire the next camera and request Preview to reconfigure // parameters. mCurrentCamera = (mCameraCurrentlyLocked + 1) % mNumberOfCameras; mCamera = Camera.open(mCurrentCamera); mCameraCurrentlyLocked = mCurrentCamera; mPreview.switchCamera(mCamera); // Start the preview mCamera.startPreview(); } } ); } return view; } /** * Recommended "safe" way to open the camera. * @param view * @return */ private boolean safeCameraOpenInView(View view) { boolean qOpened = false; // make sure camera is availiable releaseCameraAndPreview(); Log.d("HELLO", "onCreate"); // get a camera object mCamera = getCameraInstance(); // set the camera orientation to portrait mCamera.setDisplayOrientation(90); mCameraView = view; qOpened = (mCamera != null); // add the camera preview to the layout if(qOpened == true){ mPreview = new CameraPreview(getActivity().getBaseContext(), mCamera,view); FrameLayout preview = (FrameLayout) view.findViewById(R.id.camera_preview); preview.addView(mPreview); mPreview.startCameraPreview(); } return qOpened; } /** * Safe method for getting a camera instance. * @return */ public static Camera getCameraInstance(){ Camera c = null; try { // attempt to get a Camera instance c = Camera.open(); } catch (Exception e){ e.printStackTrace(); } // returns null if camera is unavailable return c; } // release the camera on pause so it is availiable for other applications @Override public void onPause() { super.onPause(); releaseCameraAndPreview(); pauseFlag = true; } // restart the camera preview when fragment is resumed @Override public void onResume() { super.onResume(); TabActivity activity = (TabActivity) getActivity(); if (activity == null || ParseUser.getCurrentUser() == null) { // The user got here by hitting back without being logged in; continue the expected // behavior of finishing back to the launcher. Log.d(TAG, "finishing activity due to unexpected onResume call"); getActivity().finish(); return; } activity.refreshMark(); View newView = getActivity().findViewById(R.id.camera_preview); if (pauseFlag){ safeCameraOpenInView(newView); } } // release the camera when the fragment is destroyed to make it availiable for other // applications @Override public void onDestroy() { super.onDestroy(); releaseCameraAndPreview(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.camera, menu); } /** * Clear any existing preview / camera. */ private void releaseCameraAndPreview() { if (mCamera != null) { FrameLayout preview = (FrameLayout) this.getActivity().findViewById(R.id.camera_preview); preview.removeView(mPreview); mCamera.setPreviewCallback(null); mCamera.stopPreview(); mCamera.release(); mCamera = null; } if(mPreview != null){ mPreview.mCamera = null; } } class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { // SurfaceHolder private SurfaceHolder mHolder; // Our Camera. private Camera mCamera; // Parent Context. private Context mContext; // Camera Sizing (For rotation, orientation changes) private Camera.Size mPreviewSize; // List of supported preview sizes private List<Camera.Size> mSupportedPreviewSizes; // Flash modes supported by this camera private List<String> mSupportedFlashModes; // View holding this camera. private View mCameraView; // Create the surface holder for the camera preview public CameraPreview(Context context, Camera camera, View cameraView) { super(context); // Capture the context mCameraView = cameraView; mContext = context; setCamera(camera); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setKeepScreenOn(true); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } // switch from front to back camera or vice versa public void switchCamera(Camera camera) { setCamera(camera); try { // orient the camera display to portrait camera.setDisplayOrientation(90); camera.setPreviewDisplay(mHolder); } catch (IOException exception) { exception.printStackTrace(); } } /** * Begin the preview of the camera input. */ public void startCameraPreview() { try{ mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch(Exception e){ e.printStackTrace(); } } /** * Extract supported preview and flash modes from the camera. * @param camera */ private void setCamera(Camera camera) { mCamera = camera; mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes(); mSupportedFlashModes = mCamera.getParameters().getSupportedFlashModes(); // Set the camera to Auto Flash mode. if (mSupportedFlashModes != null && mSupportedFlashModes.contains(Camera.Parameters.FLASH_MODE_AUTO)){ Camera.Parameters parameters = mCamera.getParameters(); parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); mCamera.setParameters(parameters); } requestLayout(); } /** * The Surface has been created, now tell the camera where to draw the preview. * @param holder */ public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); } catch (IOException e) { e.printStackTrace(); } } /** * Dispose of the camera preview. * @param holder */ public void surfaceDestroyed(SurfaceHolder holder) { if (mCamera != null){ mCamera.stopPreview(); } } /** * React to surface changed events * @param holder * @param format * @param w * @param h */ public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. if (mHolder.getSurface() == null){ // preview surface does not exist return; } // stop preview before making changes try { Camera.Parameters parameters = mCamera.getParameters(); // Set the auto-focus mode to "continuous" parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); // Preview size must exist. if(mPreviewSize != null) { Camera.Size previewSize = mPreviewSize; parameters.setPreviewSize(previewSize.width, previewSize.height); } mCamera.setParameters(parameters); mCamera.startPreview(); } catch (Exception e){ e.printStackTrace(); } } /** * Calculate the measurements of the layout * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(width, height); if (mSupportedPreviewSizes != null){ mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height); } } /** * Update the layout based on rotation and orientation changes. * @param changed * @param left * @param top * @param right * @param bottom */ @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (changed) { final int width = right - left; final int height = bottom - top; int previewWidth = width; int previewHeight = height; if (mPreviewSize != null){ Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); switch (display.getRotation()) { case Surface.ROTATION_0: previewWidth = mPreviewSize.height; previewHeight = mPreviewSize.width; mCamera.setDisplayOrientation(90); break; case Surface.ROTATION_90: previewWidth = mPreviewSize.width; previewHeight = mPreviewSize.height; break; case Surface.ROTATION_180: previewWidth = mPreviewSize.height; previewHeight = mPreviewSize.width; break; case Surface.ROTATION_270: previewWidth = mPreviewSize.width; previewHeight = mPreviewSize.height; mCamera.setDisplayOrientation(180); break; } } final int scaledChildHeight = previewHeight * width / previewWidth; mCameraView.layout(0, height - scaledChildHeight, width, height); } } /** * * @param sizes * @param width * @param height * @return */ private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int width, int height) { Camera.Size optimalSize = null; final double ASPECT_TOLERANCE = 0.1; double targetRatio = (double) height / width; // Try to find a size match which suits the whole screen minus the menu on the left. for (Camera.Size size : sizes){ if (size.height != width) continue; double ratio = (double) size.width / size.height; if (ratio <= targetRatio + ASPECT_TOLERANCE && ratio >= targetRatio - ASPECT_TOLERANCE){ optimalSize = size; } } // If we cannot find the one that matches the aspect ratio, ignore the requirement. if (optimalSize == null) { // TODO : Backup in case we don't get a size. } return optimalSize; } } /** * Picture Callback for handling a picture capture and saving it out to a file. */ private Camera.PictureCallback mPicture = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { // rotate the picture for embedded camera boolean rotateFlag = true; File pictureFile = getOutputMediaFile(); // create a parse photo file to facilitate uploading try { PhotoUtils.getInstance().createPhotoFile(); } catch (IOException e){ e.printStackTrace(); } // get the location data and upload the photo to parse TabActivity activity = (TabActivity) getActivity(); Location location = activity.getCurrentLocation(); // ParseGeoPoint geoPoint = new ParseGeoPoint(location.getLatitude(), location.getLongitude()); //PhotoUtils.getInstance().uploadPhoto(data, geoPoint, rotateFlag); Intent confirmationIntent = new Intent(getActivity(), ConfirmationActivity.class); confirmationIntent.putExtra("data", data); confirmationIntent.putExtra("location", location); confirmationIntent.putExtra("rotateFlag", rotateFlag); getActivity().startActivity(confirmationIntent); // temporary file save to local device for testing if (pictureFile == null){ Toast.makeText(getActivity(), "Image retrieval failed.", Toast.LENGTH_SHORT) .show(); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); // Restart the camera preview. safeCameraOpenInView(mCameraView); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }; /* * temporary local storage for testing/debugging * Used to return the camera File output. * @return */ private File getOutputMediaFile(){ File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "UltimateCameraGuideApp"); if (! mediaStorageDir.exists()){ if (! mediaStorageDir.mkdirs()){ Log.d("Camera Guide", "Required media storage does not exist"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg"); Toast.makeText(getActivity(), "Image saved.", Toast.LENGTH_SHORT) .show(); return mediaFile; } }
package com.samourai.wallet.util; import android.content.Context; import com.samourai.wallet.SamouraiWallet; import org.bitcoinj.core.Coin; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.utils.BtcFixedFormat; import org.bitcoinj.utils.BtcFormat; import org.bitcoinj.utils.MonetaryFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; public class FormatsUtil extends FormatsUtilGeneric { private static FormatsUtil instance = null; private static final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); private static final DecimalFormat df = new DecimalFormat("#", symbols); private FormatsUtil() { super(); } public static FormatsUtil getInstance() { if (instance == null) { instance = new FormatsUtil(); } return instance; } private NetworkParameters getNetworkParams() { return SamouraiWallet.getInstance().getCurrentNetworkParams(); } public String validateBitcoinAddress(final String address) { return super.validateBitcoinAddress(address, getNetworkParams()); } public boolean isValidBitcoinAddress(final String address) { return super.isValidBitcoinAddress(address, getNetworkParams()); } public static String formatBTC(Long sats) { return formatBTCWithoutUnit(sats).concat(" ").concat(MonetaryUtil.getInstance().getBTCUnits()); } public static String formatBTCWithoutUnit(Long sats) { return BtcFormat .builder() .locale(Locale.ENGLISH) .fractionDigits(8) .build().format(sats); } public static String formatSats(Long sats) { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setGroupingSeparator(' '); DecimalFormat _df = new DecimalFormat("#", symbols); _df.setMinimumIntegerDigits(1); _df.setMaximumIntegerDigits(16); _df.setGroupingUsed(true); _df.setGroupingSize(3); return _df.format(sats).concat(" ").concat(MonetaryUtil.getInstance().getSatoshiUnits()); } public static String getPoolBTCDecimalFormat(Long sats) { DecimalFormat format = new DecimalFormat("0. format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(3); format.setMinimumFractionDigits(1); return format.format(sats / 1e8); } public static String getBTCDecimalFormat(Long sats) { DecimalFormat format = new DecimalFormat("0. format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(8); format.setMinimumFractionDigits(8); return format.format(sats / 1e8); } public static String getBTCDecimalFormat(Long sats, int fractions) { DecimalFormat format = new DecimalFormat("0. format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(fractions); format.setMinimumFractionDigits(fractions); return format.format(sats / 1e8); } }
package com.team3009.foodie; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.braintreepayments.api.dropin.DropInResult; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.squareup.picasso.Picasso; import com.braintreepayments.api.dropin.DropInRequest; import com.braintreepayments.api.dropin.DropInResult; import static android.app.Activity.RESULT_OK; public class PostListFragment extends Fragment { private static final int DROP_IN_REQUEST_CODE = 567; private static final String SANDBOX_TOKENIZATION_KEY = "sandbox_tmxhyf7d_dcpspy2brwdjr3qn"; // [START define_database_reference] private DatabaseReference mDatabase; // [END define_database_reference] private FirebaseRecyclerAdapter<Serve, PostViewHolder> mAdapter; private RecyclerView mRecycler; private LinearLayoutManager mManager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false); // [START create_database_reference] mDatabase = FirebaseDatabase.getInstance().getReference("Serving"); // [END create_database_reference] mRecycler = (RecyclerView) rootView.findViewById(R.id.messages_list); mRecycler.setHasFixedSize(true); mManager = new LinearLayoutManager(getActivity()); mManager.setReverseLayout(true); mManager.setStackFromEnd(true); mRecycler.setLayoutManager(mManager); // Set up FirebaseRecyclerAdapter with the Query Query postsQuery = mDatabase; mAdapter = new FirebaseRecyclerAdapter<Serve, PostViewHolder>(Serve.class, R.layout.item_post, PostViewHolder.class, postsQuery) { @Override protected void populateViewHolder(final PostViewHolder viewHolder, final Serve model, final int position) { viewHolder.title.setText(model.title); viewHolder.body.setText(model.description); viewHolder.price.setText(model.price.toString()); Picasso.with(getActivity()) .load(model.downloadUrl) .error(R.drawable.common_google_signin_btn_text_light_disabled) .into(viewHolder.imageView); final DatabaseReference postRef = getRef(position); final String postKey = postRef.getKey(); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(getDropInRequest().getIntent(getActivity()), DROP_IN_REQUEST_CODE); } }); } }; mRecycler.setAdapter(mAdapter); return rootView; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == DROP_IN_REQUEST_CODE) { DropInResult result = data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT); // Send the result to Firebase //Post p = new Post(); //p.sendData(result); // Show a message that the transaction was successful Toast.makeText(getActivity(), R.string.payment_succesful, Toast.LENGTH_LONG).show(); } } } private DropInRequest getDropInRequest() { return new DropInRequest() // Use the Braintree sandbox for dev/demo purposes .clientToken(SANDBOX_TOKENIZATION_KEY) .requestThreeDSecureVerification(true) .collectDeviceData(true); } }
package de.dhge.ar.arnavigator.ui; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import de.dhge.ar.arnavigator.navigation.Node; import de.dhge.ar.arnavigator.util.Arrow; public class GLRenderer implements GLSurfaceView.Renderer, SensorEventListener { private Arrow arrow; // mMVPMatrix is an abbreviation for "Model View Projection Matrix" private final float[] mMVPMatrix = new float[16]; private final float[] mProjectionMatrix = new float[16]; private final float[] mViewMatrix = new float[16]; private float[] rotationMatrix = new float[16]; private float[] gravity; private float[] geomagnetic; float[] position; private long prevTimestamp = -1; private SensorManager mSensorManager; public void onSurfaceCreated(GL10 unused, EGLConfig config) { // Set the background frame color GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); arrow = new Arrow(null, null); rotationMatrix = new float[16]; Matrix.setIdentityM(rotationMatrix, 0); // initialise geomagnetic (values may not be null) geomagnetic = new float[3]; geomagnetic[0] = 15; geomagnetic[1] = -44; geomagnetic[2] = -33; position = new float[3]; mSensorManager = (SensorManager) NavigationActivity.getSystemServiceHelper(Activity.SENSOR_SERVICE); Sensor acc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorManager.registerListener(this, acc, SensorManager.SENSOR_DELAY_GAME); Sensor mag = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mSensorManager.registerListener(this, mag, SensorManager.SENSOR_DELAY_GAME); Sensor linAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION); mSensorManager.registerListener(this, linAcc, SensorManager.SENSOR_DELAY_GAME); } public void onDrawFrame(GL10 unused) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // set camera view Matrix.setIdentityM(mViewMatrix, 0); Matrix.translateM(mViewMatrix, 0, position[0], position[1], position[2] - 2); Matrix.multiplyMM(mViewMatrix, 0, rotationMatrix, 0, mViewMatrix, 0); float[] target = new float[]{0, -1, 0, 1}; float[] input = target.clone(); Matrix.multiplyMV(target, 0, mViewMatrix, 0, input, 0); // calculate target direction float mag = (float) Math.sqrt(target[0] * target[0] + target[1] * target[1] + target[2] * target[2]); if (mag != 0) { target[0] /= mag; target[1] /= mag; target[2] /= mag; } else { target[0] = 0; target[1] = 0; target[2] = 0; } // set arrow position float[] modelMatrix = new float[16]; Matrix.setIdentityM(modelMatrix, 0); if (NavigationActivity.getCurrentNode() != null) { Node mCurrentNode = NavigationActivity.getCurrentNode(); Matrix.setLookAtM(modelMatrix, 0, position[0] + target[0] * 2, position[1] + target[1] * 2, position[2] + target[2] * 2, mCurrentNode.x, position[1] + target[1] * 2, mCurrentNode.y, 0, 0, 1); } Matrix.translateM(modelMatrix, 0, position[0] + target[0] * 2, position[1] + target[1] * 2, position[2] + target[2] * 2); // rotate arrow relative to camera Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, modelMatrix, 0); Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0); arrow.draw(mMVPMatrix); } public void onSurfaceChanged(GL10 unused, int width, int height) { GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 1f, 20f); } public static int loadShader(int type, String shaderCode) { // create a vertex shader type (GLES20.GL_VERTEX_SHADER) // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER) int shader = GLES20.glCreateShader(type); // add the source code to the shader and compile it GLES20.glShaderSource(shader, shaderCode); GLES20.glCompileShader(shader); return shader; } public static int createShader(int vertexShader, int fragmentShader) { int program = GLES20.glCreateProgram(); // add the vertex shader to program GLES20.glAttachShader(program, vertexShader); // add the fragment shader to program GLES20.glAttachShader(program, fragmentShader); // creates OpenGL ES program executables GLES20.glLinkProgram(program); return program; } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { if (prevTimestamp == -1 || (event.timestamp - prevTimestamp > 2000000684)) { //first run [in a while], ignore sensor and just update timestamp prevTimestamp = event.timestamp; } else { float deltaT = (event.timestamp - prevTimestamp) / (float) 1e9; prevTimestamp = event.timestamp; float[] a = event.values; float[] velocity = new float[3]; velocity[0] = velocity[0] + deltaT * (rotationMatrix[0] * a[0] + rotationMatrix[1] * a[1] + rotationMatrix[2] * a[2]); velocity[1] = velocity[1] + deltaT * (rotationMatrix[4] * a[0] + rotationMatrix[5] * a[1] + rotationMatrix[6] * a[2]); velocity[2] = velocity[2] + deltaT * (rotationMatrix[8] * a[0] + rotationMatrix[9] * a[1] + rotationMatrix[10] * a[2]); if (velocity[0] < 0.125f && velocity[1] < 0.125f && velocity[2] < 0.125f) return; for (int i = 0; i < 3; i++) { position[i] = position[i] + velocity[i];// * deltaT; } } } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { float accelX = event.values[0]; float accelY = event.values[1]; float accelZ = event.values[2]; final float alpha = (float) 0.8; gravity = new float[3]; // Isolate the force of gravity with the low-pass filter. gravity[0] = alpha * gravity[0] + (1 - alpha) * accelX; gravity[1] = alpha * gravity[1] + (1 - alpha) * accelY; gravity[2] = alpha * gravity[2] + (1 - alpha) * accelZ; mSensorManager.getRotationMatrix(rotationMatrix, null, gravity, geomagnetic); } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { geomagnetic = event.values.clone(); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
package com.artemis.io; import com.artemis.*; import com.artemis.annotations.EntityId; import com.artemis.utils.Bag; import com.artemis.utils.ConverterUtil; import com.artemis.utils.IntBag; import com.artemis.utils.reflect.ClassReflection; import com.artemis.utils.reflect.Field; import com.artemis.utils.reflect.ReflectionException; import java.util.BitSet; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Maintains state of all component types which can reference other components. */ class ReferenceTracker { Bag<EntityReference> referenced = new Bag<EntityReference>(); private Set<Class<?>> referencingTypes = new HashSet<Class<?>>(); private Set<Field> referencingFields = new HashSet<Field>(); private BitSet entityIds = new BitSet(); private World world; ReferenceTracker(World world) { this.world = world; } void inspectTypes(World world) { clear(); ComponentManager cm = world.getComponentManager(); for (ComponentType ct : cm.getComponentTypes()) { inspectType(ct.getType()); } } void inspectTypes(Collection<Class<? extends Component>> types) { clear(); for (Class<?> component : types) { inspectType(component); } } private void clear() { referencingFields.clear(); referencingTypes.clear(); referenced.clear(); } private void inspectType(Class<?> type) { Field[] fields = ClassReflection.getDeclaredFields(type); for (int i = 0; fields.length > i; i++) { Field f = fields[i]; if (isReferencingEntity(f) && !referencingFields.contains(type)) { referencingFields.add(f); referencingTypes.add(type); referenced.add(new EntityReference(type, f)); } } } void addEntityReferencingComponent(Component c) { Class<? extends Component> componentClass = c.getClass(); if (!referencingTypes.contains(componentClass)) return; for (int i = 0, s = referenced.size(); s > i; i++) { EntityReference ref = referenced.get(i); if (ref.componentType == componentClass) { // a component can be referenced once per field // referencing another entity ref.operations.add(c); } } } void translate(Bag<Entity> translations) { for (EntityReference ref : referenced) { ref.translate(translations); } translations.clear(); } EntityReference find(Class<?> componentType, String fieldName) { for (int i = 0, s = referenced.size(); s > i; i++) { EntityReference ref = referenced.get(i); if (ref.componentType.equals(componentType) && ref.field.getName().equals(fieldName)) return ref; } throw new RuntimeException( componentType.getSimpleName() + "." + fieldName); } private boolean isReferencingEntity(Field f) { boolean explicitEntityId = f.getDeclaredAnnotation(EntityId.class) != null; Class type = f.getType(); return (Entity.class == type) || (Bag.class == type) // due to GWT limitations || (int.class == type && explicitEntityId) || (IntBag.class == type && explicitEntityId); } void preWrite(SaveFileFormat save) { entityIds.clear(); ConverterUtil.toBitSet(save.entities, entityIds); boolean foundNew = true; BitSet bs = entityIds; while (foundNew) { foundNew = false; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { for (Field f : referencingFields) { foundNew |= findReferences(i, f, bs); } } } ConverterUtil.toIntBag(entityIds, save.entities); } private boolean findReferences(int entityId, Field f, BitSet referencedIds) { Component c = world.getEntity(entityId).getComponent(f.getDeclaringClass()); if (c == null) return false; Class type = f.getType(); try { if (type.equals(int.class)) { return updateReferenced((Integer)f.get(c), referencedIds); } else if (type.equals(Entity.class)) { return updateReferenced((Entity)f.get(c), referencedIds); } else if (type.equals(IntBag.class)) { return updateReferenced((IntBag)f.get(c), referencedIds); } else if (type.equals(Bag.class)) { return updateReferenced((Bag<Entity>)f.get(c), referencedIds); } else { throw new RuntimeException("unknown type: " + type); } } catch (ReflectionException e) { throw new RuntimeException(e); } } private boolean updateReferenced(Bag<Entity> entities, BitSet referencedIds) { boolean updated = false; for (int i = 0; i < entities.size(); i++) updated |= updateReferenced(entities.get(i), referencedIds); return updated; } private boolean updateReferenced(IntBag ids, BitSet referencedIds) { boolean updated = false; for (int i = 0; i < ids.size(); i++) updated |= updateReferenced(ids.get(i), referencedIds); return updated; } private boolean updateReferenced(Entity e, BitSet referencedIds) { return updateReferenced(e.id, referencedIds); } private boolean updateReferenced(int entityId, BitSet referencedIds) { if (!referencedIds.get(entityId)) { referencedIds.set(entityId); return true; } else { return false; } } }
package lt.markmerkk.ui.clock; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.ResourceBundle; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.DatePicker; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.ToggleButton; import javafx.scene.control.Tooltip; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.util.StringConverter; import javax.inject.Inject; import lt.markmerkk.storage2.BasicIssueStorage; import lt.markmerkk.storage2.BasicLogStorage; import lt.markmerkk.storage2.SimpleIssue; import lt.markmerkk.storage2.SimpleLog; import lt.markmerkk.storage2.SimpleLogBuilder; import lt.markmerkk.utils.UserSettings; import lt.markmerkk.utils.Utils; import lt.markmerkk.utils.hourglass.HourGlass; import org.joda.time.DateTime; public class ClockPresenter implements Initializable { public static final String BUTTON_LABEL_ENTER = "Enter"; @Inject HourGlass hourGlass; @Inject BasicLogStorage logStorage; @Inject BasicIssueStorage issueStorage; @Inject UserSettings settings; @FXML DatePicker inputTo; @FXML DatePicker inputFrom; @FXML TextArea inputComment; @FXML ToggleButton buttonClock; @FXML Button buttonEnter; @FXML Button buttonOpen; @FXML Button buttonNew; @FXML Button buttonSettings; @FXML ComboBox<SimpleIssue> inputTaskCombo; Listener listener; @Override public void initialize(URL location, ResourceBundle resources) { inputTaskCombo.setItems(issueStorage.getData()); inputTaskCombo.setOnKeyReleased(comboKeyListener); inputFrom.setTooltip(new Tooltip("Worklog start" + "\n\nStart time for the current log. " + "It can be edited whenever timer is running. " + "\nThis timer acts as today's date, " + "changing this will change display for the whole work log.")); inputTo.setTooltip(new Tooltip("Worklog end" + "\n\nEnd time for the current log." + "It can be edited whenever timer is running. ")); inputTaskCombo.setTooltip(new Tooltip("Issue search bar " + "\n\nType in issue number, title to begin searching.")); buttonClock.setTooltip(new Tooltip("Start/Stop " + "\n\nEnable/disable work timer.")); buttonEnter.setTooltip(new Tooltip("Enter " + "\n\nEnters currently running work.")); buttonOpen.setTooltip(new Tooltip("Forward " + "\n\nOpen selected issue details.")); buttonNew.setTooltip(new Tooltip("New. " + "\n\nCreate new issue.")); buttonSettings.setTooltip(new Tooltip("Settings. " + "\n\nSetting up remote host, user credentials.")); inputComment.setTooltip(new Tooltip("Comment" + "\n\nEnter comment here for the work log.")); hourGlass.setCurrentDay(DateTime.now()); hourGlass.setListener(hourglassListener); inputFrom.getEditor().textProperty().addListener(timeChangeListener); inputTo.getEditor().textProperty().addListener(timeChangeListener); inputFrom.setConverter(startDateConverter); inputTo.setConverter(endDateConverter); updateUI(); } //region Keyboard input public void onClickClock() { if (hourGlass.getState() == HourGlass.State.STOPPED) hourGlass.start(); else hourGlass.stop(); buttonClock.setSelected(hourGlass.getState() == HourGlass.State.RUNNING); updateUI(); } public void onClickEnter() { logWork(); } public void onClickNew() { try { URI newPath = new URI(settings.getHost()+"/secure/CreateIssue!default.jspa"); listener.onOpen(newPath.toString(), "New task"); } catch (URISyntaxException e) { } } public void onClickForward() { if (inputTaskCombo.getSelectionModel() == null) return; if (inputTaskCombo.getSelectionModel().getSelectedIndex() < 0) return; SimpleIssue selectedIssue = issueStorage.getData().get(inputTaskCombo.getSelectionModel().getSelectedIndex()); if (selectedIssue == null) return; URI issuePath = null; try { issuePath = new URI(settings.getHost()+"/browse/"+selectedIssue.getKey()); listener.onOpen(issuePath.toString(), selectedIssue.getKey()); } catch (URISyntaxException e) { } } public void onClickSettings() { listener.onSettings(); } //endregion //region Convenience /** * Updates UI depending on {@link HourGlass} state */ private void updateUI() { boolean disableElement = (hourGlass.getState() == HourGlass.State.STOPPED); inputFrom.setEditable(!disableElement); inputFrom.setDisable(disableElement); inputTo.setEditable(!disableElement); inputTo.setDisable(disableElement); inputComment.setEditable(!disableElement); inputComment.setPromptText( (disableElement) ? "Start timer to log work!" : "Go go go!"); buttonEnter.setDisable(disableElement); } /** * Gathers data and logs work to a database */ private void logWork() { try { if (hourGlass.getState() == HourGlass.State.STOPPED) throw new IllegalArgumentException("Please run timer first!"); if (!hourGlass.isValid()) throw new IllegalArgumentException("Error calculating time!"); SimpleLog log = new SimpleLogBuilder(DateTime.now().getMillis()) .setStart(HourGlass.parseMillisFromText(inputFrom.getEditor().getText())) .setEnd(HourGlass.parseMillisFromText(inputTo.getEditor().getText())) .setTask(inputTaskCombo.getEditor().getText()) .setComment(inputComment.getText()).build(); logStorage.insert(log); // Resetting controls inputComment.setText(""); hourGlass.restart(); inputTo.requestFocus(); inputFrom.requestFocus(); inputComment.requestFocus(); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } //endregion //region Listeners StringConverter startDateConverter = new StringConverter<LocalDate>() { @Override public String toString(LocalDate date) { if (date == null) return HourGlass.longFormat.print(DateTime.now()); DateTime updateTime = new DateTime(hourGlass.getStartMillis()).withDate( date.getYear(), date.getMonthValue(), date.getDayOfMonth() ); return HourGlass.longFormat.print(updateTime); } @Override public LocalDate fromString(String string) { try { DateTime dateTime = HourGlass.longFormat.parseDateTime(string); return LocalDate.of(dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth()); } catch (IllegalArgumentException e) { DateTime oldTime = DateTime.now(); return LocalDate.of(oldTime.getYear(), oldTime.getMonthOfYear(), oldTime.getDayOfMonth()); } } }; StringConverter endDateConverter = new StringConverter<LocalDate>() { @Override public String toString(LocalDate date) { if (date == null) return HourGlass.longFormat.print(DateTime.now()); DateTime updateTime = new DateTime(hourGlass.getEndMillis()).withDate( date.getYear(), date.getMonthValue(), date.getDayOfMonth() ); return HourGlass.longFormat.print(updateTime); } @Override public LocalDate fromString(String string) { try { DateTime dateTime = HourGlass.longFormat.parseDateTime(string); return LocalDate.of(dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth()); } catch (IllegalArgumentException e) { DateTime oldTime = DateTime.now(); return LocalDate.of(oldTime.getYear(), oldTime.getMonthOfYear(), oldTime.getDayOfMonth()); } } }; EventHandler<KeyEvent> comboKeyListener = new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getCode() == KeyCode.ESCAPE || event.getCode() == KeyCode.ENTER) { inputTaskCombo.hide(); return; } if ( event.getCode() == KeyCode.UP || event.getCode() == KeyCode.DOWN) { inputTaskCombo.show(); return; } if (event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT || event.getCode() == KeyCode.HOME || event.getCode() == KeyCode.END || event.getCode() == KeyCode.TAB) return; if (event.getCode() == KeyCode.BACK_SPACE || event.getCode() == KeyCode.DELETE) { issueStorage.updateFilter(inputTaskCombo.getEditor().getText()); inputTaskCombo.show(); return; } if (Utils.isEmpty(event.getText())) return; issueStorage.updateFilter(inputTaskCombo.getEditor().getText()); inputTaskCombo.show(); } }; ChangeListener<String> timeChangeListener = new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { hourGlass.updateTimers(inputFrom.getEditor().getText(), inputTo.getEditor().getText()); logStorage.setTargetDate(inputFrom.getEditor().getText()); } }; private HourGlass.Listener hourglassListener = new HourGlass.Listener() { @Override public void onStart(long start, long end, long duration) { inputFrom.getEditor().setText(HourGlass.longFormat.print(start)); inputTo.getEditor().setText(HourGlass.longFormat.print(end)); buttonEnter.setText(String.format("%s (%s)", BUTTON_LABEL_ENTER, Utils.formatShortDuration( duration))); } @Override public void onStop(long start, long end, long duration) { inputFrom.getEditor().setText(""); inputTo.getEditor().setText(""); buttonEnter.setText(String.format("%s (%s)", BUTTON_LABEL_ENTER, Utils.formatShortDuration(duration))); } @Override public void onTick(final long start, final long end, final long duration) { clearError(inputFrom.getEditor()); clearError(inputTo.getEditor()); String newFrom = HourGlass.longFormat.print(start); if (!newFrom.equals(inputFrom.getEditor().getText()) && !inputFrom.isFocused()) { inputFrom.getEditor().setText(newFrom); } String newTo = HourGlass.longFormat.print(end); if (!newTo.equals(inputTo.getEditor().getText()) && !inputTo.isFocused()) { inputTo.getEditor().setText(newTo); } buttonEnter.setText(String.format("%s (%s)", BUTTON_LABEL_ENTER, Utils.formatShortDuration(duration))); } @Override public void onError(HourGlass.Error error) { switch (error) { case START: case END: reportError(inputFrom.getEditor()); reportError(inputTo.getEditor()); break; case DURATION: reportError(inputFrom.getEditor()); reportError(inputTo.getEditor()); break; } buttonEnter.setText(String.format("%s (%s)", BUTTON_LABEL_ENTER, error.getMessage())); } }; //endregion //region Convenience /** * Adds an indicator as an error for the text field * @param tf provided text field */ private void reportError(TextField tf) { ObservableList<String> styleClass = tf.getStyleClass(); if (!styleClass.contains("error")) styleClass.add("error"); } /** * Removes error indicator for the text field * @param tf provided text field */ private void clearError(TextField tf) { ObservableList<String> styleClass = tf.getStyleClass(); styleClass.removeAll(Collections.singleton("error")); } //endregion /** * Helper listener for the clock window */ public interface Listener { /** * Occurs settings window is requested */ void onSettings(); /** * Occurs when url should be opened */ void onOpen(String url, String title); } }
package me.jaxbot.wear.leafstatus; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class MyActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final SharedPreferences settings = getSharedPreferences("U", 0); if (settings.getString("username", "").equals("")) { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); } setContentView(R.layout.activity_my); final Context context = this; final Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { SharedPreferences.Editor editor = settings.edit(); int interval = ((SeekBar) findViewById(R.id.seekBar)).getProgress(); boolean checked = ((CheckBox) findViewById(R.id.checkBox)).isChecked(); editor.putInt("interval", interval); editor.putBoolean("autoupdate", checked); editor.commit(); if (checked) AlarmSetter.setAlarm(context); else { AlarmSetter.cancelAlarm(context); } updateCarStatusAsync(); button.setEnabled(false); showToast("Saved, updating vehicle status..."); } }); int interval = settings.getInt("interval", 30); final SeekBar seekbar = (SeekBar)findViewById(R.id.seekBar); seekbar.setProgress(interval); setProgressText(interval); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { setProgressText(i); findViewById(R.id.button).setEnabled(true); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); CheckBox checkbox = ((CheckBox)(findViewById(R.id.checkBox))); checkbox.setChecked(settings.getBoolean("autoupdate", true)); checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { findViewById(R.id.button).setEnabled(true); seekbar.setEnabled(b); } }); Carwings carwings = new Carwings(this); if (carwings.lastUpdateTime.equals("")) { updateCarStatusAsync(); } else { updateCarStatusUI(carwings); LeafNotification.sendNotification(context, carwings); } } void updateCarStatusAsync() { (findViewById(R.id.progressBar)).setVisibility(View.VISIBLE); final Context context = this; final Activity activity = this; new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { final Carwings carwings = new Carwings(context); carwings.update(); LeafNotification.sendNotification(context, carwings); activity.runOnUiThread(new Runnable() { public void run() { updateCarStatusUI(carwings); } }); return null; } }.execute(null, null, null); } void updateCarStatusUI(Carwings carwings) { (findViewById(R.id.progressBar)).setVisibility(View.GONE); ((TextView) findViewById(R.id.battery_bars)).setText(carwings.currentBattery + " / 12 bars"); ((TextView) findViewById(R.id.chargetime)).setText(carwings.chargeTime); ((TextView) findViewById(R.id.range)).setText(carwings.range); ((TextView) findViewById(R.id.lastupdated)).setText(carwings.lastUpdateTime); } private void setProgressText(int interval) { ((TextView) findViewById(R.id.txtMinutes)).setText("Update every " + (interval + 15) + " minutes"); } void showToast(String text) { int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(this, text, duration); toast.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.my, 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_signoff) { SharedPreferences settings = getSharedPreferences("U", 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("username", ""); editor.putString("password", ""); editor.commit(); Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); } return super.onOptionsItemSelected(item); } }
package net.ossrs.sea.rtmp.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.concurrent.atomic.AtomicInteger; import android.util.Log; import net.ossrs.sea.rtmp.RtmpPublisher; import net.ossrs.sea.rtmp.amf.AmfNull; import net.ossrs.sea.rtmp.amf.AmfNumber; import net.ossrs.sea.rtmp.amf.AmfObject; import net.ossrs.sea.rtmp.amf.AmfString; import net.ossrs.sea.rtmp.packets.Abort; import net.ossrs.sea.rtmp.packets.Acknowledgement; import net.ossrs.sea.rtmp.packets.Data; import net.ossrs.sea.rtmp.packets.Handshake; import net.ossrs.sea.rtmp.packets.Command; import net.ossrs.sea.rtmp.packets.Audio; import net.ossrs.sea.rtmp.packets.Video; import net.ossrs.sea.rtmp.packets.UserControl; import net.ossrs.sea.rtmp.packets.RtmpPacket; import net.ossrs.sea.rtmp.packets.WindowAckSize; /** * Main RTMP connection implementation class * * @author francois, leoma */ public class RtmpConnection implements RtmpPublisher, PacketRxHandler { private static final String TAG = "RtmpConnection"; private static final Pattern rtmpUrlPattern = Pattern.compile("^rtmp: private RtmpPublisher.EventHandler mHandler; private String appName; private String streamName; private String publishType; private String swfUrl; private String tcUrl; private String pageUrl; private Socket socket; private RtmpSessionInfo rtmpSessionInfo; private ReadThread readThread; private WriteThread writeThread; private final ConcurrentLinkedQueue<RtmpPacket> rxPacketQueue = new ConcurrentLinkedQueue<>(); private final Object rxPacketLock = new Object(); private volatile boolean active = false; private volatile boolean connecting = false; private volatile boolean fullyConnected = false; private volatile boolean publishPermitted = false; private final Object connectingLock = new Object(); private final Object publishLock = new Object(); private AtomicInteger videoFrameCacheNumber = new AtomicInteger(0); private int currentStreamId = -1; private int transactionIdCounter = 0; private AmfString serverIp; private AmfNumber serverPid; private AmfNumber serverId; public RtmpConnection(RtmpPublisher.EventHandler handler) { mHandler = handler; } private void handshake(InputStream in, OutputStream out) throws IOException { Handshake handshake = new Handshake(); handshake.writeC0(out); handshake.writeC1(out); // Write C1 without waiting for S0 out.flush(); handshake.readS0(in); handshake.readS1(in); handshake.writeC2(out); handshake.readS2(in); } @Override public void connect(String url) throws IOException { int port; String host; Matcher matcher = rtmpUrlPattern.matcher(url); if (matcher.matches()) { tcUrl = url.substring(0, url.lastIndexOf('/')); swfUrl = ""; pageUrl = ""; host = matcher.group(1); String portStr = matcher.group(3); port = portStr != null ? Integer.parseInt(portStr) : 1935; appName = matcher.group(4); streamName = matcher.group(6); } else { throw new IllegalArgumentException("Invalid RTMP URL. Must be in format: rtmp://host[:port]/application[/streamName]"); } // socket connection Log.d(TAG, "connect() called. Host: " + host + ", port: " + port + ", appName: " + appName + ", publishPath: " + streamName); socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(host, port); socket.connect(socketAddress, 3000); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream()); Log.d(TAG, "connect(): socket connection established, doing handhake..."); handshake(in, out); active = true; Log.d(TAG, "connect(): handshake done"); rtmpSessionInfo = new RtmpSessionInfo(); readThread = new ReadThread(rtmpSessionInfo, in, this); writeThread = new WriteThread(rtmpSessionInfo, out, videoFrameCacheNumber); readThread.start(); writeThread.start(); // Start the "main" handling thread new Thread(new Runnable() { @Override public void run() { try { Log.d(TAG, "starting main rx handler loop"); handleRxPacketLoop(); } catch (IOException ex) { Logger.getLogger(RtmpConnection.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); rtmpConnect(); } private void rtmpConnect() throws IOException, IllegalStateException { if (fullyConnected || connecting) { throw new IllegalStateException("Already connected or connecting to RTMP server"); } // Mark session timestamp of all chunk stream information on connection. ChunkStreamInfo.markSessionTimestampTx(); Log.d(TAG, "rtmpConnect(): Building 'connect' invoke packet"); ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_COMMAND_CHANNEL); Command invoke = new Command("connect", ++transactionIdCounter, chunkStreamInfo); invoke.getHeader().setMessageStreamId(0); AmfObject args = new AmfObject(); args.setProperty("app", appName); args.setProperty("flashVer", "LNX 11,2,202,233"); args.setProperty("swfUrl", swfUrl); args.setProperty("tcUrl", tcUrl); args.setProperty("fpad", false); args.setProperty("capabilities", 239); args.setProperty("audioCodecs", 3575); args.setProperty("videoCodecs", 252); args.setProperty("videoFunction", 1); args.setProperty("pageUrl", pageUrl); args.setProperty("objectEncoding", 0); invoke.addData(args); writeThread.send(invoke); connecting = true; mHandler.onRtmpConnecting("connecting"); } @Override public void publish(String type) throws IllegalStateException, IOException { if (connecting) { synchronized (connectingLock) { try { connectingLock.wait(5000); } catch (InterruptedException ex) { // do nothing } } } publishType = type; createStream(); } private void createStream() { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId != -1) { throw new IllegalStateException("Current stream object has existed"); } Log.d(TAG, "createStream(): Sending releaseStream command..."); // transactionId == 2 Command releaseStream = new Command("releaseStream", ++transactionIdCounter); releaseStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_STREAM_CHANNEL); releaseStream.addData(new AmfNull()); // command object: null for "createStream" releaseStream.addData(streamName); // command object: null for "releaseStream" writeThread.send(releaseStream); Log.d(TAG, "createStream(): Sending FCPublish command..."); // transactionId == 3 Command FCPublish = new Command("FCPublish", ++transactionIdCounter); FCPublish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_STREAM_CHANNEL); FCPublish.addData(new AmfNull()); // command object: null for "FCPublish" FCPublish.addData(streamName); writeThread.send(FCPublish); Log.d(TAG, "createStream(): Sending createStream command..."); ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_COMMAND_CHANNEL); // transactionId == 4 Command createStream = new Command("createStream", ++transactionIdCounter, chunkStreamInfo); createStream.addData(new AmfNull()); // command object: null for "createStream" writeThread.send(createStream); // Waiting for "NetStream.Publish.Start" response. synchronized (publishLock) { try { publishLock.wait(5000); } catch (InterruptedException ex) { // do nothing } } } private void fmlePublish() throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } Log.d(TAG, "fmlePublish(): Sending publish command..."); // transactionId == 0 Command publish = new Command("publish", 0); publish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_STREAM_CHANNEL); publish.getHeader().setMessageStreamId(currentStreamId); publish.addData(new AmfNull()); // command object: null for "publish" publish.addData(streamName); publish.addData(publishType); writeThread.send(publish); } private void onMetaData() throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } Log.d(TAG, "onMetaData(): Sending empty onMetaData..."); Data emptyMetaData = new Data("@setDataFrame"); emptyMetaData.addData("onMetaData"); emptyMetaData.addData(new AmfNull()); emptyMetaData.getHeader().setMessageStreamId(currentStreamId); writeThread.send(emptyMetaData); } @Override public void closeStream() throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } if (!publishPermitted) { throw new IllegalStateException("Not get the _result(Netstream.Publish.Start)"); } Log.d(TAG, "closeStream(): setting current stream ID to -1"); Command closeStream = new Command("closeStream", 0); closeStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_STREAM_CHANNEL); closeStream.getHeader().setMessageStreamId(currentStreamId); closeStream.addData(new AmfNull()); writeThread.send(closeStream); mHandler.onRtmpStopped("stopped"); } @Override public void shutdown() { if (active) { // shutdown read thread try { // It will invoke EOFException in read thread socket.shutdownInput(); } catch (IOException ioe) { ioe.printStackTrace(); } readThread.shutdown(); try { readThread.join(); } catch (InterruptedException ie) { ie.printStackTrace(); readThread.interrupt(); } // shutdown write thread writeThread.shutdown(); try { writeThread.join(); } catch (InterruptedException ie) { ie.printStackTrace(); writeThread.interrupt(); } // shutdown handleRxPacketLoop rxPacketQueue.clear(); active = false; synchronized (rxPacketLock) { rxPacketLock.notify(); } // shutdown socket as well as its input and output stream if (socket != null) { try { socket.close(); Log.d(TAG, "socket closed"); } catch (IOException ex) { Log.e(TAG, "shutdown(): failed to close socket", ex); } } mHandler.onRtmpDisconnected("disconnected"); } reset(); } private void reset() { active = false; connecting = false; fullyConnected = false; publishPermitted = false; tcUrl = null; swfUrl = null; pageUrl = null; appName = null; streamName = null; publishType = null; currentStreamId = -1; transactionIdCounter = 0; videoFrameCacheNumber.set(0); serverIp = null; serverPid = null; serverId = null; rtmpSessionInfo = null; } @Override public void notifyWindowAckRequired(final int numBytesReadThusFar) { Log.i(TAG, "notifyWindowAckRequired() called"); // Create and send window bytes read acknowledgement writeThread.send(new Acknowledgement(numBytesReadThusFar)); } @Override public void publishAudioData(byte[] data) throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } if (!publishPermitted) { throw new IllegalStateException("Not get the _result(Netstream.Publish.Start)"); } Audio audio = new Audio(); audio.setData(data); audio.getHeader().setMessageStreamId(currentStreamId); writeThread.send(audio); mHandler.onRtmpAudioStreaming("audio streaming"); } @Override public void publishVideoData(byte[] data) throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } if (!publishPermitted) { throw new IllegalStateException("Not get the _result(Netstream.Publish.Start)"); } Video video = new Video(); video.setData(data); video.getHeader().setMessageStreamId(currentStreamId); writeThread.send(video); videoFrameCacheNumber.getAndIncrement(); mHandler.onRtmpVideoStreaming("video streaming"); } public final int getVideoFrameCacheNumber() { return videoFrameCacheNumber.get(); } @Override public void handleRxPacket(RtmpPacket rtmpPacket) { if (rtmpPacket != null) { rxPacketQueue.add(rtmpPacket); } synchronized (rxPacketLock) { rxPacketLock.notify(); } } private void handleRxPacketLoop() throws IOException { // Handle all queued received RTMP packets while (active) { while (!rxPacketQueue.isEmpty()) { RtmpPacket rtmpPacket = rxPacketQueue.poll(); //Log.d(TAG, "handleRxPacketLoop(): RTMP rx packet message type: " + rtmpPacket.getHeader().getMessageType()); switch (rtmpPacket.getHeader().getMessageType()) { case ABORT: rtmpSessionInfo.getChunkStreamInfo(((Abort) rtmpPacket).getChunkStreamId()).clearStoredChunks(); break; case USER_CONTROL_MESSAGE: { UserControl ping = (UserControl) rtmpPacket; switch (ping.getType()) { case PING_REQUEST: { ChunkStreamInfo channelInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CONTROL_CHANNEL); Log.d(TAG, "handleRxPacketLoop(): Sending PONG reply.."); UserControl pong = new UserControl(ping, channelInfo); writeThread.send(pong); break; } case STREAM_EOF: Log.i(TAG, "handleRxPacketLoop(): Stream EOF reached, closing RTMP writer..."); break; } break; } case WINDOW_ACKNOWLEDGEMENT_SIZE: WindowAckSize windowAckSize = (WindowAckSize) rtmpPacket; int size = windowAckSize.getAcknowledgementWindowSize(); Log.d(TAG, "handleRxPacketLoop(): Setting acknowledgement window size: " + size); rtmpSessionInfo.setAcknowledgmentWindowSize(size); // Set socket option socket.setSendBufferSize(size); break; case SET_PEER_BANDWIDTH: int acknowledgementWindowsize = rtmpSessionInfo.getAcknowledgementWindowSize(); final ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CONTROL_CHANNEL); Log.d(TAG, "handleRxPacketLoop(): Send acknowledgement window size: " + acknowledgementWindowsize); writeThread.send(new WindowAckSize(acknowledgementWindowsize, chunkStreamInfo)); break; case COMMAND_AMF0: handleRxInvoke((Command) rtmpPacket); break; default: Log.w(TAG, "handleRxPacketLoop(): Not handling unimplemented/unknown packet of type: " + rtmpPacket.getHeader().getMessageType()); break; } } // Wait for next received packet synchronized (rxPacketLock) { try { rxPacketLock.wait(500); } catch (InterruptedException ex) { Log.w(TAG, "handleRxPacketLoop: Interrupted", ex); } } } } private void handleRxInvoke(Command invoke) throws IOException { String commandName = invoke.getCommandName(); if (commandName.equals("_result")) { // This is the result of one of the methods invoked by us String method = rtmpSessionInfo.takeInvokedCommand(invoke.getTransactionId()); Log.d(TAG, "handleRxInvoke: Got result for invoked method: " + method); if ("connect".equals(method)) { // Capture server ip/pid/id information if any String serverInfo = onSrsServerInfo(invoke); mHandler.onRtmpConnected("connected" + serverInfo); // We can now send createStream commands connecting = false; fullyConnected = true; synchronized (connectingLock) { connectingLock.notifyAll(); } } else if ("createStream".contains(method)) { // Get stream id currentStreamId = (int) ((AmfNumber) invoke.getData().get(1)).getValue(); Log.d(TAG, "handleRxInvoke(): Stream ID to publish: " + currentStreamId); if (streamName != null && publishType != null) { fmlePublish(); } } else if ("releaseStream".contains(method)) { Log.d(TAG, "handleRxInvoke(): 'releaseStream'"); } else if ("FCPublish".contains(method)) { Log.d(TAG, "handleRxInvoke(): 'FCPublish'"); } else { Log.w(TAG, "handleRxInvoke(): '_result' message received for unknown method: " + method); } } else if (commandName.equals("onBWDone")) { Log.d(TAG, "handleRxInvoke(): 'onBWDone'"); } else if (commandName.equals("onFCPublish")) { Log.d(TAG, "handleRxInvoke(): 'onFCPublish'"); } else if (commandName.equals("onStatus")) { String code = ((AmfString) ((AmfObject) invoke.getData().get(1)).getProperty("code")).getValue(); if (code.equals("NetStream.Publish.Start")) { // We can now publish AV data publishPermitted = true; synchronized (publishLock) { publishLock.notifyAll(); } } } else { Log.e(TAG, "handleRxInvoke(): Uknown/unhandled server invoke: " + invoke); } } private String onSrsServerInfo(Command invoke) { // SRS server special information AmfObject data = ((AmfObject) ((AmfObject) invoke.getData().get(1)).getProperty("data")); serverIp = (AmfString) data.getProperty("srs_server_ip"); serverPid = (AmfNumber) data.getProperty("srs_pid"); serverId = (AmfNumber) data.getProperty("srs_id"); String info = ""; info += serverIp == null ? "" : " ip: " + serverIp.getValue(); info += serverPid == null ? "" : " pid: " + serverPid.getValue(); info += serverPid == null ? "" : " id: " + serverId.getValue(); return info; } }
package org.stepic.droid.util; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.SwipeRefreshLayout; import android.view.View; import android.widget.ProgressBar; import org.stepic.droid.ui.dialogs.LoadingProgressDialog; public class ProgressHelper { public static void dismiss(ProgressBar mProgressLogin) { if (mProgressLogin != null && mProgressLogin.getVisibility() != View.GONE) { mProgressLogin.setVisibility(View.GONE); } } public static void activate(ProgressBar progressBar) { if (progressBar != null) progressBar.setVisibility(View.VISIBLE); } public static void dismiss(SwipeRefreshLayout swipeRefreshLayout) { if (swipeRefreshLayout != null) swipeRefreshLayout.setRefreshing(false); } public static void activate(SwipeRefreshLayout swipeRefreshLayout) { if (swipeRefreshLayout != null) swipeRefreshLayout.setRefreshing(true); } public static void activate(LoadingProgressDialog progressDialog) { if (progressDialog != null && !progressDialog.isShowing()) { progressDialog.show(); } } public static void dismiss(LoadingProgressDialog progressDialog) { if (progressDialog != null && progressDialog.isShowing()) { try { progressDialog.dismiss(); } catch (Exception ignored) { } } } public static void activate(DialogFragment progressDialog, FragmentManager fragmentManager, String tag) { if (progressDialog != null && !progressDialog.isAdded() && fragmentManager.findFragmentByTag(tag) == null) { progressDialog.show(fragmentManager, tag); } } public static void dismiss(FragmentManager fragmentManager, String tag) { if (fragmentManager != null) { try { DialogFragment fragment = (DialogFragment) fragmentManager.findFragmentByTag(tag); fragment.dismiss(); } catch (Exception ignored) { } } } }
package org.wikipedia.page; import androidx.annotation.NonNull; import org.wikipedia.history.HistoryEntry; import org.wikipedia.model.BaseModel; public class PageBackStackItem extends BaseModel { @NonNull private PageTitle title; @NonNull private HistoryEntry historyEntry; private int scrollY; public PageBackStackItem(@NonNull PageTitle title, @NonNull HistoryEntry historyEntry) { // TODO: remove this crash probe upon fixing if (title == null || historyEntry == null) { throw new IllegalArgumentException("Nonnull parameter is in fact null."); } this.title = title; this.historyEntry = historyEntry; } @NonNull public PageTitle getTitle() { return title; } public void setTitle(@NonNull PageTitle title) { this.title = title; } @NonNull public HistoryEntry getHistoryEntry() { return historyEntry; } public int getScrollY() { return scrollY; } public void setScrollY(int scrollY) { this.scrollY = scrollY; } }
package com.dihanov.musiq; import android.content.Context; import android.view.ViewGroup; import com.dihanov.musiq.models.User; import com.dihanov.musiq.service.LastFmApiClient; import com.dihanov.musiq.service.LastFmApiService; import com.dihanov.musiq.ui.login.LoginContract; import com.dihanov.musiq.ui.login.LoginPresenter; import com.dihanov.musiq.util.Connectivity; import com.dihanov.musiq.util.HelperMethods; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.reactivex.Observable; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class) @PrepareForTest({ Connectivity.class, HelperMethods.class }) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) public class LoginPresenterTest extends RxJavaTestRule{ @Mock LoginContract.View view; LoginPresenter presenter; @Mock LastFmApiClient lastFmApiClient; @Mock LastFmApiService lastFmApiService; @Rule public PowerMockRule rule = new PowerMockRule(); @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); PowerMockito.mockStatic(Connectivity.class); PowerMockito.mockStatic(HelperMethods.class); presenter = Mockito.spy(new LoginPresenter(lastFmApiClient)); presenter.takeView(view); } @Test public void authenticateUserTest() throws Exception { User user = new User(); when(lastFmApiClient.getLastFmApiService()).thenReturn(lastFmApiService); when(Connectivity.isConnected(any(Context.class))).thenReturn(true); PowerMockito.doNothing().when(HelperMethods.class, "setLayoutChildrenEnabled", anyBoolean(), any(ViewGroup.class)); when(lastFmApiClient.getLastFmApiService().getMobileSessionToken( anyString(), anyString(), anyString(), anyString(), anyString(), anyString() )).thenReturn(Observable.just(user)); presenter.authenticateUser("dasd", "131", view, true); verify(view).showProgressBar(); } }
package nl.mpi.kinnate.ui.menu; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenu; import javax.swing.JMenuItem; import nl.mpi.kinnate.ui.window.AbstractDiagramManager; public class DocumentNewMenu extends JMenu implements ActionListener { AbstractDiagramManager diagramWindowManager; public enum DocumentType { Simple("Standard Diagram (database driven)"), Freeform("Freeform Diagram (transient)"), KinTerms("Kin Terms Diagram"), Query("Query Diagram"), EntitySearch("Entity Search"), ArchiveLinker("Archive Data Linker"), CustomQuery("Custom Data Formats"); private String displayName; private DocumentType(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } } public DocumentNewMenu(AbstractDiagramManager diagramWindowManager) { this.diagramWindowManager = diagramWindowManager; for (DocumentType documentType : DocumentType.values()) { JMenuItem menuItem = new JMenuItem(documentType.getDisplayName()); menuItem.setActionCommand(documentType.name()); menuItem.addActionListener(this); this.add(menuItem); } } public void actionPerformed(ActionEvent e) { DocumentType documentType = DocumentType.valueOf(e.getActionCommand()); diagramWindowManager.newDiagram(documentType); } }
package org.basex.util; import static org.basex.core.Text.*; import java.io.*; import java.lang.reflect.*; import org.basex.core.parse.*; import org.basex.io.*; public abstract class ConsoleReader implements AutoCloseable { /** Password prompt. */ private static final String PW_PROMPT = PASSWORD + COLS; /** Password reader. */ private final PasswordReader pwReader = new PasswordReader() { @Override public String password() { return readPassword(); } }; /** * Reads next line. If no input, then the method blocks the thread. * @param prompt prompt * @return next line or {@code null} if EOF is reached */ public abstract String readLine(final String prompt); /** * Reads a password. * @return password as plain text */ protected abstract String readPassword(); @Override public abstract void close(); /** * Create a new password reader for this console. * @return a new instance of {@link PasswordReader} */ public PasswordReader pwReader() { return pwReader; } /** * Creates a new instance. * @return instance of console reader */ public static ConsoleReader get() { if(JLineConsoleReader.isAvailable()) { try { return new JLineConsoleReader(); } catch(final Exception ex) { Util.errln(ex); } } return new SimpleConsoleReader(); } /** Simple console reader implementation. */ private static class SimpleConsoleReader extends ConsoleReader { /** Input reader. */ private final BufferedReader in; /** Constructor. */ SimpleConsoleReader() { in = new BufferedReader(new InputStreamReader(System.in)); } @Override public String readLine(final String prompt) { try { Util.out(prompt); return in.readLine(); } catch(final IOException ex) { // should not happen throw new RuntimeException(ex); } } @Override public String readPassword() { Util.out(PW_PROMPT); return Util.password(); } @Override public void close() { } } /** Implementation which provides advanced features, such as history. */ private static class JLineConsoleReader extends ConsoleReader { /** JLine console reader class name. */ private static final String JLINE_CONSOLE_READER = "jline.console.ConsoleReader"; /** JLine file history class name. */ private static final String JLINE_FILE_HISTORY = "jline.console.history.FileHistory"; /** JLine history class name. */ private static final String JLINE_HISTORY = "jline.console.history.History"; /** JLine history class name. */ private static final String JLINE_COMPLETER = "jline.console.completer.Completer"; /** JLine history class name. */ private static final String JLINE_ENUM_COMPLETER = "jline.console.completer.EnumCompleter"; /** JLine history class name. */ private static final String JLINE_FILE_NAME_COMPLETER = "jline.console.completer.FileNameCompleter"; /** Command history file. */ private static final String HISTORY_FILE = IO.BASEXSUFFIX + "history"; /** Password echo character. */ private static final Character PASSWORD_ECHO = (char) 0; /** Method to read the next line. */ private final Method readLine; /** Method to read the next line with echoing a character. */ private final Method readEcho; /** Implementation. */ private final Object reader; /** File history class. */ private final Class<?> fileHistoryC; /** File history. */ private final Object fileHistory; /** * Checks if JLine implementation is available? * @return {@code true} if JLine is in the classpath */ static boolean isAvailable() { return Reflect.available(JLINE_CONSOLE_READER); } /** * Constructor. * @throws Exception error */ JLineConsoleReader() throws Exception { // reflection final Class<?> readerC = Reflect.find(JLINE_CONSOLE_READER); readLine = Reflect.method(readerC, "readLine", String.class); readEcho = Reflect.method(readerC, "readLine", String.class, Character.class); // initialization reader = readerC.newInstance(); final Class<?> history = Reflect.find(JLINE_HISTORY); fileHistoryC = Reflect.find(JLINE_FILE_HISTORY); fileHistory = Reflect.get(Reflect.find(fileHistoryC, File.class), new File(Prop.HOME, HISTORY_FILE)); final Class<?> completer = Reflect.find(JLINE_COMPLETER); final Class<?> enumCompleter = Reflect.find(JLINE_ENUM_COMPLETER); final Class<?> fileNameCompleter = Reflect.find(JLINE_FILE_NAME_COMPLETER); Reflect.invoke(Reflect.method(readerC, "setBellEnabled", boolean.class), reader, false); Reflect.invoke(Reflect.method(readerC, "setHistory", history), reader, fileHistory); Reflect.invoke(Reflect.method(readerC, "setHistoryEnabled", boolean.class), reader, true); // command completions Reflect.invoke(Reflect.method(readerC, "addCompleter", completer), reader, Reflect.get(Reflect.find(enumCompleter, Class.class), Commands.Cmd.class)); Reflect.invoke(Reflect.method(readerC, "addCompleter", completer), reader, Reflect.get(Reflect.find(fileNameCompleter))); } @Override public String readLine(final String prompt) { return (String) Reflect.invoke(readLine, reader, prompt); } @Override public String readPassword() { return (String) Reflect.invoke(readEcho, reader, PW_PROMPT, PASSWORD_ECHO); } @Override public void close() { Reflect.invoke(Reflect.method(fileHistoryC, "flush"), fileHistory); } } }
package app.iamin.iamin.util; import android.content.Context; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import app.iamin.iamin.R; public class TimeUtils { public static final int SECOND = 1000; public static final int MINUTE = 60 * SECOND; public static final int HOUR = 60 * MINUTE; public static final int DAY = 24 * HOUR; public static final SimpleDateFormat FORMAT_API = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); private static final SimpleDateFormat FORMAT_SHORT_DATE = new SimpleDateFormat("dd. MMM"); private static final SimpleDateFormat FORMAT_TIME_OF_DAY = new SimpleDateFormat("HH:mm"); /** * Returns "Today", "Tomorrow", "Yesterday", or a short date format. */ public static String formatHumanFriendlyShortDate(Context context, Date date) { long localTimestamp, localTime; long timestamp = date.getTime(); long now = System.currentTimeMillis(); TimeZone tz = TimeZone.getDefault(); localTimestamp = timestamp + tz.getOffset(timestamp); localTime = now + tz.getOffset(now); long dayOrd = localTimestamp / 86400000L; long nowOrd = localTime / 86400000L; if (dayOrd == nowOrd) { return context.getString(R.string.day_title_today); } else if (dayOrd == nowOrd - 1) { return context.getString(R.string.day_title_yesterday); } else if (dayOrd == nowOrd + 1) { return context.getString(R.string.day_title_tomorrow); } else { return formatShortDate(new Date(timestamp)); } } public static String formatShortDate(Date date) { return FORMAT_SHORT_DATE.format(date); } public static String formatTimeOfDay(Date date) { return FORMAT_TIME_OF_DAY.format(date); } public static String getDuration(Date start, Date end) { long diffHours = (end.getTime() - start.getTime()) / (1000l * 60l * 60l); return "mind. " + diffHours + "h"; } }
package beaform.dao; import java.io.File; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.factory.GraphDatabaseFactory; /** * A handler for the graph database using JTA. * * @author Steven Post * */ public final class GraphDbHandler { /** The instance of this singleton */ private static GraphDbHandler instance; /** A lock for accessing the instance */ private static final Object INSTANCELOCK = new Object(); /** The DB service */ private final GraphDatabaseService graphDb; private GraphDbHandler(final String dbPath) { this.graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(new File(dbPath)); registerShutdownHook(this.graphDb); } private static void registerShutdownHook( final GraphDatabaseService graphDb ) { // Registers a shutdown hook for the Neo4j instance so that it // shuts down nicely when the VM exits (even if you "Ctrl-C" the // running application). Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { graphDb.shutdown(); } } ); } public GraphDatabaseService getService() { return this.graphDb; } /** * Get the instance of this handler. * @param persistenceUnit the persistence unit to use */ public static void initInstance(final String persistenceUnit) { synchronized (INSTANCELOCK) { if (instance == null) { instance = new GraphDbHandler(persistenceUnit); } } } /** * Get the instance of this handler. * @return the instance */ public static GraphDbHandler getInstance() { synchronized (INSTANCELOCK) { if (instance == null) { throw new IllegalStateException("The instance is not yet initialised"); } return instance; } } }
package com.kickstarter.libs; import java.util.ArrayList; import java.util.List; public class ListUtils { private ListUtils() { throw new AssertionError(); } /** * Concats the second argument onto the end of the first, but also mutates the * first argument. */ public static <T> List<T> mutatingConcat(final List<T> xs, final List<T> ys) { xs.addAll(ys); return xs; } /** * Concats the second argument onto the end of the first without mutating * either list. */ public static <T> List<T> concat(final List<T> xs, final List<T> ys) { final List<T> zs = new ArrayList<>(xs); ListUtils.mutatingConcat(zs, ys); return zs; } /** * Concats the distinct elements of the second argument onto the end of the * first, but also mutates the first. */ public static <T> List<T> mutatingConcatDistinct(final List<T> xs, final List<T> ys) { for (final T y : ys) { if (! xs.contains(y)) { xs.add(y); } } return xs; } /** * Concats the distinct elements of the second argument onto the end of the * first without mutating either list. */ public static <T> List<T> concatDistinct(final List<T> xs, final List<T> ys) { final List<T> zs = new ArrayList<>(xs); ListUtils.mutatingConcatDistinct(zs, ys); return zs; } /** * Prepends `x` to the beginning of the list `xs`. */ public static <T> List<T> prepend(final List<T> xs, final T x) { final List<T> ys = new ArrayList<>(xs); ys.add(0, x); return ys; } /** * Appends `x` to the end of the list `xs`. */ public static <T> List<T> append(final List<T> xs, final T x) { final List<T> ys = new ArrayList<>(xs); ys.add(x); return ys; } }
package com.kickstarter.models; import android.content.Context; import android.net.Uri; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringDef; import com.kickstarter.R; import com.kickstarter.libs.qualifiers.AutoGson; import com.kickstarter.libs.CurrencyOptions; import com.kickstarter.libs.utils.DateTimeUtils; import com.kickstarter.libs.utils.NumberUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Duration; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; import auto.parcel.AutoParcel; @AutoGson @AutoParcel public abstract class Project implements Parcelable { public abstract int backersCount(); public abstract String blurb(); @Nullable public abstract Backing backing(); @Nullable public abstract Category category(); @Nullable public abstract Integer commentsCount(); public abstract String country(); // e.g.: US public abstract DateTime createdAt(); public abstract User creator(); public abstract String currency(); // e.g.: USD public abstract String currencySymbol(); public abstract boolean currencyTrailingCode(); @Nullable public abstract DateTime deadline(); public abstract float goal(); public abstract long id(); // in the Kickstarter app, this is project.pid not project.id public abstract boolean isBacking(); public abstract boolean isStarred(); @Nullable public abstract DateTime launchedAt(); @Nullable public abstract Location location(); public abstract String name(); public abstract float pledged(); @Nullable public abstract Photo photo(); @Nullable public abstract DateTime potdAt(); @Nullable public abstract String slug(); @State public abstract String state(); public abstract @Nullable DateTime stateChangedAt(); @Nullable public abstract Integer updatesCount(); @Nullable public abstract List<Reward> rewards(); public abstract DateTime updatedAt(); public abstract Urls urls(); @Nullable public abstract Video video(); @AutoParcel.Builder public abstract static class Builder { public abstract Builder backersCount(int __); public abstract Builder blurb(String __); public abstract Builder backing(Backing __); public abstract Builder category(Category __); public abstract Builder commentsCount(Integer __); public abstract Builder country(String __); public abstract Builder createdAt(DateTime __); public abstract Builder creator(User __); public abstract Builder currency(String __); public abstract Builder currencySymbol(String __); public abstract Builder currencyTrailingCode(boolean __); public abstract Builder deadline(DateTime __); public abstract Builder goal(float __); public abstract Builder id(long __); public abstract Builder isBacking(boolean __); public abstract Builder isStarred(boolean __); public abstract Builder launchedAt(DateTime __); public abstract Builder location(Location __); public abstract Builder name(String __); public abstract Builder pledged(float __); public abstract Builder photo(Photo __); public abstract Builder potdAt(DateTime __); public abstract Builder rewards(List<Reward> __); public abstract Builder slug(String __); public abstract Builder state(@State String __); public abstract Builder stateChangedAt(DateTime __); public abstract Builder updatedAt(DateTime __); public abstract Builder updatesCount(Integer __); public abstract Builder urls(Urls __); public abstract Builder video(Video __); public abstract Project build(); } public static Builder builder() { return new AutoParcel_Project.Builder() .isBacking(false) .isStarred(false) .rewards(new ArrayList<>()); } public abstract Builder toBuilder(); public static final String STATE_STARTED = "started"; public static final String STATE_SUBMITTED = "submitted"; public static final String STATE_LIVE = "live"; public static final String STATE_SUCCESSFUL = "successful"; public static final String STATE_FAILED = "failed"; public static final String STATE_CANCELED = "canceled"; public static final String STATE_SUSPENDED = "suspended"; public static final String STATE_PURGED = "purged"; @Retention(RetentionPolicy.SOURCE) @StringDef({STATE_STARTED, STATE_SUBMITTED, STATE_LIVE, STATE_SUCCESSFUL, STATE_FAILED, STATE_CANCELED, STATE_SUSPENDED, STATE_PURGED}) public @interface State {} public @NonNull String creatorBioUrl() { return urls().web().creatorBio(); } public boolean isBackingRewardId(final long rewardId) { return this.backing() != null && this.backing().rewardId() != null && this.backing().rewardId() == rewardId; } public @NonNull String descriptionUrl() { return urls().web().description(); } public @NonNull String formattedBackersCount() { return NumberUtils.numberWithDelimiter(backersCount()); } public @Nullable String formattedCommentsCount() { return NumberUtils.numberWithDelimiter(commentsCount()); } public @Nullable String formattedStateChangedAt() { return DateTimeUtils.relativeDateInWords(stateChangedAt(), false, true); } public @Nullable String formattedUpdatesCount() { return NumberUtils.numberWithDelimiter(updatesCount()); } public @NonNull String updatesUrl() { return urls().web().updates(); } public @NonNull String webProjectUrl() { return urls().web().project(); } @AutoParcel @AutoGson public abstract static class Urls implements Parcelable { public abstract Web web(); @Nullable public abstract Api api(); @AutoParcel.Builder public abstract static class Builder { public abstract Builder web(Web __); public abstract Builder api(Api __); public abstract Urls build(); } public static Builder builder() { return new AutoParcel_Project_Urls.Builder(); } @AutoParcel @AutoGson public abstract static class Web implements Parcelable { public abstract String project(); @Nullable public abstract String projectShort(); public abstract String rewards(); @Nullable public abstract String updates(); @AutoParcel.Builder public abstract static class Builder { public abstract Builder project(String __); public abstract Builder projectShort(String __); public abstract Builder rewards(String __); public abstract Builder updates(String __); public abstract Web build(); } public static Builder builder() { return new AutoParcel_Project_Urls_Web.Builder(); } public String creatorBio() { return Uri.parse(project()) .buildUpon() .appendEncodedPath("/creator_bio") .toString(); } public String description() { return Uri.parse(project()) .buildUpon() .appendEncodedPath("/description") .toString(); } } @AutoParcel @AutoGson public abstract static class Api implements Parcelable { @Nullable public abstract String project(); @Nullable public abstract String comments(); @Nullable public abstract String updates(); @AutoParcel.Builder public abstract static class Builder { public abstract Builder project(String __); public abstract Builder comments(String __); public abstract Builder updates(String __); public abstract Api build(); } public static Builder builder() { return new AutoParcel_Project_Urls_Api.Builder(); } } } public @NonNull CurrencyOptions currencyOptions() { return new CurrencyOptions(country(), currencySymbol(), currency()); } public boolean hasComments() { return this.commentsCount() != null && Integer.valueOf(this.commentsCount()) != 0; } public boolean hasRewards() { return rewards() != null; } public boolean hasVideo() { return video() != null; } /** Returns whether the project is in a canceled state. */ public boolean isCanceled() { return STATE_CANCELED.equals(state()); } /** Returns whether the project is in a failed state. */ public boolean isFailed() { return STATE_FAILED.equals(state()); } /** Returns whether the project is in a live state. */ public boolean isLive() { return STATE_LIVE.equals(state()); } public boolean isPotdToday() { if (potdAt() == null) { return false; } final DateTime startOfDayUTC = new DateTime(DateTimeZone.UTC).withTime(0, 0, 0, 0); return startOfDayUTC.isEqual(potdAt().withZone(DateTimeZone.UTC)); } /** Returns whether the project is in a purged state. */ public boolean isPurged() { return STATE_PURGED.equals(state()); } /** Returns whether the project is in a live state. */ public boolean isStarted() { return STATE_STARTED.equals(state()); } /** Returns whether the project is in a submitted state. */ public boolean isSubmitted() { return STATE_SUBMITTED.equals(state()); } /** Returns whether the project is in a suspended state. */ public boolean isSuspended() { return STATE_SUSPENDED.equals(state()); } /** Returns whether the project is in a successful state. */ public boolean isSuccessful() { return STATE_SUCCESSFUL.equals(state()); } public @NonNull Float percentageFunded() { if (goal() > 0.0f) { return (pledged() / goal()) * 100.0f; } return 0.0f; } /** * Returns a String describing the time remaining for a project, e.g. * 25 minutes to go, 8 days to go. * * @param context an Android context. * @return the String time remaining. */ public @NonNull String timeToGo(final Context context) { return new StringBuilder(deadlineCountdown(context)) .append(context.getString(R.string._to_go)) .toString(); } /** * Returns time until project reaches deadline along with the unit, * e.g. 25 minutes, 8 days. * * @param context an Android context. * @return the String time remaining. */ public @NonNull String deadlineCountdown(final Context context) { return new StringBuilder().append(deadlineCountdownValue()) .append(" ") .append(deadlineCountdownUnit(context)) .toString(); } /** * Returns time until project reaches deadline in seconds, or 0 if the * project has already finished. * * @return the Long number of seconds remaining. */ public @NonNull Long timeInSecondsUntilDeadline() { return Math.max(0L, new Duration(new DateTime(), deadline()).getStandardSeconds()); } /** * Returns time remaining until project reaches deadline in either seconds, * minutes, hours or days. A time unit is chosen such that the number is * readable, e.g. 5 minutes would be preferred to 300 seconds. * * @return the Integer time remaining. */ public @NonNull Integer deadlineCountdownValue() { final Long seconds = timeInSecondsUntilDeadline(); if (seconds <= 120.0) { return seconds.intValue(); // seconds } else if (seconds <= 120.0 * 60.0) { return (int) Math.floor(seconds / 60.0); // minutes } else if (seconds < 72.0 * 60.0 * 60.0) { return (int) Math.floor(seconds / 60.0 / 60.0); // hours } return (int) Math.floor(seconds / 60.0 / 60.0 / 24.0); // days } /** * Returns the most appropriate unit for the time remaining until the project * reaches its deadline. * * @param context an Android context. * @return the String unit. */ public @NonNull String deadlineCountdownUnit(final Context context) { final Long seconds = timeInSecondsUntilDeadline(); if (seconds <= 1.0 && seconds > 0.0) { return context.getString(R.string.secs); } else if (seconds <= 120.0) { return context.getString(R.string.secs); } else if (seconds <= 120.0 * 60.0) { return context.getString(R.string.mins); } else if (seconds <= 72.0 * 60.0 * 60.0) { return context.getString(R.string.hours); } return context.getString(R.string.days); } public @NonNull String param() { return slug() != null ? slug() : String.valueOf(id()); } public @NonNull String secureWebProjectUrl() { // TODO: Just use http with local env return Uri.parse(webProjectUrl()).buildUpon().scheme("https").build().toString(); } public @NonNull String newPledgeUrl() { return Uri.parse(secureWebProjectUrl()).buildUpon().appendEncodedPath("pledge/new").toString(); } public @NonNull String editPledgeUrl() { return Uri.parse(secureWebProjectUrl()).buildUpon().appendEncodedPath("pledge/edit").toString(); } public @NonNull String rewardSelectedUrl(final Reward reward) { return Uri.parse(newPledgeUrl()) .buildUpon().scheme("https") .appendQueryParameter("backing[backer_reward_id]", String.valueOf(reward.id())) .appendQueryParameter("clicked_reward", "true") .build() .toString(); } @Override public final @NonNull String toString() { return "Project{" + "id=" + id() + ", " + "name=" + name() + ", " + "}"; } @Override public final boolean equals(@Nullable final Object o) { if (o != null && o instanceof Project) { final Project p = (Project)o; return id() == p.id(); } return false; } @Override public final int hashCode() { return (int)id(); } }
package notizync.core.http; import com.google.gson.Gson; import notizync.core.api.INote; import notizync.core.api.IStorageProvider; import notizync.core.api.IUpdateEventDistributor; import notizync.core.conflict.IConflict; import notizync.core.conflict.INegotiator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.*; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; /** * An implementation of IStorageProvider based on the HTTP Protocol and an Web-API. * * @author Andreas Willinger * @version 0.1 * @since 14.11.13 08:45 */ public class HTTPStorageProvider implements IStorageProvider { private IUpdateEventDistributor eventDistributor; private INegotiator negotiator; private CloseableHttpClient backend; private Gson json; private String token; private HashSet<INote> noteSet; public HTTPStorageProvider(IUpdateEventDistributor eventDistributor, INegotiator negotiator, String username, String password) throws HTTPStoreException { this.eventDistributor = eventDistributor; this.negotiator = negotiator; this.backend = HttpClients.createDefault(); this.json = new Gson(); if(!this.doLogin(username, password)) throw new HTTPStoreException("Logon failed"); } /** * Adds or updates a note for storage. * * @param note note that should be stored * @return note that was stored before with the same title or null */ @Override public INote putNote(INote note) throws HTTPStoreException { boolean exists = false; INote existing = null; //compares title of new note to existing ones for(Iterator<INote> iterator = this.noteSet.iterator(); iterator.hasNext(); existing = iterator.next()) { if(existing.getTitle().toString().equals(note.getTitle().toString())) { exists = true; break; } } if(exists) { // which of the note should be kept IConflict conflict = note.clash(existing); note = this.negotiator.negotiate(conflict); this.noteSet.remove(existing); if(!this.removeNote(note)) throw new HTTPStoreException("Transport error while removing the Note!\nEither the API is down or refused to communicate with us."); } else { if(!this.storeNote(note)) throw new HTTPStoreException("Transport error while storing the Note!\nEither the API is down or refused to communicate with us."); } this.noteSet.add(note); return exists ? existing : null; } /** * Send a login request to the backend, containing username and password. * * @param username Plain-Text Username * @param password Plain-Text Password * @return true if the login was successful, false if not */ private boolean doLogin(String username, String password) { List<NameValuePair> data = new ArrayList<>(); data.add(new BasicNameValuePair("username", username)); data.add(new BasicNameValuePair("password", password)); String raw = this.sendPost(WebAPI.getAPI("IUser", "OAuth"), data); if(raw == null) return false; HTTPLoginResponse parsed = this.json.fromJson(raw, HTTPLoginResponse.class); if(parsed.success) { this.token = parsed.session_data.token; return true; } return false; } public boolean storeNote(INote note) { List<NameValuePair> data = new ArrayList<>(); data.add(new BasicNameValuePair("title", note.getTitle().toString())); data.add(new BasicNameValuePair("content", note.getContent().toString())); data.add(new BasicNameValuePair("stamp", note.getStamp().toString())); String raw = this.sendPost(WebAPI.getAPI("INote", "StoreNote"), data); if(raw == null) return false; HTTPNoteResponse parsed = this.json.fromJson(raw, HTTPNoteResponse.class); return parsed.success; } public boolean removeNote(INote note) { List<NameValuePair> data = new ArrayList<>(); data.add(new BasicNameValuePair("title", note.getTitle().toString())); String raw = this.sendPost(WebAPI.getAPI("INote", "RemoveNote"), data); if(raw == null) return false; HTTPNoteResponse parsed = this.json.fromJson(raw, HTTPNoteResponse.class); return parsed.success; } private String sendPost(String url, List<NameValuePair> data) { HttpPost request = new HttpPost(url); try { request.setEntity(new UrlEncodedFormEntity(data)); HttpResponse response = this.backend.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = "", raw = ""; while((line = reader.readLine()) != null) { raw += line; } return raw; } catch (UnsupportedEncodingException e) { return null; } catch (ClientProtocolException e) { return null; } catch (IOException e) { return null; } } /** * @return set of notes stored by this StorageProvider */ @Override public Set<INote> getNoteSet() { return new HashSet<>(this.noteSet); } /** * As we invoke the different Sync-Methods on every Update, this Method is unused. */ @Override public void sync() {} }
package com.sinyuk.yuk.ui; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; import butterknife.Unbinder; import rx.Subscription; import rx.subscriptions.CompositeSubscription; public abstract class BaseFragment extends Fragment { private Unbinder unbinder; private CompositeSubscription mCompositeSubscription; protected Context mContext = null; private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN"; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Override public void onDetach() { super.onDetach(); mContext = null; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN); FragmentTransaction ft = getFragmentManager().beginTransaction(); if (isSupportHidden) { ft.hide(this); } else { ft.show(this); } ft.commit(); } mCompositeSubscription = new CompositeSubscription(); beforeInflate(); } /** * FragmentHidden * Fragment * @param outState */ @Override public void onSaveInstanceState(Bundle outState) { outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden()); } protected abstract void beforeInflate(); @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(getRootViewId(), container, false); } protected abstract int getRootViewId(); @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); unbinder = ButterKnife.bind(this, view); finishInflate(); } protected abstract void finishInflate(); protected void addSubscription(Subscription s) { mCompositeSubscription.add(s); } protected void removeSubscription(Subscription s) { mCompositeSubscription.remove(s); } protected void clearSubscription() { mCompositeSubscription.clear(); } @Override public void onDestroy() { super.onDestroy(); unbinder.unbind(); if (!mCompositeSubscription.isUnsubscribed()) { mCompositeSubscription.unsubscribe(); } } }
package io.scrollback.app; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.app.Activity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.webkit.ConsoleMessage; import android.webkit.JavascriptInterface; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.facebook.AppEventsLogger; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.model.GraphObject; import com.facebook.model.GraphUser; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.gms.common.AccountPicker; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import static android.webkit.WebSettings.LOAD_DEFAULT; public class MainActivity extends Activity { public static final String ORIGIN = Constants.domain; public static final String INDEX = Constants.protocol + "//" + ORIGIN; public static final String HOME = INDEX + "/me"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final int REQ_SIGN_IN_REQUIRED = 55664; private static final int SOME_REQUEST_CODE = 12323; private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; private final static int FB_REQUEST_CODE_OPEN = 14141; private final static int FB_REQUEST_CODE_PERM = 14142; private static final String TAG = "android_wrapper"; private String accountName; private String accessToken; GoogleCloudMessaging gcm; String regid; private WebView mWebView; private ProgressBar mProgressBar; private TextView mLoadError; private boolean inProgress = false; ProgressDialog dialog; ArrayList<String> permissions; private ValueCallback<Uri> mUploadMessage; private ValueCallback<Uri[]> mUploadMessageArr; private final static int REQUEST_SELECT_FILE_LEGACY = 19264; private final static int REQUEST_SELECT_FILE = 19275; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView) findViewById(R.id.main_webview); mProgressBar = (ProgressBar) findViewById(R.id.main_pgbar); mLoadError = (TextView) findViewById(R.id.main_loaderror); // Enable debugging in webview if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (BuildConfig.DEBUG) { WebView.setWebContentsDebuggingEnabled(true); } } // Check device for Play Services APK. If check succeeds, proceed with // GCM registration. if (checkPlayServices()) { gcm = GoogleCloudMessaging.getInstance(this); regid = getRegistrationId(getApplicationContext()); } else { Log.i(TAG, "No valid Google Play Services APK found."); } mWebView.setWebViewClient(mWebViewClient); mWebView.setWebChromeClient(new WebChromeClient() { // For Android < 3.0 @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); MainActivity.this.startActivityForResult(Intent.createChooser(i, getString(R.string.select_file)), REQUEST_SELECT_FILE_LEGACY); } // For Android 3.0+ @SuppressWarnings("unused") public void openFileChooser(ValueCallback uploadMsg, String acceptType) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(acceptType); MainActivity.this.startActivityForResult(Intent.createChooser(i, getString(R.string.select_file)), REQUEST_SELECT_FILE_LEGACY); } // For Android 4.1+ @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(acceptType); MainActivity.this.startActivityForResult(Intent.createChooser(i, getString(R.string.select_file)), REQUEST_SELECT_FILE_LEGACY); } // For Android 5.0+ @SuppressLint("NewApi") public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (mUploadMessageArr != null) { mUploadMessageArr.onReceiveValue(null); mUploadMessageArr = null; } mUploadMessageArr = filePathCallback; Intent intent = fileChooserParams.createIntent(); try { MainActivity.this.startActivityForResult(intent, REQUEST_SELECT_FILE); } catch (ActivityNotFoundException e) { mUploadMessageArr = null; Toast.makeText(MainActivity.this, getString(R.string.file_chooser_error), Toast.LENGTH_LONG).show(); return false; } return true; } }); WebSettings mWebSettings = mWebView.getSettings(); String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath(); mWebSettings.setJavaScriptEnabled(true); mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true); mWebSettings.setSupportZoom(false); mWebSettings.setSaveFormData(true); mWebSettings.setDomStorageEnabled(true); mWebSettings.setAppCacheEnabled(true); mWebSettings.setAppCachePath(appCachePath); mWebSettings.setAllowFileAccess(true); mWebSettings.setCacheMode(LOAD_DEFAULT); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { String databasePath = getApplicationContext().getDir("databases", Context.MODE_PRIVATE).getPath(); mWebSettings.setDatabaseEnabled(true); mWebSettings.setDatabasePath(databasePath); } mWebView.addJavascriptInterface(new ScrollbackInterface(getApplicationContext()) { @SuppressWarnings("unused") @JavascriptInterface public boolean isFileUploadAvailable(final boolean needsCorrectMimeType) { if (Build.VERSION.SDK_INT == 19) { final String platformVersion = (Build.VERSION.RELEASE == null) ? "" : Build.VERSION.RELEASE; return !needsCorrectMimeType && (platformVersion.startsWith("4.4.3") || platformVersion.startsWith("4.4.4")); } else { return true; } } @SuppressWarnings("unused") @JavascriptInterface public boolean isFileUploadAvailable() { return isFileUploadAvailable(false); } @SuppressWarnings("unused") @JavascriptInterface public void setStatusBarColor() { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { getWindow().setStatusBarColor(getResources().getColor(R.color.primary_dark)); } catch (Exception e) { Log.d(TAG, "Failed to set statusbar color " + e); } } } }); } @SuppressWarnings("unused") @JavascriptInterface public void setStatusBarColor(final String color) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { getWindow().setStatusBarColor(Color.parseColor(color)); } catch (Exception e) { Log.d(TAG, "Failed to set statusbar color to " + color + " " + e); } } } }); } @SuppressWarnings("unused") @JavascriptInterface public void shareItem(String title, String content) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, content); startActivity(Intent.createChooser(sharingIntent, title)); } @SuppressWarnings("unused") @JavascriptInterface public void copyToClipboard(String label, String text) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(label, text); clipboard.setPrimaryClip(clip); Toast toast = Toast.makeText(MainActivity.this, getString(R.string.clipboard_success), Toast.LENGTH_SHORT); toast.show(); } @SuppressWarnings("unused") @JavascriptInterface public void onFinishedLoading() { runOnUiThread(new Runnable() { @Override public void run() { hideLoading(); } }); } @SuppressWarnings("unused") @JavascriptInterface public void googleLogin() { Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null); startActivityForResult(intent, SOME_REQUEST_CODE); } @SuppressWarnings("unused") @JavascriptInterface public void facebookLogin() { // Get a handler that can be used to post to the main thread Handler mainHandler = new Handler(MainActivity.this.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { doFacebookLogin(); } }; mainHandler.post(myRunnable); } @SuppressWarnings("unused") @JavascriptInterface public void registerGCM() { registerBackground(); } @SuppressWarnings("unused") @JavascriptInterface public void unregisterGCM() { unRegisterBackground(); } }, "Android"); Intent intent = getIntent(); String action = intent.getAction(); Uri uri = intent.getData(); if (intent.hasExtra("scrollback_path")) { mWebView.loadUrl(INDEX + getIntent().getStringExtra("scrollback_path")); } else if (Intent.ACTION_VIEW.equals(action) && uri != null) { final String URL = uri.toString(); mWebView.loadUrl(URL); } else { mWebView.loadUrl(HOME); } mLoadError.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mWebView.loadUrl(mWebView.getUrl()); mLoadError.setVisibility(View.GONE); showLoading(); } }); showLoading(); Session session = Session.getActiveSession(); if (session == null) { session = new Session(this); Session.setActiveSession(session); session.addCallback(statusCallback); } } void doFacebookLogin() { Session session = Session.getActiveSession(); if(!session.isOpened()) { session.openForRead(new Session.OpenRequest(MainActivity.this).setCallback(statusCallback).setPermissions(permissions).setRequestCode(FB_REQUEST_CODE_OPEN)); } else { Session.openActiveSession(MainActivity.this, true, statusCallback); } } void hideLoading() { mProgressBar.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } void showLoading() { mProgressBar.setVisibility(View.VISIBLE); mWebView.setVisibility(View.GONE); } void emitGoogleLoginEvent(String token) { Log.d("emitGoogleLoginEvent", "email:"+accountName+" token:"+token); mWebView.loadUrl("javascript:window.dispatchEvent(new CustomEvent('login', { detail :{'provider': 'google', 'email': '" + accountName + "', 'token': '" + token + "'} }))"); } void emitFacebookLoginEvent(String email, String token) { Log.d("emitFacebookLoginEvent", "email:"+email+" token:"+token); mWebView.loadUrl("javascript:window.dispatchEvent(new CustomEvent('login', { detail :{'provider': 'facebook', 'email': '" + email + "', 'token': '" + token + "'} }))"); } void emitGCMRegisterEvent(String regid, String uuid, String model) { Log.d("emitGCMRegisterEvent", "uuid:"+uuid+" regid:"+regid); mWebView.loadUrl("javascript:window.dispatchEvent(new CustomEvent('gcm_register', { detail :{'regId': '" + regid + "', 'uuid': '" + uuid + "', 'model': '" + model + "'} }))"); } void emitGCMUnregisterEvent(String uuid) { mWebView.loadUrl("javascript:window.dispatchEvent(new CustomEvent('gcm_unregister', { detail :{'uuid': '" + uuid + "'} }))"); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // Check if the key event was the Back button and if there's history if (mWebView.getUrl().equals(HOME) || !mWebView.canGoBack()) { finish(); } else if (mWebView.canGoBack()) { mWebView.goBack(); } return true; } // Bubble up to the default system behavior (probably exit the activity) return super.onKeyDown(keyCode, event); } private WebViewClient mWebViewClient = new WebViewClient() { @SuppressWarnings("unused") public boolean onConsoleMessage(ConsoleMessage cm) { Log.d(getString(R.string.app_name), cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId() ); return true; } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if (uri.getAuthority().equals(ORIGIN)) { // This is my web site, so do not override; let my WebView load the page return false; } else { Log.d(TAG, uri.getAuthority() + " is not " + ORIGIN); // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { mLoadError.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.GONE); } }; @Override protected void onResume() { super.onResume(); // Logs 'install' and 'app activate' App Events. AppEventsLogger.activateApp(this); } @Override protected void onPause() { super.onPause(); // Logs 'app deactivate' App Event. AppEventsLogger.deactivateApp(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Session.saveSession(Session.getActiveSession(), outState); mWebView.saveState(outState); } @Override protected void onDestroy() { super.onDestroy(); mWebView.destroy(); } @SuppressLint("NewApi") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_SELECT_FILE_LEGACY) { if (mUploadMessage == null) return; Uri result = data == null || resultCode != RESULT_OK ? null : data.getData(); mUploadMessage.onReceiveValue(result); mUploadMessage = null; } else if (requestCode == REQUEST_SELECT_FILE) { if (mUploadMessageArr == null) return; mUploadMessageArr.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data)); mUploadMessageArr = null; } else if (requestCode == SOME_REQUEST_CODE && resultCode == RESULT_OK) { accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); new RetrieveGoogleTokenTask().execute(accountName); } else if (requestCode == REQ_SIGN_IN_REQUIRED && resultCode == RESULT_OK) { // We had to sign in - now we can finish off the token request. new RetrieveGoogleTokenTask().execute(accountName); } else if (requestCode == FB_REQUEST_CODE_PERM || requestCode == FB_REQUEST_CODE_OPEN) { if (Session.getActiveSession() != null) { Session.getActiveSession().onActivityResult(MainActivity.this, requestCode, resultCode, data); } } } Session.StatusCallback statusCallback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { Log.d("SessionState", state.toString()); processSessionStatus(session, state, exception); } }; public void processSessionStatus(final Session session, SessionState state, Exception exception) { if (exception!=null) { Log.d("FBException", exception.getMessage()); } Log.d("processSessionState", "State: " + state.toString()); if (session != null && session.isOpened()) { if (session.getPermissions().contains("email")) { session.getAccessToken(); //Show Progress Dialog dialog = new ProgressDialog(MainActivity.this); dialog.setMessage(getString(R.string.fb_signing_in)); dialog.show(); Request.newMeRequest(session, new Request.GraphUserCallback() { @Override public void onCompleted(GraphUser user, Response response) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } if (user != null) { GraphObject graphObject = response.getGraphObject(); Map<String, Object> responseMap = graphObject.asMap(); Log.i("FbLogin", "Response Map KeySet - " + responseMap.keySet()); // String fb_id = user.getId(); // String name = (String) responseMap.get("name"); String email; if (responseMap.get("email") != null) { email = responseMap.get("email").toString(); emitFacebookLoginEvent(email, session.getAccessToken()); } else { // Clear all session info & ask user to login again Session session = Session.getActiveSession(); if (session != null) { session.closeAndClearTokenInformation(); } } } } }).executeAsync(); } else { session.requestNewReadPermissions(new Session.NewPermissionsRequest(this, permissions).setRequestCode(FB_REQUEST_CODE_PERM)); } } } private class RetrieveGoogleTokenTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); dialog = new ProgressDialog(MainActivity.this); dialog.setMessage(getString(R.string.google_signing_in)); dialog.show(); } @Override protected String doInBackground(String... params) { String accountName = params[0]; String scopes = "oauth2:profile email"; String token = null; try { token = GoogleAuthUtil.getToken(getApplicationContext(), accountName, scopes); } catch (IOException e) { Log.e(TAG, e.getMessage()); } catch (UserRecoverableAuthException e) { startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED); } catch (GoogleAuthException e) { Log.e(TAG, e.getMessage()); } return token; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } if (s == null) { Toast.makeText(MainActivity.this, getString(R.string.requesting_permission), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, getString(R.string.signed_in), Toast.LENGTH_SHORT).show(); emitGoogleLoginEvent(s); accessToken = s; } } } private class DeleteTokenTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); inProgress = true; } @Override protected String doInBackground(String... params) { accessToken = params[0]; String result = null; try { GoogleAuthUtil.clearToken(getApplicationContext(), accessToken); result = "true"; } catch (GoogleAuthException e) { Log.e(TAG, e.getMessage()); } catch (IOException e) { Log.e(TAG, e.getMessage()); } return result; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); inProgress = false; } } /** * Registers the application with GCM servers asynchronously. * <p/> * Stores the registration id, app versionCode, and expiration time in the application's * shared preferences. */ private void registerBackground() { new AsyncTask<Void, Void, String>() { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(Void... params) { String msg; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); } regid = gcm.register(getString(R.string.gcm_sender_id)); msg = "Device registered, registration id=" + regid; // You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. // For this demo: we don't need to send it because the device will send // upstream messages to a server that echo back the message using the // 'from' address in the message. // Save the regid - no need to register again. setRegistrationId(getApplicationContext(), regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } String uuid = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID); emitGCMRegisterEvent(regid, uuid, Build.MODEL); } }.execute(null, null, null); } private void unRegisterBackground() { new AsyncTask<Void, Void, String>() { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); } gcm.unregister(); // You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. // For this demo: we don't need to send it because the device will send // upstream messages to a server that echo back the message using the // 'from' address in the message. // Save the regid - no need to register again. setRegistrationId(getApplicationContext(), regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } emitGCMUnregisterEvent(Build.MODEL); } }.execute(null, null, null); } /** * Stores the registration id, app versionCode, and expiration time in the application's * {@code SharedPreferences}. * * @param context application's context. * @param regId registration id */ private void setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(); int appVersion = getAppVersion(context); Log.v(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.apply(); } /** * Gets the current registration id for application on GCM service. * <p/> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(); final String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.length() == 0) { Log.v(TAG, "Registration not found."); return ""; } // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.v(TAG, "App version changed or registration expired."); return ""; } return registrationId; } /** * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { // Should never happen throw new RuntimeException("Could not get package name: " + e); } } /** * @return Application's {@code SharedPreferences}. */ private SharedPreferences getGCMPreferences() { return getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE); } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } }
package com.mindoo.domino.jna; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import com.mindoo.domino.jna.constants.DateFormat; import com.mindoo.domino.jna.constants.DateTimeStructure; import com.mindoo.domino.jna.constants.TimeFormat; import com.mindoo.domino.jna.constants.ZoneFormat; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.internal.DisposableMemory; import com.mindoo.domino.jna.internal.InnardsConverter; import com.mindoo.domino.jna.internal.NotesConstants; import com.mindoo.domino.jna.internal.NotesNativeAPI; import com.mindoo.domino.jna.internal.structs.IntlFormatStruct; import com.mindoo.domino.jna.internal.structs.NotesTFMTStruct; import com.mindoo.domino.jna.internal.structs.NotesTimeDateStruct; import com.mindoo.domino.jna.utils.NotesDateTimeUtils; import com.mindoo.domino.jna.utils.NotesStringUtils; import com.mindoo.domino.jna.utils.StringUtil; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.ptr.ShortByReference; /** * Wrapper class for the TIMEDATE C API data structure * * @author Karsten Lehmann */ public class NotesTimeDate implements Comparable<NotesTimeDate>, IAdaptable { private int[] m_innards = new int[2]; private NotesTimeDateStruct m_structReused; private TimeZone m_guessedTimezone; /** * Creates a new date/time object and sets it to the current date/time */ public NotesTimeDate() { this(NotesDateTimeUtils.calendarToInnards(Calendar.getInstance())); } /** * Creates a new date/time object and sets it to a date/time specified as * innards array * * @param innards innards array */ public NotesTimeDate(int innards[]) { m_innards = innards.clone(); } /** * Creates a new date/time object and sets it to the specified {@link Date} * * @param dt date object */ public NotesTimeDate(Date dt) { this(NotesDateTimeUtils.dateToInnards(dt)); } /** * Creates a new date/time object and sets it to the specified {@link Calendar} * * @param cal calendar object */ public NotesTimeDate(Calendar cal) { this(NotesDateTimeUtils.calendarToInnards(cal)); } /** * Creates a new date/time object and sets it to the specified time in milliseconds since * GMT 1/1/70 * * @param timeMs the milliseconds since January 1, 1970, 00:00:00 GMT */ public NotesTimeDate(long timeMs) { this(new Date(timeMs)); } /** * Constructs a new date/time object * * @param year year * @param month month, january is 1 * @param day day * @param hour hour * @param minute minute * @param second second * @param millis milliseconds (Notes can only store hundredth seconds) * @param zone timezone */ public NotesTimeDate(int year, int month, int day, int hour, int minute, int second, int millis, TimeZone zone) { this(createCalendar(year, month, day, hour, minute, second, millis, zone)); } /** * Constructs a new date/time by merging the date and time part of two other {@link NotesTimeDate} objects * * @param date date part * @param time time part */ public NotesTimeDate(NotesTimeDate date, NotesTimeDate time) { m_innards[0] = time.getInnardsNoClone()[0]; // time part m_innards[1] = date.getInnardsNoClone()[1]; // date part } private static Calendar createCalendar(int year, int month, int day, int hour, int minute, int second, int millis, TimeZone zone) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month-1); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, second); cal.set(Calendar.MILLISECOND, millis); cal.set(Calendar.ZONE_OFFSET, zone.getRawOffset()); return cal; } /** * Constructs a new date/time object in the default timezone * * @param year year * @param month month * @param day day * @param hour hour * @param minute minute * @param second second * @param millis milliseconds (Notes can only store hundredth seconds) */ public NotesTimeDate(int year, int month, int day, int hour, int minute, int second, int millis) { this(year, month, day, hour, minute, second, millis, TimeZone.getDefault()); } /** * Constructs a new date/time object in the default timezone * * @param year year * @param month month * @param day day * @param hour hour * @param minute minute * @param second second */ public NotesTimeDate(int year, int month, int day, int hour, int minute, int second) { this(year, month, day, hour, minute, second, 0, TimeZone.getDefault()); } /** * Constructs a new date/time object in the default timezone * * @param year year * @param month month * @param day day * @param hour hour * @param minute minute */ public NotesTimeDate(int year, int month, int day, int hour, int minute) { this(year, month, day, hour, minute, 0, 0, TimeZone.getDefault()); } /** * Constructs a new date-only date/time object * * @param year year * @param month month * @param day day */ public NotesTimeDate(int year, int month, int day) { Calendar cal = createCalendar(year, month, day, 0, 0, 0, 0, TimeZone.getDefault()); NotesDateTimeUtils.setAnyTime(cal); m_innards = NotesDateTimeUtils.calendarToInnards(cal); } /** * Creates a new instance * * @param adaptable object providing a supported data object for the time/date state */ public NotesTimeDate(IAdaptable adaptable) { NotesTimeDateStruct struct = adaptable.getAdapter(NotesTimeDateStruct.class); if (struct!=null) { m_innards = struct.Innards.clone(); return; } Pointer p = adaptable.getAdapter(Pointer.class); if (p!=null) { struct = NotesTimeDateStruct.newInstance(p); struct.read(); m_innards = struct.Innards.clone(); return; } throw new IllegalArgumentException("Constructor argument cannot provide a supported datatype"); } @Override public <T> T getAdapter(Class<T> clazz) { if (NotesTimeDateStruct.class.equals(clazz)) { return (T) lazilyCreateStruct(); } return null; } private NotesTimeDateStruct lazilyCreateStruct() { if (m_structReused==null) { m_structReused = NotesTimeDateStruct.newInstance(); } m_structReused.Innards = m_innards; m_structReused.write(); return m_structReused; } /** * Returns a copy of the internal Innards values * * @return innards */ public int[] getInnards() { if (m_innards!=null) { return m_innards.clone(); } else return new int[] {NotesConstants.ALLDAY,NotesConstants.ANYDAY}; } int[] getInnardsNoClone() { if (m_innards!=null) { return m_innards; } else return new int[] {NotesConstants.ALLDAY,NotesConstants.ANYDAY}; } /** * Checks whether the timedate has a date portion * * @return true if date part exists */ public boolean hasDate() { int[] innards = getInnardsNoClone(); boolean hasDate=(innards[1]!=0 && innards[1]!=NotesConstants.ANYDAY); return hasDate; } /** * Checks whether the timedate has a time portion * * @return true if time part exists */ public boolean hasTime() { int[] innards = getInnardsNoClone(); boolean hasTime=(innards[0]!=0 && innards[0]!=NotesConstants.ALLDAY); return hasTime; } /** * Converts the time date to a calendar * * @return calendar or null if data is invalid */ public Calendar toCalendar() { int[] innards = getInnardsNoClone(); Calendar cal = InnardsConverter.decodeInnards(innards); if (cal==null) { //invalid innards Calendar nullCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); nullCal.set(Calendar.DAY_OF_MONTH, 1); nullCal.set(Calendar.MONTH, 1); nullCal.set(Calendar.YEAR, 0); nullCal.set(Calendar.HOUR, 0); nullCal.set(Calendar.MINUTE, 0); nullCal.set(Calendar.SECOND, 0); nullCal.set(Calendar.MILLISECOND, 0); return nullCal; } else return cal; } /** * Converts the time date to a Java {@link Date} * * @return date or null if data is invalid */ public Date toDate() { Calendar cal = toCalendar(); return cal==null ? null : cal.getTime(); } @Override public int hashCode() { int[] innards = getInnardsNoClone(); return Arrays.hashCode(innards); } @Override public boolean equals(Object o) { if (o instanceof NotesTimeDate) { return Arrays.equals(getInnardsNoClone(), ((NotesTimeDate)o).getInnardsNoClone()); } return false; } /** * Returns a new {@link NotesTimeDate} with date and time info set to "now" * * @return time date */ public static NotesTimeDate now() { NotesTimeDate td = new NotesTimeDate(); td.setNow(); return td; } /** * Returns a new {@link NotesTimeDate} with date only, set to today * * @return time date */ public static NotesTimeDate today() { NotesTimeDate td = new NotesTimeDate(); td.setToday(); return td; } /** * Returns a new {@link NotesTimeDate} with date only, set to tomorrow * * @return time date */ public static NotesTimeDate tomorrow() { NotesTimeDate td = new NotesTimeDate(); td.setTomorrow(); return td; } /** * Returns a new {@link NotesTimeDate} with date only, set to yesterday * * @return time date */ public static NotesTimeDate yesterday() { NotesTimeDate td = new NotesTimeDate(); td.setYesterday(); return td; } /** * Returns a new {@link NotesTimeDate} with date and time info, adjusted from the current date/time * * @param year positive or negative value or 0 for no change * @param month positive or negative value or 0 for no change * @param day positive or negative value or 0 for no change * @param hours positive or negative value or 0 for no change * @param minutes positive or negative value or 0 for no change * @param seconds positive or negative value or 0 for no change * @return timedate */ public static NotesTimeDate adjustedFromNow(int year, int month, int day, int hours, int minutes, int seconds) { NotesTimeDate td = new NotesTimeDate(); td.adjust(year, month, day, hours, minutes, seconds); return td; } /** * Sets the date/time of this timedate to the current time */ public void setNow() { m_innards = NotesDateTimeUtils.calendarToInnards(Calendar.getInstance(), true, true); m_guessedTimezone = null; } /** * Changes the internally stored date/time value * * @param dt new value */ public void setTime(Date dt) { Calendar cal = Calendar.getInstance(); cal.setTime(dt); setTime(cal); m_guessedTimezone = null; } /** * Changes the internally stored date/time value * * @param innards new value as innards array (will be copied) */ public void setTime(int[] innards) { if (innards.length!=2) throw new IllegalArgumentException("Innards array must have 2 elements ("+innards.length+"!=2"); m_innards = innards.clone(); m_guessedTimezone = null; } /** * Changes the internally stored date/time value * * @param cal new value */ public void setTime(Calendar cal) { m_innards = NotesDateTimeUtils.calendarToInnards(cal); m_guessedTimezone = null; } public TimeZone getTimeZone() { if (m_guessedTimezone==null) { if (m_innards[1] == NotesConstants.ANYDAY) { return null; } long innard1Long = m_innards[1]; int tzSign; if (((innard1Long >> 30) & 1 ) == 0) { tzSign = -1; } else { tzSign = 1; } //The high-order bit, bit 31 (0x80000000), is set if Daylight Savings Time is observed boolean useDST; if (((innard1Long >> 31) & 1 ) == 0) { useDST = false; } else { useDST = true; } int tzOffsetHours = (int) (innard1Long >> 24) & 0xF; int tzOffsetFraction15MinuteIntervalls = (int) (innard1Long >> 28) & 0x3; long rawOffsetMillis = tzSign * 1000 * (tzOffsetHours * 60 * 60 + 15*60*tzOffsetFraction15MinuteIntervalls); if (rawOffsetMillis==0) { m_guessedTimezone = TimeZone.getTimeZone("GMT"); } else { //not great, go through the JDK locales to find a matching one by comparing the //raw offset; grep its short id and try to load a TimeZone for it //the purpose is to return short ids like "CET" instead of "Africa/Ceuta" String[] timezonesWithOffset = TimeZone.getAvailableIDs((int) rawOffsetMillis); for (String currTZID : timezonesWithOffset) { TimeZone currTZ = TimeZone.getTimeZone(currTZID); if (useDST==currTZ.useDaylightTime()) { String tzShortId = currTZ.getDisplayName(false, TimeZone.SHORT, Locale.ENGLISH); m_guessedTimezone = TimeZone.getTimeZone(tzShortId); if ("GMT".equals(m_guessedTimezone.getID())) { //parse failed m_guessedTimezone = currTZ; } break; } } if (m_guessedTimezone==null) { String tzString = "GMT" + (tzSign < 0 ? "-" : "+") + StringUtil.pad(Integer.toString(tzOffsetHours + (useDST ? 1 : 0)), 2, '0', false) + ":" + StringUtil.pad(Integer.toString(15 * tzOffsetFraction15MinuteIntervalls), 2, '0', false); m_guessedTimezone = TimeZone.getTimeZone(tzString); } } } return m_guessedTimezone; } /** * Changes the timezone of this {@link NotesTimeDate} while keeping the current date/time * * @param tz new timezone */ public void setTimeZone(TimeZone tz) { long zoneMask = 0; //The high-order bit, bit 31 (0x80000000), is set if Daylight Savings Time is observed if (tz.useDaylightTime()) { zoneMask |= 1l << 31; } //Bit 30 (0x40000000) is set if the time zone is east of Greenwich mean time. int tzOffsetSeconds = (int)(tz.getRawOffset() / 1000); if (tzOffsetSeconds>0) { zoneMask |= 1l << 30; } int tzOffsetHours = Math.abs(tzOffsetSeconds / (60*60)); //Bits 27-24 contain the number of hours difference between the time zone and Greenwich mean time zoneMask |= ((long)tzOffsetHours) << 24; //bits 29-28 contain the number of 15-minute intervals in the difference int tzOffsetFractionSeconds = tzOffsetSeconds - tzOffsetHours*60*60; // tzOffset % 60; int tzOffsetFractionMinutes = tzOffsetFractionSeconds % 60; int tzOffsetFraction15MinuteIntervalls = tzOffsetFractionMinutes / 15; zoneMask |= ((long)tzOffsetFraction15MinuteIntervalls) << 28; m_innards[1] = m_innards[1] & 0xFFFFFF; long newInnard1AsLong = m_innards[1]; newInnard1AsLong = (newInnard1AsLong & 0xFFFFFF) | zoneMask; m_innards[1] = (int) (newInnard1AsLong & 0xffffffff); m_guessedTimezone = tz; } /** * Sets the date part of this timedate to today and the time part to ALLDAY */ public void setToday() { m_innards = NotesDateTimeUtils.calendarToInnards(Calendar.getInstance(), true, false); m_guessedTimezone = null; } /** * Sets the date part of this timedate to tomorrow and the time part to ALLDAY */ public void setTomorrow() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); m_innards = NotesDateTimeUtils.calendarToInnards(cal, true, false); m_guessedTimezone = null; } /** * Sets the date part of this timedate to yesterday and the time part to ALLDAY */ public void setYesterday() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); m_innards = NotesDateTimeUtils.calendarToInnards(cal, true, false); m_guessedTimezone = null; } /** * Removes the time part of this timedate */ public void setAnyTime() { if (m_innards!=null) { m_innards[0] = NotesConstants.ALLDAY; } else { m_innards = new int[] {NotesConstants.ALLDAY, NotesConstants.ANYDAY}; } m_guessedTimezone = null; } /** * Checks whether the time part of this timedate is a wildcard * * @return true if there is no time */ public boolean isAnyTime() { int[] innards = getInnardsNoClone(); return innards[0] == NotesConstants.ALLDAY; } /** * Removes the date part of this timedate */ public void setAnyDate() { if (m_innards!=null) { m_innards[1] = NotesConstants.ANYDAY; } else { m_innards = new int[] {NotesConstants.ALLDAY, NotesConstants.ANYDAY}; } m_guessedTimezone = null; } /** * Checks whether the date part of this timedate is a wildcard * * @return true if there is no date */ public boolean isAnyDate() { int[] innards = getInnardsNoClone(); return innards[1] == NotesConstants.ANYDAY; } /** * Creates a new {@link NotesTimeDate} instance with the same data as this one */ public NotesTimeDate clone() { return new NotesTimeDate(getInnardsNoClone()); } /** * Modifies the data by adding/subtracting values for year, month, day, hours, minutes and seconds * * @param year positive or negative value or 0 for no change * @param month positive or negative value or 0 for no change * @param day positive or negative value or 0 for no change * @param hours positive or negative value or 0 for no change * @param minutes positive or negative value or 0 for no change * @param seconds positive or negative value or 0 for no change */ public void adjust(int year, int month, int day, int hours, int minutes, int seconds) { int[] innards = getInnardsNoClone(); Calendar cal = NotesDateTimeUtils.innardsToCalendar(innards); if (cal!=null) { boolean modified = false; if (NotesDateTimeUtils.hasDate(cal)) { if (year!=0) { cal.add(Calendar.YEAR, year); modified=true; } if (month!=0) { cal.add(Calendar.MONTH, month); modified=true; } if (day!=0) { cal.add(Calendar.DATE, day); modified=true; } } if (NotesDateTimeUtils.hasTime(cal)) { if (hours!=0) { cal.add(Calendar.HOUR, hours); modified=true; } if (minutes!=0) { cal.add(Calendar.MINUTE, minutes); modified=true; } if (seconds!=0) { cal.add(Calendar.SECOND, seconds); modified=true; } } if (modified) { m_innards = NotesDateTimeUtils.calendarToInnards(cal); } } } /** * Converts the time date to the number of milliseconds since 1/1/70. * * @return milliseconds since January 1, 1970, 00:00:00 GMT */ public long toDateInMillis() { return toCalendar().getTimeInMillis(); } public boolean isBefore(NotesTimeDate o) { return toDateInMillis() < o.toDateInMillis(); } public boolean isAfter(NotesTimeDate o) { return toDateInMillis() > o.toDateInMillis(); } @Override public int compareTo(NotesTimeDate o) { long thisTimeInMillis = toDateInMillis(); long otherTimeInMillis = o.toDateInMillis(); if (thisTimeInMillis < otherTimeInMillis) { return -1; } else if (thisTimeInMillis > otherTimeInMillis) { return 1; } else { return 0; } } /** * Method to clear the {@link NotesTimeDate} value */ public void setMinimum() { NotesTimeDateStruct struct = lazilyCreateStruct(); NotesNativeAPI.get().TimeConstant(NotesConstants.TIMEDATE_MINIMUM, struct); struct.read(); m_innards = struct.Innards.clone(); m_guessedTimezone = null; } /** * Method to set the {@link NotesTimeDate} value to the maximum value. */ public void setMaximum() { NotesTimeDateStruct struct = lazilyCreateStruct(); NotesNativeAPI.get().TimeConstant(NotesConstants.TIMEDATE_MAXIMUM, struct); struct.read(); m_innards = struct.Innards.clone(); m_guessedTimezone = null; } /** * Method to set the {@link NotesTimeDate} value to ANYDAY/ALLDAY */ public void setWildcard() { NotesTimeDateStruct struct = lazilyCreateStruct(); NotesNativeAPI.get().TimeConstant(NotesConstants.TIMEDATE_WILDCARD, struct); struct.read(); m_innards = struct.Innards.clone(); m_guessedTimezone = null; } /** * Converts a {@link NotesTimeDate} to string * * @return string with formatted timedate */ public String toString() { return toString(DateFormat.FULL, TimeFormat.FULL, ZoneFormat.ALWAYS, DateTimeStructure.DATETIME); } /** * Converts a {@link NotesTimeDate} to string with formatting options. * * @param dFormat how to format the date part * @param tFormat how to format the time part * @param zFormat how to format the timezone * @param dtStructure overall structure of the result, e.g. {@link DateTimeStructure} for date only * @return string with formatted timedate */ public String toString(DateFormat dFormat, TimeFormat tFormat, ZoneFormat zFormat, DateTimeStructure dtStructure) { return toString((NotesIntlFormat) null, dFormat, tFormat, zFormat, dtStructure); } /** * Converts a {@link NotesTimeDate} to string with formatting options. * * @param intl the internationalization settings in effect. Can be <code>null</code>, in which case this function works with the client/server default settings for the duration of the call. * @param dFormat how to format the date part * @param tFormat how to format the time part * @param zFormat how to format the timezone * @param dtStructure overall structure of the result, e.g. {@link DateTimeStructure} for date only * @return string with formatted timedate */ public String toString(NotesIntlFormat intl, DateFormat dFormat, TimeFormat tFormat, ZoneFormat zFormat, DateTimeStructure dtStructure) { NotesTimeDateStruct struct = lazilyCreateStruct(); if (struct.Innards==null || struct.Innards.length<2) return ""; if (struct.Innards[0]==0 && struct.Innards[1]==0) return "MINIMUM"; if (struct.Innards[0]==0 && struct.Innards[1]==0xffffff) return "MAXIMUM"; IntlFormatStruct intlStruct = intl==null ? null : intl.getAdapter(IntlFormatStruct.class); NotesTFMTStruct tfmtStruct = NotesTFMTStruct.newInstance(); tfmtStruct.Date = dFormat==null ? NotesConstants.TDFMT_FULL : dFormat.getValue(); tfmtStruct.Time = tFormat==null ? NotesConstants.TTFMT_FULL : tFormat.getValue(); tfmtStruct.Zone = zFormat==null ? NotesConstants.TZFMT_ALWAYS : zFormat.getValue(); tfmtStruct.Structure = dtStructure==null ? NotesConstants.TSFMT_DATETIME : dtStructure.getValue(); tfmtStruct.write(); String txt; int outBufLength = 40; DisposableMemory retTextBuffer = new DisposableMemory(outBufLength); while (true) { ShortByReference retTextLength = new ShortByReference(); short result = NotesNativeAPI.get().ConvertTIMEDATEToText(intlStruct, tfmtStruct.getPointer(), struct, retTextBuffer, (short) retTextBuffer.size(), retTextLength); if (result==1037) { // "Invalid Time or Date Encountered", return empty string like Notes UI does return ""; } if (result!=1033) { // "Output Buffer Overflow" NotesErrorUtils.checkResult(result); } if (result==1033 || (retTextLength.getValue() >= retTextBuffer.size())) { retTextBuffer.dispose(); outBufLength = outBufLength * 2; retTextBuffer = new DisposableMemory(outBufLength); continue; } else { txt = NotesStringUtils.fromLMBCS(retTextBuffer, retTextLength.getValue()); break; } } retTextBuffer.dispose(); return txt; } /** * Parses a timedate string to a {@link NotesTimeDate} * * @param dateTimeStr timedate string * @return timedate */ public static NotesTimeDate fromString(String dateTimeStr) { return fromString((NotesIntlFormat) null, dateTimeStr); } /** * Parses a timedate string to a {@link NotesTimeDate} * * @param intl international settings to be used for parsing * @param dateTimeStr timedate string * @return timedate */ public static NotesTimeDate fromString(NotesIntlFormat intl, String dateTimeStr) { Memory dateTimeStrLMBCS = NotesStringUtils.toLMBCS(dateTimeStr, true); //convert method expects a pointer to the date string in memory Memory dateTimeStrLMBCSPtr = new Memory(Pointer.SIZE); dateTimeStrLMBCSPtr.setPointer(0, dateTimeStrLMBCS); IntlFormatStruct intlStruct = intl==null ? null : intl.getAdapter(IntlFormatStruct.class); DisposableMemory retTimeDateMem = new DisposableMemory(NotesConstants.timeDateSize); NotesTimeDateStruct retTimeDate = NotesTimeDateStruct.newInstance(retTimeDateMem); short result = NotesNativeAPI.get().ConvertTextToTIMEDATE(intlStruct, null, dateTimeStrLMBCSPtr, NotesConstants.MAXALPHATIMEDATE, retTimeDate); NotesErrorUtils.checkResult(result); retTimeDate.read(); int[] innards = retTimeDate.Innards; NotesTimeDate td = new NotesTimeDate(innards); retTimeDateMem.dispose(); return td; } }
package it.asg.hustle; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.HttpMethod; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class FacebookActivity extends AppCompatActivity { String logtag = "ActivityFacebook"; LoginButton loginButton; CallbackManager callbackManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_facebook); //facebook login button callbackManager = new CallbackManager.Factory().create(); loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.setReadPermissions("user_friends"); // Other app specific specialization // Callback registration loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { // App code Log.d(logtag, "onSuccess Facebook"); /* make the API call */ new GraphRequest( AccessToken.getCurrentAccessToken(), "/me/friends", null, HttpMethod.GET, new GraphRequest.Callback() { public void onCompleted(GraphResponse response) { /* handle the result */ Log.d(logtag,response.toString()); } } ).executeAsync(); } @Override public void onCancel() { // App code Log.d(logtag, "onCancel Facebook"); } @Override public void onError(FacebookException exception) { // App code Log.d(logtag, "onError Facebook"); } }); //end facebook login button } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_facebook, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
/** * For storing and syncing entities with Simperium. To create a bucket you use * the Simperium.bucket instance method: * * // Initialize simperium * Simperium simperium = new Simperium(...); * Bucket notesBucket = simperium.bucket("notes", Note.class); * * Simperium creates a Bucket instance that is backed by a Channel. The Channel * takes care of the network operations by communicating with the WebSocketManager. * * TODO: A bucket should be able to be queried: "give me all your entities". This * potentially needs to be flexible to allow storage mechanisms way to extend how * things can be queried. * * Buckets should also provide a way for other objects to listen for when entities * get added, updated or removed due to operations coming in from the network. * * A bucket should also provide an interface that can listen to local changes so * that the channel can see when entities are changed on the client and push them * out to Simperium. * */ package com.simperium.client; import android.database.Cursor; import android.database.CursorWrapper; import com.simperium.SimperiumException; import com.simperium.client.ObjectCacheProvider.ObjectCache; import com.simperium.storage.StorageProvider.BucketStore; import com.simperium.util.JSONDiff; import com.simperium.util.Logger; import com.simperium.util.Uuid; import org.json.JSONException; import org.json.JSONObject; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.Executor; public class Bucket<T extends Syncable> { public interface Channel { public Change queueLocalChange(Syncable object); public Change queueLocalDeletion(Syncable object); public void log(int level, CharSequence message); public void start(); public void stop(); public void reset(); } public interface OnBeforeUpdateObjectListener<T extends Syncable> { void onBeforeUpdateObject(Bucket<T> bucket, T object); } public interface OnSaveObjectListener<T extends Syncable> { void onSaveObject(Bucket<T> bucket, T object); } public interface OnDeleteObjectListener<T extends Syncable> { void onDeleteObject(Bucket<T> bucket, T object); } public interface OnNetworkChangeListener<T extends Syncable> { void onChange(Bucket<T> bucket, ChangeType type, String key); } public interface Listener<T extends Syncable> extends OnSaveObjectListener<T>, OnDeleteObjectListener<T>, OnNetworkChangeListener<T>, OnBeforeUpdateObjectListener<T> { // implements all listener methods } public enum ChangeType { REMOVE, MODIFY, INDEX, RESET } public static final String TAG="Simperium.Bucket"; // The name used for the Simperium namespace private String name; // User provides the access token for authentication private User user; // The channel that provides networking and change processing. private Channel channel; // For storing the bucket listeners private Set<OnSaveObjectListener<T>> onSaveListeners = Collections.synchronizedSet(new HashSet<OnSaveObjectListener<T>>()); private Set<OnDeleteObjectListener<T>> onDeleteListeners = Collections.synchronizedSet(new HashSet<OnDeleteObjectListener<T>>()); private Set<OnBeforeUpdateObjectListener<T>> onBeforeUpdateListeners = Collections.synchronizedSet(new HashSet<OnBeforeUpdateObjectListener<T>>()); private Set<OnNetworkChangeListener<T>> onChangeListeners = Collections.synchronizedSet(new HashSet<OnNetworkChangeListener<T>>()); private BucketStore<T> storage; private BucketSchema<T> schema; private GhostStorageProvider ghostStore; private ObjectCache<T> cache; final private Executor executor; /** * Represents a Simperium bucket which is a namespace where an app syncs a user's data * @param name the name to use for the bucket namespace * @param user provides a way to namespace data if a different user logs in */ public Bucket(Executor executor, String name, BucketSchema<T>schema, User user, BucketStore<T> storage, GhostStorageProvider ghostStore, ObjectCache<T> cache) throws BucketNameInvalid { this.executor = executor; this.name = name; this.user = user; this.storage = storage; this.ghostStore = ghostStore; this.schema = schema; this.cache = cache; validateBucketName(name); } public void log(int level, CharSequence message) { if (channel == null) return; channel.log(level, message); } public void log(CharSequence message) { log(ChannelProvider.LOG_VERBOSE, message); } /** * Return the instance of this bucket's schema */ public BucketSchema<T> getSchema(){ return schema; } /** * Return the user for this bucket */ public User getUser(){ return user; } /** * Cursor for bucket data */ public interface ObjectCursor<T extends Syncable> extends Cursor { /** * Return the current item's siperium key */ public String getSimperiumKey(); /** * Return the object for the current index in the cursor */ public T getObject(); } private class BucketCursor extends CursorWrapper implements ObjectCursor<T> { private ObjectCursor<T> cursor; BucketCursor(ObjectCursor<T> cursor){ super(cursor); this.cursor = cursor; } @Override public String getSimperiumKey(){ return cursor.getSimperiumKey(); } @Override public T getObject(){ String key = getSimperiumKey(); T object = cache.get(key); if (object != null) { return object; } object = cursor.getObject(); try { Ghost ghost = ghostStore.getGhost(Bucket.this, key); object.setGhost(ghost); } catch (GhostMissingException e) { object.setGhost(new Ghost(key, 0, new JSONObject())); } object.setBucket(Bucket.this); cache.put(key, object); return object; } } /** * Tell the bucket to sync changes. */ public void sync(final T object){ executor.execute(new Runnable(){ @Override public void run(){ Boolean modified = object.isModified(); storage.save(object, schema.indexesFor(object)); channel.queueLocalChange(object); if (modified){ // Notify listeners that an object has been saved, this was // triggered locally notifyOnSaveListeners(object); } } }); } /** * Delete the object from the bucket. * * @param object the Syncable to remove from the bucket */ public void remove(T object){ remove(object, true); } /** * Remove the object from the bucket. If isLocal is true, this will queue * an operation to sync with the Simperium service. * * @param object The Syncable to remove from the bucket * @param isLocal if the operation originates from this client */ private void remove(final T object, final boolean isLocal){ cache.remove(object.getSimperiumKey()); executor.execute(new Runnable() { @Override public void run() { if (isLocal) channel.queueLocalDeletion(object); storage.delete(object); notifyOnDeleteListeners(object); } }); } /** * Given the key for an object in the bucket, remove it if it exists */ private void removeObjectWithKey(String key) throws BucketObjectMissingException { T object = get(key); if (object != null) { // this will call onObjectRemoved on the listener remove(object, false); } } /** * Get the bucket's namespace * @return (String) bucket's namespace */ public String getName(){ return name; } public String getRemoteName(){ return schema.getRemoteName(); } public Boolean hasChangeVersion(){ return ghostStore.hasChangeVersion(this); } public Boolean hasChangeVersion(String version){ return ghostStore.hasChangeVersion(this, version); } public String getChangeVersion(){ String version = ghostStore.getChangeVersion(this); if (version == null) { version = ""; } return version; } public void indexComplete(String changeVersion){ setChangeVersion(changeVersion); notifyOnNetworkChangeListeners(ChangeType.INDEX); } public void setChangeVersion(String version){ ghostStore.setChangeVersion(this, version); } // starts tracking the object /** * Add an object to the bucket so simperium can start syncing it. Must * conform to the Diffable interface. So simperium can diff/apply patches. * */ public void add(T object){ if (!object.getBucket().equals(this)) { object.setBucket(this); } } protected T buildObject(String key, JSONObject properties){ return buildObject(new Ghost(key, 0, properties)); } protected T buildObject(String key){ return buildObject(key, new JSONObject()); } protected T buildObject(Ghost ghost){ T object = schema.buildWithDefaults(ghost.getSimperiumKey(), JSONDiff.deepCopy(ghost.getDiffableValue())); object.setGhost(ghost); object.setBucket(this); return object; } public int count(){ return count(query()); } public int count(Query<T> query){ return storage.count(query); } /** * Find all objects */ public ObjectCursor<T> allObjects(){ return new BucketCursor(storage.all()); } /** * Search using a query */ public ObjectCursor<T> searchObjects(Query<T> query){ return new BucketCursor(storage.search(query)); } /** * Support cancelation */ /** * Build a query for this object */ public Query<T> query(){ return new Query<T>(this); } /** * Get a single object object that matches key */ public T get(String key) throws BucketObjectMissingException { // If the cache has it, return the cached object T object = cache.get(key); if (object != null) { return object; } // Datastore constructs the object for us Ghost ghost = null; try { ghost = ghostStore.getGhost(this, key); } catch (GhostMissingException e) { throw(new BucketObjectMissingException(String.format("Bucket %s does not have object %s", getName(), key))); } object = storage.get(key); if (object == null) { throw(new BucketObjectMissingException(String.format("Storage provider for bucket:%s did not have object %s", getName(), key))); } Logger.log(TAG, String.format("Fetched ghost for %s %s", key, ghost)); object.setBucket(this); object.setGhost(ghost); cache.put(key, object); return object; } /** * Get an object by its key, should we throw an error if the object isn't * there? */ public T getObject(String uuid) throws BucketObjectMissingException { return get(uuid); } /** * Returns a new objecty tracked by this bucket */ public T newObject(){ try { return newObject(uuid()); } catch (BucketObjectNameInvalid e) { throw new RuntimeException(e); } } /** * Returns a new object with the given uuid * return null if the uuid exists? */ public T newObject(String key) throws BucketObjectNameInvalid { return insertObject(key, new JSONObject()); } public T insertObject(String key, JSONObject properties) throws BucketObjectNameInvalid { if (key == null) throw new BucketObjectNameInvalid(key); String name = key.trim(); validateObjectName(name); T object = buildObject(name, properties); object.setBucket(this); Ghost ghost = new Ghost(name, 0, new JSONObject()); object.setGhost(ghost); ghostStore.saveGhost(this, ghost); cache.put(name, object); return object; } /** * Add object from new ghost data, no corresponding change version so this * came from an index request */ protected void addObjectWithGhost(final Ghost ghost){ executor.execute(new Runnable() { @Override public void run(){ ghostStore.saveGhost(Bucket.this, ghost); T object = buildObject(ghost); addObject(object); } }); } /** * Update the ghost data */ protected void updateObjectWithGhost(final Ghost ghost){ ghostStore.saveGhost(Bucket.this, ghost); T object = buildObject(ghost); updateObject(object); } protected void updateGhost(final Ghost ghost, final Runnable complete){ executor.execute(new Runnable(){ @Override public void run() { // find the object try { T object = get(ghost.getSimperiumKey()); if (object.isModified()) { // TODO: we already have the object, how do we handle if we have modifications? } else { updateObjectWithGhost(ghost); } } catch (BucketObjectMissingException e) { // The object doesn't exist, insert the new object updateObjectWithGhost(ghost); } if (complete != null) { complete.run(); } } }); } protected Ghost getGhost(String key) throws GhostMissingException { return ghostStore.getGhost(this, key); } /** * Add a new object with corresponding change version */ protected void addObject(String changeVersion, T object){ addObject(object); setChangeVersion(changeVersion); } /** * Adds a new object to the bucket */ protected void addObject(T object){ if (object.getGhost() == null) { object.setGhost(new Ghost(object.getSimperiumKey())); } // Allows the storage provider to persist the object Boolean notifyListeners = true; if (!object.getBucket().equals(this)) { notifyListeners = true; } object.setBucket(this); storage.save(object, schema.indexesFor(object)); // notify listeners that an object has been added } /** * Updates an existing object */ protected void updateObject(T object){ object.setBucket(this); storage.save(object, schema.indexesFor(object)); } protected void updateObject(String changeVersion, T object){ updateObject(object); setChangeVersion(changeVersion); } public void addListener(Listener<T> listener){ addOnSaveObjectListener(listener); addOnBeforeUpdateObjectListener(listener); addOnDeleteObjectListener(listener); addOnNetworkChangeListener(listener); } public void removeListener(Listener<T> listener){ removeOnSaveObjectListener(listener); removeOnBeforeUpdateObjectListener(listener); removeOnDeleteObjectListener(listener); removeOnNetworkChangeListener(listener); } public void addOnSaveObjectListener(OnSaveObjectListener<T> listener){ onSaveListeners.add(listener); } public void removeOnSaveObjectListener(OnSaveObjectListener<T> listener){ onSaveListeners.remove(listener); } public void addOnDeleteObjectListener(OnDeleteObjectListener<T> listener){ onDeleteListeners.add(listener); } public void removeOnDeleteObjectListener(OnDeleteObjectListener<T> listener){ onDeleteListeners.remove(listener); } public void addOnNetworkChangeListener(OnNetworkChangeListener<T> listener){ onChangeListeners.add(listener); } public void removeOnNetworkChangeListener(OnNetworkChangeListener<T> listener){ onChangeListeners.remove(listener); } public void addOnBeforeUpdateObjectListener(OnBeforeUpdateObjectListener<T> listener){ onBeforeUpdateListeners.add(listener); } public void removeOnBeforeUpdateObjectListener(OnBeforeUpdateObjectListener<T> listener){ onBeforeUpdateListeners.remove(listener); } public void notifyOnSaveListeners(T object){ Set<OnSaveObjectListener<T>> notify = new HashSet<OnSaveObjectListener<T>>(onSaveListeners); Iterator<OnSaveObjectListener<T>> iterator = notify.iterator(); while(iterator.hasNext()) { OnSaveObjectListener<T> listener = iterator.next(); try { listener.onSaveObject(this, object); } catch(Exception e) { Logger.log(TAG, String.format("Listener failed onSaveObject %s", listener), e); } } } public void notifyOnDeleteListeners(T object){ Set<OnDeleteObjectListener<T>> notify = new HashSet<OnDeleteObjectListener<T>>(onDeleteListeners); Iterator<OnDeleteObjectListener<T>> iterator = notify.iterator(); while(iterator.hasNext()) { OnDeleteObjectListener<T> listener = iterator.next(); try { listener.onDeleteObject(this, object); } catch(Exception e) { Logger.log(TAG, String.format("Listener failed onDeleteObject %s", listener), e); } } } public void notifyOnBeforeUpdateObjectListeners(T object){ Set<OnBeforeUpdateObjectListener<T>> notify = new HashSet<OnBeforeUpdateObjectListener<T>>(onBeforeUpdateListeners); Iterator<OnBeforeUpdateObjectListener<T>> iterator = notify.iterator(); while(iterator.hasNext()) { OnBeforeUpdateObjectListener<T> listener = iterator.next(); try { listener.onBeforeUpdateObject(this, object); } catch(Exception e) { Logger.log(TAG, String.format("Listener failed onBeforeUpdateObject %s", listener), e); } } } public void notifyOnNetworkChangeListeners(ChangeType type){ notifyOnNetworkChangeListeners(type, null); } public void notifyOnNetworkChangeListeners(ChangeType type, String key){ Set<OnNetworkChangeListener> notify = new HashSet<OnNetworkChangeListener>(onChangeListeners); Iterator<OnNetworkChangeListener> iterator = notify.iterator(); while(iterator.hasNext()) { OnNetworkChangeListener listener = iterator.next(); try { listener.onChange(this, type, key); } catch(Exception e) { Logger.log(TAG, String.format("Listener failed onChange %s", listener), e); } } } public void setChannel(Channel channel){ this.channel = channel; } /** * Initialize the bucket to start tracking changes. */ public void start(){ channel.start(); } public void stop(){ channel.stop(); } public void reset(){ storage.reset(); // Clear the ghost store ghostStore.resetBucket(this); channel.reset(); stop(); notifyOnNetworkChangeListeners(ChangeType.RESET); } /** * Does bucket have at least the requested version? */ public Boolean containsKey(String key){ return ghostStore.hasGhost(this, key); } /** * Ask storage if it has at least the requested version or newer */ public Boolean hasKeyVersion(String key, Integer version){ try { Ghost ghost = ghostStore.getGhost(this, key); return ghost.getVersion().equals(version); } catch (GhostMissingException e) { // we don't have the ghost return false; } } /** * Which version of the key do we have */ public Integer getKeyVersion(String key) throws GhostMissingException { Ghost ghost = ghostStore.getGhost(this, key); return ghost.getVersion(); } /** * Submit a Runnable to this Bucket's executor */ public void executeAsync(Runnable task){ executor.execute(task); } public String uuid(){ String key; do { key = Uuid.uuid(); } while(containsKey(key)); return key; } public Ghost acknowledgeChange(RemoteChange remoteChange, Change change) throws RemoteChangeInvalidException { Ghost ghost = null; if (!remoteChange.isRemoveOperation()) { try { T object = get(remoteChange.getKey()); // apply the diff to the underyling object ghost = remoteChange.apply(object.getGhost()); ghostStore.saveGhost(this, ghost); // update the object's ghost object.setGhost(ghost); } catch (BucketObjectMissingException e) { throw(new RemoteChangeInvalidException(remoteChange, e)); } } else { ghostStore.deleteGhost(this, remoteChange.getKey()); } setChangeVersion(remoteChange.getChangeVersion()); remoteChange.setApplied(); // TODO: remove changes don't need ghosts, need to rethink this a bit return ghost; } public Ghost applyRemoteChange(RemoteChange change) throws RemoteChangeInvalidException { Ghost updatedGhost = null; if (change.isRemoveOperation()) { try { removeObjectWithKey(change.getKey()); ghostStore.deleteGhost(this, change.getKey()); } catch (BucketObjectMissingException e) { throw(new RemoteChangeInvalidException(change, e)); } } else { try { T object = null; Boolean isNew = false; if (change.isAddOperation()) { object = newObject(change.getKey()); isNew = true; } else { object = getObject(change.getKey()); isNew = false; notifyOnBeforeUpdateObjectListeners(object); } Ghost ghost = object.getGhost(); JSONObject localModifications = null; JSONObject currentProperties = ghost.getDiffableValue(); try { localModifications = JSONDiff.diff(currentProperties, object.getDiffableValue()); } catch (JSONException e) { localModifications = new JSONObject(); } // updates the ghost and sets it on the object updatedGhost = change.apply(ghost); JSONObject updatedProperties = JSONDiff.deepCopy(updatedGhost.getDiffableValue()); // persist the ghost to storage ghostStore.saveGhost(this, updatedGhost); object.setGhost(updatedGhost); // allow the schema to update the object instance with the new if (isNew) { schema.updateWithDefaults(object, updatedProperties); addObject(object); } else { if (localModifications != null && localModifications.length() > 0) { try { JSONObject incomingDiff = change.getPatch(); JSONObject localDiff = localModifications.getJSONObject(JSONDiff.DIFF_VALUE_KEY); JSONObject transformedDiff = JSONDiff.transform(localDiff, incomingDiff, currentProperties); updatedProperties = JSONDiff.apply(updatedProperties, transformedDiff); } catch (JSONException e) { // could not transform properties // continue with updated properties } } schema.update(object, updatedProperties); updateObject(object); } } catch(SimperiumException e) { Logger.log(TAG, String.format("Unable to apply remote change %s", change), e); throw(new RemoteChangeInvalidException(change, e)); } } setChangeVersion(change.getChangeVersion()); change.setApplied(); ChangeType type = change.isRemoveOperation() ? ChangeType.REMOVE : ChangeType.MODIFY; notifyOnNetworkChangeListeners(type, change.getKey()); return updatedGhost; } static public final String BUCKET_OBJECT_NAME_REGEX = "^[a-zA-Z0-9_\\.\\-%@]{1,256}$"; public static void validateObjectName(String name) throws BucketObjectNameInvalid { if (name == null || !name.matches(BUCKET_OBJECT_NAME_REGEX)) { throw new BucketObjectNameInvalid(name); } } static public final String BUCKET_NAME_REGEX = "^[a-zA-Z0-9_\\.\\-%]{1,64}$"; public static void validateBucketName(String name) throws BucketNameInvalid { if (name == null || !name.matches(BUCKET_NAME_REGEX)) { throw new BucketNameInvalid(name); } } }
package com.datastax.driver.core; import java.util.*; import com.google.common.base.Joiner; import org.testng.annotations.Test; import static com.datastax.driver.core.DataTypeIntegrationTest.getSampleData; import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE; import static com.datastax.driver.core.TestUtils.versionCheck; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; public class TupleTest extends CCMBridge.PerClassSingleNodeCluster { @Override protected Collection<String> getTableDefinitions() { versionCheck(2.1, 0, "This will only work with Cassandra 2.1.0"); return Arrays.asList("CREATE TABLE t (k int PRIMARY KEY, v tuple<int, text, float>)"); } @Test(groups = "short") public void simpleValueTest() throws Exception { TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat()); TupleValue v = t.newValue(); v.setInt(0, 1); v.setString(1, "a"); v.setFloat(2, 1.0f); assertEquals(v.getType().getComponentTypes().size(), 3); assertEquals(v.getType().getComponentTypes().get(0), DataType.cint()); assertEquals(v.getType().getComponentTypes().get(1), DataType.text()); assertEquals(v.getType().getComponentTypes().get(2), DataType.cfloat()); assertEquals(v.getInt(0), 1); assertEquals(v.getString(1), "a"); assertEquals(v.getFloat(2), 1.0f); assertEquals(t.format(v), "(1, 'a', 1.0)"); } @Test(groups = "short") public void simpleWriteReadTest() throws Exception { try { session.execute("USE " + SIMPLE_KEYSPACE); PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)"); PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?"); TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat()); int k = 1; TupleValue v = t.newValue(1, "a", 1.0f); session.execute(ins.bind(k, v)); TupleValue v2 = session.execute(sel.bind(k)).one().getTupleValue("v"); assertEquals(v2, v); // Test simple statement interpolation k = 2; v = t.newValue(2, "b", 2.0f); session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v); v2 = session.execute(sel.bind(k)).one().getTupleValue("v"); assertEquals(v2, v); } catch (Exception e) { errorOut(); throw e; } } /** * Basic test of tuple functionality. * Original code found in python-driver:integration.standard.test_types.py:test_tuple_type * @throws Exception */ @Test(groups = "short") public void tupleTypeTest() throws Exception { try { session.execute("CREATE KEYSPACE test_tuple_type " + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); session.execute("USE test_tuple_type"); session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b tuple<ascii, int, boolean>)"); TupleType t = TupleType.of(DataType.ascii(), DataType.cint(), DataType.cboolean()); // test non-prepared statement TupleValue complete = t.newValue("foo", 123, true); session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete); TupleValue r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); assertEquals(r, complete); // test incomplete tuples try { TupleValue partial = t.newValue("bar", 456); fail(); } catch (IllegalArgumentException e) {} // test incomplete tuples with new TupleType TupleType t1 = TupleType.of(DataType.ascii(), DataType.cint()); TupleValue partial = t1.newValue("bar", 456); TupleValue partionResult = t.newValue("bar", 456, null); session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial); r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); assertEquals(r, partionResult); // test single value tuples try { TupleValue subpartial = t.newValue("zoo"); fail(); } catch (IllegalArgumentException e) {} // test single value tuples with new TupleType TupleType t2 = TupleType.of(DataType.ascii()); TupleValue subpartial = t2.newValue("zoo"); TupleValue subpartialResult = t.newValue("zoo", null, null); session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial); r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); assertEquals(r, subpartialResult); // test prepared statements PreparedStatement prepared = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); session.execute(prepared.bind(3, complete)); session.execute(prepared.bind(4, partial)); session.execute(prepared.bind(5, subpartial)); prepared = session.prepare("SELECT b FROM mytable WHERE a=?"); assertEquals(session.execute(prepared.bind(3)).one().getTupleValue("b"), complete); assertEquals(session.execute(prepared.bind(4)).one().getTupleValue("b"), partionResult); assertEquals(session.execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult); } catch (Exception e) { errorOut(); throw e; } } /** * Test tuple types of lengths of 1, 2, 3, and 384 to ensure edge cases work * as expected. * Original code found in python-driver:integration.standard.test_types.py:test_tuple_type_varying_lengths * * @throws Exception */ @Test(groups = "short") public void tupleTestTypeVaryingLengths() throws Exception { try { session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); session.execute("USE test_tuple_type_varying_lengths"); // programmatically create the table with tuples of said sizes int[] lengths = {1, 2, 3, 384}; ArrayList<String> valueSchema = new ArrayList<String>(); for (int i : lengths) { ArrayList<String> ints = new ArrayList<String>(); for (int j = 0; j < i; ++j) { ints.add("int"); } valueSchema.add(String.format(" v_%d tuple<%s>", i, Joiner.on(',').join(ints))); } session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema))); // insert tuples into same key using different columns // and verify the results for (int i : lengths) { // create tuple ArrayList<DataType> dataTypes = new ArrayList<DataType>(); ArrayList<Integer> values = new ArrayList<Integer>(); for (int j = 0; j < i; ++j) { dataTypes.add(DataType.cint()); values.add(j); } TupleType t = new TupleType(dataTypes); TupleValue createdTuple = t.newValue(values.toArray()); // write tuple session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); // read tuple TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i)); assertEquals(r, createdTuple); } } catch (Exception e) { errorOut(); throw e; } } /** * Ensure tuple subtypes are appropriately handled. * Original code found in python-driver:integration.standard.test_types.py:test_tuple_subtypes * * @throws Exception */ @Test(groups = "short") public void tupleSubtypesTest() throws Exception { // hold onto constants ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(); for (DataType dt : DataType.allPrimitiveTypes()) { // skip counter types since counters are not allowed inside tuples if (dt == DataType.counter()) continue; DATA_TYPE_PRIMITIVES.add(dt); } HashMap<DataType, Object> SAMPLE_DATA = getSampleData(); try { session.execute("CREATE KEYSPACE test_tuple_subtypes " + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); session.execute("USE test_tuple_subtypes"); // programmatically create the table with a tuple of all datatypes session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v tuple<%s>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES))); // insert tuples into same key using different columns // and verify the results int i = 1; for (DataType datatype : DATA_TYPE_PRIMITIVES) { // create tuples to be written and ensure they match with the expected response // responses have trailing None values for every element that has not been written ArrayList<DataType> dataTypes = new ArrayList<DataType>(); ArrayList<DataType> completeDataTypes = new ArrayList<DataType>(); ArrayList<Object> createdValues = new ArrayList<Object>(); ArrayList<Object> completeValues = new ArrayList<Object>(); // create written portion of the arrays for (int j = 0; j < i; ++j) { dataTypes.add(DATA_TYPE_PRIMITIVES.get(j)); completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j)); createdValues.add(SAMPLE_DATA.get(DATA_TYPE_PRIMITIVES.get(j))); completeValues.add(SAMPLE_DATA.get(DATA_TYPE_PRIMITIVES.get(j))); } // complete portion of the arrays needed for trailing nulls for (int j = 0; j < DATA_TYPE_PRIMITIVES.size() - i; ++j) { completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(i + j)); completeValues.add(null); } // actually create the tuples TupleType t = new TupleType(dataTypes); TupleType t2 = new TupleType(completeDataTypes); TupleValue createdTuple = t.newValue(createdValues.toArray()); TupleValue completeTuple = t2.newValue(completeValues.toArray()); // write tuple session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple); // read tuple TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v"); assertEquals(r.toString(), completeTuple.toString()); ++i; } } catch (Exception e) { errorOut(); throw e; } } /** * Ensure tuple subtypes are appropriately handled for maps, sets, and lists. * Original code found in python-driver:integration.standard.test_types.py:test_tuple_non_primitive_subtypes * * @throws Exception */ @Test(groups = "short") public void tupleNonPrimitiveSubTypesTest() throws Exception { // hold onto constants ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(); for (DataType dt : DataType.allPrimitiveTypes()) { // skip counter types since counters are not allowed inside tuples if (dt == DataType.counter()) continue; DATA_TYPE_PRIMITIVES.add(dt); } ArrayList<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = new ArrayList<DataType.Name>(Arrays.asList(DataType.Name.MAP, DataType.Name.SET, DataType.Name.LIST)); HashMap<DataType, Object> SAMPLE_DATA = getSampleData(); try { session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); session.execute("USE test_tuple_non_primitive_subtypes"); ArrayList<String> values = new ArrayList<String>(); //create list values for (DataType datatype : DATA_TYPE_PRIMITIVES) { values.add(String.format("v_%s tuple<list<%s>>", values.size(), datatype)); } // create set values for (DataType datatype : DATA_TYPE_PRIMITIVES) { values.add(String.format("v_%s tuple<set<%s>>", values.size(), datatype)); } // create map values for (DataType datatype : DATA_TYPE_PRIMITIVES) { DataType dataType1 = datatype; DataType dataType2 = datatype; if (datatype == DataType.blob()) { // unhashable type: 'bytearray' dataType1 = DataType.ascii(); } values.add(String.format("v_%s tuple<map<%s, %s>>", values.size(), dataType1, dataType2)); } // create table session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values))); int i = 1; // test tuple<list<datatype>> for (DataType datatype : DATA_TYPE_PRIMITIVES) { // create tuple ArrayList<DataType> dataTypes = new ArrayList<DataType>(); ArrayList<Object> createdValues = new ArrayList<Object>(); dataTypes.add(DataType.list(datatype)); createdValues.add(Arrays.asList(SAMPLE_DATA.get(datatype))); TupleType t = new TupleType(dataTypes); TupleValue createdTuple = t.newValue(createdValues.toArray()); // write tuple session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); // read tuple TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) .one().getTupleValue(String.format("v_%s", i)); assertEquals(r.toString(), createdTuple.toString()); ++i; } // test tuple<set<datatype>> for (DataType datatype : DATA_TYPE_PRIMITIVES) { // create tuple ArrayList<DataType> dataTypes = new ArrayList<DataType>(); ArrayList<Object> createdValues = new ArrayList<Object>(); dataTypes.add(DataType.list(datatype)); createdValues.add(new HashSet<Object>(Arrays.asList(SAMPLE_DATA.get(datatype)))); TupleType t = new TupleType(dataTypes); TupleValue createdTuple = t.newValue(createdValues.toArray()); // write tuple session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); // read tuple TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) .one().getTupleValue(String.format("v_%s", i)); assertEquals(r.toString(), createdTuple.toString()); ++i; } // test tuple<map<datatype, datatype>> for (DataType datatype : DATA_TYPE_PRIMITIVES) { // create tuple ArrayList<DataType> dataTypes = new ArrayList<DataType>(); ArrayList<Object> createdValues = new ArrayList<Object>(); HashMap<Object, Object> hm = new HashMap<Object, Object>(); if (datatype == DataType.blob()) hm.put(SAMPLE_DATA.get(DataType.ascii()), SAMPLE_DATA.get(datatype)); else hm.put(SAMPLE_DATA.get(datatype), SAMPLE_DATA.get(datatype)); dataTypes.add(DataType.list(datatype)); createdValues.add(hm); TupleType t = new TupleType(dataTypes); TupleValue createdTuple = t.newValue(createdValues.toArray()); // write tuple session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); // read tuple TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) .one().getTupleValue(String.format("v_%s", i)); assertEquals(r.toString(), createdTuple.toString()); ++i; } } catch (Exception e) { errorOut(); throw e; } } /** * Helper method for creating nested tuple schema * @param depth * @return */ private String nestedTuplesSchemaHelper(int depth) { if (depth == 0) return "int"; else return String.format("tuple<%s>", nestedTuplesSchemaHelper(depth - 1)); } /** * Helper method for creating nested tuples * @param depth * @return */ private TupleValue nestedTuplesCreatorHelper(int depth) { if (depth == 1) { TupleType baseTuple = TupleType.of(DataType.cint()); return baseTuple.newValue(303); } else { TupleValue innerTuple = nestedTuplesCreatorHelper(depth - 1); TupleType t = TupleType.of(innerTuple.getType()); return t.newValue(innerTuple); } } /** * Ensure nested are appropriately handled. * Original code found in python-driver:integration.standard.test_types.py:test_nested_tuples * * @throws Exception */ @Test(groups = "short") public void nestedTuplesTest() throws Exception { // hold onto constants ArrayList<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(); for (DataType dt : DataType.allPrimitiveTypes()) { // skip counter types since counters are not allowed inside tuples if (dt == DataType.counter()) continue; DATA_TYPE_PRIMITIVES.add(dt); } HashMap<DataType, Object> SAMPLE_DATA = getSampleData(); try { session.execute("CREATE KEYSPACE test_nested_tuples " + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); session.execute("USE test_nested_tuples"); // create a table with multiple sizes of nested tuples session.execute(String.format("CREATE TABLE mytable (" + "k int PRIMARY KEY, " + "v_1 %s, " + "v_2 %s, " + "v_3 %s, " + "v_128 %s)", nestedTuplesSchemaHelper(1), nestedTuplesSchemaHelper(2), nestedTuplesSchemaHelper(3), nestedTuplesSchemaHelper(128))); for (int i : Arrays.asList(1, 2, 3, 128)) { // create tuple TupleValue createdTuple = nestedTuplesCreatorHelper(i); // write tuple session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple); // verify tuple was written and read correctly TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i) .one().getTupleValue(String.format("v_%s", i)); assertEquals(r.toString(), createdTuple.toString()); } } catch (Exception e) { errorOut(); throw e; } } }
package org.commcare.android.util; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.webkit.MimeTypeMap; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.commcare.android.database.UserStorageClosedException; import org.javarosa.core.model.User; import org.commcare.android.io.DataSubmissionEntity; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.mime.EncryptedFileBody; import org.commcare.android.net.HttpRequestGenerator; import org.commcare.android.tasks.DataSubmissionListener; import org.javarosa.core.io.StreamsUtil.InputIOException; import org.javarosa.core.services.Logger; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; public class FormUploadUtil { private static final String TAG = FormUploadUtil.class.getSimpleName(); /** * Everything worked great! */ public static final long FULL_SUCCESS = 0; /** * There was a problem with the server's response */ public static final long FAILURE = 2; /** * There was a problem with the transport layer during transit */ public static final long TRANSPORT_FAILURE = 4; /** * There is a problem with this record that prevented submission success */ public static final long RECORD_FAILURE = 8; private static final long MAX_BYTES = (5 * 1048576) - 1024; private static final String[] SUPPORTED_FILE_EXTS = {".xml", ".jpg", "jpeg", ".3gpp", ".3gp", ".3ga", ".3g2", ".mp3", ".wav", ".amr", ".mp4", ".3gp2", ".mpg4", ".mpeg4", ".m4v", ".mpg", ".mpeg", ".qcp", ".ogg"}; public static Cipher getDecryptCipher(SecretKeySpec key) { Cipher cipher; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher; //TODO: Something smart here; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { e.printStackTrace(); } return null; } /** * Send unencrypted data to the server without user facing progress * reporting. * * @param submissionNumber For progress reporting * @param folder All supported files in this folder will be * attached to the submission * @param url Submission server url * @param user Used to build the http post * @return Submission status code * @throws FileNotFoundException Is raised if xml file isn't found on the * file-system */ public static long sendInstance(int submissionNumber, File folder, String url, User user) throws FileNotFoundException { return FormUploadUtil.sendInstance(submissionNumber, folder, null, url, null, user); } /** * Send data to the server, encrypting xml files and reporting progress * along the way. * * @param submissionNumber For progress reporting * @param folder All supported files in this folder will be * attached to the submission * @param key For encrypting xml files * @param url Submission server url * @param listener Used to report progress to the calling task * @param user Used to build the http post * @return Submission status code * @throws FileNotFoundException Is raised if xml file isn't found on the * file-system */ public static long sendInstance(int submissionNumber, File folder, SecretKeySpec key, String url, AsyncTask listener, User user) throws FileNotFoundException { boolean hasListener = false; DataSubmissionListener myListener = null; if (listener instanceof DataSubmissionListener) { hasListener = true; myListener = (DataSubmissionListener)listener; } File[] files = folder.listFiles(); if (files == null) { // make sure external storage is available to begin with. String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { // If so, just bail as if the user had logged out. throw new UserStorageClosedException("External Storage Removed"); } else { throw new FileNotFoundException("No directory found at: " + folder.getAbsoluteFile()); } } // If we're listening, figure out how much (roughly) we have to send long bytes = estimateUploadBytes(files); if (hasListener) { myListener.startSubmission(submissionNumber, bytes); } if (files.length == 0) { Log.e(TAG, "no files to upload"); listener.cancel(true); } FileInputStream fileInputStream; for(File f: files) { byte[] bFile = new byte[(int) f.length()]; try { //convert file into array of bytes fileInputStream = new FileInputStream(f); fileInputStream.read(bFile); fileInputStream.close(); for (int i = 0; i < bFile.length; i++) { System.out.print((char) bFile[i]); } } catch (Exception e) { e.printStackTrace(); } } // mime post MultipartEntity entity = new DataSubmissionEntity(myListener, submissionNumber); if (!buildMultipartEntity(entity, key, files)) { return RECORD_FAILURE; } HttpRequestGenerator generator; if (user.getUserType().equals(User.TYPE_DEMO)) { generator = new HttpRequestGenerator(); } else { generator = new HttpRequestGenerator(user); } return submitEntity(entity, url, generator); } /** * Submit multipart entity with plenty of logging * * @return submission status of multipart entity post */ private static long submitEntity(MultipartEntity entity, String url, HttpRequestGenerator generator) { HttpResponse response; try { response = generator.postData(url, entity); } catch (InputIOException ioe) { // This implies that there was a problem with the _source_ of the // transmission, not the processing or receiving end. Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Internal error reading form record during submission: " + ioe.getWrapped().getMessage()); return RECORD_FAILURE; } catch (ClientProtocolException e) { e.printStackTrace(); return TRANSPORT_FAILURE; } catch (IOException | IllegalStateException e) { e.printStackTrace(); return TRANSPORT_FAILURE; } int responseCode = response.getStatusLine().getStatusCode(); Log.e(TAG, "Response code:" + responseCode); if (!(responseCode >= 200 && responseCode < 300)) { Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Response Code: " + responseCode); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { AndroidStreamUtil.writeFromInputToOutput(response.getEntity().getContent(), bos); } catch (IllegalStateException | IOException e) { e.printStackTrace(); } String responseString = new String(bos.toByteArray()); Log.d(TAG, responseString); if (responseCode >= 200 && responseCode < 300) { return FULL_SUCCESS; } else { return FAILURE; } } /** * Validate the content body of the XML submission file. * * TODO: this should really be the responsibility of the form record, not * of the submission process, persay. * * NOTE: this is a shallow validation (everything should be more or else * constant time). Throws an exception if the file is gone because that's * a common issue that gets caught to check if storage got removed * * @param f xml file to check * @return false if the file is empty; otherwise true * @throws FileNotFoundException file in question isn't found on the * file-system */ private static boolean validateSubmissionFile(File f) throws FileNotFoundException { if (!f.exists()) { throw new FileNotFoundException("Submission file: " + f.getAbsolutePath()); } // Gotta check f exists here since f.length returns 0 if the file isn't // there for some reason. if (f.length() == 0 && f.exists()) { Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Submission body has no content at: " + f.getAbsolutePath()); return false; } return true; } /** * @return The aggregated size in bytes the files of supported extension * type. */ private static long estimateUploadBytes(File[] files) { long bytes = 0; for (File file : files) { // Make sure we'll be sending it if (!isSupportedMultimediaFile(file.getName())) { continue; } bytes += file.length(); Log.d(TAG, "Added file: " + file.getName() + ". Bytes to send: " + bytes); } return bytes; } /** * Add files of supported type to the multipart entity, encrypting xml * files. * * @param entity Add files to this * @param key Used to encrypt xml files * @param files The files to be added to the entity, * @return false if invalid xml files are found; otherwise true. * @throws FileNotFoundException Is raised when an xml doesn't exist on the * file-system */ private static boolean buildMultipartEntity(MultipartEntity entity, SecretKeySpec key, File[] files) throws FileNotFoundException { for (File f : files) { ContentBody fb; if (f.getName().endsWith(".xml")) { if (key != null) { if (!validateSubmissionFile(f)) { return false; } fb = new EncryptedFileBody(f, FormUploadUtil.getDecryptCipher(key), ContentType.TEXT_XML); } else { fb = new FileBody(f, ContentType.TEXT_XML, f.getName()); } entity.addPart("xml_submission_file", fb); } else if (f.getName().endsWith(".jpg")) { fb = new FileBody(f, "image/jpeg"); if (fb.getContentLength() <= MAX_BYTES) { entity.addPart(f.getName(), fb); Log.i(TAG, "added image file " + f.getName()); } else { Log.i(TAG, "file " + f.getName() + " is too big"); } } else if (f.getName().endsWith(".3gpp")) { fb = new FileBody(f, "audio/3gpp"); if (fb.getContentLength() <= MAX_BYTES) { entity.addPart(f.getName(), fb); Log.i(TAG, "added audio file " + f.getName()); } else { Log.i(TAG, "file " + f.getName() + " is too big"); } } else if (f.getName().endsWith(".3gp")) { fb = new FileBody(f, "video/3gpp"); if (fb.getContentLength() <= MAX_BYTES) { entity.addPart(f.getName(), fb); Log.i(TAG, "added video file " + f.getName()); } else { Log.i(TAG, "file " + f.getName() + " is too big"); } } else if (isSupportedMultimediaFile(f.getName())) { fb = new FileBody(f, "application/octet-stream"); if (fb.getContentLength() <= MAX_BYTES) { entity.addPart(f.getName(), fb); Log.i(TAG, "added unknown file " + f.getName()); } else { Log.i(TAG, "file " + f.getName() + " is too big"); } } else { Log.w(TAG, "unsupported file type, not adding file: " + f.getName()); } } return true; } /** * @return Is the filename's extension in the hard-coded list of supported * files or have a media mimetype? */ public static boolean isSupportedMultimediaFile(String filename) { for (String ext : SUPPORTED_FILE_EXTS) { if (filename.endsWith(ext)) { return true; } } return isAudioVisualMimeType(filename); } /** * Use the file's extension to determine if it has an audio, * video, or image mimetype. * * @return true if the file has an audio, image, or video mimetype */ private static boolean isAudioVisualMimeType(String filename) { MimeTypeMap mtm = MimeTypeMap.getSingleton(); String[] filenameSegments = filename.split("\\."); if (filenameSegments.length > 1) { // use the file extension to determine the mimetype String ext = filenameSegments[filenameSegments.length - 1]; String mimeType = mtm.getMimeTypeFromExtension(ext); return (mimeType != null) && (mimeType.startsWith("audio") || mimeType.startsWith("image") || mimeType.startsWith("video")); } return false; } }
package org.drools.process.core; import org.drools.process.core.Work; import org.drools.process.core.WorkDefinition; public interface WorkEditor { void setWorkDefinition(WorkDefinition definition); void setWork(Work work); boolean show(); Work getWork(); }
package personal.gino.dnsmasq; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.AssetManager; import android.net.ConnectivityManager; import android.net.DhcpInfo; import android.net.LinkAddress; import android.net.NetworkInfo; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.SystemClock; import android.util.Log; import android.widget.RemoteViews; import android.widget.Toast; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; /** * Implementation of App Widget functionality. */ public class DNSWidget extends AppWidgetProvider { private static final String TAG = "dnsmasq widget"; // Environment.getExternalStorageDirectory().getPath() can't use, // because some devices return /storage/emulated/0 private static final String CONF = "/sdcard/dnsmasq.conf"; private static final String DNSMASQ_ACTION = "personal.gino.dnsmasq.DNSMASQ_ACTION"; private static String PID = "/sdcard/dnsmasq.pid"; private static String s_ipaddress; private static String s_gateway; private static int s_netmask; private static Object getField(Object obj, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field f = obj.getClass().getField(name); Object out = f.get(obj); return out; } private static Object getDeclaredField(Object obj, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field f = obj.getClass().getDeclaredField(name); f.setAccessible(true); Object out = f.get(obj); return out; } private static void setEnumField(Object obj, String value, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field f = obj.getClass().getField(name); f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value)); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // There may be multiple widgets active, so update all of them for (int appWidgetId : appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId); } } @Override public void onEnabled(Context context) { // Enter relevant functionality for when the first widget is created File dnsconf = new File(CONF); if (!dnsconf.exists()) { Log.i(TAG, "copy conf file"); AssetManager assetManager = context.getAssets(); InputStream in = null; OutputStream out = null; try { in = assetManager.open("dnsmasq.conf"); out = new FileOutputStream(dnsconf); copyFile(in, out); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // NOOP } } if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { // NOOP } } } } } @Override public void onDisabled(Context context) { // Enter relevant functionality for when the last widget is disabled } @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); Log.d(TAG, intent.getAction()); if (intent.getAction() != null && intent.getAction().equals(DNSMASQ_ACTION)) { if (!isConnectWIFI(context)) { Toast.makeText(context, R.string.wifi_close, Toast.LENGTH_LONG).show(); Log.w(TAG, "wifi is not open"); return; } // check dnsmasq whether is running if (check()) { stop(); setDhcp(context); } else { start(); setStatic(context); } //app widget update AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); ComponentName thisAppWidget = new ComponentName(context.getPackageName(), DNSWidget.class.getName()); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget); onUpdate(context, appWidgetManager, appWidgetIds); } } private void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { // Create an Intent to broadcast action Intent intent = new Intent(context, DNSWidget.class); intent.setAction(DNSMASQ_ACTION); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); // Construct the RemoteViews object RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.dnswidget); views.setOnClickPendingIntent(R.id.widget_button, pendingIntent); if (check()) { views.setImageViewResource(R.id.widget_button, R.mipmap.open); Toast.makeText(context, R.string.start, Toast.LENGTH_LONG).show(); } else { views.setImageViewResource(R.id.widget_button, R.mipmap.close); Toast.makeText(context, R.string.stop, Toast.LENGTH_LONG).show(); } // Instruct the widget manager to update the widget // Tell the AppWidgetManager to perform an update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, views); } private void setIpAssignment(String assign, WifiConfiguration wifiConf) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Object ipConfiguration = wifiConf.getClass().getMethod("getIpConfiguration").invoke(wifiConf); setEnumField(ipConfiguration, assign, "ipAssignment"); } else { setEnumField(wifiConf, assign, "ipAssignment"); } } private void setDNS(InetAddress dns, WifiConfiguration wifiConf) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // support android 5.x Object ipConfiguration = wifiConf.getClass().getMethod("getIpConfiguration").invoke(wifiConf); Object staticIpConfiguration = ipConfiguration.getClass().getMethod("getStaticIpConfiguration").invoke(ipConfiguration); Field ipAddress = null; Field gateway = null; // maybe is null, so you need to initial it manually if (staticIpConfiguration == null) { Log.d(TAG, "staticIpConfiguration is null"); try { // create staticIpConfiguration staticIpConfiguration = Class.forName("android.net.StaticIpConfiguration").newInstance(); // create static info @SuppressWarnings("unchecked") ArrayList<InetAddress> dnsServers = (ArrayList<InetAddress>) getDeclaredField(staticIpConfiguration, "dnsServers"); dnsServers.add(dns); LinkAddress obj = (LinkAddress) Class.forName("android.net.LinkAddress").getConstructor(InetAddress.class, int.class).newInstance(InetAddress.getByName(s_ipaddress), s_netmask); ipAddress = staticIpConfiguration.getClass().getField("ipAddress"); ipAddress.set(staticIpConfiguration, obj); gateway = staticIpConfiguration.getClass().getField("gateway"); gateway.set(staticIpConfiguration, InetAddress.getByName(s_gateway)); // get Enum object @SuppressWarnings("unchecked") Class<Enum> ipencl = (Class<Enum>) Class.forName("android.net.IpConfiguration$IpAssignment"); @SuppressWarnings("unchecked") Class<Enum> encl = (Class<Enum>) Class.forName("android.net.IpConfiguration$ProxySettings"); // initial staticipconfiguration Method method = ipConfiguration.getClass().getDeclaredMethod("init", ipencl, encl, Class.forName("android.net.StaticIpConfiguration"), Class.forName("android.net.ProxyInfo")); method.setAccessible(true); method.invoke(ipConfiguration, Enum.valueOf(ipencl, "STATIC"), Enum.valueOf(encl, "NONE"), staticIpConfiguration, null); } catch (UnknownHostException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { try { @SuppressWarnings("unchecked") ArrayList<InetAddress> dnsServers = (ArrayList<InetAddress>) getDeclaredField(staticIpConfiguration, "dnsServers"); dnsServers.clear(); dnsServers.add(dns); LinkAddress obj = (LinkAddress) Class.forName("android.net.LinkAddress").getConstructor(InetAddress.class, int.class).newInstance(InetAddress.getByName(s_ipaddress), s_netmask); ipAddress = staticIpConfiguration.getClass().getField("ipAddress"); ipAddress.set(staticIpConfiguration, obj); gateway = staticIpConfiguration.getClass().getField("gateway"); gateway.set(staticIpConfiguration, InetAddress.getByName(s_gateway)); } catch (InstantiationException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } } } else { // support android 3.X~4.X Object linkProperties = getField(wifiConf, "linkProperties"); if (linkProperties == null) return; ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses"); mDnses.clear(); //or add a new dns address , here I just want to replace DNS1 mDnses.add(dns); } } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } // check dnsmasq service status private boolean check() { boolean result = false; Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("ps dnsmasq"); if (process.waitFor() == 0) { BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String msg; while ((msg = in.readLine()) != null) { result = msg.contains("dnsmasq"); Log.d(TAG, "ps result: " + msg + "and result: " + Boolean.toString(result)); } in.close(); } } catch (IOException | InterruptedException e) { e.printStackTrace(); Log.e(TAG, "check dnsmasq process error"); } return result; } // start dnsmasq private void start() { Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("su"); DataOutputStream dos = new DataOutputStream(process.getOutputStream()); String cmd = "dnsmasq -C " + CONF + " -x " + PID + "\n"; // String cmd = "dnsmasq -C /sdcard/dnsmasq.conf -x /sdcard/dnsmasq.pid\n"; Log.d(TAG, "start cmd:" + cmd); dos.writeBytes(cmd); dos.flush(); // wait 0.5s for dnsmasq startup SystemClock.sleep(500); dos.close(); } catch (IOException e) { Log.e(TAG, "dnsmasq start error"); } } // stop dnsmasq private void stop() { Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("su"); DataOutputStream dos = new DataOutputStream(process.getOutputStream()); String cmd = "kill $(cat " + PID + ")\n"; // String cmd = "kill $(cat /sdcard/dnsmasq.pid)\n"; Log.d(TAG, "stop cmd:" + cmd); dos.writeBytes(cmd); dos.writeBytes("rm " + PID + "\n"); dos.flush(); SystemClock.sleep(500); dos.close(); } catch (IOException e) { Log.e(TAG, "dnsmasq stop error"); } } // set wifi to static ip private void setStatic(Context context) { WifiConfiguration wifiConf = null; WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcpInfo = wifiManager.getDhcpInfo(); getStaticDefualt(dhcpInfo); WifiInfo connectionInfo = wifiManager.getConnectionInfo(); List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks(); for (WifiConfiguration conf : configuredNetworks) { if (conf.networkId == connectionInfo.getNetworkId()) { wifiConf = conf; break; } } try { setIpAssignment("STATIC", wifiConf); //or "DHCP" for dynamic setting wifiManager.updateNetwork(wifiConf); setDNS(InetAddress.getByName("127.0.0.1"), wifiConf); wifiManager.updateNetwork(wifiConf); wifiManager.disconnect(); wifiManager.reconnect(); Log.d(TAG, "set static"); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } // set wifi to dhcp private void setDhcp(Context context) { WifiConfiguration wifiConf = null; WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo connectionInfo = wifiManager.getConnectionInfo(); List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks(); for (WifiConfiguration conf : configuredNetworks) { if (conf.networkId == connectionInfo.getNetworkId()) { wifiConf = conf; break; } } try { setIpAssignment("DHCP", wifiConf); //or "DHCP" for dynamic setting wifiManager.updateNetwork(wifiConf); wifiManager.disconnect(); wifiManager.reconnect(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } // check wifi status private boolean isConnectWIFI(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return info != null && info.isConnected(); } // get dhcp for static default private void getStaticDefualt(DhcpInfo dhcpInfo) { int ip = dhcpInfo.ipAddress; s_ipaddress = (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF); ip = dhcpInfo.netmask; String temp = Integer.toString(ip, 2); s_netmask = temp.length() - temp.replace("1", "").length(); ip = dhcpInfo.gateway; s_gateway = (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF); Log.d(TAG, "newtork info:" + s_ipaddress + " " + s_netmask + " " + s_gateway); } }
package com.airbnb.epoxy; import android.view.View; import com.airbnb.epoxy.ViewHolderState.ViewState; import com.airbnb.epoxy.VisibilityState.Visibility; import java.util.List; import androidx.annotation.FloatRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.Px; import androidx.recyclerview.widget.RecyclerView; @SuppressWarnings("WeakerAccess") public class EpoxyViewHolder extends RecyclerView.ViewHolder { @SuppressWarnings("rawtypes") private EpoxyModel epoxyModel; private List<Object> payloads; private EpoxyHolder epoxyHolder; @Nullable ViewHolderState.ViewState initialViewState; public EpoxyViewHolder(View view, boolean saveInitialState) { super(view); if (saveInitialState) { // We save the initial state of the view when it is created so that we can reset this initial // state before a model is bound for the first time. Otherwise the view may carry over // state from a previously bound model. initialViewState = new ViewState(); initialViewState.save(itemView); } } void restoreInitialViewState() { if (initialViewState != null) { initialViewState.restore(itemView); } } public void bind(@SuppressWarnings("rawtypes") EpoxyModel model, @Nullable EpoxyModel<?> previouslyBoundModel, List<Object> payloads, int position) { this.payloads = payloads; if (epoxyHolder == null && model instanceof EpoxyModelWithHolder) { epoxyHolder = ((EpoxyModelWithHolder) model).createNewHolder(); epoxyHolder.bindView(itemView); } if (model instanceof GeneratedModel) { // The generated method will enforce that only a properly typed listener can be set //noinspection unchecked ((GeneratedModel) model).handlePreBind(this, objectToBind(), position); } if (previouslyBoundModel != null) { // noinspection unchecked model.bind(objectToBind(), previouslyBoundModel); } else if (payloads.isEmpty()) { // noinspection unchecked model.bind(objectToBind()); } else { // noinspection unchecked model.bind(objectToBind(), payloads); } if (model instanceof GeneratedModel) { // The generated method will enforce that only a properly typed listener can be set //noinspection unchecked ((GeneratedModel) model).handlePostBind(objectToBind(), position); } epoxyModel = model; } @NonNull Object objectToBind() { return epoxyHolder != null ? epoxyHolder : itemView; } public void unbind() { assertBound(); // noinspection unchecked epoxyModel.unbind(objectToBind()); epoxyModel = null; payloads = null; } public void visibilityStateChanged(@Visibility int visibilityState) { assertBound(); // noinspection unchecked epoxyModel.onVisibilityStateChanged(visibilityState, objectToBind()); } public void visibilityChanged( @FloatRange(from = 0.0f, to = 100.0f) float percentVisibleHeight, @FloatRange(from = 0.0f, to = 100.0f) float percentVisibleWidth, @Px int visibleHeight, @Px int visibleWidth ) { assertBound(); // noinspection unchecked epoxyModel.onVisibilityChanged(percentVisibleHeight, percentVisibleWidth, visibleHeight, visibleWidth, objectToBind()); } public List<Object> getPayloads() { assertBound(); return payloads; } public EpoxyModel<?> getModel() { assertBound(); return epoxyModel; } public EpoxyHolder getHolder() { assertBound(); return epoxyHolder; } private void assertBound() { if (epoxyModel == null) { throw new IllegalStateException("This holder is not currently bound."); } } @Override public String toString() { return "EpoxyViewHolder{" + "epoxyModel=" + epoxyModel + ", view=" + itemView + ", super=" + super.toString() + '}'; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Optional; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JTree tree = new JTree(makeModel()) { @Override public boolean getScrollableTracksViewportWidth() { return true; } @Override public void updateUI() { super.updateUI(); setCellRenderer(new TableOfContentsTreeCellRenderer()); setBorder(BorderFactory.createTitledBorder("TreeCellRenderer")); } }; tree.setRootVisible(false); // TEST: tree.setRowHeight(40); JTree tree2 = new TableOfContentsTree(makeModel()); tree2.setRootVisible(false); // tree2.setLargeModel(false); // TEST: tree2.setRowHeight(40); JSplitPane sp = new JSplitPane(); sp.setResizeWeight(.5); sp.setLeftComponent(new JScrollPane(tree)); sp.setRightComponent(new JScrollPane(tree2)); add(sp); setPreferredSize(new Dimension(320, 240)); } private static DefaultTreeModel makeModel() { DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); DefaultMutableTreeNode s0 = new DefaultMutableTreeNode(new TableOfContents("1. Introduction", 1)); root.add(s0); DefaultMutableTreeNode s1 = new DefaultMutableTreeNode(new TableOfContents("2. Chapter", 1)); s1.add(new DefaultMutableTreeNode(new TableOfContents("2.1. Section", 2))); s1.add(new DefaultMutableTreeNode(new TableOfContents("2.2. Section", 4))); s1.add(new DefaultMutableTreeNode(new TableOfContents("2.3. Section", 8))); root.add(s1); DefaultMutableTreeNode s2 = new DefaultMutableTreeNode(new TableOfContents("3. Chapter", 10)); s2.add(new DefaultMutableTreeNode(new TableOfContents("ddd", 12))); s2.add(new DefaultMutableTreeNode(new TableOfContents("eee", 24))); s2.add(new DefaultMutableTreeNode(new TableOfContents("fff", 38))); root.add(s2); return new DefaultTreeModel(root); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class TableOfContents { public final String title; public final Integer page; protected TableOfContents(String title, int page) { this.title = title; this.page = page; } @Override public String toString() { return title; } } class TableOfContentsTreeCellRenderer extends DefaultTreeCellRenderer { protected static final BasicStroke READER = new BasicStroke( 1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1f, new float[] {1f}, 0f); protected int pn = -1; protected final Point pnPt = new Point(); protected int rxs; protected int rxe; protected boolean isSynth; protected final JPanel renderer = new JPanel(new BorderLayout()) { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (pn >= 0) { String str = String.format("%3d", pn); FontMetrics metrics = g.getFontMetrics(); // int xx = pnPt.x - getX() - metrics.stringWidth(str); Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(isSynth ? getForeground() : getTextNonSelectionColor()); g2.drawString(str, pnPt.x - getX() - metrics.stringWidth(str), pnPt.y); g2.setStroke(READER); g2.drawLine(rxs, pnPt.y, rxe - getX() - metrics.stringWidth("000"), pnPt.y); g2.dispose(); } } @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.width = Short.MAX_VALUE; return d; } }; @Override public void updateUI() { super.updateUI(); isSynth = getUI().getClass().getName().contains("Synth"); if (isSynth) { // System.out.println("XXX: FocusBorder bug?, JDK 1.7.0, Nimbus start LnF"); setBackgroundSelectionColor(new Color(0x0, true)); } } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel l = (JLabel) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); return Optional.ofNullable(value) .filter(DefaultMutableTreeNode.class::isInstance).map(DefaultMutableTreeNode.class::cast) .map(DefaultMutableTreeNode::getUserObject) .filter(TableOfContents.class::isInstance).map(TableOfContents.class::cast) .<Component>map(toc -> { renderer.removeAll(); renderer.add(l, BorderLayout.WEST); if (isSynth) { renderer.setForeground(l.getForeground()); } int gap = l.getIconTextGap(); Dimension d = l.getPreferredSize(); d.height = tree.isFixedRowHeight() ? tree.getRowHeight() : d.height; pnPt.setLocation(tree.getWidth() - gap, l.getBaseline(d.width, d.height)); pn = toc.page; rxs = d.width + gap; rxe = tree.getWidth() - tree.getInsets().right - gap; renderer.setOpaque(false); return renderer; }) .orElseGet(() -> { pn = -1; return l; }); } // @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // JLabel l = (JLabel) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); // if (value instanceof DefaultMutableTreeNode) { // DefaultMutableTreeNode n = (DefaultMutableTreeNode) value; // Object o = n.getUserObject(); // if (o instanceof TableOfContents) { // TableOfContents toc = (TableOfContents) o; // int gap = l.getIconTextGap(); // Dimension d = l.getPreferredSize(); // Insets ins = tree.getInsets(); // p.removeAll(); // p.add(l, BorderLayout.WEST); // if (isSynth) { // p.setForeground(l.getForeground()); // pnPt.setLocation(tree.getWidth() - gap, l.getBaseline(d.width, d.height)); // pn = toc.page; // rxs = d.width + gap; // rxe = tree.getWidth() - ins.right - gap; // p.setOpaque(false); // return p; // pn = -1; // return l; } // // TEST: // class ShortTableOfContentsTreeCellRenderer extends DefaultTreeCellRenderer { // protected static final String READER = "... "; // protected final Point pt = new Point(); // protected String pn; // protected boolean isSynth; // protected final JPanel p = new JPanel(new BorderLayout()) { // @Override protected void paintComponent(Graphics g) { // super.paintComponent(g); // if (pn != null) { // g.setColor(isSynth ? getForeground() : getTextNonSelectionColor()); // g.drawString(pn, pt.x - getX(), pt.y); // @Override public Dimension getPreferredSize() { // Dimension d = super.getPreferredSize(); // d.width = Short.MAX_VALUE; // return d; // @Override public void updateUI() { // super.updateUI(); // isSynth = getUI().getClass().getName().contains("Synth"); // if (isSynth) { // // System.out.println("XXX: FocusBorder bug?, JDK 1.7.0, Nimbus start LnF"); // setBackgroundSelectionColor(new Color(0x0, true)); // @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // JLabel l = (JLabel) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); // if (value instanceof DefaultMutableTreeNode) { // DefaultMutableTreeNode n = (DefaultMutableTreeNode) value; // Object o = n.getUserObject(); // if (o instanceof TableOfContents) { // TableOfContents toc = (TableOfContents) o; // FontMetrics metrics = l.getFontMetrics(l.getFont()); // int gap = l.getIconTextGap(); // p.removeAll(); // p.add(l, BorderLayout.WEST); // if (isSynth) { // p.setForeground(l.getForeground()); // pn = String.format("%s%3d", READER, toc.page); // pt.x = tree.getWidth() - metrics.stringWidth(pn) - gap; // pt.y = (l.getIcon().getIconHeight() + metrics.getAscent()) / 2; // p.setOpaque(false); // return p; // pn = null; // return l; class TableOfContentsTree extends JTree { protected static final BasicStroke READER = new BasicStroke( 1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1f, new float[] {1f}, 0f); protected boolean isSynth; protected TableOfContentsTree(TreeModel model) { super(model); } @Override public void updateUI() { super.updateUI(); setBorder(BorderFactory.createTitledBorder("JTree#paintComponent(...)")); isSynth = getUI().getClass().getName().contains("Synth"); } // protected Rectangle getVisibleRowsRect() { // Insets i = getInsets(); // Rectangle visRect = getVisibleRect(); // //if (visRect.width == 0 && visRect.height == 0 && getVisibleRowCount() > 0) { // if (visRect.isEmpty() && getVisibleRowCount() > 0) { // // The tree doesn't have a valid bounds yet. Calculate // // based on visible row count. // visRect.width = 1; // visRect.height = getRowHeight() * getVisibleRowCount(); // } else { // visRect.x -= i.left; // visRect.y -= i.top; // // we should consider a non-visible area above // Class<JScrollPane> clz = JScrollPane.class; // Optional.ofNullable(SwingUtilities.getAncestorOfClass(clz, this)) // .filter(clz::isInstance).map(clz::cast) // .map(JScrollPane::getHorizontalScrollBar) // .filter(JScrollBar::isVisible) // .ifPresent(bar -> { // int height = bar.getHeight(); // visRect.y -= height; // visRect.height += height; // // Container container = SwingUtilities.getAncestorOfClass(JScrollPane.class, this); // // if (container instanceof JScrollPane) { // // JScrollPane pane = (JScrollPane) container; // // JScrollBar bar = pane.getHorizontalScrollBar(); // // if (bar != null && bar.isVisible()) { // // int height = bar.getHeight(); // // visRect.y -= height; // // visRect.height += height; // return visRect; @Override protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); FontMetrics fm = g.getFontMetrics(); int pageNumMaxWidth = fm.stringWidth("000"); Insets ins = getInsets(); Rectangle rect = getVisibleRect(); // getVisibleRowsRect(); for (int i = 0; i < getRowCount(); i++) { Rectangle r = getRowBounds(i); if (rect.intersects(r)) { TreePath path = getPathForRow(i); TreeCellRenderer tcr = getCellRenderer(); if (isSynth && isRowSelected(i)) { if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tcr; g2.setPaint(renderer.getTextSelectionColor()); } } else { g2.setPaint(getForeground()); } DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); Object o = node.getUserObject(); if (o instanceof TableOfContents) { TableOfContents toc = (TableOfContents) o; String pn = Integer.toString(toc.page); int x = getWidth() - 1 - fm.stringWidth(pn) - ins.right; // int y = (int) (.5 + r.y + (r.height + fm.getAscent()) * .5); int y = r.y + ((Component) tcr).getBaseline(r.width, r.height); g2.drawString(pn, x, y); int gap = 5; int x2 = getWidth() - 1 - pageNumMaxWidth - ins.right; Stroke s = g2.getStroke(); g2.setStroke(READER); g2.drawLine(r.x + r.width + gap, y, x2 - gap, y); g2.setStroke(s); } } } g2.dispose(); } }
package org.pathvisio.biopax.reflect; import java.util.ArrayList; import java.util.List; public class PublicationXRef extends BiopaxElement { public PublicationXRef() { super(); setName("PublicationXRef"); setValidProperties(new PropertyType[] { PropertyType.AUTHORS, PropertyType.DB, PropertyType.ID, PropertyType.SOURCE, PropertyType.TITLE, PropertyType.YEAR, }); } public PublicationXRef(String id) { this(); setId(id); } private String getPropertyValue(PropertyType pt) { BiopaxProperty p = getProperty(pt.name()); if(p != null) { return p.getText(); } else { return null; } } private void setPropertyValue(PropertyType pt, String value) { addProperty(new BiopaxProperty(pt, value)); } public String getTitle() { return getPropertyValue(PropertyType.TITLE); } public void setTitle(String title) { setPropertyValue(PropertyType.TITLE, title); } public String getSource() { return getPropertyValue(PropertyType.SOURCE); } public void setSource(String source) { setPropertyValue(PropertyType.SOURCE, source); } public String getYear() { return getPropertyValue(PropertyType.YEAR); } public void setYear(String year) { setPropertyValue(PropertyType.YEAR, year); } public String getPubmedId() { return getPropertyValue(PropertyType.ID); } public void setPubmedId(String id) { setPropertyValue(PropertyType.ID, id); setPropertyValue(PropertyType.DB, "PubMed"); } public List<String> getAuthors() { List<String> authors = new ArrayList<String>(); for(BiopaxProperty p : getProperties(PropertyType.AUTHORS.name())) { authors.add(p.getValue()); } return authors; } public void addAuthor(String author) { setPropertyValue(PropertyType.AUTHORS, author); } public void removeAuthor(String author) { for(BiopaxProperty p : getProperties(PropertyType.AUTHORS.name())) { if(author.equals(p.getValue())) { removeProperty(p); } } } private void clearAuthors() { for(BiopaxProperty p : getProperties(PropertyType.AUTHORS.name())) { removeProperty(p); } } public void setAuthors(String authorString) { clearAuthors(); String[] authors = parseAuthorString(authorString); for(String a : authors) { addAuthor(a.trim()); } } public static final String AUTHOR_SEP = ";"; public String[] parseAuthorString(String s) { String[] splitted = s.split(AUTHOR_SEP); String[] result = new String[splitted.length]; for(int i = 0; i < result.length; i++) { result[i] = splitted[i].trim(); } return result; } public String getAuthorString() { return createAuthorString(getAuthors()); } public static String createAuthorString(List<String> authors) { String as = ""; for(String a : authors) { as += a + AUTHOR_SEP + " "; } if(as.length() > 0) { as = as.substring(0, as.length() - AUTHOR_SEP.length() - 1); } return as; } public String toString() { String title = getTitle(); String pmid = getPubmedId(); String authors = getAuthorString(); return (title != null && title.length() > 0 ? title + "; " : "") + (authors != null && authors.length() > 0 ? authors + "; ": "") + (pmid != null && pmid.length() > 0 ? " pmid=" + pmid : ""); } }
package org.intermine.bio.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.intermine.bio.io.gff3.GFF3Record; import org.intermine.util.DynamicUtil; import org.intermine.model.bio.Chromosome; import org.intermine.model.bio.Gene; import org.intermine.model.bio.Exon; import org.intermine.model.bio.Location; /** * Tests for the GFF3Util class. */ public class GFF3UtilTest extends TestCase { /* * Test method for 'org.intermine.bio.io.gff3.GFF3Util.makeGFF3Record(LocatedSequenceFeature)' */ public void testMakeGFF3Record() { Gene gene = (Gene) DynamicUtil.createObject(Collections.singleton(Gene.class)); Exon exon = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class)); Chromosome chromosome = (Chromosome) DynamicUtil.createObject(Collections.singleton(Chromosome.class)); Location geneLocation = (Location) DynamicUtil.createObject(Collections.singleton(Location.class)); Location exonLocation = (Location) DynamicUtil.createObject(Collections.singleton(Location.class)); gene.setChromosome(chromosome); gene.setChromosomeLocation(geneLocation); gene.setPrimaryIdentifier("gene1"); geneLocation.setStart(new Integer(100)); geneLocation.setEnd(new Integer(800)); geneLocation.setStrand("1"); exon.setChromosome(chromosome); exon.setChromosomeLocation(exonLocation); exon.setPrimaryIdentifier("exon1"); exonLocation.setStart(new Integer(200)); exonLocation.setEnd(new Integer(300)); exonLocation.setStrand("-1"); chromosome.setPrimaryIdentifier("4"); chromosome.setLength(new Integer(1000)); Map<String, List<String>> extraAttributes = new LinkedHashMap<String, List<String>>(); // test adding multiple values List<String> valList = new ArrayList<String>(); valList.add("test_string1"); valList.add("test_string2"); extraAttributes.put("name3", valList); Map<String, String> soClassNameMap = getSoClassNameMap(); GFF3Record gff3Gene = GFF3Util.makeGFF3Record(gene, soClassNameMap, "FlyMine", extraAttributes); GFF3Record gff3Exon = GFF3Util.makeGFF3Record(exon, soClassNameMap, "FlyMine", new HashMap<String, List<String>>()); System.err.println (gff3Gene); System.err.println (gff3Exon); System.err.println (gff3Gene.toGFF3()); System.err.println (gff3Exon.toGFF3()); assertEquals("4\tFlyMine\tgene\t100\t800\t.\t+\t.\tname3=test_string1,test_string2;ID=gene1", gff3Gene.toGFF3()); assertEquals("4\tFlyMine\texon\t200\t300\t.\t-\t.\tID=exon1", gff3Exon.toGFF3()); } // Exon location has no strand information - should default to '.' public void testNoStrandSet() throws Exception { Exon exon = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class)); Chromosome chromosome = (Chromosome) DynamicUtil.createObject(Collections.singleton(Chromosome.class)); Location exonLocation = (Location) DynamicUtil.createObject(Collections.singleton(Location.class)); exon.setChromosome(chromosome); exon.setChromosomeLocation(exonLocation); exon.setPrimaryIdentifier("exon1"); exonLocation.setStart(new Integer(200)); exonLocation.setEnd(new Integer(300)); chromosome.setPrimaryIdentifier("4"); chromosome.setLength(new Integer(1000)); Map<String, String> soClassNameMap = getSoClassNameMap(); GFF3Record gff3Exon = GFF3Util.makeGFF3Record(exon, soClassNameMap, "FlyMine", new HashMap<String, List<String>>()); assertEquals("4\tFlyMine\texon\t200\t300\t.\t.\t.\tID=exon1", gff3Exon.toGFF3()); } private Map<String, String> getSoClassNameMap() { Map<String, String> soClassNameMap = new LinkedHashMap<String, String>(); soClassNameMap.put("Gene", "gene"); soClassNameMap.put("Exon", "exon"); soClassNameMap.put("Chromosome", "chromosome"); return soClassNameMap; } }
/** * This package provides an object model and parser for Java class files. */ @Version("1." + ClassFile.MAJOR_VERSION + "0.0") package aQute.bnd.classfile; import org.osgi.annotation.versioning.Version;
package com.samsinite.redraw; import org.apache.cordova; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; public class SplashScreen extends CordovaPlugin { @override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("redraw")) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { this.webView.invalidate(); } }); } else { return false; } callbackContext.success(); return true; } }
package de.mrapp.android.adapter.list; import static de.mrapp.android.adapter.util.Condition.ensureAtLeast; import static de.mrapp.android.adapter.util.Condition.ensureAtMaximum; import static de.mrapp.android.adapter.util.Condition.ensureNotNull; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import android.content.Context; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import de.mrapp.android.adapter.ListAdapter; import de.mrapp.android.adapter.datastructure.SerializableWrapper; import de.mrapp.android.adapter.datastructure.item.Item; import de.mrapp.android.adapter.datastructure.item.ItemIterator; import de.mrapp.android.adapter.datastructure.item.ItemListIterator; import de.mrapp.android.adapter.inflater.Inflater; import de.mrapp.android.adapter.logging.LogLevel; import de.mrapp.android.adapter.logging.Logger; import de.mrapp.android.adapter.util.VisibleForTesting; /** * An abstract base class for all adapters, whose underlying data is managed as * a list of arbitrary items. Such an adapter's purpose is to provide the * underlying data for visualization using a {@link ListView} widget. * * @param <DataType> * The type of the adapter's underlying data * @param <DecoratorType> * The type of the decorator, which allows to customize the * appearance of the views, which are used to visualize the items of * the adapter * * @author Michael Rapp * * @since 1.0.0 */ public abstract class AbstractListAdapter<DataType, DecoratorType> extends BaseAdapter implements ListAdapter<DataType> { /** * The constant serial version UID. */ private static final long serialVersionUID = 1L; /** * The key, which is used to store the adapter's underlying data within a * bundle, if it implements the interface {@link Parcelable}. */ @VisibleForTesting protected static final String PARCELABLE_ITEMS_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::ParcelableItems"; /** * The key, which is used to store the adapter's underlying data within a * bundle, if it implements the interface {@link Serializable}. */ @VisibleForTesting protected static final String SERIALIZABLE_ITEMS_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::SerializableItems"; /** * The key, which is used to store, whether duplicate items should be * allowed, or not, within a bundle. */ @VisibleForTesting protected static final String ALLOW_DUPLICATES_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::AllowDuplicates"; /** * The key, which is used to store, whether the method * <code>notifyDataSetChanged():void</code> should be called automatically * when the adapter's underlying data has been changed, or not, within a * bundle. */ @VisibleForTesting protected static final String NOTIFY_ON_CHANGE_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::NotifyOnChange"; /** * The key, which is used to store the key value pairs, which are stored * within the adapter, within a bundle. */ @VisibleForTesting protected static final String PARAMETERS_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::Parameters"; /** * The key, which is used to store the log level, which is used for logging, * within a bundle. */ @VisibleForTesting protected static final String LOG_LEVEL_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::LogLevel"; /** * The context, the adapter belongs to. */ private final transient Context context; /** * The inflater, which is used to inflate the views, which are used to * visualize the adapter's items. */ private final transient Inflater inflater; /** * The decorator, which allows to customize the appearance of the views, * which are used to visualize the items of the adapter. */ private final transient DecoratorType decorator; /** * The logger, which is used for logging. */ private final transient Logger logger; /** * A set, which contains the listeners, which should be notified, when the * adapter's underlying data has been modified. */ private transient Set<ListAdapterListener<DataType>> adapterListeners; /** * A bundle, which contains key value pairs, which are stored within the * adapter. */ private Bundle parameters; /** * True, if duplicate items are allowed, false otherwise. */ private boolean allowDuplicates; /** * True, if the method <code>notifyDataSetChanged():void</code> is * automatically called when the adapter's underlying data has been changed, * false otherwise. */ private boolean notifyOnChange; /** * A list, which contains the the adapter's underlying data. */ private ArrayList<Item<DataType>> items; /** * Notifies all listeners, which have been registered to be notified, when * the adapter's underlying data has been modified, about an item, which has * been added to the adapter. * * @param item * The item, which has been added to the adapter, as an instance * of the generic type DataType. The item may not be null * @param index * The index of the item, which has been added to the adapter, as * an {@link Integer} value. The index must be between 0 and the * value of the method <code>getNumberOfItems():int</code> - 1 */ private void notifyOnItemAdded(final DataType item, final int index) { for (ListAdapterListener<DataType> listener : adapterListeners) { listener.onItemAdded(this, item, index); } } /** * Notifies all listeners, which have been registered to be notified, when * the adapter's underlying data has been modified, about an item, which has * been removed from the adapter. * * @param item * The item, which has been removed from the adapter, as an * instance of the generic type DataType. The item may not be * null * @param index * The index of the item, which has been removed from the * adapter, as an {@link Integer} value. The index must be * between 0 and the value of the method * <code>getNumberOfItems():int</code> */ private void notifyOnItemRemoved(final DataType item, final int index) { for (ListAdapterListener<DataType> listener : adapterListeners) { listener.onItemRemoved(this, item, index); } } /** * Returns, whether the adapter's underlying data implements the interface * {@link Parcelable}, or not. * * @return True, if the adapter's underlying data implements the interface * {@link Parcelable} or if the adapter is empty, false otherwise */ private boolean isUnderlyingDataParcelable() { if (!isEmpty()) { if (!Parcelable.class.isAssignableFrom(getItem(0).getClass())) { return false; } } return true; } /** * Creates and returns an {@link OnClickListener}, which is invoked, when a * specific item has been clicked. * * @param index * The index of the item, which should cause the listener to be * invoked, when clicked, as an {@link Integer} value * @return The listener, which has been created as an instance of the type * {@link OnClickListener} */ private OnClickListener createItemOnClickListener(final int index) { return new OnClickListener() { @Override public void onClick(final View v) { onItemClicked(index); } }; } /** * Returns, whether the adapter's underlying data implements the interface * {@link Serializable}, or not. * * @return True, if the adapter's underlying data implements the interface * {@link Serializable} or if the adapter is empty, false otherwise */ private boolean isUnderlyingDataSerializable() { if (!isEmpty()) { if (!Serializable.class.isAssignableFrom(getItem(0).getClass())) { return false; } } return true; } /** * Returns, the context, the adapter belongs to. * * @return The context, the adapter belongs to, as an instance of the class * {@link Context}. The context may not be null */ protected final Context getContext() { return context; } /** * Returns the inflater, which is used to inflate the views, which are used * to visualize the adapter's items. * * @return The inflater, which is used to inflate views, which are used to * visualize the adapter's items, as an instance of the type * {@link Inflater}. The inflater may not be null */ protected final Inflater getInflater() { return inflater; } /** * Returns the decorator, which allows to customize the appearance of the * views, which are used to visualize the items of the adapter. * * @return The decorator, which allows to customize the appearance of the * views, which are used to visualize the items of the adapter, as * an instance of the generic type DecoratorType. The decorator may * not be null */ protected final DecoratorType getDecorator() { return decorator; } /** * Returns the logger, which is used for logging. * * @return The logger, which is used for logging, as an instance of the * class {@link Logger}. The logger may not be null */ protected final Logger getLogger() { return logger; } /** * Returns a list, which contains the adapter's underlying data. * * @return A list, which contains the adapters underlying data, as an * instance of the type {@link ArrayList} or an empty list, if the * adapter does not contain any data */ protected final ArrayList<Item<DataType>> getItems() { return items; } /** * Sets the list, which contains the adapter's underlying data. * * @param items * The list, which should be set, as an instance of the type * {@link ArrayList} or an empty list, if the adapter should not * contain any data */ protected final void setItems(final ArrayList<Item<DataType>> items) { ensureNotNull(items, "The items may not be null"); this.items = items; } /** * Creates and returns a deep copy of the list, which contains the adapter's * underlying data. * * @return A deep copy of the list, which contains the adapter's underlying * data, as an instance of the type {@link ArrayList}. The list may * not be null * @throws CloneNotSupportedException * The exception, which is thrown, if cloning is not supported * by the adapter's underlying data */ protected final ArrayList<Item<DataType>> cloneItems() throws CloneNotSupportedException { ArrayList<Item<DataType>> clonedItems = new ArrayList<Item<DataType>>(); for (Item<DataType> item : items) { clonedItems.add(item.clone()); } return clonedItems; } /** * Returns a set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified. * * @return A set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified, as an * instance of the type {@link Set} or an empty set, if no listeners * should be notified */ protected final Set<ListAdapterListener<DataType>> getAdapterListeners() { return adapterListeners; } /** * The method, which is invoked, when an item has been clicked. * * @param index * The index of the item, which has been clicked, as an * {@link Integer} value */ protected void onItemClicked(final int index) { return; } /** * Notifies, that the adapter's underlying data has been changed, if * automatically notifying such events is currently enabled. */ protected final void notifyOnDataSetChanged() { if (isNotifiedOnChange()) { notifyDataSetChanged(); } } /** * This method is invoked to apply the decorator, which allows to customize * the view, which is used to visualize a specific item. * * @param context * The context, the adapter belongs to, as an instance of the * class {@link Context}. The context may not be null * @param view * The view, which is used to visualize the item, as an instance * of the class {@link View}. The view may not be null * @param index * The index of the item, which should be visualized, as an * {@link Integer} value */ protected abstract void applyDecorator(final Context context, final View view, final int index); /** * Creates a new adapter, whose underlying data is managed as a list of * arbitrary items. * * @param context * The context, the adapter belongs to, as an instance of the * class {@link Context}. The context may not be null * @param inflater * The inflater, which should be used to inflate the views, which * are used to visualize the adapter's items, as an instance of * the type {@link Inflater}. The inflater may not be null * @param decorator * The decorator, which should be used to customize the * appearance of the views, which are used to visualize the items * of the adapter, as an instance of the generic type * DecoratorType. The decorator may not be null * @param logLevel * The log level, which should be used for logging, as a value of * the enum {@link LogLevel}. The log level may not be null * @param items * A list, which contains the adapter's items, or an empty list, * if the adapter should not contain any items * @param allowDuplicates * True, if duplicate items should be allowed, false otherwise * @param notifyOnChange * True, if the method <code>notifyDataSetChanged():void</code> * should be automatically called when the adapter's underlying * data has been changed, false otherwise * @param adapterListeners * A set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified, as an * instance of the type {@link Set} or an empty set, if no * listeners should be notified */ protected AbstractListAdapter(final Context context, final Inflater inflater, final DecoratorType decorator, final LogLevel logLevel, final ArrayList<Item<DataType>> items, final boolean allowDuplicates, final boolean notifyOnChange, final Set<ListAdapterListener<DataType>> adapterListeners) { ensureNotNull(context, "The context may not be null"); ensureNotNull(inflater, "The inflater may not be null"); ensureNotNull(decorator, "The decorator may not be null"); ensureNotNull(items, "The items may not be null"); ensureNotNull(adapterListeners, "The adapter listeners may not be null"); this.context = context; this.inflater = inflater; this.decorator = decorator; this.logger = new Logger(logLevel); this.items = items; this.parameters = null; this.allowDuplicates = allowDuplicates; this.notifyOnChange = notifyOnChange; this.adapterListeners = adapterListeners; } @Override public final LogLevel getLogLevel() { return getLogger().getLogLevel(); } @Override public final void setLogLevel(final LogLevel logLevel) { getLogger().setLogLevel(logLevel); } @Override public final Bundle getParameters() { return parameters; } @Override public final void setParameters(final Bundle parameters) { this.parameters = parameters; String message = "Set parameters to \"" + parameters + "\""; getLogger().logDebug(getClass(), message); } @Override public final boolean areDuplicatesAllowed() { return allowDuplicates; } @Override public final void allowDuplicates(final boolean allowDuplicates) { this.allowDuplicates = allowDuplicates; String message = "Duplicate items are now " + (allowDuplicates ? "allowed" : "disallowed"); getLogger().logDebug(getClass(), message); } @Override public final boolean isNotifiedOnChange() { return notifyOnChange; } @Override public final void notifyOnChange(final boolean notifyOnChange) { this.notifyOnChange = notifyOnChange; String message = "Changes of the adapter's underlying data are now " + (notifyOnChange ? "" : "not ") + "automatically notified"; getLogger().logDebug(getClass(), message); } @Override public final void addAdapterListener( final ListAdapterListener<DataType> listener) { ensureNotNull(listener, "The listener may not be null"); adapterListeners.add(listener); String message = "Added adapter listener \"" + listener + "\""; getLogger().logDebug(getClass(), message); } @Override public final void removeAdapterListener( final ListAdapterListener<DataType> listener) { ensureNotNull(listener, "The listener may not be null"); adapterListeners.remove(listener); String message = "Removed adapter listener \"" + listener + "\""; getLogger().logDebug(getClass(), message); } @Override public final boolean addItem(final DataType item) { return addItem(getNumberOfItems(), item); } @Override public final boolean addItem(final int index, final DataType item) { ensureNotNull(item, "The item may not be null"); if (!areDuplicatesAllowed() && containsItem(item)) { String message = "Item \"" + item + "\" at index " + index + " not added, because adapter already contains item"; getLogger().logDebug(getClass(), message); return false; } items.add(index, new Item<DataType>(item)); notifyOnItemAdded(item, index); notifyOnDataSetChanged(); String message = "Item \"" + item + "\" added at index " + index; getLogger().logInfo(getClass(), message); return true; } @Override public final boolean addAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); return addAllItems(getNumberOfItems(), items); } @Override public final boolean addAllItems(final int index, final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); boolean result = true; int currentIndex = index; for (DataType item : items) { result &= addItem(currentIndex, item); currentIndex++; } return result; } @Override public final boolean addAllItems(final DataType... items) { return addAllItems(getNumberOfItems(), items); } @Override public final boolean addAllItems(final int index, final DataType... items) { ensureNotNull(items, "The array may not be null"); return addAllItems(index, Arrays.asList(items)); } @Override public final DataType replaceItem(final int index, final DataType item) { ensureNotNull(item, "The item may not be null"); DataType replacedItem = items.set(index, new Item<DataType>(item)) .getData(); notifyOnItemRemoved(replacedItem, index); notifyOnItemAdded(item, index); notifyOnDataSetChanged(); String message = "Replaced item \"" + replacedItem + "\" at index " + index + " with item \"" + item + "\""; getLogger().logInfo(getClass(), message); return replacedItem; } @Override public final DataType removeItem(final int index) { DataType removedItem = items.remove(index).getData(); notifyOnItemRemoved(removedItem, index); notifyOnDataSetChanged(); String message = "Removed item \"" + removedItem + "\" from index " + index; getLogger().logInfo(getClass(), message); return removedItem; } @Override public final boolean removeItem(final DataType item) { ensureNotNull(item, "The item may not be null"); int index = indexOf(item); if (index != -1) { items.remove(index); notifyOnItemRemoved(item, index); notifyOnDataSetChanged(); String message = "Removed item \"" + item + "\" from index " + index; getLogger().logInfo(getClass(), message); return true; } String message = "Item \"" + item + "\" not removed, because adapter does not contain item"; getLogger().logDebug(getClass(), message); return false; } @Override public final boolean removeAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); int numberOfRemovedItems = 0; for (int i = getNumberOfItems() - 1; i >= 0; i if (items.contains(getItem(i))) { removeItem(i); numberOfRemovedItems++; } } return numberOfRemovedItems == items.size(); } @Override public final boolean removeAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); return removeAllItems(Arrays.asList(items)); } @Override public final void retainAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); for (int i = getNumberOfItems() - 1; i >= 0; i if (!items.contains(getItem(i))) { removeItem(i); } } } @Override public final void retainAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); retainAllItems(Arrays.asList(items)); } @Override public final void clearItems() { for (int i = getNumberOfItems() - 1; i >= 0; i removeItem(i); } } @Override public final Iterator<DataType> iterator() { return new ItemIterator<DataType>(items, this); } @Override public final ListIterator<DataType> listIterator() { return new ItemListIterator<DataType>(items, this); } @Override public final ListIterator<DataType> listIterator(final int index) { return new ItemListIterator<DataType>(items, this, index); } @Override public final Collection<DataType> subList(final int start, final int end) { Collection<DataType> subList = new ArrayList<DataType>(); for (int i = start; i < end; i++) { subList.add(getItem(i)); } return subList; } @Override public final Object[] toArray() { return getAllItems().toArray(); } @Override public final <T> T[] toArray(final T[] array) { return getAllItems().toArray(array); } @Override public final int indexOf(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().indexOf(item); } @Override public final int lastIndexOf(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().lastIndexOf(item); } @Override public final boolean containsItem(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().contains(item); } @Override public final boolean containsAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); return getAllItems().containsAll(items); } @Override public final boolean containsAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); return containsAllItems(Arrays.asList(items)); } @Override public final int getNumberOfItems() { return items.size(); } @Override public final DataType getItem(final int index) { return items.get(index).getData(); } @Override public final List<DataType> getAllItems() { List<DataType> result = new ArrayList<DataType>(); for (Item<DataType> item : items) { result.add(item.getData()); } return result; } @Override public final boolean isEmpty() { return items.isEmpty(); } @Override public final int getCount() { return getNumberOfItems(); } @Override public final long getItemId(final int index) { ensureAtLeast(index, 0, "The index must be at least 0"); ensureAtMaximum(index, items.size() - 1, isEmpty() ? "The index must be at maximum " + (items.size() - 1) : "The adapter is empty"); return index; } @Override public final View getView(final int index, final View convertView, final ViewGroup parent) { View view = convertView; if (view == null) { view = getInflater().inflate(getContext(), parent, false); String message = "Inflated view to visualize the item at index " + index; getLogger().logVerbose(getClass(), message); } view.setOnClickListener(createItemOnClickListener(index)); applyDecorator(getContext(), view, index); return view; } @Override public void onSaveInstanceState(final Bundle outState) { if (isUnderlyingDataParcelable()) { outState.putParcelableArrayList(PARCELABLE_ITEMS_BUNDLE_KEY, items); } else if (isUnderlyingDataSerializable()) { SerializableWrapper<ArrayList<Item<DataType>>> wrappedItems = new SerializableWrapper<ArrayList<Item<DataType>>>( getItems()); outState.putSerializable(SERIALIZABLE_ITEMS_BUNDLE_KEY, wrappedItems); } else { String message = "The adapter's items can not be stored, because the " + "underlying data does neither implement the interface \"" + Parcelable.class.getName() + "\", nor the interface \"" + Serializable.class.getName() + "\""; getLogger().logWarn(getClass(), message); } outState.putBundle(PARAMETERS_BUNDLE_KEY, getParameters()); outState.putBoolean(ALLOW_DUPLICATES_BUNDLE_KEY, areDuplicatesAllowed()); outState.putBoolean(NOTIFY_ON_CHANGE_BUNDLE_KEY, isNotifiedOnChange()); outState.putInt(LOG_LEVEL_BUNDLE_KEY, getLogLevel().getRank()); getLogger().logDebug(getClass(), "Saved instance state"); } @SuppressWarnings("unchecked") @Override public void onRestoreInstanceState(final Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey(PARCELABLE_ITEMS_BUNDLE_KEY)) { items = savedInstanceState .getParcelableArrayList(PARCELABLE_ITEMS_BUNDLE_KEY); } else if (savedInstanceState .containsKey(SERIALIZABLE_ITEMS_BUNDLE_KEY)) { SerializableWrapper<ArrayList<Item<DataType>>> wrappedItems = (SerializableWrapper<ArrayList<Item<DataType>>>) savedInstanceState .getSerializable(SERIALIZABLE_ITEMS_BUNDLE_KEY); items = wrappedItems.getWrappedInstance(); } setParameters(savedInstanceState.getBundle(PARAMETERS_BUNDLE_KEY)); allowDuplicates(savedInstanceState .getBoolean(ALLOW_DUPLICATES_BUNDLE_KEY)); notifyOnChange(savedInstanceState .getBoolean(NOTIFY_ON_CHANGE_BUNDLE_KEY)); setLogLevel(LogLevel.fromRank(savedInstanceState .getInt(LOG_LEVEL_BUNDLE_KEY))); notifyDataSetChanged(); getLogger().logDebug(getClass(), "Restored instance state"); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (allowDuplicates ? 1231 : 1237); result = prime * result + (notifyOnChange ? 1231 : 1237); result = prime * result + items.hashCode(); result = prime * result + getLogLevel().getRank(); result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractListAdapter<?, ?> other = (AbstractListAdapter<?, ?>) obj; if (allowDuplicates != other.allowDuplicates) return false; if (notifyOnChange != other.notifyOnChange) return false; if (!items.equals(other.items)) return false; if (!getLogLevel().equals(other.getLogLevel())) return false; if (parameters == null) { if (other.parameters != null) return false; } else if (!parameters.equals(other.parameters)) return false; return true; } @Override public abstract AbstractListAdapter<DataType, DecoratorType> clone() throws CloneNotSupportedException; }
package de.yellowant.janis.xojtoimage.renderer; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.Line2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.LinkedList; import javax.imageio.ImageIO; import de.yellowant.janis.xojtoimage.xournalelements.Layer; import de.yellowant.janis.xojtoimage.xournalelements.Page; import de.yellowant.janis.xojtoimage.xournalelements.Stroke; import de.yellowant.janis.xojtoimage.xournalelements.Text; import de.yellowant.janis.xojtoimage.xournalelements.Tool; public class PageCanvas implements Renderer { private float factor; private LinkedList<Page> pages; public PageCanvas(float factor) { this.factor = factor; } private static class Line { final double x1; final double y1; final double x2; final double y2; final Color color; final double width; private Line(double x1, double y1, double x2, double y2, double width, Color color) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.color = color; this.width = width; } } private LinkedList<LinkedList<Line>> lines = new LinkedList<LinkedList<Line>>(); private LinkedList<LinkedList<Text>> texts = new LinkedList<LinkedList<Text>>(); public void paintXOJ(Graphics g, Page p, LinkedList<Text> ptexts, LinkedList<Line> plines) { for (Line line : plines) { g.setColor(line.color); Graphics2D g2d = (Graphics2D) g.create(); Composite old = g2d.getComposite(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); Line2D.Double l = new Line2D.Double(line.x1, line.y1, line.x2, line.y2); g2d.setStroke(new BasicStroke((float) line.width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); // g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.XOR, // line.color.getAlpha() / 255f)); g2d.draw(l); g2d.setComposite(old); // rect = new Rectangle2D.Double(line.x1, line.y1, // Math.sqrt((line.y2 - line.y1) * (line.y2 - line.y1) // + (line.x2 - line.x1) * (line.x2 - line.x1)), // line.width); // g2d.fill(rect); } for (Text text : ptexts) { g.setColor(text.getColor().getAwtColor(Tool.PEN)); g.setFont(text.getFont().deriveFont( text.getFont().getSize() * factor)); Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); // Magic number here. float y = (float) (text.getY() - 4) * factor; for (String line : text.getText().split("\n")) { g2d.drawString(line, (float) text.getX() * factor, y += g .getFontMetrics().getHeight()); } } } @Override public void export(String imageName, String format, int pageIndex) throws IOException { Page p = pages.get(pageIndex); int width = (int) Math.round(p.getWidth() * factor); int height = (int) (Math.round(p.getHeight() * factor)); BufferedImage buf = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB); Graphics2D d = buf.createGraphics(); p.paintBackround(d, Tool.PEN, width, height, factor); paintXOJ(d, p, texts.get(pageIndex), lines.get(pageIndex)); ImageIO.write(buf, format, new File(imageName + "." + format)); d.dispose(); } @Override public void setPages(LinkedList<Page> pages) { this.pages = pages; for (Page p : pages) { LinkedList<Text> pageTexts = new LinkedList<Text>(); LinkedList<Line> pageLines = new LinkedList<PageCanvas.Line>(); for (Layer l : p.getLayers()) { pageTexts.addAll(l.getTexts()); for (Stroke stroke : l.getStrokes()) { Color awtColor = stroke.getColor().getAwtColor( stroke.getTool()); double[] coords = stroke.getCoords(); double[] widths = stroke.getWidths(); for (int i = 0; i < coords.length - 2; i += 2) { double width; if (widths.length == 0) { width = 1; } else { if (i > widths.length - 1) { width = widths[widths.length - 1]; } else { width = widths[i]; if (i != 0) { width = widths[i - 1]; } } } pageLines.add(new Line(coords[i] * factor, coords[i + 1] * factor, coords[i + 2] * factor, coords[i + 3] * factor, Math.max(width, 1) * factor, awtColor)); } } } lines.add(pageLines); texts.add(pageTexts); } } }
package dr.evomodel.treelikelihood; import dr.evolution.alignment.PatternList; import dr.evolution.datatype.DataType; import dr.evolution.tree.NodeRef; import dr.evomodel.tree.TreeModel; import dr.inference.model.AbstractModel; import dr.inference.model.Likelihood; import dr.inference.model.Model; import dr.inference.model.Parameter; /** * AbstractTreeLikelihood - a base class for likelihood calculators of sites on a tree. * * @version $Id: AbstractTreeLikelihood.java,v 1.16 2005/06/07 16:27:39 alexei Exp $ * * @author Andrew Rambaut */ public abstract class AbstractTreeLikelihood extends AbstractModel implements Likelihood { public AbstractTreeLikelihood(String name, PatternList patternList, TreeModel treeModel) { super(name); this.patternList = patternList; this.dataType = patternList.getDataType(); patternCount = patternList.getPatternCount(); stateCount = dataType.getStateCount(); patternWeights = patternList.getPatternWeights(); this.treeModel = treeModel; addModel(treeModel); nodeCount = treeModel.getNodeCount(); updateNode = new boolean[nodeCount]; for (int i = 0; i < nodeCount; i++) { updateNode[i] = true; } likelihoodKnown = false; } /** * Sets the partials from a sequence in an alignment. */ protected final void setStates(LikelihoodCore likelihoodCore, PatternList patternList, int sequenceIndex, int nodeIndex) { int i; int[] states = new int[patternCount]; for (i = 0; i < patternCount; i++) { states[i] = patternList.getPatternState(sequenceIndex, i); } likelihoodCore.setNodeStates(nodeIndex, states); } /** * Sets the partials from a sequence in an alignment. */ protected final void setPartials(LikelihoodCore likelihoodCore, PatternList patternList, int categoryCount, int sequenceIndex, int nodeIndex) { int i, j; double[] partials = new double[patternCount * stateCount]; boolean[] stateSet; int v = 0; for (i = 0; i < patternCount; i++) { int state = patternList.getPatternState(sequenceIndex, i); stateSet = dataType.getStateSet(state); for (j = 0; j < stateCount; j++) { if (stateSet[j]) { partials[v] = 1.0; } else { partials[v] = 0.0; } v++; } } likelihoodCore.setNodePartials(nodeIndex, partials); } /** * Set update flag for a node and its children */ protected void updateNode(NodeRef node) { updateNode[node.getNumber()] = true; likelihoodKnown = false; } /** * Set update flag for a node and its direct children */ protected void updateNodeAndChildren(NodeRef node) { updateNode[node.getNumber()] = true; for (int i = 0; i < treeModel.getChildCount(node); i++) { NodeRef child = treeModel.getChild(node, i); updateNode[child.getNumber()] = true; } likelihoodKnown = false; } /** * Set update flag for a node and all its descendents */ protected void updateNodeAndDescendents(NodeRef node) { updateNode[node.getNumber()] = true; for (int i = 0; i < treeModel.getChildCount(node); i++) { NodeRef child = treeModel.getChild(node, i); updateNodeAndDescendents(child); } likelihoodKnown = false; } /** * Set update flag for all nodes */ protected void updateAllNodes() { for (int i = 0; i < nodeCount; i++) { updateNode[i] = true; } likelihoodKnown = false; } /** * Set update flag for a pattern */ protected void updatePattern(int i) { if (updatePattern != null) { updatePattern[i] = true; } likelihoodKnown = false; } /** * Set update flag for all patterns */ protected void updateAllPatterns() { if (updatePattern != null) { for (int i = 0; i < patternCount; i++) { updatePattern[i] = true; } } likelihoodKnown = false; } public final double[] getPatternWeights() { return patternWeights; } // ParameterListener IMPLEMENTATION protected void handleParameterChangedEvent(Parameter parameter, int index) { // do nothing } // Model IMPLEMENTATION protected void handleModelChangedEvent(Model model, Object object, int index) { likelihoodKnown = false; } /** * Stores the additional state other than model components */ protected void storeState() { storedLikelihoodKnown = likelihoodKnown; storedLogLikelihood = logLikelihood; } /** * Restore the additional stored state */ protected void restoreState() { likelihoodKnown = storedLikelihoodKnown; logLikelihood = storedLogLikelihood; } protected void acceptState() { } // nothing to do // Likelihood IMPLEMENTATION public final Model getModel() { return this; } public final double getLogLikelihood() { if (!likelihoodKnown) { logLikelihood = calculateLogLikelihood(); likelihoodKnown = true; } return logLikelihood; } /** * Forces a complete recalculation of the likelihood next time getLikelihood is called */ public void makeDirty() { likelihoodKnown = false; updateAllNodes(); updateAllPatterns(); } protected abstract double calculateLogLikelihood(); public String toString() { return getClass().getName() + "(" + getLogLikelihood() + ")"; } // Loggable IMPLEMENTATION /** * @return the log columns. */ public dr.inference.loggers.LogColumn[] getColumns() { return new dr.inference.loggers.LogColumn[] { new LikelihoodColumn(getId()) }; } private class LikelihoodColumn extends dr.inference.loggers.NumberColumn { public LikelihoodColumn(String label) { super(label); } public double getDoubleValue() { return getLogLikelihood(); } } // INSTANCE VARIABLES /** the tree */ protected TreeModel treeModel = null; /** the patternList */ protected PatternList patternList = null; protected DataType dataType = null; /** the pattern weights */ protected double[] patternWeights; /** the number of patterns */ protected int patternCount; /** the number of states in the data */ protected int stateCount; /** the number of nodes in the tree */ protected int nodeCount; /** Flags to specify which patterns are to be updated */ protected boolean [] updatePattern = null; /** Flags to specify which nodes are to be updated */ protected boolean[] updateNode; private double logLikelihood; private double storedLogLikelihood; private boolean likelihoodKnown = false; private boolean storedLikelihoodKnown = false; }
package edu.umd.cs.findbugs.detect; import edu.umd.cs.findbugs.*; import java.util.*; import java.io.PrintStream; import org.apache.bcel.Repository; import org.apache.bcel.classfile.*; import java.util.zip.*; import java.io.*; import edu.umd.cs.findbugs.visitclass.Constants2; public class FindDoubleCheck extends BytecodeScanningDetector implements Constants2 { int stage = 0; int startPC, endPC; int count; boolean sawMonitorEnter; HashSet<FieldAnnotation> fields = new HashSet<FieldAnnotation>(); HashSet<FieldAnnotation> twice = new HashSet<FieldAnnotation>(); private BugReporter bugReporter; public FindDoubleCheck(BugReporter bugReporter) { this.bugReporter = bugReporter; } public void visit(Method obj) { super.visit(obj); fields.clear(); twice.clear(); stage = 0; count = 0; sawMonitorEnter = false; } public void sawOpcode(int seen) { if (seen == MONITORENTER) sawMonitorEnter = true; if (seen == GETFIELD || seen == GETSTATIC) { FieldAnnotation f = FieldAnnotation.fromReferencedField(this); if (!sawMonitorEnter) { fields.add(f); startPC = getPC(); } else if(fields.contains(f)) twice.add(f); } switch (stage) { case 0: if (seen == IFNULL || seen == IFNONNULL) { int b = getBranchOffset(); if (b > 0 && (seen == IFNONNULL || b < 10)) stage++; } count = 0; break; case 1: if (seen == MONITORENTER) stage++; else { count++; if (count > 10) stage = 0; } break; case 2: if ((seen == IFNULL || seen == IFNONNULL) && getBranchOffset() >= 0) { endPC = getPC(); stage++; } else { count++; if (count > 10) stage = 0; } break; case 3: if (seen == PUTFIELD || seen == PUTSTATIC) { FieldAnnotation f = FieldAnnotation.fromReferencedField(this); if (twice.contains(f) && !getNameConstantOperand().startsWith("class$") && !getSigConstantOperand().equals("Ljava/lang/String;")) { Field declaration = findField(getClassConstantOperand(), getNameConstantOperand()); /* System.out.println(f); System.out.println(declaration); System.out.println(getSigConstantOperand()); */ if (declaration == null || !declaration.isVolatile()) bugReporter.reportBug(new BugInstance("DC_DOUBLECHECK", NORMAL_PRIORITY) .addClassAndMethod(this) .addField(f).describe("FIELD_ON") .addSourceLineRange(this, startPC, endPC)); stage++; } } break; default: } } Field findField(String className, String fieldName) { try { // System.out.println("Looking for " + className); JavaClass fieldDefinedIn = getThisClass(); if (!className.equals(getClassName())) { // System.out.println("Using repository to look for " + className); fieldDefinedIn = Repository.lookupClass(className); } Field [] f = fieldDefinedIn.getFields(); for(int i = 0; i < f.length; i++) if (f[i].getName().equals(fieldName)) { // System.out.println("Found " + f[i]); return f[i]; } return null; }catch (ClassNotFoundException e) { return null; } } }
package pl.dpawlak.flocoge.diagram; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.stream.EventFilter; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import pl.dpawlak.flocoge.diagram.ModelElementParser.Connection; import pl.dpawlak.flocoge.diagram.ModelElementParser.Label; import pl.dpawlak.flocoge.model.ModelConnection; import pl.dpawlak.flocoge.model.ModelElement; public class ModelLoader { private final XMLInputFactory factory; private final ModelElementParser parser; private final List<Label> labels; private final Map<String, Connection> connections; private final Map<String, ModelElement> elements; public ModelLoader(XMLInputFactory factory) { this.factory = factory; parser = new ModelElementParser(); labels = new LinkedList<>(); connections = new LinkedHashMap<>(); elements = new HashMap<>(); } public Collection<ModelElement> loadModel(XMLEventReader reader, StartElement rootElement) throws DiagramLoadingException { parseElements(reader, rootElement); assignLabelsToConnections(); return connectElements(); } private void assignLabelsToConnections() { for (Label label : labels) { Connection connection = connections.get(label.parentId); if (connection != null) { connection.label = label.value; } } labels.clear(); } private Collection<ModelElement> connectElements() { Map<String, ModelElement> startElements = new LinkedHashMap<>(elements); for (Connection connection : connections.values()) { ModelElement sourceElement = elements.get(connection.sourceId); if (sourceElement != null) { ModelElement targetElement = startElements.remove(connection.targetId); if (targetElement == null) { targetElement = elements.get(connection.targetId); } if (targetElement != null) { ModelConnection modelConnection = new ModelConnection(); modelConnection.label = connection.label; modelConnection.target = targetElement; sourceElement.connections.add(modelConnection); } } } connections.clear(); elements.clear(); return startElements.values(); } private void parseElements(XMLEventReader reader, StartElement rootElement) throws DiagramLoadingException { try { XMLEventReader filteredReader = factory.createFilteredReader(reader, new MxCellElementFilter()); while (filteredReader.hasNext()) { parseElement(filteredReader.nextEvent().asStartElement()); } } catch (XMLStreamException ex) { throw new DiagramLoadingException(ex); } } private void parseElement(StartElement element) throws DiagramLoadingException { switch (parser.parseNextElement(element)) { case ELEMENT: ModelElement modelElement = parser.getModelElement(); elements.put(modelElement.id, modelElement); break; case CONNECTION: Connection connection = parser.getConnection(); connections.put(connection.id, connection); break; case LABEL: labels.add(parser.getLabel()); break; default: break; } } public XMLInputFactory getFactory() { return factory; } private static class MxCellElementFilter implements EventFilter { @Override public boolean accept(XMLEvent event) { if (event.isStartElement()) { StartElement element = event.asStartElement(); return "mxCell".equals(element.getName().toString()) && element.getAttributeByName(QName.valueOf("style")) != null; } else { return false; } } } }
package org.flymine.task; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.ObjectStoreWriterFactory; import org.flymine.model.genomic.Organism; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; /** * A base class for Tasks that read from files and use the information to set fields in a particular * class. * * @author Kim Rutherford */ public class FileReadTask extends Task { private String organismAbbreviation; private String className; private String keyFieldName; private String oswAlias; private List fileSets = new ArrayList(); private ObjectStoreWriter osw; /** * The ObjectStoreWriter alias to use when querying and creating objects. * @param oswAlias the ObjectStoreWriter alias */ public void setOswAlias(String oswAlias) { this.oswAlias = oswAlias; } /** * Return the oswAlias set by setOswAlias() * @return the object store alias */ public String getOswAlias() { return oswAlias; } /** * Set the class name of the objects to operate on. * @param className the class name */ public void setClassName(String className) { this.className = className; } /** * Return the className set by setClassName() * @return the class name */ public String getClassName() { return className; } /** * Return the sets of file that should be read from. * @return the List of FileSets */ public List getFileSets() { return fileSets; } /** * Return the ObjectStoreWriter given by oswAlias. * @return the ObjectStoreWriter * @throws BuildException if there is an error while processing */ protected ObjectStoreWriter getObjectStoreWriter() throws BuildException { if (oswAlias == null) { throw new BuildException("oswAlias attribute is not set"); } if (osw == null) { try { osw = ObjectStoreWriterFactory.getObjectStoreWriter(oswAlias); } catch (ObjectStoreException e) { throw new BuildException("cannot get ObjectStoreWriter for: " + oswAlias, e); } } return osw; } /** * Add a FileSet to read from * @param fileSet the FileSet */ public void addFileSet(FileSet fileSet) { fileSets.add(fileSet); } /** * return a Map from identifier to InterMine ID for all the objects of type className and * organism given by organismAbbreviation. * @param os The ObjectStore to use when creating the ID Map * @return the ID Map */ public Map getIdMap(ObjectStore os) { return buildIdMap(os); } /** * Set the organism abbreviation. Only objects that have a reference to this organism will have * their sequences set. * @param organismAbbreviation the organism of the objects to set */ public void setOrganismAbbreviation(String organismAbbreviation) { this.organismAbbreviation = organismAbbreviation; } /** * Return the organismAbbreviation set by setOrganismAbbreviation() * @return the organism abbreviation */ public String getOrganismAbbreviation() { return organismAbbreviation; } /** * Build a Map from an identifier to InterMine ID for all the objects of type className and * organism given by organismAbbreviation. The identifier field to use as the key is set * by setKeyFieldName(). * @param keyFieldName the field in the clasto use * @param os the ObjectStore to read the objects from * @throws BuildException */ private Map buildIdMap(ObjectStore os) throws BuildException { Map idMap = new HashMap(); Query q = new Query(); q.setDistinct(true); Class c; try { if (className.indexOf(".") == -1) { c = Class.forName(os.getModel().getPackageName() + "." + className); } else { c = Class.forName(className); } } catch (ClassNotFoundException e) { throw new BuildException("cannot find class for: " + className); } QueryClass qcObj = new QueryClass(c); QueryField qfObjIdentifier = new QueryField(qcObj, keyFieldName); q.addFrom(qcObj); q.addToSelect(qfObjIdentifier); q.addToSelect(qcObj); QueryClass qcOrg = new QueryClass(Organism.class); QueryObjectReference ref = new QueryObjectReference(qcObj, "organism"); ContainsConstraint cc = new ContainsConstraint(ref, ConstraintOp.CONTAINS, qcOrg); SimpleConstraint sc = new SimpleConstraint(new QueryField(qcOrg, "abbreviation"), ConstraintOp.EQUALS, new QueryValue(organismAbbreviation)); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); cs.addConstraint(cc); cs.addConstraint(sc); q.setConstraint(cs); q.addFrom(qcOrg); Results res = new Results(q, os, os.getSequence()); res.setBatchSize(10000); Iterator iter = res.iterator(); while (iter.hasNext()) { List row = (List) iter.next(); // we queried for the InterMineObject but we just store the ID // we hope that the ObjectStore will cache the objects idMap.put(row.get(0), ((InterMineObject) row.get(1)).getId()); } return idMap; } /** * Set the he name of the field (in the class specified by className) to use in buildIdMap(). * @param keyFieldName the key field name */ public void setKeyFieldName(String keyFieldName) { this.keyFieldName = keyFieldName; } /** * Return the name of the field (in the class specified by className) to use in buildIdMap(). * @return the key field name */ public String getKeyFieldName() { return keyFieldName; } }
package org.apache.jmeter.functions; import java.io.Serializable; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.LinkedList; import java.util.List; //import org.apache.jmeter.engine.util.CompoundVariable; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.Sampler; import org.apache.jmeter.threads.JMeterVariables; import org.apache.jmeter.util.JMeterUtils; public class MachineName extends AbstractFunction implements Serializable { private static final List desc = new LinkedList(); private static final String KEY = "__machineName"; static { // desc.add("Use fully qualified host name: TRUE/FALSE (Default FALSE)"); desc.add(JMeterUtils.getResString("function_name_param")); } private Object[] values; public MachineName() {} public Object clone() { return new MachineName(); } public synchronized String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { JMeterVariables vars = getVariables(); // boolean fullHostName = false; // if ( ((CompoundFunction)values[0]).execute().toLowerCase().equals("true") ) // fullHostName = true; String varName = ((CompoundFunction)values[values.length - 1]).execute(); String machineName = ""; try { InetAddress Address = InetAddress.getLocalHost(); //fullHostName disabled until we move up to 1.4 as the support jre // if ( fullHostName ) { // machineName = Address.getCanonicalHostName(); // } else { machineName = Address.getHostName(); } catch ( UnknownHostException e ) { } vars.put( varName, machineName ); return machineName; } public void setParameters(String parameters) throws InvalidVariableException { Collection params = parseArguments2(parameters); values = params.toArray(); if ( values.length < 2 ) { throw new InvalidVariableException(); } } public String getReferenceKey() { return KEY; } public List getArgumentDesc() { return desc; } }
package gov.nih.nci.calab.service.util; import java.util.HashMap; import java.util.Map; public class CaNanoLabConstants { public static final String DOMAIN_MODEL_NAME = "caNanoLab"; public static final String CSM_APP_NAME = "caNanoLab"; public static final String DATE_FORMAT = "MM/dd/yyyy"; public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy"; // Storage element public static final String STORAGE_BOX = "Box"; public static final String STORAGE_SHELF = "Shelf"; public static final String STORAGE_RACK = "Rack"; public static final String STORAGE_FREEZER = "Freezer"; public static final String STORAGE_ROOM = "Room"; public static final String STORAGE_LAB = "Lab"; // DataStatus public static final String MASK_STATUS = "Masked"; public static final String ACTIVE_STATUS = "Active"; // for Container type public static final String OTHER = "Other"; public static final String[] DEFAULT_CONTAINER_TYPES = new String[] { "Tube", "Vial" }; // Sample Container type public static final String ALIQUOT = "Aliquot"; public static final String SAMPLE_CONTAINER = "Sample_container"; // Run Name public static final String RUN = "Run"; // File upload public static final String FILEUPLOAD_PROPERTY = "fileupload.properties"; public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles"; public static final String EMPTY = "N/A"; // File input/output type public static final String INPUT = "Input"; public static final String OUTPUT = "Output"; // zip file name public static final String ALL_FILES = "ALL_FILES"; public static final String URI_SEPERATOR = "/"; // caNanoLab property file public static final String CANANOLAB_PROPERTY = "caNanoLab.properties"; public static final String CSM_READ_ROLE = "R"; public static final String CSM_READ_PRIVILEGE = "READ"; public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE"; public static final String CSM_DELETE_PRIVILEGE = "DELETE"; // caLAB Submission property file public static final String SUBMISSION_PROPERTY = "exception.properties"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES, BOOLEAN_NO }; public static final String[] PROTOCOL_TYPES = new String[] { "Physical assay", "Synthesis", "In vitro assay", "In vivo assay", "Sample preparation", "Safety", "Radiolabeling" }; public static final String DEFAULT_SAMPLE_PREFIX = "NANO-"; public static final String DEFAULT_APP_OWNER = "NCICB"; public static final String APP_OWNER; static { String appOwner = PropertyReader.getProperty(CANANOLAB_PROPERTY, "applicationOwner"); if (appOwner == null || appOwner.length() == 0) appOwner = DEFAULT_APP_OWNER; APP_OWNER = appOwner; } public static final String SAMPLE_PREFIX; static { String samplePrefix = PropertyReader.getProperty(CANANOLAB_PROPERTY, "samplePrefix"); if (samplePrefix == null || samplePrefix.length() == 0) samplePrefix = DEFAULT_SAMPLE_PREFIX; SAMPLE_PREFIX = samplePrefix; } public static final String GRID_INDEX_SERVICE_URL; static { String gridIndexServiceURL = PropertyReader.getProperty( CANANOLAB_PROPERTY, "gridIndexServiceURL"); GRID_INDEX_SERVICE_URL = gridIndexServiceURL; } /* * The following Strings are nano specific * */ public static final String PHYSICAL_CHARACTERIZATION = "Physical"; public static final String COMPOSITION_CHARACTERIZATION = "Composition"; public static final String INVITRO_CHARACTERIZATION = "In Vitro"; public static final String INVIVO_CHARACTERIZATION = "In Vivo"; public static final String TOXICITY_CHARACTERIZATION = "Toxicity"; public static final String CYTOXICITY_CHARACTERIZATION = "Cytoxicity"; public static final String APOPTOSIS_CELL_DEATH_METHOD_CYTOXICITY_CHARACTERIZATION = "apoptosis"; public static final String NECROSIS_CELL_DEATH_METHOD_CYTOXICITY_CHARACTERIZATION = "necrosis"; public static final String BLOOD_CONTACT_IMMUNOTOXICITY_CHARACTERIZATION = "Blood Contact"; public static final String IMMUNE_CELL_FUNCTION_IMMUNOTOXICITY_CHARACTERIZATION = "Immune Cell Function"; public static final String METABOLIC_STABILITY_TOXICITY_CHARACTERIZATION = "Metabolic Stability"; public static final String PHYSICAL_SIZE = "Size"; public static final String PHYSICAL_SHAPE = "Shape"; public static final String PHYSICAL_MOLECULAR_WEIGHT = "Molecular Weight"; public static final String PHYSICAL_SOLUBILITY = "Solubility"; public static final String PHYSICAL_SURFACE = "Surface"; public static final String PHYSICAL_STABILITY = "Stability"; public static final String PHYSICAL_PURITY = "Purity"; public static final String PHYSICAL_FUNCTIONAL = "Functional"; public static final String PHYSICAL_MORPHOLOGY = "Morphology"; public static final String PHYSICAL_COMPOSITION = "Composition"; public static final String TOXICITY_OXIDATIVE_STRESS = "Oxidative Stress"; public static final String TOXICITY_OXIDATIVE_STRESS_DATA_TYPE = "Percent Oxidative Stress"; public static final String TOXICITY_ENZYME_FUNCTION = "Enzyme Function"; public static final String TOXICITY_ENZYME_FUNCTION_DATA_TYPE = "Percent Enzyme Induction"; public static final String CYTOTOXICITY_CELL_VIABILITY = "Cell Viability"; public static final String CYTOTOXICITY_CELL_VIABILITY_DATA_TYPE = "Percent Cell Viability"; public static final String CYTOTOXICITY_CASPASE3_ACTIVIATION = "Caspase 3 Activation"; public static final String CYTOTOXICITY_CASPASE3_ACTIVIATION_DATA_TYPE = "Percent Caspase 3 Activation"; public static final String BLOODCONTACTTOX_PLATE_AGGREGATION = "Platelet Aggregation"; public static final String BLOODCONTACTTOX_PLATELET_AGGREGATION_DATA_TYPE = "Percent Platelet Aggregation"; public static final String BLOODCONTACTTOX_HEMOLYSIS = "Hemolysis"; public static final String BLOODCONTACTTOX_HEMOLYSIS_DATA_TYPE = "Percent Hemolysis"; public static final String BLOODCONTACTTOX_COAGULATION = "Coagulation"; public static final String BLOODCONTACTTOX_COAGULATION_DATA_TYPE = "Coagulation Time"; public static final String BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING = "Plasma Protein Binding"; public static final String BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING_DATA_TYPE = "Percent Plasma Protein Binding"; public static final String IMMUNOCELLFUNCTOX_PHAGOCYTOSIS = "Phagocytosis"; public static final String IMMUNOCELLFUNCTOX_PHAGOCYTOSIS_DATA_TYPE = "Fold Induction"; public static final String IMMUNOCELLFUNCTOX_OXIDATIVE_BURST = "Oxidative Burst"; public static final String IMMUNOCELLFUNCTOX_OXIDATIVE_BURST_DATA_TYPE = "Percent Oxidative Burst"; public static final String IMMUNOCELLFUNCTOX_CHEMOTAXIS = "Chemotaxis"; public static final String IMMUNOCELLFUNCTOX_CHEMOTAXIS_DATA_TYPE = "Relative Fluorescent Values"; public static final String IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION = "Cytokine Induction"; public static final String IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION_DATA_TYPE = "Cytokine Concentration"; public static final String IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION = "Complement Activation"; public static final String IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION_DATA_TYPE = "Percent Complement Activation"; public static final String IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION = "Leukocyte Proliferation"; public static final String IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION_DATA_TYPE = "Percent Leukocyte Proliferation"; public static final String IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY = "Cytotoxic Activity of NK Cells"; public static final String IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY_DATA_TYPE = "Percent Cytotoxic Activity"; public static final String METABOLIC_STABILITY_CYP450 = "CYP450"; public static final String METABOLIC_STABILITY_ROS = "ROS"; public static final String METABOLIC_STABILITY_GLUCURONIDATION_SULPHATION = "Glucuronidation Sulphation"; public static final String IMMUNOCELLFUNCTOX_CFU_GM = "CFU_GM"; public static final String IMMUNOCELLFUNCTOX_CFU_GM_DATA_TYPE = "CFU_GM"; public static final String DENDRIMER_TYPE = "Dendrimer"; public static final String POLYMER_TYPE = "Polymer"; public static final String LIPOSOME_TYPE = "Liposome"; public static final String CARBON_NANOTUBE_TYPE = "Carbon Nanotube"; public static final String FULLERENE_TYPE = "Fullerene"; public static final String QUANTUM_DOT_TYPE = "Quantum Dot"; public static final String METAL_PARTICLE_TYPE = "Metal Particle"; public static final String EMULSION_TYPE = "Emulsion"; public static final String COMPLEX_PARTICLE_TYPE = "Complex Particle"; public static final String CORE = "core"; public static final String SHELL = "shell"; public static final String COATING = "coating"; public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER }; public static final String[] CARBON_NANOTUBE_WALLTYPES = new String[] { "Single (SWNT)", "Double (DWMT)", "Multiple (MWNT)" }; public static final String REPORT = "Report"; public static final String ASSOCIATED_FILE = "Other Associated File"; public static final String PROTOCOL_FILE = "Protocol File"; public static final String FOLDER_WORKFLOW_DATA = "workflow_data"; public static final String FOLDER_PARTICLE = "particles"; public static final String FOLDER_REPORT = "reports"; public static final String FOLDER_PROTOCOL = "protocols"; public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] { "Free Radicals", "Peroxide" }; public static final String[] DEFAULT_DENDRIMER_BRANCHES = new String[] { "1-2", "1-3" }; public static final String[] DEFAULT_DENDRIMER_GENERATIONS = new String[] { "0", "0.5", "1.0", "1.5", "2.0", "2.5", "3.0", "3.5", "4.0", "4.5", "5.0", "5.5", "6.0", "6.5", "7.0", "7.5", "8.0", "8.5", "9.0", "9.5", "10.0" }; public static final String CHARACTERIZATION_FILE = "characterizationFile"; public static final String DNA = "DNA"; public static final String PEPTIDE = "Peptide"; public static final String SMALL_MOLECULE = "Small Molecule"; public static final String PROBE = "Probe"; public static final String ANTIBODY = "Antibody"; public static final String IMAGE_CONTRAST_AGENT = "Image Contrast Agent"; public static final String ATTACHMENT = "Attachment"; public static final String ENCAPSULATION = "Encapsulation"; public static final String[] FUNCTION_AGENT_TYPES = new String[] { DNA, PEPTIDE, SMALL_MOLECULE, PROBE, ANTIBODY, IMAGE_CONTRAST_AGENT }; public static final String[] FUNCTION_LINKAGE_TYPES = new String[] { ATTACHMENT, ENCAPSULATION }; public static final String RECEPTOR = "Receptor"; public static final String ANTIGEN = "Antigen"; public static final int MAX_VIEW_TITLE_LENGTH = 23; public static final String ABBR_COMPOSITION = "CP"; public static final String ABBR_SIZE = "SZ"; public static final String ABBR_MOLECULAR_WEIGHT = "MW"; public static final String ABBR_MORPHOLOGY = "MP"; public static final String ABBR_SHAPE = "SH"; public static final String ABBR_SURFACE = "SF"; public static final String ABBR_SOLUBILITY = "SL"; public static final String ABBR_PURITY = "PT"; public static final String ABBR_OXIDATIVE_STRESS = "OS"; public static final String ABBR_ENZYME_FUNCTION = "EF"; public static final String ABBR_CELL_VIABILITY = "CV"; public static final String ABBR_CASPASE3_ACTIVATION = "C3"; public static final String ABBR_PLATELET_AGGREGATION = "PA"; public static final String ABBR_HEMOLYSIS = "HM"; public static final String ABBR_PLASMA_PROTEIN_BINDING = "PB"; public static final String ABBR_COAGULATION = "CG"; public static final String ABBR_OXIDATIVE_BURST = "OB"; public static final String ABBR_CHEMOTAXIS = "CT"; public static final String ABBR_LEUKOCYTE_PROLIFERATION = "LP"; public static final String ABBR_PHAGOCYTOSIS = "PC"; public static final String ABBR_CYTOKINE_INDUCTION = "CI"; public static final String ABBR_CFU_GM = "CU"; public static final String ABBR_COMPLEMENT_ACTIVATION = "CA"; public static final String ABBR_NKCELL_CYTOTOXIC_ACTIVITY = "NK"; public static final String[] SPECIES_SCIENTIFIC = { "Mus musculus", "Homo sapiens", "Rattus rattus", "Sus scrofa", "Meriones unguiculatus", "Mesocricetus auratus", "Cavia porcellus", "Bos taurus", "Canis familiaris", "Capra hircus", "Equus Caballus", "Ovis aries", "Felis catus", "Saccharomyces cerevisiae", "Danio rerio" }; public static final String[] SPECIES_COMMON = { "Mouse", "Human", "Rat", "Pig", "Mongolian Gerbil", "Hamster", "Guinea pig", "Cattle", "Dog", "Goat", "Horse", "Sheep", "Cat", "Yeast", "Zebrafish" }; public static final String UNIT_PERCENT = "%"; public static final String UNIT_CFU = "CFU"; public static final String UNIT_RFU = "RFU"; public static final String UNIT_SECOND = "SECOND"; public static final String UNIT_MG_ML = "mg/ml"; public static final String UNIT_FOLD = "Fold"; public static final String ORGANIC_HYDROCARBON = "organic:hydrocarbon"; public static final String ORGANIC_CARBON = "organic:carbon"; public static final String ORGANIC = "organic"; public static final String INORGANIC = "inorganic"; public static final String COMPLEX = "complex"; public static final Map<String, String> PARTICLE_CLASSIFICATION_MAP; static { PARTICLE_CLASSIFICATION_MAP = new HashMap<String, String>(); PARTICLE_CLASSIFICATION_MAP.put(DENDRIMER_TYPE, ORGANIC_HYDROCARBON); PARTICLE_CLASSIFICATION_MAP.put(POLYMER_TYPE, ORGANIC_HYDROCARBON); PARTICLE_CLASSIFICATION_MAP.put(FULLERENE_TYPE, ORGANIC_CARBON); PARTICLE_CLASSIFICATION_MAP.put(CARBON_NANOTUBE_TYPE, ORGANIC_CARBON); PARTICLE_CLASSIFICATION_MAP.put(LIPOSOME_TYPE, ORGANIC); PARTICLE_CLASSIFICATION_MAP.put(EMULSION_TYPE, ORGANIC); PARTICLE_CLASSIFICATION_MAP.put(METAL_PARTICLE_TYPE, INORGANIC); PARTICLE_CLASSIFICATION_MAP.put(QUANTUM_DOT_TYPE, INORGANIC); PARTICLE_CLASSIFICATION_MAP.put(COMPLEX_PARTICLE_TYPE, COMPLEX); } public static final String CSM_PI = APP_OWNER + "_PI"; public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher"; public static final String CSM_ADMIN = APP_OWNER + "_Administrator"; public static final String CSM_PUBLIC_GROUP = "Public"; public static final String[] VISIBLE_GROUPS = new String[] { CSM_PI, CSM_RESEARCHER }; public static final String AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX = "copy_"; public static final String AUTO_COPY_CHARACTERIZATION_VIEW_COLOR = "red"; }
package io.tetrapod.core; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.util.ReferenceCountUtil; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.serialize.DataSource; import io.tetrapod.core.serialize.datasources.ByteBufDataSource; import io.tetrapod.protocol.core.*; import java.io.IOException; import org.slf4j.*; /** * Manages a session between two tetrapods */ public class WireSession extends Session { private static final Logger logger = LoggerFactory.getLogger(WireSession.class); private static final int WIRE_VERSION = 1; private static final int WIRE_OPTIONS = 0x00000000; private boolean needsHandshake = true; public WireSession(SocketChannel channel, WireSession.Helper helper) { super(channel, helper); channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4, 0, 0)); channel.pipeline().addLast(this); } private synchronized boolean needsHandshake() { return needsHandshake; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { lastHeardFrom.set(System.currentTimeMillis()); try { final ByteBuf in = (ByteBuf) msg; final int len = in.readInt() - 1; final byte envelope = in.readByte(); logger.trace("{} channelRead {}", this, envelope); if (needsHandshake()) { readHandshake(in, envelope); fireSessionStartEvent(); } else { read(in, len, envelope); } } finally { ReferenceCountUtil.release(msg); } } private void read(final ByteBuf in, final int len, final byte envelope) throws IOException { assert (len == in.readableBytes()); logger.trace("Read message {} with {} bytes", envelope, len); switch (envelope) { case ENVELOPE_REQUEST: readRequest(in); break; case ENVELOPE_RESPONSE: readResponse(in); break; case ENVELOPE_MESSAGE: case ENVELOPE_BROADCAST: readMessage(in, envelope == ENVELOPE_BROADCAST); break; case ENVELOPE_PING: sendPong(); break; case ENVELOPE_PONG: break; default: logger.error("{} Unexpected Envelope Type {}", this, envelope); close(); } } private void readHandshake(final ByteBuf in, final byte envelope) throws IOException { if (envelope != ENVELOPE_HANDSHAKE) { throw new IOException(this + "handshake not valid"); } int theirVersion = in.readInt(); @SuppressWarnings("unused") int theirOptions = in.readInt(); if (theirVersion != WIRE_VERSION) { throw new IOException(this + "handshake version does not match " + theirVersion); } logger.trace("{} handshake succeeded", this); synchronized (this) { needsHandshake = false; } } private void readResponse(final ByteBuf in) throws IOException { final ByteBufDataSource reader = new ByteBufDataSource(in); final ResponseHeader header = new ResponseHeader(); boolean logged = false; header.read(reader); final Async async = pendingRequests.remove(header.requestId); if (async != null) { // Dispatches response to ourselves if we sent the request (fromId == myId) or // if fromId is UNADRESSED this handles the edge case where we are registering // ourselves and so did not yet have an entityId if (async.header.fromId == myId || async.header.fromId == Core.UNADDRESSED) { final Response res = (Response) StructureFactory.make(async.header.contractId, header.structId); if (res != null) { res.read(reader); logged = commsLog("%s [%d] <- %s", this, header.requestId, res.dump()); getDispatcher().dispatch(new Runnable() { public void run() { async.setResponse(res); } }); } else { logger.warn("{} Could not find response structure {}", this, header.structId); } } else if (relayHandler != null) { // HACK: Expensive, for better debug logs. Response res = null; // if (logger.isDebugEnabled() && header.structId == 1) { // res = (Response) StructureFactory.make(async.header.contractId, header.structId); // if (res != null) { // int mark = in.readerIndex(); // res.read(reader); // in.readerIndex(mark); logged = commsLog("%s [%d] <- Response.%d %s", this, header.requestId, header.structId, res == null ? "" : res.dump()); relayResponse(header, async, in); } } else { logger.warn("{} Could not find pending request for {}", this, header.dump()); } if (!logged) logged = commsLog("%s [%d] <- Response.%d", this, header.requestId, header.structId); } private void readRequest(final ByteBuf in) throws IOException { DataSource reader = new ByteBufDataSource(in); final RequestHeader header = new RequestHeader(); boolean logged = true; header.read(reader); // set/clobber with known details, unless it's from a trusted tetrapod if (theirType != TYPE_TETRAPOD) { header.fromId = theirId; header.fromType = theirType; } if ((header.toId == DIRECT) || header.toId == myId) { final Request req = (Request) StructureFactory.make(header.contractId, header.structId); if (req != null) { req.read(reader); logged = commsLog("%s [%d] <- %s", this, header.requestId, req.dump()); dispatchRequest(header, req); } else { logger.warn("Could not find request structure {}", header.structId); sendResponse(new Error(ERROR_SERIALIZATION), header.requestId); } } else if (relayHandler != null) { logged = commsLog("%s [%d] <- Request.%d", this, header.requestId, header.structId); relayRequest(header, in); } if (!logged) logged = commsLog("%s [%d] <- Request.%d", this, header.requestId, header.structId); } private void readMessage(ByteBuf in, boolean isBroadcast) throws IOException { final ByteBufDataSource reader = new ByteBufDataSource(in); final MessageHeader header = new MessageHeader(); header.read(reader); if (theirType != TYPE_TETRAPOD) { // fromId MUST be their id, unless it's a tetrapod session, which could be relaying header.fromId = theirId; } commsLog("%s [M] <- T%d.Message:%d %s toId=%d, myId=%d", this, header.topicId, header.structId, getNameFor(header), header.toId, myId); if (relayHandler == null || header.toId == myId || (header.toId == UNADDRESSED && header.topicId == UNADDRESSED)) { dispatchMessage(header, reader); } else { relayHandler.relayMessage(header, in, isBroadcast); } } protected void dispatchMessage(final MessageHeader header, final ByteBufDataSource reader) throws IOException { final Message msg = (Message) StructureFactory.make(header.contractId, header.structId); if (msg != null) { msg.read(reader); dispatchMessage(header, msg); } else { logger.warn("Could not find message structure {}", header.structId); } } @Override protected ByteBuf makeFrame(Structure header, Structure payload, byte envelope) { return makeFrame(header, payload, envelope, channel.alloc().buffer(128)); } private ByteBuf makeFrame(Structure header, Structure payload, byte envelope, ByteBuf buffer) { final ByteBufDataSource data = new ByteBufDataSource(buffer); buffer.writeInt(0); buffer.writeByte(envelope); try { header.write(data); payload.write(data); buffer.setInt(0, buffer.writerIndex() - 4); // go back and write message length, now that we know it return buffer; } catch (IOException e) { ReferenceCountUtil.release(buffer); logger.error(e.getMessage(), e); return null; } } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { writeHandshake(); scheduleHealthCheck(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { fireSessionStopEvent(); cancelAllPendingRequests(); } private void writeHandshake() { logger.trace("{} Writing handshake", this); synchronized (this) { needsHandshake = true; } final ByteBuf buffer = channel.alloc().buffer(9); buffer.writeInt(9); buffer.writeByte(ENVELOPE_HANDSHAKE); buffer.writeInt(WIRE_VERSION); buffer.writeInt(WIRE_OPTIONS); writeFrame(buffer); } @Override protected void sendPing() { final ByteBuf buffer = channel.alloc().buffer(5); buffer.writeInt(1); buffer.writeByte(ENVELOPE_PING); writeFrame(buffer); } @Override protected void sendPong() { final ByteBuf buffer = channel.alloc().buffer(5); buffer.writeInt(1); buffer.writeByte(ENVELOPE_PONG); writeFrame(buffer); } // /////////////////////////////////// RELAY ///////////////////////////////////// @Override protected Object makeFrame(Structure header, ByteBuf payload, byte envelope) { // OPTIMIZE: Find a way to relay without the extra allocation & copy ByteBuf buffer = channel.alloc().buffer(32 + payload.readableBytes()); ByteBufDataSource data = new ByteBufDataSource(buffer); try { buffer.writeInt(0); buffer.writeByte(envelope); header.write(data); buffer.writeBytes(payload); buffer.setInt(0, buffer.writerIndex() - 4); // Write message length, now that we know it return buffer; } catch (IOException e) { ReferenceCountUtil.release(buffer); logger.error(e.getMessage(), e); return null; } } private void relayRequest(final RequestHeader header, final ByteBuf in) { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { ses.sendRelayedRequest(header, in, this); } else { logger.warn("Could not find a relay session for {}", header.toId); sendResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header.requestId); } } private void relayResponse(ResponseHeader header, Async async, ByteBuf in) { header.requestId = async.header.requestId; async.session.sendRelayedResponse(header, in); } public static String dumpBuffer(ByteBuf buf) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.writerIndex(); i++) { sb.append(buf.getByte(i)); sb.append(' '); } return sb.toString(); } @Override public String getPeerHostname() { return channel.remoteAddress().getHostString(); } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.Concept; import gov.nih.nci.ncicb.cadsr.domain.DomainObjectFactory; import gov.nih.nci.ncicb.cadsr.domain.ObjectClassRelationship; import gov.nih.nci.ncicb.cadsr.loader.ElementsLists; import gov.nih.nci.ncicb.cadsr.loader.ReviewTracker; import gov.nih.nci.ncicb.cadsr.loader.ReviewTrackerType; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewListener; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationListener; import gov.nih.nci.ncicb.cadsr.loader.ui.event.SearchEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.SearchListener; import gov.nih.nci.ncicb.cadsr.loader.ui.event.TreeEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.TreeListener; import gov.nih.nci.ncicb.cadsr.loader.ui.event.ViewChangeEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.ViewChangeListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.AbstractUMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.AssociationEndNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.AssociationNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.AttributeNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ClassNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.InheritedAttributeNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.NodeUtil; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.PackageNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ReviewableUMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.RootNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.TreeBuilder; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ValidationNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ValueDomainNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ValueMeaningNode; import gov.nih.nci.ncicb.cadsr.loader.ui.util.TreeUtil; import gov.nih.nci.ncicb.cadsr.loader.util.LookupUtil; import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor; import gov.nih.nci.ncicb.cadsr.loader.util.RunMode; import gov.nih.nci.ncicb.cadsr.loader.util.UserPreferences; import gov.nih.nci.ncicb.cadsr.loader.util.UserPreferencesEvent; import gov.nih.nci.ncicb.cadsr.loader.util.UserPreferencesListener; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import java.util.Set; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.ToolTipManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; /** * Panel from where you navigate the UML Elements. * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> * @author <a href="mailto:rokickik@mail.nih.gov">Konrad Rokicki</a> */ public class NavigationPanel extends JPanel implements ActionListener, MouseListener, ReviewListener, NavigationListener, KeyListener, SearchListener, TreeListener, UserPreferencesListener { private JTree tree; private TreeNode rootTreeNode; // only one of these tree nodes is used at a time, // the one being used is pointed to by rootTreeNode private TreeNode rootUnsortedTreeNode; private TreeNode rootSortedTreeNode; private JPopupMenu nodePopup, blankPopup; private JScrollPane scrollPane; private UMLNode rootNode = TreeBuilder.getInstance().getRootNode(); private List<ViewChangeListener> viewListeners = new ArrayList(); private List<NavigationListener> navigationListeners = new ArrayList(); private ElementsLists elements = ElementsLists.getInstance(); private JCheckBoxMenuItem inheritedAttItem, assocItem, sortItem; private TreePath selectedPath; private ReviewTracker reviewTracker; public NavigationPanel() { try { initUI(); TreeBuilder.getInstance().addTreeListener(this); UserPreferences prefs = UserPreferences.getInstance(); prefs.addUserPreferencesListener(this); RunMode runMode = (RunMode)(UserSelections.getInstance().getProperty("MODE")); if(runMode.equals(RunMode.Curator)) { reviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator); } else { reviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner); } } catch(Exception e) { e.printStackTrace(); } } public void addViewChangeListener(ViewChangeListener l) { viewListeners.add(l); } public void addNavigationListener(NavigationListener l) { navigationListeners.add(l); } public void reviewChanged(ReviewEvent event) { ReviewableUMLNode node = (ReviewableUMLNode)event.getUserObject(); node.setReviewed(event.isReviewed()); tree.repaint(); } private void initUI() throws Exception { rootTreeNode = buildTree(); rootUnsortedTreeNode = rootTreeNode; tree = new JTree(new DefaultTreeModel(rootTreeNode)); tree.setRootVisible(false); tree.setShowsRootHandles(true); tree.addKeyListener(this); UserPreferences prefs = UserPreferences.getInstance(); if (prefs.getSortElements()) { showSortedTree(true); } //Traverse Tree expanding all nodes TreeUtil.expandAll(tree, rootTreeNode); tree.setCellRenderer(new UMLTreeCellRenderer()); this.setLayout(new BorderLayout()); scrollPane = new JScrollPane(tree); this.add(scrollPane, BorderLayout.CENTER); ToolTipManager.sharedInstance().registerComponent(tree); buildPopupMenu(); } /** * Replace the current tree model with a sorted or unsorted one, depending * on the boolean parameter. * @param sorted true to show a sorted tree, false to show the original tree */ private void showSortedTree(boolean sorted) { if (sorted) { if (rootSortedTreeNode == null) { // this extra tree is only built if the user requests it rootSortedTreeNode = buildSortedTree( (DefaultMutableTreeNode)rootUnsortedTreeNode); } rootTreeNode = rootSortedTreeNode; } else { rootTreeNode = rootUnsortedTreeNode; } tree.setModel(new DefaultTreeModel(rootTreeNode)); } /** * Find the specified path in the given tree. To compare objects between * the path and the tree, toString() is called on the respective objects. * Thus, the path could be composed of Strings or TreeNodes from another * tree or whatever. * @param path list of objects on the path, beginning with the root * @param node root of the subtree to search * @return nodes in the tree forming the path, or null if the path is not found */ private List<TreeNode> translatePath(List path, TreeNode node) { // TODO: Find the correct node given two identical paths. // For example suppose we have two paths Classes/String and Classes/String. // This method will always translate to the first path, regardless of the // actual path given. List tail = new ArrayList(); tail.addAll(path); Object target = tail.remove(0); if (!node.toString().equals(target.toString())) { return null; } List<TreeNode> newPath = new ArrayList<TreeNode>(); newPath.add(node); // no more nodes to find, just return this one if (tail.isEmpty()) return newPath; Enumeration e = node.children(); while(e.hasMoreElements()) { TreeNode child = (TreeNode)e.nextElement(); List nodes = translatePath(tail, child); if (nodes != null) { newPath.addAll(nodes); return newPath; } } // the path was not found under this subtree return null; } /** * Builds a sorted version of the tree. * @param oldNode the root of the unsorted tree * @return the root of the sorted tree */ private DefaultMutableTreeNode buildSortedTree(DefaultMutableTreeNode oldNode) { return buildSortedTree(oldNode, new DefaultMutableTreeNode(oldNode.getUserObject())); } /** * Builds a sorted version of the specified subtree. * @param oldNode the node on the unsorted tree * @param newNode the node on the sorted tree * @return the node on the sorted tree */ private DefaultMutableTreeNode buildSortedTree(DefaultMutableTreeNode oldNode, DefaultMutableTreeNode newNode) { List<DefaultMutableTreeNode> children = new ArrayList(); Enumeration e = oldNode.children(); while(e.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode)e.nextElement(); children.add(child); } // sort everything except the first level if (!(oldNode.getUserObject() instanceof RootNode)) { Collections.sort(children, new Comparator<DefaultMutableTreeNode>() { public int compare(DefaultMutableTreeNode node1, DefaultMutableTreeNode node2) { return node1.getUserObject().toString().compareTo( node2.getUserObject().toString()); } }); } for(DefaultMutableTreeNode oldChild : children) { DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(oldChild.getUserObject()); newNode.add(newChild); buildSortedTree(oldChild, newChild); } return newNode; } public void actionPerformed(ActionEvent event) { DefaultMutableTreeNode dmtn, node; TreePath path = tree.getSelectionPath(); if(path != null) { dmtn = (DefaultMutableTreeNode) path.getLastPathComponent(); if(event.getSource() instanceof JMenuItem) { JMenuItem menuItem = (JMenuItem)event.getSource(); ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_CONCEPTS); evt.setViewObject(dmtn.getUserObject()); if(menuItem.getActionCommand().equals("OPEN_NEW_TAB")) evt.setInNewTab(true); else evt.setInNewTab(false); fireViewChangeEvent(evt); } } if(event.getSource() instanceof JMenuItem) { JMenuItem menuItem = (JMenuItem)event.getSource(); if(menuItem.getActionCommand().equals("COLLAPSE_ALL")) { TreeUtil.collapseAll(tree); } else if(menuItem.getActionCommand().equals("EXPAND_ALL")) { TreeUtil.expandAll(tree, rootTreeNode); } else if(menuItem.getActionCommand().equals("PREF_INHERITED_ATT")) { UserPreferences prefs = UserPreferences.getInstance(); prefs.setShowInheritedAttributes(inheritedAttItem.isSelected()); } else if(menuItem.getActionCommand().equals("PREF_INCLASS_ASSOC")) { UserPreferences prefs = UserPreferences.getInstance(); prefs.setViewAssociationType(assocItem.isSelected()?"true":"false"); } else if(menuItem.getActionCommand().equals("PREF_SORT_ELEM")) { UserPreferences prefs = UserPreferences.getInstance(); prefs.setSortElements(sortItem.isSelected()); } } } public void keyPressed(KeyEvent e) { DefaultMutableTreeNode selected = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //if the down arrow is pressed then display the next element //in the tree in the ViewPanel if(e.getKeyCode() == KeyEvent.VK_DOWN && selected != null) { if (selected.getNextNode() != null) { TreePath path = new TreePath(selected.getNextNode().getPath()); tree.makeVisible(path); newViewEvent(path); } } //if the up arrow is pressed then display the previous element //in the tree in the ViewPanel if(e.getKeyCode() == KeyEvent.VK_UP && selected != null) { if (selected.getPreviousNode() != null) { TreePath path = new TreePath(selected.getPreviousNode().getPath()); tree.makeVisible(path); newViewEvent(path); } } } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void mousePressed(MouseEvent e) { showPopup(e); } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseReleased(MouseEvent e) { showPopup(e); doMouseEvent(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger()) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); tree.setSelectionPath(path); if(path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); Object o = node.getUserObject(); if((o instanceof ClassNode) || (o instanceof AttributeNode) ) nodePopup.show(e.getComponent(), e.getX(), e.getY()); } else { blankPopup.show(e.getComponent(), e.getX(), e.getY()); } } } private void doMouseEvent(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) { selectedPath = tree.getPathForLocation(e.getX(), e.getY()); newViewEvent(selectedPath); } else if(e.getButton() == MouseEvent.BUTTON2) { selectedPath = tree.getPathForLocation(e.getX(), e.getY()); if(selectedPath != null) { DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) selectedPath.getLastPathComponent(); ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_CONCEPTS); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(true); fireViewChangeEvent(evt); } } } private void newViewEvent(TreePath path) { if(path != null) { DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) path.getLastPathComponent(); Object o = dmtn.getUserObject(); if((o instanceof ClassNode) || (o instanceof AttributeNode)) { if(o instanceof InheritedAttributeNode) { // inherited attribute InheritedAttributeNode attNode = (InheritedAttributeNode)o; String fpath = attNode.getFullPath(); int sd = fpath.lastIndexOf("."); String sourceClassName = fpath.substring(0, sd); String attributeName = fpath.substring(sd+1); AttributeNode anode = findSuper(sourceClassName,attributeName); if (anode != null) { ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_INHERITED); evt.setViewObject(anode); evt.setInNewTab(false); fireViewChangeEvent(evt); } } else { // normal attribute ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_CONCEPTS); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(false); fireViewChangeEvent(evt); } } else if(o instanceof AssociationNode) { ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_ASSOCIATION); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(false); fireViewChangeEvent(evt); } else if(o instanceof ValueDomainNode) { ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_VALUE_DOMAIN); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(false); fireViewChangeEvent(evt); } else if(o instanceof ValueMeaningNode) { ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_VALUE_MEANING); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(false); fireViewChangeEvent(evt); } } } /** * Find the given attribute in the given class's inheritance hierarchy. * Returns the first non-inherited AttributeNode. * @param className fully qualified class name * @param attributeName attribute name * @return */ private AttributeNode findSuper(String className, String attributeName) { // find the superclass by searching the OCR's for a generalization List<ObjectClassRelationship> ocrs = elements.getElements(DomainObjectFactory.newObjectClassRelationship()); String superClassName = null; for(ObjectClassRelationship ocr : ocrs) { if (ocr.getType() == ObjectClassRelationship.TYPE_IS && ocr.getSource().getLongName().equals(className)) { superClassName = LookupUtil.lookupFullName(ocr.getTarget()); break; } } if (superClassName == null) { System.err.println("Superclass not found for "+className); return null; } // find the super class in the tree int div = superClassName.lastIndexOf("."); String sPackage = superClassName.substring(0, div); String sName = superClassName.substring(div+1); for(Object pchild : rootNode.getChildren()) { PackageNode pnode = (PackageNode)pchild; if (pnode.getFullPath().equals(sPackage)) { for(Object cchild : pnode.getChildren()) { ClassNode cnode = (ClassNode)cchild; if (cnode.getDisplay().equals(sName)) { PackageNode inherited = null; for(Object achild : cnode.getChildren()) { if ("Inherited Attributes".equals( ((UMLNode)achild).getDisplay())) { // remember the inheritance subtree for later inherited = (PackageNode)achild; } else if (achild instanceof AttributeNode) { AttributeNode anode = (AttributeNode)achild; if (anode.getDisplay().equals(attributeName)) { return anode; } } } // attribute wasn't found, check inheritance subtree if (inherited != null) { for(Object achild : inherited.getChildren()) { AttributeNode anode = (AttributeNode)achild; if (anode.getDisplay().equals(attributeName)) { return findSuper(cnode.getFullPath(), attributeName); } } } } } } } return null; } private void buildPopupMenu() { JMenuItem newTabItem = new JMenuItem("Open in New Tab"); JMenuItem openItem = new JMenuItem("Open"); newTabItem.setActionCommand("OPEN_NEW_TAB"); openItem.setActionCommand("OPEN"); nodePopup = new JPopupMenu(); newTabItem.addActionListener(this); openItem.addActionListener(this); nodePopup.add(openItem); nodePopup.add(newTabItem); nodePopup.addSeparator(); JMenu preferenceMenu = new JMenu("Preferences"); inheritedAttItem = new JCheckBoxMenuItem(PropertyAccessor.getProperty("preference.inherited.attributes")); inheritedAttItem.setActionCommand("PREF_INHERITED_ATT"); assocItem = new JCheckBoxMenuItem(PropertyAccessor.getProperty("preference.view.association")); assocItem.setActionCommand("PREF_INCLASS_ASSOC"); sortItem = new JCheckBoxMenuItem(PropertyAccessor.getProperty("preference.sort.elements")); sortItem.setActionCommand("PREF_SORT_ELEM"); UserPreferences prefs = UserPreferences.getInstance(); inheritedAttItem.setSelected(prefs.getShowInheritedAttributes()); inheritedAttItem.addActionListener(this); assocItem.setSelected(prefs.getViewAssociationType().equalsIgnoreCase("true")); assocItem.addActionListener(this); sortItem.setSelected(prefs.getSortElements()); sortItem.addActionListener(this); preferenceMenu.add(inheritedAttItem); preferenceMenu.add(assocItem); preferenceMenu.add(sortItem); JMenuItem collapseAllItem = new JMenuItem("Collapse All"); collapseAllItem.setActionCommand("COLLAPSE_ALL"); collapseAllItem.addActionListener(this); JMenuItem expandAllItem = new JMenuItem("Expand All"); expandAllItem.setActionCommand("EXPAND_ALL"); expandAllItem.addActionListener(this); blankPopup = new JPopupMenu(); blankPopup.add(collapseAllItem); blankPopup.add(expandAllItem); blankPopup.add(preferenceMenu); // nodePopup.add(collapseAllItem); // nodePopup.add(expandAllItem); // nodePopup.add(preferenceMenu); tree.addMouseListener(this); } private DefaultMutableTreeNode buildTree() { DefaultMutableTreeNode node = new DefaultMutableTreeNode(rootNode); return doNode(node, rootNode); } private DefaultMutableTreeNode doNode(DefaultMutableTreeNode node, UMLNode parentNode) { Set<UMLNode> children = parentNode.getChildren(); for(UMLNode child : children) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(child); if(!(child instanceof ValidationNode) && !(child instanceof AssociationEndNode)) node.add(newNode); doNode(newNode, child); } return node; } public void treeChange(TreeEvent event) { this.remove(scrollPane); rootNode = TreeBuilder.getInstance().getRootNode(); try { initUI(); } catch (Exception e) { } this.updateUI(); } public void navigate(NavigationEvent event) { DefaultMutableTreeNode selected = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if(event.getType() == NavigationEvent.NAVIGATE_NEXT && selected.getNextNode() != null) { TreePath path = new TreePath(selected.getNextNode().getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); } else if(event.getType() == NavigationEvent.NAVIGATE_PREVIOUS && selected.getPreviousNode() != null) { TreePath path = new TreePath(selected.getPreviousNode().getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); } } public void search(SearchEvent event) { DefaultMutableTreeNode selected = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); TreePath path = null; if(event.getSearchFromBeginning()) selected = null; //if(event.getSearchByLongName()) { //search the tree in a forward direction from top to bottom if(!event.getSearchFromBottom()) { //if no node is selected then select the first node if(selected == null) selected = (DefaultMutableTreeNode)tree.getPathForRow(0).getLastPathComponent(); selected = selected.getNextNode(); while(selected != null) { AbstractUMLNode n = (AbstractUMLNode) selected.getUserObject(); if(event.getSearchByLongName()) { Concept [] concepts = NodeUtil.getConceptsFromNode(n); for(int i=0; i < concepts.length; i++) { //System.out.println("Concepts" + i +" "+ concepts[i]); if(!event.getSearchString().toLowerCase().contains(concepts[i].getLongName().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); selected = null; break; } } } else { //if there is a match then select that node in the tree if(event.getExactMatch()) { if((n.getDisplay().toLowerCase()).equals(event.getSearchString().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); break; } } else if((n.getDisplay().toLowerCase()).contains(event.getSearchString().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); break; } } if(selected != null) selected = selected.getNextNode(); } } //search the tree in backward direction from bottom to top else { //if no node is selected then select the last node in the tree if(selected == null) selected = (DefaultMutableTreeNode)tree.getPathForRow(tree.getRowCount()-1).getLastPathComponent(); selected = selected.getPreviousNode(); while(selected != null) { AbstractUMLNode n = (AbstractUMLNode) selected.getUserObject(); if(event.getSearchByLongName()) { Concept [] concepts = NodeUtil.getConceptsFromNode(n); for(int i=0; i < concepts.length; i++) { //System.out.println("Concepts" + i +" "+ concepts[i]); if(event.getSearchString().toLowerCase().contains(concepts[i].getLongName().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); selected = null; break; } } } else { //if there is a match then select that node in the tree if((n.getDisplay().toLowerCase()).contains(event.getSearchString().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); break; } } if(selected != null) selected = selected.getPreviousNode(); } } //if no match was found display error message if(path == null) { //int result = JOptionPane.showConfirmDialog(null, "Text Not Found", "No Match", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); //if(result == JOptionPane.YES_OPTION) // search(event); JOptionPane.showMessageDialog(null,"Text Not Found", "No Match",JOptionPane.ERROR_MESSAGE); } } private void fireViewChangeEvent(ViewChangeEvent evt) { fireNavigationEvent(new NavigationEvent(NavigationEvent.NAVIGATE_NEXT)); for(ViewChangeListener vcl : viewListeners) vcl.viewChanged(evt); } private void fireNavigationEvent(NavigationEvent evt) { for(NavigationListener nl : navigationListeners) { nl.navigate(evt); } } public void preferenceChange(UserPreferencesEvent event) { if(event.getTypeOfEvent() == UserPreferencesEvent.SORT_ELEMENTS) { Boolean sortClasses = new Boolean (event.getValue()); showSortedTree(sortClasses); TreeUtil.expandAll(tree, rootTreeNode); if (selectedPath != null) { // reselect the node which was selected List pathList = Arrays.asList(selectedPath.getPath()); List newPath = translatePath(pathList, rootTreeNode); if (newPath != null) tree.setSelectionPath(new TreePath(newPath.toArray())); } } } }
package io.tetrapod.core; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.util.ReferenceCountUtil; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.serialize.DataSource; import io.tetrapod.core.serialize.datasources.ByteBufDataSource; import io.tetrapod.protocol.core.*; import java.io.IOException; import org.slf4j.*; /** * Manages a session between two tetrapods */ public class WireSession extends Session { private static final Logger logger = LoggerFactory.getLogger(WireSession.class); private static final int WIRE_VERSION = 1; private static final int WIRE_OPTIONS = 0x00000000; private boolean needsHandshake = true; public WireSession(SocketChannel channel, WireSession.Helper helper) { super(channel, helper); channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4, 0, 0)); channel.pipeline().addLast(this); } private synchronized boolean needsHandshake() { return needsHandshake; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { lastHeardFrom.set(System.currentTimeMillis()); try { final ByteBuf in = (ByteBuf) msg; final int len = in.readInt() - 1; final byte envelope = in.readByte(); logger.trace("{} channelRead {}", this, envelope); if (needsHandshake()) { readHandshake(in, envelope); fireSessionStartEvent(); } else { read(in, len, envelope); } } finally { ReferenceCountUtil.release(msg); } } private void read(final ByteBuf in, final int len, final byte envelope) throws IOException { assert (len == in.readableBytes()); logger.trace("Read message {} with {} bytes", envelope, len); switch (envelope) { case ENVELOPE_REQUEST: readRequest(in); break; case ENVELOPE_RESPONSE: readResponse(in); break; case ENVELOPE_MESSAGE: case ENVELOPE_BROADCAST: readMessage(in, envelope == ENVELOPE_BROADCAST); break; case ENVELOPE_PING: sendPong(); break; case ENVELOPE_PONG: break; default: logger.error("{} Unexpected Envelope Type {}", this, envelope); close(); } } private void readHandshake(final ByteBuf in, final byte envelope) throws IOException { if (envelope != ENVELOPE_HANDSHAKE) { throw new IOException(this + "handshake not valid"); } int theirVersion = in.readInt(); @SuppressWarnings("unused") int theirOptions = in.readInt(); if (theirVersion != WIRE_VERSION) { throw new IOException(this + "handshake version does not match " + theirVersion); } logger.trace("{} handshake succeeded", this); synchronized (this) { needsHandshake = false; } } private void readResponse(final ByteBuf in) throws IOException { final ByteBufDataSource reader = new ByteBufDataSource(in); final ResponseHeader header = new ResponseHeader(); boolean logged = false; header.read(reader); final Async async = pendingRequests.remove(header.requestId); if (async != null) { // Dispatches response to ourselves if we sent the request (fromId == myId) or // if fromId is UNADRESSED this handles the edge case where we are registering // ourselves and so did not yet have an entityId if (async.header.fromId == myId || async.header.fromId == Core.UNADDRESSED) { final Response res = (Response) StructureFactory.make(async.header.contractId, header.structId); if (res != null) { res.read(reader); logged = commsLog("%s [%d] <- %s", this, header.requestId, res.dump()); getDispatcher().dispatch(new Runnable() { public void run() { async.setResponse(res); } }); } else { logger.warn("{} Could not find response structure {}", this, header.structId); } } else if (relayHandler != null) { // HACK: Expensive, for better debug logs. Response res = null; // if (logger.isDebugEnabled() && header.structId == 1) { // res = (Response) StructureFactory.make(async.header.contractId, header.structId); // if (res != null) { // int mark = in.readerIndex(); // res.read(reader); // in.readerIndex(mark); logged = commsLog("%s [%d] <- Response.%d %s", this, header.requestId, header.structId, res == null ? "" : res.dump()); relayResponse(header, async, in); } } else { logger.warn("{} Could not find pending request for {}", this, header.dump()); } if (!logged) logged = commsLog("%s [%d] <- Response.%d", this, header.requestId, header.structId); } private void readRequest(final ByteBuf in) throws IOException { DataSource reader = new ByteBufDataSource(in); final RequestHeader header = new RequestHeader(); boolean logged = true; header.read(reader); // set/clobber with known details, unless it's from a trusted tetrapod if (theirType != TYPE_TETRAPOD) { header.fromId = theirId; header.fromType = theirType; } if ((header.toId == DIRECT) || header.toId == myId) { final Request req = (Request) StructureFactory.make(header.contractId, header.structId); if (req != null) { req.read(reader); logged = commsLog("%s [%d] <- %s", this, header.requestId, req.dump()); dispatchRequest(header, req); } else { logger.warn("Could not find request structure {}", header.structId); sendResponse(new Error(ERROR_SERIALIZATION), header.requestId); } } else if (relayHandler != null) { logged = commsLog("%s [%d] <- Request.%d", this, header.requestId, header.structId); relayRequest(header, in); } if (!logged) logged = commsLog("%s [%d] <- Request.%d", this, header.requestId, header.structId); } private void readMessage(ByteBuf in, boolean isBroadcast) throws IOException { final ByteBufDataSource reader = new ByteBufDataSource(in); final MessageHeader header = new MessageHeader(); header.read(reader); if (theirType != TYPE_TETRAPOD) { // fromId MUST be their id, unless it's a tetrapod session, which could be relaying header.fromId = theirId; } commsLog("%s [M] <- T%d.Message:%d %s", this, header.topicId, header.structId, getNameFor(header)); if (relayHandler == null || header.toId == myId || (header.toId == UNADDRESSED && header.topicId == UNADDRESSED)) { dispatchMessage(header, reader); } else { relayHandler.relayMessage(header, in, isBroadcast); } } protected void dispatchMessage(final MessageHeader header, final ByteBufDataSource reader) throws IOException { final Message msg = (Message) StructureFactory.make(header.contractId, header.structId); if (msg != null) { msg.read(reader); dispatchMessage(header, msg); } else { logger.warn("Could not find message structure {}", header.structId); } } @Override protected ByteBuf makeFrame(Structure header, Structure payload, byte envelope) { return makeFrame(header, payload, envelope, channel.alloc().buffer(128)); } private ByteBuf makeFrame(Structure header, Structure payload, byte envelope, ByteBuf buffer) { final ByteBufDataSource data = new ByteBufDataSource(buffer); buffer.writeInt(0); buffer.writeByte(envelope); try { header.write(data); payload.write(data); buffer.setInt(0, buffer.writerIndex() - 4); // go back and write message length, now that we know it return buffer; } catch (IOException e) { ReferenceCountUtil.release(buffer); logger.error(e.getMessage(), e); return null; } } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { writeHandshake(); scheduleHealthCheck(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { fireSessionStopEvent(); cancelAllPendingRequests(); } private void writeHandshake() { logger.trace("{} Writing handshake", this); synchronized (this) { needsHandshake = true; } final ByteBuf buffer = channel.alloc().buffer(9); buffer.writeInt(9); buffer.writeByte(ENVELOPE_HANDSHAKE); buffer.writeInt(WIRE_VERSION); buffer.writeInt(WIRE_OPTIONS); writeFrame(buffer); } @Override protected void sendPing() { final ByteBuf buffer = channel.alloc().buffer(5); buffer.writeInt(1); buffer.writeByte(ENVELOPE_PING); writeFrame(buffer); } @Override protected void sendPong() { final ByteBuf buffer = channel.alloc().buffer(5); buffer.writeInt(1); buffer.writeByte(ENVELOPE_PONG); writeFrame(buffer); } // /////////////////////////////////// RELAY ///////////////////////////////////// @Override protected Object makeFrame(Structure header, ByteBuf payload, byte envelope) { // OPTIMIZE: Find a way to relay without the extra allocation & copy ByteBuf buffer = channel.alloc().buffer(32 + payload.readableBytes()); ByteBufDataSource data = new ByteBufDataSource(buffer); try { buffer.writeInt(0); buffer.writeByte(envelope); header.write(data); buffer.writeBytes(payload); buffer.setInt(0, buffer.writerIndex() - 4); // Write message length, now that we know it return buffer; } catch (IOException e) { ReferenceCountUtil.release(buffer); logger.error(e.getMessage(), e); return null; } } private void relayRequest(final RequestHeader header, final ByteBuf in) { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { ses.sendRelayedRequest(header, in, this); } else { logger.warn("Could not find a relay session for {}", header.toId); sendResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header.requestId); } } private void relayResponse(ResponseHeader header, Async async, ByteBuf in) { header.requestId = async.header.requestId; async.session.sendRelayedResponse(header, in); } public static String dumpBuffer(ByteBuf buf) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.writerIndex(); i++) { sb.append(buf.getByte(i)); sb.append(' '); } return sb.toString(); } @Override public String getPeerHostname() { return channel.remoteAddress().getHostString(); } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.Concept; import gov.nih.nci.ncicb.cadsr.loader.ui.event.*; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.*; import gov.nih.nci.ncicb.cadsr.loader.ui.util.TreeUtil; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import java.util.*; /** * Panel from where you navigate the UML Elements. * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> */ public class NavigationPanel extends JPanel implements ActionListener, MouseListener, ReviewListener, NavigationListener, KeyListener, SearchListener, TreeListener { private JTree tree; private JPopupMenu popup; private JScrollPane scrollPane; private UMLNode rootNode = TreeBuilder.getInstance().getRootNode(); private List<ViewChangeListener> viewListeners = new ArrayList(); private List<NavigationListener> navigationListeners = new ArrayList(); public NavigationPanel() { try { initUI(); TreeBuilder.getInstance().addTreeListener(this); } catch(Exception e) { e.printStackTrace(); } } public void addViewChangeListener(ViewChangeListener l) { viewListeners.add(l); } public void addNavigationListener(NavigationListener l) { navigationListeners.add(l); } public void reviewChanged(ReviewEvent event) { ReviewableUMLNode node = (ReviewableUMLNode)event.getUserObject(); node.setReviewed(event.isReviewed()); tree.repaint(); } private void initUI() throws Exception { DefaultMutableTreeNode top = buildTree(); tree = new JTree(top); tree.setRootVisible(false); tree.setShowsRootHandles(true); tree.addKeyListener(this); //Traverse Tree expanding all nodes TreeUtil.expandAll(tree, top); tree.setCellRenderer(new UMLTreeCellRenderer()); this.setLayout(new BorderLayout()); scrollPane = new JScrollPane(tree); this.add(scrollPane, BorderLayout.CENTER); buildPopupMenu(); } public void actionPerformed(ActionEvent event) { DefaultMutableTreeNode dmtn, node; TreePath path = tree.getSelectionPath(); dmtn = (DefaultMutableTreeNode) path.getLastPathComponent(); if(event.getSource() instanceof JMenuItem) { JMenuItem menuItem = (JMenuItem)event.getSource(); ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_CONCEPTS); evt.setViewObject(dmtn.getUserObject()); if(menuItem.getActionCommand().equals("OPEN_NEW_TAB")) evt.setInNewTab(true); else evt.setInNewTab(false); fireViewChangeEvent(evt); } } public void keyPressed(KeyEvent e) { DefaultMutableTreeNode selected = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //if the down arrow is pressed then display the next element //in the tree in the ViewPanel if(e.getKeyCode() == KeyEvent.VK_DOWN && selected != null) { if (selected.getNextNode() != null) { TreePath path = new TreePath(selected.getNextNode().getPath()); tree.makeVisible(path); newViewEvent(path); } } //if the up arrow is pressed then display the previous element //in the tree in the ViewPanel if(e.getKeyCode() == KeyEvent.VK_UP && selected != null) { if (selected.getPreviousNode() != null) { TreePath path = new TreePath(selected.getPreviousNode().getPath()); tree.makeVisible(path); newViewEvent(path); } } } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void mousePressed(MouseEvent e) { showPopup(e); } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseReleased(MouseEvent e) { showPopup(e); doMouseEvent(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger()) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); tree.setSelectionPath(path); if(path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); Object o = node.getUserObject(); if((o instanceof ClassNode) || (o instanceof AttributeNode) ) popup.show(e.getComponent(), e.getX(), e.getY()); } } } private void doMouseEvent(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); newViewEvent(path); } else if(e.getButton() == MouseEvent.BUTTON2) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if(path != null) { DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) path.getLastPathComponent(); ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_CONCEPTS); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(true); fireViewChangeEvent(evt); } } } private void newViewEvent(TreePath path) { if(path != null) { DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) path.getLastPathComponent(); Object o = dmtn.getUserObject(); if((o instanceof ClassNode) || (o instanceof AttributeNode) ) { ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_CONCEPTS); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(false); fireViewChangeEvent(evt); } else if(o instanceof AssociationNode) { ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_ASSOCIATION); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(false); fireViewChangeEvent(evt); } else if(o instanceof ValueDomainNode) { ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_VALUE_DOMAIN); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(false); fireViewChangeEvent(evt); } else if(o instanceof ValueMeaningNode) { ViewChangeEvent evt = new ViewChangeEvent(ViewChangeEvent.VIEW_VALUE_MEANING); evt.setViewObject(dmtn.getUserObject()); evt.setInNewTab(false); fireViewChangeEvent(evt); } } } private void buildPopupMenu() { JMenuItem newTabItem = new JMenuItem("Open in New Tab"); JMenuItem openItem = new JMenuItem("Open"); newTabItem.setActionCommand("OPEN_NEW_TAB"); openItem.setActionCommand("OPEN"); popup = new JPopupMenu(); newTabItem.addActionListener(this); openItem.addActionListener(this); popup.add(openItem); popup.add(newTabItem); tree.addMouseListener(this); } private DefaultMutableTreeNode buildTree() { DefaultMutableTreeNode node = new DefaultMutableTreeNode(rootNode); return doNode(node, rootNode); } private DefaultMutableTreeNode doNode(DefaultMutableTreeNode node, UMLNode parentNode) { Set<UMLNode> children = parentNode.getChildren(); for(UMLNode child : children) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(child); if(!(child instanceof ValidationNode)) node.add(newNode); doNode(newNode, child); } return node; } public void treeChange(TreeEvent event) { this.remove(scrollPane); rootNode = TreeBuilder.getInstance().getRootNode(); try { initUI(); } catch (Exception e) { } this.updateUI(); } public void navigate(NavigationEvent event) { DefaultMutableTreeNode selected = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if(event.getType() == NavigationEvent.NAVIGATE_NEXT && selected.getNextNode() != null) { TreePath path = new TreePath(selected.getNextNode().getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); } else if(event.getType() == NavigationEvent.NAVIGATE_PREVIOUS && selected.getPreviousNode() != null) { TreePath path = new TreePath(selected.getPreviousNode().getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); } } public void search(SearchEvent event) { DefaultMutableTreeNode selected = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); TreePath path = null; if(event.getSearchFromBeginning()) selected = null; //if(event.getSearchByLongName()) { //search the tree in a forward direction from top to bottom if(!event.getSearchFromBottom()) { //if no node is selected then select the first node if(selected == null) selected = (DefaultMutableTreeNode)tree.getPathForRow(0).getLastPathComponent(); selected = selected.getNextNode(); while(selected != null) { AbstractUMLNode n = (AbstractUMLNode) selected.getUserObject(); if(event.getSearchByLongName()) { Concept [] concepts = NodeUtil.getConceptsFromNode(n); for(int i=0; i < concepts.length; i++) { //System.out.println("Concepts" + i +" "+ concepts[i]); if(!event.getSearchString().toLowerCase().contains(concepts[i].getLongName().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); selected = null; break; } } } else { //if there is a match then select that node in the tree if((n.getDisplay().toLowerCase()).contains(event.getSearchString().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); break; } } if(selected != null) selected = selected.getNextNode(); } } //search the tree in backward direction from bottom to top else { //if no node is selected then select the last node in the tree if(selected == null) selected = (DefaultMutableTreeNode)tree.getPathForRow(tree.getRowCount()-1).getLastPathComponent(); selected = selected.getPreviousNode(); while(selected != null) { AbstractUMLNode n = (AbstractUMLNode) selected.getUserObject(); if(event.getSearchByLongName()) { Concept [] concepts = NodeUtil.getConceptsFromNode(n); for(int i=0; i < concepts.length; i++) { //System.out.println("Concepts" + i +" "+ concepts[i]); if(event.getSearchString().toLowerCase().contains(concepts[i].getLongName().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); selected = null; break; } } } else { //if there is a match then select that node in the tree if((n.getDisplay().toLowerCase()).contains(event.getSearchString().toLowerCase())) { path = new TreePath(selected.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); newViewEvent(path); break; } } if(selected != null) selected = selected.getPreviousNode(); } } //if no match was found display error message if(path == null) { //int result = JOptionPane.showConfirmDialog(null, "Text Not Found", "No Match", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); //if(result == JOptionPane.YES_OPTION) // search(event); JOptionPane.showMessageDialog(null,"Text Not Found", "No Match",JOptionPane.ERROR_MESSAGE); } } private void fireViewChangeEvent(ViewChangeEvent evt) { fireNavigationEvent(new NavigationEvent(NavigationEvent.NAVIGATE_NEXT)); for(ViewChangeListener vcl : viewListeners) vcl.viewChanged(evt); } private void fireNavigationEvent(NavigationEvent evt) { for(NavigationListener nl : navigationListeners) { nl.navigate(evt); } } }
package resources; public class SettingsProperties { public static boolean debugModeG = true; public static String gameName = "Multiplication Dungeon"; }
package persistanceController; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import persistanceModel.DeleteASyncTask; import persistanceModel.LoadASyncTask; import persistanceModel.LoadAllASyncTask; import persistanceModel.LocalPersistance; import persistanceModel.NetworkPersistance; import persistanceModel.SaveASyncTask; import persistanceModel.UpdateASyncTask; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; import ca.ualberta.cmput301w15t13.Controllers.ClaimListSingleton; import ca.ualberta.cmput301w15t13.Models.Claim; import ca.ualberta.cmput301w15t13.Models.ExpenseItem; import ca.ualberta.cmput301w15t13.Models.ExpenseItemList; /** * This is the Data Manager class. * It servers as as API for the save/Load functionality of the app. * * It uses the following design patterns: * Facade: It provides the user with a simple save/load API that hides the complexity of the code. * Singleton: Static method with static calls. * @author eorod_000 * */ public class DataManager { private static boolean networkAvailable = false; private static Context currentContext; /** * This returns the status of the network * @return */ public static boolean isNetworkAvailable(){ return networkAvailable; } public static void setOfflineMode(){ networkAvailable = false; } public static void setOnlineMode(){ networkAvailable = true; } /** * This will save 1 Claim * @param claim * @return */ public static boolean saveClaim(Claim claim){ //This will go through a claim and save all the expenses DataHelper helper = new DataHelper(); helper.saveClaim(claim); return false; } public static void saveClaims(ArrayList<Claim> claimList){ for(Claim claim: claimList){ saveClaim(claim); } } /** * This will delete 1 claim * @param claimID: Claim ID */ public static void deleteClaim(String claimID){ //This will go through a claim and save all the expenses DataHelper helper = new DataHelper(); helper.DeleteClaim(claimID); } /** * This will load all the claims made by a specific User * @param userName * @return */ public static void loadClaimsByUserName(String userName){ DataHelper helper = new DataHelper(); helper.loadClaimsByUserName(userName); } public static void setCurrentContext(Context context){ currentContext = context; } public static Context getCurrentContext(){ return currentContext ; } public static void loadAllClaims() throws InterruptedException, ExecutionException{ DataHelper helper = new DataHelper(); helper.loadAllClaims(); } public static void updateClaim(String claimID) { DataHelper helper = new DataHelper(); helper.updateClaim(claimID); } } class DataHelper{ LocalPersistance local = new LocalPersistance(); NetworkPersistance network = new NetworkPersistance(); private void isNetworkConnected(){ ConnectivityManager cm = (ConnectivityManager)DataManager.getCurrentContext().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if(isConnected){ DataManager.setOnlineMode(); Toast.makeText(DataManager.getCurrentContext(), "Is connected", Toast.LENGTH_SHORT).show(); }else{ DataManager.setOfflineMode(); Toast.makeText(DataManager.getCurrentContext(), "Is NOT connected", Toast.LENGTH_SHORT).show(); } } /** * This will determine what type of saving method to use depending on the network status. * @param claim */ public void saveClaim(Claim claim) { this.isNetworkConnected(); if (DataManager.isNetworkAvailable()){ new SaveASyncTask().execute(claim.getclaimID()); } local.saveClaims(ClaimListSingleton.getClaimList().getClaimArrayList(), DataManager.getCurrentContext()); } public void updateClaim(String claimID) { this.isNetworkConnected(); if (DataManager.isNetworkAvailable()){ new UpdateASyncTask().execute(claimID); } } public void loadAllClaims() throws InterruptedException, ExecutionException { this.isNetworkConnected(); if (DataManager.isNetworkAvailable()){ new LoadAllASyncTask().execute(""); }else{ local.LoadClaims(DataManager.getCurrentContext()); } } /** * This will delete a claim from the network * @param claimID */ public void DeleteClaim(String claimID){ this.isNetworkConnected(); if (DataManager.isNetworkAvailable()){ new DeleteASyncTask().execute(claimID); } } /** * This method is for network persistance. It will Save a claim's Expenses. * @param expenseList */ public void saveClaimExpenses(ExpenseItemList expenseList){ this.isNetworkConnected(); if (DataManager.isNetworkAvailable()){ for (ExpenseItem expense: expenseList.getExpenseList()){ network.saveExpense(expense); } } } /** * This will load a user's claimList from the network * @param userName * @return */ public void loadClaimsByUserName(String userName) { this.isNetworkConnected(); if (DataManager.isNetworkAvailable()){ //Start an Async task to load claims new LoadASyncTask().execute(userName); }else{ local.LoadClaims(DataManager.getCurrentContext()); } } /** * This will determine what type of saving method to use depending on the network status. * @param claim */ public String LoadLocalClaims() { this.isNetworkConnected(); if (!DataManager.isNetworkAvailable()){ local.LoadClaims(); } return null; } }
package org.grobid.core.main; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.SystemUtils; import org.grobid.core.engines.tagging.GrobidCRFEngine; import org.grobid.core.exceptions.GrobidException; import org.grobid.core.jni.PythonEnvironmentConfig; import org.grobid.core.utilities.GrobidProperties; import org.grobid.core.utilities.Utilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FilenameFilter; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.Set; import static org.apache.commons.lang3.ArrayUtils.isEmpty; public class LibraryLoader { private static Logger LOGGER = LoggerFactory.getLogger(LibraryLoader.class); public static final String CRFPP_NATIVE_LIB_NAME = "libcrfpp"; public static final String WAPITI_NATIVE_LIB_NAME = "libwapiti"; public static final String DELFT_NATIVE_LIB_NAME_LINUX = "libjep"; public static final String DELFT_NATIVE_LIB_NAME = "jep"; private static boolean loaded = false; public static void load() { if (!loaded) { LOGGER.info("Loading external native sequence labelling library"); LOGGER.debug(getLibraryFolder()); Set<GrobidCRFEngine> distinctModels = GrobidProperties.getInstance().getDistinctModels(); for(GrobidCRFEngine distinctModel : distinctModels) { if (distinctModel != GrobidCRFEngine.CRFPP && distinctModel != GrobidCRFEngine.WAPITI && distinctModel != GrobidCRFEngine.DELFT) { throw new IllegalStateException("Unsupported sequence labelling engine: " + distinctModel); } } File libraryFolder = new File(getLibraryFolder()); if (!libraryFolder.exists() || !libraryFolder.isDirectory()) { LOGGER.error("Unable to find a native sequence labelling library: Folder " + libraryFolder + " does not exist"); throw new RuntimeException( "Unable to find a native sequence labelling library: Folder " + libraryFolder + " does not exist"); } if (CollectionUtils.containsAny(distinctModels, Collections.singletonList(GrobidCRFEngine.CRFPP))) { File[] files = libraryFolder.listFiles(file -> file.getName().toLowerCase().startsWith(CRFPP_NATIVE_LIB_NAME)); if (ArrayUtils.isEmpty(files)) { LOGGER.error("Unable to find a native CRF++ library: No files starting with " + CRFPP_NATIVE_LIB_NAME + " are in folder " + libraryFolder); throw new RuntimeException( "Unable to find a native CRF++ library: No files starting with " + CRFPP_NATIVE_LIB_NAME + " are in folder " + libraryFolder); } if (files.length > 1) { LOGGER.error("Unable to load a native CRF++ library: More than 1 library exists in " + libraryFolder); throw new RuntimeException( "Unable to load a native CRF++ library: More than 1 library exists in " + libraryFolder); } String libPath = files[0].getAbsolutePath(); // finally loading a library try { System.load(libPath); } catch (Exception e) { LOGGER.error("Unable to load a native CRF++ library, although it was found under path " + libPath); throw new RuntimeException( "Unable to load a native CRF++ library, although it was found under path " + libPath, e); } } if (CollectionUtils.containsAny(distinctModels, Collections.singletonList(GrobidCRFEngine.WAPITI))) { File[] wapitiLibFiles = libraryFolder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(WAPITI_NATIVE_LIB_NAME); } }); if (isEmpty(wapitiLibFiles)) { LOGGER.info("No wapiti library in the Grobid home folder"); } else { LOGGER.info("Loading Wapiti native library..."); if (CollectionUtils.containsAny(distinctModels, Collections.singletonList(GrobidCRFEngine.DELFT))) { // if DeLFT will be used, we must not load libstdc++, it would create a conflict with tensorflow libstdc++ version // so we temporary rename the lib so that it is not loaded in this case // note that we know that, in this case, the local lib can be ignored because as DeFLT and tensorflow are installed // we are sure that a compatible libstdc++ lib is installed on the system and can be dynamically loaded String libstdcppPath = libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6"; File libstdcppFile = new File(libstdcppPath); if (libstdcppFile.exists()) { File libstdcppFileNew = new File(libstdcppPath + ".new"); libstdcppFile.renameTo(libstdcppFileNew); } String libgccPath = libraryFolder.getAbsolutePath() + File.separator + "libgcc_s.so.1"; File libgccFile = new File(libgccPath); if (libgccFile.exists()) { File libgccFileNew = new File(libgccPath + ".new"); libgccFile.renameTo(libgccFileNew); } } try { System.load(wapitiLibFiles[0].getAbsolutePath()); } finally { if (CollectionUtils.containsAny(distinctModels, Arrays.asList(GrobidCRFEngine.DELFT))) { // restore libstdc++ String libstdcppPathNew = libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6.new"; File libstdcppFileNew = new File(libstdcppPathNew); if (libstdcppFileNew.exists()) { File libstdcppFile = new File(libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6"); libstdcppFileNew.renameTo(libstdcppFile); } // restore libgcc String libgccPathNew = libraryFolder.getAbsolutePath() + File.separator + "libgcc_s.so.1.new"; File libgccFileNew = new File(libgccPathNew); if (libgccFileNew.exists()) { File libgccFile = new File(libraryFolder.getAbsolutePath() + File.separator + "libgcc_s.so.1"); libgccFileNew.renameTo(libgccFile); } } } } } if (CollectionUtils.containsAny(distinctModels, Collections.singletonList(GrobidCRFEngine.DELFT))) { LOGGER.info("Loading JEP native library for DeLFT... " + libraryFolder.getAbsolutePath()); // actual loading will be made at JEP initialization, so we just need to add the path in the // java.library.path (JEP will anyway try to load from java.library.path, so explicit file // loading here will not help) try { addLibraryPath(libraryFolder.getAbsolutePath() + File.separator + DELFT_NATIVE_LIB_NAME); PythonEnvironmentConfig pythonEnvironmentConfig = PythonEnvironmentConfig.getInstance(); if (pythonEnvironmentConfig.isEmpty()) { LOGGER.info("No python environment configured"); } else { LOGGER.info("Configuring python environment: " + pythonEnvironmentConfig.getVirtualEnv()); LOGGER.info("Adding library paths " + Arrays.toString(pythonEnvironmentConfig.getNativeLibPaths())); for (Path path : pythonEnvironmentConfig.getNativeLibPaths()) { if (Files.exists(path)) { addLibraryPath(path.toString()); } else { LOGGER.warn(path.toString() + " does not exists. Skipping it. "); } } if (SystemUtils.IS_OS_MAC) { // System.setProperty("java.library.path", System.getProperty("java.library.path") + ":" + libraryFolder.getAbsolutePath()); System.loadLibrary("python" + pythonEnvironmentConfig.getPythonVersion()); System.loadLibrary(DELFT_NATIVE_LIB_NAME); } else if (SystemUtils.IS_OS_LINUX) { System.loadLibrary(DELFT_NATIVE_LIB_NAME); } else if (SystemUtils.IS_OS_WINDOWS) { throw new UnsupportedOperationException("Delft on Windows is not supported."); } } } catch (Exception e) { throw new GrobidException("Loading JEP native library for DeLFT failed", e); } } loaded = true; LOGGER.info("Native library for sequence labelling loaded"); } } public static void addLibraryPath(String pathToAdd) throws Exception { Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths"); usrPathsField.setAccessible(true); String[] paths = (String[]) usrPathsField.get(null); for (String path : paths) if (path.equals(pathToAdd)) return; String[] newPaths = new String[paths.length + 1]; System.arraycopy(paths, 0, newPaths, 1, paths.length); newPaths[0] = pathToAdd; usrPathsField.set(null, newPaths); } public static String getLibraryFolder() { GrobidProperties.getInstance(); return String.format("%s" + File.separator + "%s", GrobidProperties.getNativeLibraryPath().getAbsolutePath(), Utilities.getOsNameAndArch()); } }
package org.grobid.core.main; import org.apache.commons.lang3.SystemUtils; import org.grobid.core.engines.tagging.GrobidCRFEngine; import org.grobid.core.exceptions.GrobidException; import org.grobid.core.jni.PythonEnvironmentConfig; import org.grobid.core.utilities.GrobidProperties; import org.grobid.core.utilities.Utilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.lang.reflect.Field; import java.nio.file.Paths; import java.util.Arrays; import static org.apache.commons.lang3.ArrayUtils.isEmpty; //import org.grobid.core.mock.MockContext; /** * @author Slava, Patrice */ public class LibraryLoader { private static Logger LOGGER = LoggerFactory.getLogger(LibraryLoader.class); //a name of a native CRF++ library without an extension public static final String CRFPP_NATIVE_LIB_NAME = "libcrfpp"; public static final String WAPITI_NATIVE_LIB_NAME = "libwapiti"; public static final String DELFT_NATIVE_LIB_NAME_LINUX = "libjep"; public static final String DELFT_NATIVE_LIB_NAME = "jep"; private static boolean loaded = false; // private static boolean isContextMocked = false; public static void load() { if (!loaded) { LOGGER.info("Loading external native sequence labelling library"); LOGGER.debug(getLibraryFolder()); if (GrobidProperties.getGrobidCRFEngine() != GrobidCRFEngine.CRFPP && GrobidProperties.getGrobidCRFEngine() != GrobidCRFEngine.WAPITI && GrobidProperties.getGrobidCRFEngine() != GrobidCRFEngine.DELFT) { throw new IllegalStateException("Unsupported sequence labelling engine: " + GrobidProperties.getGrobidCRFEngine()); } File libraryFolder = new File(getLibraryFolder()); if (!libraryFolder.exists() || !libraryFolder.isDirectory()) { LOGGER.error("Unable to find a native sequence labelling library: Folder " + libraryFolder + " does not exist"); throw new RuntimeException( "Unable to find a native sequence labelling library: Folder " + libraryFolder + " does not exist"); } if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.CRFPP) { File[] files = libraryFolder.listFiles(new FileFilter() { public boolean accept(File file) { return file.getName().toLowerCase() .startsWith(CRFPP_NATIVE_LIB_NAME); } }); if (files.length == 0) { LOGGER.error("Unable to find a native CRF++ library: No files starting with " + CRFPP_NATIVE_LIB_NAME + " are in folder " + libraryFolder); throw new RuntimeException( "Unable to find a native CRF++ library: No files starting with " + CRFPP_NATIVE_LIB_NAME + " are in folder " + libraryFolder); } if (files.length > 1) { LOGGER.error("Unable to load a native CRF++ library: More than 1 library exists in " + libraryFolder); throw new RuntimeException( "Unable to load a native CRF++ library: More than 1 library exists in " + libraryFolder); } String libPath = files[0].getAbsolutePath(); // finally loading a library try { System.load(libPath); } catch (Exception e) { LOGGER.error("Unable to load a native CRF++ library, although it was found under path " + libPath); throw new RuntimeException( "Unable to load a native CRF++ library, although it was found under path " + libPath, e); } } if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.WAPITI || GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.DELFT) { // note: if DeLFT is used, we still make Wapiti available for models not existing in DeLFT (currently segmentation and // fulltext) File[] wapitiLibFiles = libraryFolder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(WAPITI_NATIVE_LIB_NAME); } }); if (isEmpty(wapitiLibFiles)) { LOGGER.info("No wapiti library in the Grobid home folder"); } else { LOGGER.info("Loading Wapiti native library..."); if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.DELFT) { // if DeLFT will be used, we must not load libstdc++, it would create a conflict with tensorflow libstdc++ version // so we temporary rename the lib so that it is not loaded in this case // note that we know that, in this case, the local lib can be ignored because as DeFLT and tensorflow are installed // we are sure that a compatible libstdc++ lib is installed on the system and can be dynamically loaded String libstdcppPath = libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6"; File libstdcppFile = new File(libstdcppPath); if (libstdcppFile.exists()) { File libstdcppFileNew = new File(libstdcppPath + ".new"); libstdcppFile.renameTo(libstdcppFileNew); } } try { System.load(wapitiLibFiles[0].getAbsolutePath()); } finally { if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.DELFT) { // restore libstdc++ String libstdcppPathNew = libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6.new"; File libstdcppFileNew = new File(libstdcppPathNew); if (libstdcppFileNew.exists()) { File libstdcppFile = new File(libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6"); libstdcppFileNew.renameTo(libstdcppFile); } } } } } if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.DELFT) { LOGGER.info("Loading JEP native library for DeLFT... " + libraryFolder.getAbsolutePath()); // actual loading will be made at JEP initialization, so we just need to add the path in the // java.library.path (JEP will anyway try to load from java.library.path, so explicit file // loading here will not help) try { addLibraryPath(libraryFolder.getAbsolutePath()); PythonEnvironmentConfig pythonEnvironmentConfig = PythonEnvironmentConfig.getInstance(); if (pythonEnvironmentConfig.isEmpty()) { LOGGER.info("no python environment configured"); } else { LOGGER.info("configuring python environment: " + pythonEnvironmentConfig.getVirtualEnv()); if (SystemUtils.IS_OS_MAC) { LOGGER.info("adding library path " + pythonEnvironmentConfig.getJepPath()); addLibraryPath(pythonEnvironmentConfig.getJepPath().toString()); // System.setProperty("java.library.path", System.getProperty("java.library.path") + ":" + LibraryLoader.getLibraryFolder()); // System.setProperty("java.library.path", System.getProperty("java.library.path") + ":" + pythonEnvironmentConfig.getVirtualEnv()); addLibraryPath(pythonEnvironmentConfig.getVirtualEnv().toString() + File.separator + "lib"); System.loadLibrary("python3.6m"); System.loadLibrary(DELFT_NATIVE_LIB_NAME); } else if (SystemUtils.IS_OS_LINUX) { LOGGER.info("java.library.path: " + System.getProperty("java.library.path")); System.loadLibrary(DELFT_NATIVE_LIB_NAME); } else if (SystemUtils.IS_OS_WINDOWS) { throw new UnsupportedOperationException("Delft on Windows is not supported."); } } } catch (Exception e) { throw new GrobidException("Loading JEP native library for DeLFT failed", e); } } loaded = true; LOGGER.info("Native library for sequence labelling loaded"); } } public static void addLibraryPath(String pathToAdd) throws Exception { Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths"); usrPathsField.setAccessible(true); String[] paths = (String[]) usrPathsField.get(null); for (String path : paths) if (path.equals(pathToAdd)) return; String[] newPaths = Arrays.copyOf(paths, paths.length + 1); newPaths[newPaths.length - 1] = pathToAdd; usrPathsField.set(null, newPaths); } // /** // * Initialize the context with mock parameters if they doesn't already // * exist. // */ // protected static void mockContextIfNotSet() { // try { // new InitialContext().lookup("java:comp/env/" // + GrobidPropertyKeys.PROP_GROBID_HOME); // LOGGER.debug("The property " + GrobidPropertyKeys.PROP_GROBID_HOME // + " already exists. No mocking of context made."); // } catch (Exception exp) { // LOGGER.debug("The property " + GrobidPropertyKeys.PROP_GROBID_HOME // + " does not exist. Mocking the context."); //// try { //// MockContext.setInitialContext(); //// isContextMocked = true; //// } catch (Exception mexp) { //// LOGGER.error("Could not mock the context." + mexp); //// throw new GrobidException("Could not mock the context.", mexp); public static String getLibraryFolder() { GrobidProperties.getInstance(); // TODO: change to fetching the basic dir from GrobidProperties object return String.format("%s" + File.separator + "%s", GrobidProperties .getNativeLibraryPath().getAbsolutePath(), Utilities .getOsNameAndArch()); } }
package com.mood.jenaPlus; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class MoodListAdapter extends ArrayAdapter<Mood> { Context context; public MoodListAdapter(Context context, ArrayList<Mood> moodList){ super(context,0,moodList); this.context = context; } @Override public View getView(int position, View view, ViewGroup parent){ Mood moodList = getItem(position); if (view == null) view = LayoutInflater.from(getContext()).inflate(R.layout.mood_plus_listview,parent,false); TextView dateText = (TextView) view.findViewById(R.id.date); TextView messageText = (TextView) view.findViewById(R.id.message); ImageView moodIconImage = (ImageView) view.findViewById(R.id.moodIcon); TextView moodIconText = (TextView) view.findViewById(R.id.moodIconString); String aId = moodList.getId(); int recId = context.getResources().getIdentifier(aId, "drawable", context.getPackageName()); dateText.setText(moodList.getDateString()); messageText.setText(moodList.getText()); moodIconText.setText(moodList.getId()); moodIconImage.setImageResource(recId); return view; } }
package org.grobid.core.main; import org.apache.commons.lang3.SystemUtils; import org.grobid.core.engines.tagging.GrobidCRFEngine; import org.grobid.core.jni.PythonEnvironmentConfig; import org.grobid.core.utilities.GrobidProperties; import org.grobid.core.utilities.Utilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.lang.reflect.Field; import java.nio.file.Path; import java.util.Arrays; import static org.apache.commons.lang3.ArrayUtils.isEmpty; //import org.grobid.core.mock.MockContext; /** * @author Slava, Patrice */ public class LibraryLoader { private static Logger LOGGER = LoggerFactory.getLogger(LibraryLoader.class); //a name of a native CRF++ library without an extension public static final String CRFPP_NATIVE_LIB_NAME = "libcrfpp"; public static final String WAPITI_NATIVE_LIB_NAME = "libwapiti"; public static final String DELFT_NATIVE_LIB_NAME_LINUX = "libjep"; public static final String DELFT_NATIVE_LIB_NAME = "jep"; private static boolean loaded = false; // private static boolean isContextMocked = false; public static void load() { if (!loaded) { LOGGER.info("Loading external native sequence labelling library"); LOGGER.debug(getLibraryFolder()); if (GrobidProperties.getGrobidCRFEngine() != GrobidCRFEngine.CRFPP && GrobidProperties.getGrobidCRFEngine() != GrobidCRFEngine.WAPITI && GrobidProperties.getGrobidCRFEngine() != GrobidCRFEngine.DELFT) { throw new IllegalStateException("Unsupported sequence labelling engine: " + GrobidProperties.getGrobidCRFEngine()); } File libraryFolder = new File(getLibraryFolder()); if (!libraryFolder.exists() || !libraryFolder.isDirectory()) { LOGGER.error("Unable to find a native sequence labelling library: Folder " + libraryFolder + " does not exist"); throw new RuntimeException( "Unable to find a native sequence labelling library: Folder " + libraryFolder + " does not exist"); } if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.CRFPP) { File[] files = libraryFolder.listFiles(new FileFilter() { public boolean accept(File file) { return file.getName().toLowerCase() .startsWith(CRFPP_NATIVE_LIB_NAME); } }); if (files.length == 0) { LOGGER.error("Unable to find a native CRF++ library: No files starting with " + CRFPP_NATIVE_LIB_NAME + " are in folder " + libraryFolder); throw new RuntimeException( "Unable to find a native CRF++ library: No files starting with " + CRFPP_NATIVE_LIB_NAME + " are in folder " + libraryFolder); } if (files.length > 1) { LOGGER.error("Unable to load a native CRF++ library: More than 1 library exists in " + libraryFolder); throw new RuntimeException( "Unable to load a native CRF++ library: More than 1 library exists in " + libraryFolder); } String libPath = files[0].getAbsolutePath(); // finally loading a library try { System.load(libPath); } catch (Exception e) { LOGGER.error("Unable to load a native CRF++ library, although it was found under path " + libPath); throw new RuntimeException( "Unable to load a native CRF++ library, although it was found under path " + libPath, e); } } if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.WAPITI || GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.DELFT) { // note: if DeLFT is used, we still make Wapiti available for models not existing in DeLFT (currently segmentation and // fulltext) File[] wapitiLibFiles = libraryFolder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(WAPITI_NATIVE_LIB_NAME); } }); if (isEmpty(wapitiLibFiles)) { LOGGER.info("No wapiti library in the Grobid home folder"); } else { LOGGER.info("Loading Wapiti native library..."); if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.DELFT) { // if DeLFT will be used, we must not load libstdc++, it would create a conflict with tensorflow libstdc++ version // so we temporary rename the lib so that it is not loaded in this case // note that we know that, in this case, the local lib can be ignored because as DeFLT and tensorflow are installed // we are sure that a compatible libstdc++ lib is installed on the system and can be dynamically loaded String libstdcppPath = libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6"; File libstdcppFile = new File(libstdcppPath); if (libstdcppFile.exists()) { File libstdcppFileNew = new File(libstdcppPath + ".new"); libstdcppFile.renameTo(libstdcppFileNew); } } try { System.load(wapitiLibFiles[0].getAbsolutePath()); } finally { if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.DELFT) { // restore libstdc++ String libstdcppPathNew = libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6.new"; File libstdcppFileNew = new File(libstdcppPathNew); if (libstdcppFileNew.exists()) { File libstdcppFile = new File(libraryFolder.getAbsolutePath() + File.separator + "libstdc++.so.6"); libstdcppFileNew.renameTo(libstdcppFile); } } } } } if (GrobidProperties.getGrobidCRFEngine() == GrobidCRFEngine.DELFT) { LOGGER.info("Loading JEP native library for DeLFT... " + libraryFolder.getAbsolutePath()); // actual loading will be made at JEP initialization, so we just need to add the path in the // java.library.path (JEP will anyway try to load from java.library.path, so explicit file // loading here will not help) try { addLibraryPath(libraryFolder.getAbsolutePath()); PythonEnvironmentConfig pythonEnvironmentConfig = PythonEnvironmentConfig.getInstance(); if (pythonEnvironmentConfig.isEmpty()) { LOGGER.info("no python environment configured"); } else { LOGGER.info("configuring python environment: " + pythonEnvironmentConfig.getVirtualEnv()); LOGGER.info("adding library paths " + pythonEnvironmentConfig.getNativeLibPaths()); for (Path path: pythonEnvironmentConfig.getNativeLibPaths()) { addLibraryPath(path.toString()); } if (SystemUtils.IS_OS_MAC) { System.loadLibrary("python3.6m"); System.loadLibrary(DELFT_NATIVE_LIB_NAME); } else if (SystemUtils.IS_OS_LINUX) { LOGGER.info("java.library.path: " + System.getProperty("java.library.path")); System.loadLibrary(DELFT_NATIVE_LIB_NAME); } else if (SystemUtils.IS_OS_WINDOWS) { throw new UnsupportedOperationException("Delft on Windows is not supported."); } } } catch (Exception e) { LOGGER.info("Loading JEP native library for DeLFT failed", e); } } loaded = true; LOGGER.info("Native library for sequence labelling loaded"); } } public static void addLibraryPath(String pathToAdd) throws Exception { Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths"); usrPathsField.setAccessible(true); String[] paths = (String[]) usrPathsField.get(null); for (String path : paths) if (path.equals(pathToAdd)) return; String[] newPaths = new String[paths.length + 1]; System.arraycopy(paths, 0, newPaths, 1, paths.length); newPaths[0] = pathToAdd; usrPathsField.set(null, newPaths); } // /** // * Initialize the context with mock parameters if they doesn't already // * exist. // */ // protected static void mockContextIfNotSet() { // try { // new InitialContext().lookup("java:comp/env/" // + GrobidPropertyKeys.PROP_GROBID_HOME); // LOGGER.debug("The property " + GrobidPropertyKeys.PROP_GROBID_HOME // + " already exists. No mocking of context made."); // } catch (Exception exp) { // LOGGER.debug("The property " + GrobidPropertyKeys.PROP_GROBID_HOME // + " does not exist. Mocking the context."); //// try { //// MockContext.setInitialContext(); //// isContextMocked = true; //// } catch (Exception mexp) { //// LOGGER.error("Could not mock the context." + mexp); //// throw new GrobidException("Could not mock the context.", mexp); public static String getLibraryFolder() { GrobidProperties.getInstance(); // TODO: change to fetching the basic dir from GrobidProperties object return String.format("%s" + File.separator + "%s", GrobidProperties .getNativeLibraryPath().getAbsolutePath(), Utilities .getOsNameAndArch()); } }
package org.genericsystem.ir; import java.lang.invoke.MethodHandles; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.AbstractVerticle; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; public class DistributedVerticle extends AbstractVerticle { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public static final String BASE_PATH = System.getenv("HOME") + "/git/genericsystem2015/gs-cv/"; protected static final String FILENAME = "filename"; protected static final String JSON_OBJECT = "jsonObject"; protected static final String TYPE = "type"; protected static final String IP = "IP"; private static final int availProc = Runtime.getRuntime().availableProcessors(); private static AtomicInteger currentExecutions = new AtomicInteger(); static { logger.debug("Available processors: {}", availProc); } public static void incrementExecutions() { currentExecutions.incrementAndGet(); } public static void decrementExecutions() { currentExecutions.decrementAndGet(); } public static int getExecutionsCount() { return currentExecutions.intValue(); } public static int getMaxExecutions() { return availProc; } @Override public void start() throws Exception { vertx.deployVerticle(new PdfConverterVerticle()); vertx.deployVerticle(new ClassifierVerticle()); vertx.deployVerticle(new OcrWorkerVerticle()); } public static void main(String[] args) { Handler<AsyncResult<String>> completionHandler = ar -> { if (ar.failed()) throw new IllegalStateException(ar.cause()); }; Tools.deployOnCluster(vertx -> { vertx.deployVerticle(new HttpServerVerticle(), complete -> { if (complete.failed()) throw new IllegalStateException(complete.cause()); for (int i = 0; i < getMaxExecutions(); ++i) { vertx.deployVerticle(new DistributedVerticle(), completionHandler); } }); }); } }
package ru.matevosyan.start; import ru.matevosyan.models.Comments; import ru.matevosyan.models.Item; public class MenuTracker { /** * Input instance variable input. */ private Input input; /** * Input instance variable tracker. */ private Tracker tracker; /** * Maximum user action. */ private final int maxUserAction = 9; /** * Instance variable for saving all user action. * And use it for run specific class, in dependence users selection action. */ private UserAction[] userAction = new UserAction[maxUserAction]; /** * Number of elements in userAction. * Variable one to use in userAction array in 0 position * */ private final int one = 1; /** * Variable two to use in userAction array in 1 position. */ private final int two = 2; /** * Variable three to use in userAction array in 2 position. */ private final int three = 3; /** * Variable four to use in userAction array in 3 position. */ private final int four = 4; /** * Variable five to use in userAction array in 4 position. */ private final int five = 5; /** * Variable six to use in userAction array in 5 position. */ private final int six = 6; /** * Variable seven to use in userAction array in 6 position. */ private final int seven = 7; /** * Variable eight to use in userAction array in 7 position. */ private final int eight = 8; /** * Constructor MenuTracker. * @since 1.0 * @param input for getting input state * @param tracker for getting tracker */ public MenuTracker(Input input, Tracker tracker) { this.input = input; this.tracker = tracker; } /** * Method fillAction fot fill out user action which invoking new class instance. */ public void fillAction() { /** * Number of elements in userAction. * @param zero to use in userAction array */ final int zero = 0; this.userAction[zero] = this.new AddItem(); this.userAction[one] = this.new ShowItems(); this.userAction[two] = this.new EditItems(); this.userAction[three] = this.new DeleteItem(); this.userAction[four] = this.new AddCommentToItem(); this.userAction[five] = this.new FindItemById(); this.userAction[six] = this.new FindItemByName(); this.userAction[seven] = this.new FindItemByDate(); this.userAction[eight] = this.new ShowItemComments(); } /** * Method select created to execute concrete action method execute that contains in array position that user had invoked. * @param key user selection */ public void select(String key) { this.userAction[Integer.parseInt(key) - 1].execute(this.input, this.tracker); } /** * Method show created for showing the list of user actions and action description. */ public void show() { for (UserAction userAction : this.userAction) { if (userAction != null) { System.out.println(userAction.info()); } } } private class AddItem implements UserAction { @Override public int key() { return one; } @Override public void execute(Input input, Tracker tracker) { String name = input.ask("Please enter the Task's name "); String description = input.ask("Please enter the Task's description "); tracker.add(new Item(name, description)); } @Override public String info() { System.out.println(" M-E-N-U"); return String.format("%s. %s", this.key(), "Add new Item"); } } private class ShowItems implements UserAction { @Override public int key() { return two; } @Override public void execute(Input input, Tracker tracker) { for (Item item : tracker.getAll()) { if (item != null) { System.out.println(String.format("\r\n Id: %s. \r\n Name: %s. \r\n Description: %s. \r\n Date: %s. \r\n" + " item.getDescription(), item.getCreate())); } } } @Override public String info() { return String.format("%s. %s", this.key(), "Show items"); } } private class EditItems implements UserAction { @Override public int key() { return three; } @Override public void execute(Input input, Tracker tracker) { String id = input.ask("Please enter the Task's id: "); String name = input.ask("Please enter the Task's name: "); String description = input.ask("Please enter the Task's description: "); Item item = new Item(name, description); item.setId(id); tracker.editItem(item); } @Override public String info() { return String.format("%s. %s", this.key(), "Edit items"); } } private class DeleteItem implements UserAction { @Override public int key() { return four; } @Override public void execute(Input input, Tracker tracker) { String id = input.ask("Please enter the Task's id: "); Item item = tracker.findById(id); if (item != null) { tracker.deleteItem(id); } } @Override public String info() { return String.format("%s. %s", this.key(), "Delete items"); } } private class AddCommentToItem implements UserAction { @Override public int key() { return five; } @Override public void execute(Input input, Tracker tracker) { String id = input.ask("Please enter the Task's id: "); String comment = input.ask("Please enter the Task's comment: "); Item findItem = tracker.findById(id); if (findItem != null) { tracker.addComment(findItem, comment); } } @Override public String info() { return String.format("%s. %s", this.key(), "Add comment to item"); } } private class FindItemById implements UserAction { @Override public int key() { return six; } @Override public void execute(Input input, Tracker tracker) { String id = input.ask("Please enter the Task's id: "); Item itemFindById = tracker.findById(id); if (itemFindById != null) { System.out.println(String.format("\r\n Id: %s. \r\n Name: %s. \r\n Description: %s. \r\n Date: %s. \r\n" + " itemFindById.getDescription(), itemFindById.getCreate())); } } @Override public String info() { return String.format("%s. %s", this.key(), "Find item by id"); } } private class FindItemByName implements UserAction { @Override public int key() { return seven; } @Override public void execute(Input input, Tracker tracker) { String name = input.ask("Please enter the Task's name: "); Item itemFindByName = tracker.findByName(name); if (itemFindByName != null) { System.out.println(String.format("\r\n Id: %s. \r\n Name: %s. \r\n Description: %s. \r\n Date: %s. \r\n" + " itemFindByName.getDescription(), itemFindByName.getCreate())); } } @Override public String info() { return String.format("%s. %s", this.key(), "Find item by name"); } } private class FindItemByDate implements UserAction { @Override public int key() { return eight; } @Override public void execute(Input input, Tracker tracker) { String date = input.ask("Please enter the Task's date: "); Item itemFindByDate = tracker.findByDate(Long.parseLong(date)); if (itemFindByDate != null) { System.out.println(String.format("\r\n Id: %s. \r\n Name: %s. \r\n Description: %s. \r\n Date: %s. \r\n" + " itemFindByDate.getDescription(), itemFindByDate.getCreate())); } } @Override public String info() { return String.format("%s. %s", this.key(), "Find item by date"); } } private class ShowItemComments implements UserAction { /** * Number for method key return value. */ private final int nine = 9; @Override public int key() { return nine; } @Override public void execute(Input input, Tracker tracker) { String id = input.ask("Please enter the Task's id: "); Item itemForComment = tracker.findById(id); final int maxCommentLength = 5; Comments[] comment = itemForComment.getAllComment(); System.out.println("\r\n Comments: \r\n for (int i = 0; i < maxCommentLength; i++) { if (comment[i] != null) { System.out.println(String.format(" |%s } } } @Override public String info() { return String.format("%s. %s", this.key(), "Show item comments \r\n"); } } }
package com.github.gwtd3.api.behaviour; import com.github.gwtd3.api.D3; import com.github.gwtd3.api.IsFunction; import com.github.gwtd3.api.arrays.Array; import com.github.gwtd3.api.functions.DatumFunction; import com.github.gwtd3.api.scales.QuantitativeScale; import com.google.gwt.core.client.JavaScriptObject; public class Zoom extends JavaScriptObject implements IsFunction { protected Zoom() { } /** * Type of scroll event to listen to. */ public static enum ZoomEventType { /** * Registers the specified listener to receive events of the specified * type from the zoom behavior. Currently, only the "zoom" event is * supported. */ ZOOM; } /** * Registers the specified listener to receive events of the specified type * from the zoom behavior. * <p> * See {@link ZoomEventType} for more information. * * @param type * @param listener * @return */ public final native Zoom on(ZoomEventType type, DatumFunction<Void> listener)/*-{ return this .on( type.@com.github.gwtd3.api.behaviour.Zoom.ZoomEventType::name()() .toLowerCase(), function(d, index) { listener.@com.github.gwtd3.api.functions.DatumFunction::apply(Lcom/google/gwt/dom/client/Element;Lcom/github/gwtd3/api/core/Value;I)(this,{datum:d},index); }); }-*/; /** * Return the current x-scale that is automatically adjusted when zooming, * or null if no scale have been specified. * <p> * * @return the x-scale */ public final native QuantitativeScale<?> x()/*-{ return this.x(); }-*/; /** * Specifies an x-scale whose domain should be automatically adjusted when * zooming. * <p> * If the scale's domain or range is modified programmatically, this * function should be called again. * * @param scale * the scale * @return Zoom the current Zoom object */ public final native Zoom x(QuantitativeScale<?> scale)/*-{ return this.x(scale); }-*/; /** * Return the current y-scale that is automatically adjusted when zooming, * or null if no scale have been specified. * <p> * * @return the y-scale */ public final native QuantitativeScale<?> y()/*-{ return this.y(); }-*/; /** * Specifies an y-scale whose domain should be automatically adjusted when * zooming. * <p> * If not specified, returns the current y-scale, which defaults to null. If * the scale's domain or range is modified programmatically, this function * should be called again * <p> * * @param the * scale * @return the current zoom object */ public final native Zoom y(QuantitativeScale<?> scale)/*-{ return this.y(scale); }-*/; /** * Return the zoom scale's allowed range as a two-element array, [*minimum*, * maximum]. * <p> * * @return the zoom scale's allowed range as a two-element array */ public final native Array<Double> scaleExtent()/*-{ return this.scaleExtent(); }-*/; /** * Specifies the zoom scale's allowed range as a two-element array, * [*minimum*, maximum]. If not specified, returns the current scale extent, * which defaults to [0, Infinity]. * <p> * * @param the * zoom scale's allowed range as a two-element array * @return the current zoom object */ public final native Zoom scaleExtent(Array<Double> scale)/*-{ return this.scaleExtent(scale); }-*/; /** * Returns the current zoom scale, which defaults to 1. * <p> * * @return the current zoom scale */ public final native double scale()/*-{ return this.scale(); }-*/; /** * Specifies the current zoom scale. * <p> * * @param scale * the zoom scale factor * @return the current zoom object */ public final native Zoom scale(double scale)/*-{ return this.scale(scale); }-*/; /** * Returns the current translation vector, which defaults to [0, 0]. * <p> * * @return the current translation vector */ public final native Array<Double> translate()/*-{ return this.translate(); }-*/; /** * Specifies the current zoom translation vector. * <p> * * @param the * current zoom translation vector * @return the current zoom object */ public final native Zoom translate(Array<Double> vector)/*-{ return this.translate(vector); }-*/; /** * Provide access to the properties of a zoom event. * <p> * Use {@link D3#zoomEvent()} from within a * {@link Zoom#on(ZoomEventType, DatumFunction)} listener. * <p> * * @author <a href="mailto:schiochetanthoni@gmail.com">Anthony Schiochet</a> * */ public static class ZoomEvent extends JavaScriptObject { protected ZoomEvent() { } /** * The scale of the zoom * <p> * * @return the scale of the zoom */ public native final double scale()/*-{ return this.scale; }-*/; /** * A two-element array representing the current translation vector. * * @return the translation vector */ public native final Array<Double> translate()/*-{ return this.translate; }-*/; /** * Shortcut to translate().getNumber(0). * * @return the translation x coord */ public native final double translateX()/*-{ return this.translate[0]; }-*/; /** * Shortcut to translate().getNumber(1). * * @return the translation y coord */ public native final double translateY()/*-{ return this.translate[1]; }-*/; } }
package org.xins.common.service; import org.xins.common.ExceptionUtils; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.text.FastStringBuffer; /** * Exception thrown to indicate that a <code>ServiceCaller</code> call failed. * * <p>When a cause exception is passed to any of the constructors, then the * root cause of that exception is passed up to the {@link Exception} class. * The root cause of an exception can be determined using * {@link ExceptionUtils#getRootCause(Throwable)}. * * <p>Call exceptions are linked. The first thrown exception is normally * returned. The next exception can then be retrieved using * {@link #getNext()}. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 0.207 */ public abstract class CallException extends Exception { // Class fields // Class functions private static final String createMessage(String shortReason, CallRequest request, TargetDescriptor target, long duration, String detail) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("shortReason", shortReason, "request", request, "target", target); if (duration < 0) { throw new IllegalArgumentException("duration (" + duration + ") < 0"); } FastStringBuffer buffer = new FastStringBuffer(295, shortReason); buffer.append(" in "); buffer.append(duration); buffer.append(" ms while executing "); buffer.append(request.describe()); buffer.append(" at "); buffer.append(target.getURL()); buffer.append(" with connection time-out "); int connectionTimeOut = target.getConnectionTimeOut(); if (connectionTimeOut < 1) { buffer.append("disabled, with socket time-out "); } else { buffer.append(connectionTimeOut); buffer.append(" ms, with socket time-out "); } int socketTimeOut = target.getSocketTimeOut(); if (socketTimeOut < 1) { buffer.append("disabled and with total time-out "); } else { buffer.append(socketTimeOut); buffer.append(" ms and with total time-out "); } int totalTimeOut = target.getTotalTimeOut(); if (totalTimeOut < 1) { buffer.append("disabled"); } else { buffer.append(totalTimeOut); buffer.append(" ms"); } if (detail == null) { buffer.append('.'); } else { buffer.append(": "); buffer.append(detail); } return buffer.toString(); } /** * Determines the root cause for the specified exception. If the argument * is <code>null</code>, then <code>null</code> is returned. * * @param t * the exception to determine the root cause for, or <code>null</code>. * * @return * the root cause of the specified exception, or <code>null</code> if * and only <code>t == null</code>. */ private static final Throwable rootCauseFor(Throwable t) { if (t == null) { return null; } else { return ExceptionUtils.getRootCause(t); } } // Constructors CallException(String shortReason, CallRequest request, TargetDescriptor target, long duration, String detail, Throwable cause) throws IllegalArgumentException { // Call superconstructor with fabricated message super(createMessage(shortReason, request, target, duration, detail), rootCauseFor(cause)); // Store request and target _request = request; _target = target; _duration = duration; } // Fields /** * The original request. Cannot be <code>null</code>. */ private final CallRequest _request; /** * Descriptor for the target that was attempted to be called. Cannot be * <code>null</code>. */ private final TargetDescriptor _target; /** * The time elapsed between the time the call attempt was started and the * time the call returned. The duration is in milliseconds and is always * &gt;= 0. */ private final long _duration; /** * The next linked <code>CallException</code>. Can be <code>null</code> if * there is none or if it has not been set yet. */ private CallException _next; // Methods /** * Returns the original request. * * @return * the original request, never <code>null</code>. */ public final CallRequest getRequest() { return _request; } /** * Returns the descriptor for the target that was attempted to be called. * * @return * the target descriptor, cannot be <code>null</code>. */ public final TargetDescriptor getTarget() { return _target; } /** * Returns the call duration. This is defined as the time elapsed between * the time the call attempt was started and the time the call returned. * The duration is in milliseconds and is always &gt;= 0. * * @return * the call duration in milliseconds, always &gt;= 0. */ public final long getDuration() { return _duration; } final void setNext(CallException next) throws IllegalStateException, IllegalArgumentException { // Check preconditions if (_next != null) { throw new IllegalStateException("Next linked CallException already set."); } MandatoryArgumentChecker.check("next", next); _next = next; } /** * Gets the next linked <code>CallException</code>, if there is any. * * @return * the next linked <code>CallException</code>, or <code>null</code> if * there is none. */ public final CallException getNext() { return _next; } }
package ch.openech.client.e21; import static ch.openech.dm.person.Relation.RELATION; import java.util.List; import ch.openech.client.e10.AddressField; import ch.openech.client.ewk.event.EchFormPanel; import ch.openech.dm.code.EchCodes; import ch.openech.dm.person.Relation; import ch.openech.mj.db.model.Constants; import ch.openech.mj.edit.fields.CodeEditField; import ch.openech.mj.edit.fields.EditField; import ch.openech.mj.edit.form.DependingOnFieldAbove; import ch.openech.mj.edit.validation.ValidationMessage; import ch.openech.mj.util.StringUtils; import ch.openech.xml.write.EchNamespaceContext; public class RelationPanel extends EchFormPanel<Relation> { public RelationPanel(EchNamespaceContext echNamespaceContext, boolean withNameOfParents) { super(echNamespaceContext); area(RELATION.partner); area(new AddressField(RELATION.address, true)); if (withNameOfParents) { line(RELATION.officialNameAtBirth); line(RELATION.firstNameAtBirth); } line(RELATION.typeOfRelationship); line(new BasedOnLawField()); // TODO: Was war hier gemeint? /* FormField<String> care = new DependenceDecorator<String>(new CodeField(RELATION.typeOfRelationship, EchCodes.careTypeOfRelationship), StringConstants.TYPE_OF_RELATIONSHIP) { @Override public void setDependedField(FormField<String> field) { String typeOfRelationship = field.getObject(); // TODO das ist isParent auf Relation boolean isParent = "3".equals(typeOfRelationship) || "4".equals(typeOfRelationship) || "5".equals(typeOfRelationship) || "6".equals(typeOfRelationship); setEnabled(isParent); } }; line(care); */ line(RELATION.care); } private class BasedOnLawField extends CodeEditField implements DependingOnFieldAbove<String> { public BasedOnLawField() { super(RELATION.basedOnLaw, getNamespaceContext() == null || getNamespaceContext().reducedBasedOnLawCode() ? EchCodes.basedOnLaw3 : EchCodes.basedOnLaw); } @Override public String getNameOfDependedField() { return Constants.getConstant(RELATION.typeOfRelationship); } @Override public void setDependedField(EditField<String> dependedField) { String typeOfRelationship = dependedField.getObject(); // TODO das ist isCare auf Relation boolean isVormund = "7".equals(typeOfRelationship) || "8".equals(typeOfRelationship) || "9".equals(typeOfRelationship); setEnabled(isVormund); } } @Override public Relation getObject() { Relation relation = super.getObject(); if (!relation.isCareRelation()) relation.basedOnLaw = null; if (!relation.isParent()) relation.care = null; return relation; } @Override public void validate(List<ValidationMessage> resultList) { super.validate(resultList); Relation relation = getObject(); if (relation.partner == null) { if (!relation.isParent()) { resultList.add(new ValidationMessage(RELATION.partner, "Person muss gesetzt sein")); } else if (relation.address != null) { resultList.add(new ValidationMessage(RELATION.partner, "Adresse darf nur gesetzt sein, wenn Person gesetzt ist")); } } if (!relation.isParent()) { if (!StringUtils.isBlank(relation.firstNameAtBirth) || !StringUtils.isBlank(relation.officialNameAtBirth)) { resultList.add(new ValidationMessage(RELATION.partner, "\"Name:\" darf nur bei Mutter oder Vater gesetzt sein")); } } } }
// $Id: FadeAnimation.java,v 1.3 2002/01/31 17:35:41 shaper Exp $ package com.threerings.media.animation; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import com.threerings.media.Log; /** * An animation that displays an image fading from one alpha level to * another in specified increments over time. The animation is finished * when the specified target alpha is reached. */ public class FadeAnimation extends Animation { /** * Constructs a fade animation. * * @param image the image to animate. * @param x the image x-position. * @param y the image y-position. * @param alpha the starting alpha. * @param step the alpha amount to step by each millisecond. * @param target the target alpha level. */ public FadeAnimation ( Image image, int x, int y, float alpha, float step, float target) { super(new Rectangle(x, y, image.getWidth(null), image.getHeight(null))); // save things off _image = image; _x = x; _y = y; _startAlpha = _alpha = alpha; _step = step; _target = target; // create the initial composite _comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, _alpha); } /** * Sets the animation starting time. */ public void setStartTime (long timestamp) { _start = timestamp; } // documentation inherited public void tick (long timestamp) { // figure out the current alpha long msecs = timestamp - _start; _alpha = _startAlpha + (msecs * _step); if (_alpha < 0.0f) { _alpha = 0.0f; } else if (_alpha > 1.0f) { _alpha = 1.0f; } _comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, _alpha); // check whether we're done _finished = ((_startAlpha < _target) ? (_alpha >= _target) : (_alpha <= _target)); // dirty ourselves invalidate(); } // documentation inherited public void paint (Graphics2D gfx) { Composite ocomp = gfx.getComposite(); if (_comp == null) { Log.warning("Fade anim has null composite [anim=" + this + "]."); } else { gfx.setComposite(_comp); } gfx.drawImage(_image, _x, _y, null); gfx.setComposite(ocomp); } // documentation inherited protected void toString (StringBuffer buf) { super.toString(buf); buf.append(", x=").append(_x); buf.append(", y=").append(_y); buf.append(", alpha=").append(_alpha); buf.append(", startAlpha=").append(_startAlpha); buf.append(", step=").append(_step); buf.append(", target=").append(_target); } /** The composite used to render the image with the current alpha. */ protected Composite _comp; /** The current alpha of the image. */ protected float _alpha; /** The target alpha. */ protected float _target; /** The alpha step per millisecond. */ protected float _step; /** The starting alpha. */ protected float _startAlpha; /** The image position. */ protected int _x, _y; /** The image to animate. */ protected Image _image; /** The starting animation time. */ protected long _start; }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.puzzle.client; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.util.ArrayList; import javax.swing.UIManager; import com.samskivert.swing.Label; import com.samskivert.swing.util.SwingUtil; import com.samskivert.util.StringUtil; import com.threerings.media.VirtualMediaPanel; import com.threerings.media.animation.Animation; import com.threerings.media.animation.AnimationAdapter; import com.threerings.media.image.Mirage; import com.threerings.media.sprite.Sprite; import com.threerings.puzzle.Log; import com.threerings.puzzle.data.Board; import com.threerings.puzzle.data.PuzzleCodes; import com.threerings.puzzle.data.PuzzleConfig; import com.threerings.puzzle.util.PuzzleContext; /** * The puzzle board view displays a view of a puzzle game. */ public abstract class PuzzleBoardView extends VirtualMediaPanel { /** * Constructs a puzzle board view. */ public PuzzleBoardView (PuzzleContext ctx) { super(ctx.getFrameManager()); // keep this for later _ctx = ctx; } /** * Initializes the board with the board dimensions. */ public void init (PuzzleConfig config) { // save off our bounds Dimension bounds = getPreferredSize(); _bounds = new Rectangle(0, 0, bounds.width, bounds.height); } /** * Sets the board to be displayed. */ public void setBoard (Board board) { _board = board; } /** * Provides the board view with a reference to its controller so that * it may communicate directly rather than by posting actions up the * interface hierarchy which sometimes fails if the puzzle board view * is hidden before we get a chance to post our actions. */ public void setController (PuzzleController pctrl) { _pctrl = pctrl; } /** * Sets the background image displayed by the board view. */ public void setBackgroundImage (Mirage image) { _background = image; } /** * Set whether this puzzle is paused or not. */ public void setPaused (boolean paused) { if (paused) { String pmsg = _pctrl.getPauseString(); pmsg = _ctx.getMessageManager().getBundle( PuzzleCodes.PUZZLE_MESSAGE_BUNDLE).xlate(pmsg); _pauseLabel = new Label(pmsg, Label.BOLD | Label.OUTLINE, Color.WHITE, Color.BLACK, _fonts[_fonts.length - 2]); _pauseLabel.setTargetWidth(_bounds.width); _pauseLabel.layout(this); } else { _pauseLabel = null; } repaint(); } /** * Adds the given animation to the set of animations currently present * on the board. The animation will be added to a list of action * animations whose count can be queried with {@link * #getActionAnimationCount}. The animation will automatically be * removed from the action list when it completes. */ public void addActionAnimation (Animation anim) { super.addAnimation(anim); // remember the animation's existence _actionAnims.add(anim); // and listen for it to finish so that we can clear it out anim.addAnimationObserver(_actionAnimObs); } // documentation inherited public void abortAnimation (Animation anim) { super.abortAnimation(anim); // always check to see if it was action-y animationFinished(anim); } /** * Called when a potential action animation is finished. */ protected void animationFinished (Animation anim) { if (DEBUG_ACTION) { Log.info("Animation cleared " + StringUtil.shortClassName(anim) + ":" + _actionAnims.contains(anim)); } // if it WAS an action animation, check for a clear if (_actionAnims.remove(anim)) { maybeFireCleared(); } } /** * Adds the given sprite to the set of sprites currently present on * the board. The sprite will be added to a list of action sprites * whose count can be queried with {@link #getActionSpriteCount}. Callers * should be sure to remove the sprite when their work with it is done * via {@link #removeSprite}. */ public void addActionSprite (Sprite sprite) { // add the piece to the sprite manager addSprite(sprite); // note that this piece is interesting _actionSprites.add(sprite); } /** * Removes the given sprite from the board. */ public void removeSprite (Sprite sprite) { super.removeSprite(sprite); if (DEBUG_ACTION) { Log.info("Sprite cleared " + StringUtil.shortClassName(sprite) + ":" + _actionSprites.contains(sprite)); } // we just always check to see if it was action-y if (_actionSprites.remove(sprite)) { maybeFireCleared(); } } // documentation inherited public void clearSprites () { super.clearSprites(); _actionSprites.clear(); } // documentation inherited public void clearAnimations () { super.clearAnimations(); _actionAnims.clear(); } /** * Returns the number of action animations on the board. */ public int getActionAnimationCount () { return _actionAnims.size(); } /** * Returns the number of action sprites on the board. */ public int getActionSpriteCount () { return _actionSprites.size(); } /** * Returns the count of action sprites and animations on the board. */ public int getActionCount () { return _actionSprites.size() + _actionAnims.size(); } /** * Dumps to the logs, a list of interesting sprites and animations * currently active on the puzzle board. */ public void dumpActors () { StringUtil.Formatter fmt = new StringUtil.Formatter() { public String toString (Object obj) { return StringUtil.shortClassName(obj); } }; Log.info("Board contents [board=" + StringUtil.shortClassName(this) + ", sprites=" + StringUtil.listToString(_actionSprites, fmt) + ", anims=" + StringUtil.listToString(_actionAnims, fmt) + "]."); } /** * Creates and returns an animation displaying the given string with * the specified parameters, floating it a short distance up the view. * * @param score the score text to display. * @param color the color of the text. * @param fontSize the size of the text; a value between 0 and {@link * #getPuzzleFontCount} - 1. * @param x the x-position at which the score is to be placed. * @param y the y-position at which the score is to be placed. */ public ScoreAnimation createScoreAnimation ( String score, Color color, int fontSize, int x, int y) { // create and configure the label Label label = new Label(score); label.setTargetWidth(_bounds.width); label.setStyle(Label.OUTLINE); label.setTextColor(color); label.setAlternateColor(Color.black); label.setFont(getPuzzleFont(fontSize)); label.setAlignment(Label.CENTER); label.layout(this); // create the score animation ScoreAnimation anim = createScoreAnimation(label, x, y); anim.setRenderOrder(getScoreRenderOrder()); return anim; } /** * Creates a score animation, allowing derived classes to use custom * animations that are customized following a call to * {@link #createScoreAnimation}. */ protected ScoreAnimation createScoreAnimation (Label label, int x, int y) { return new ScoreAnimation(label, x, y); } /** * Returns the render order to be assigned to score animations by * default. Derived classes may wish to override this method to * change the default render order. * * @see #createScoreAnimation */ protected int getScoreRenderOrder () { return 1; } /** * Returns the puzzle font to be used for the specified score. */ public int getFont (String why, int score, int maxScore) { int fontSize = (int)(score*getPuzzleFontCount()/maxScore); fontSize = Math.min(FONT_SIZES.length-1, fontSize); // Log.info("Font for " + why + " (" + score + " of " + maxScore + // ") => " + fontSize + "."); return fontSize; } /** * Returns the number of different puzzle font sizes so that those who * care to choose a font size out of the range of possible sizes can * do so gracefully. */ public int getPuzzleFontCount () { return FONT_SIZES.length; } /** * Returns the puzzle font of the specified size. * * @param size the desired font size; a value between 0 and {@link * #getPuzzleFontCount} - 1. */ public static Font getPuzzleFont (int size) { return _fonts[size]; } /** * Positions the supplied animation so as to avoid any active * animations previously registered with this method, and adds the * animation to the list of animations to be avoided by any future * avoid animations. */ public void trackAvoidAnimation (Animation anim) { // reposition the animation as appropriate Rectangle abounds = new Rectangle(anim.getBounds()); ArrayList avoidables = (ArrayList)_avoidAnims.clone(); if (SwingUtil.positionRect(abounds, _vbounds, avoidables)) { anim.setLocation(abounds.x, abounds.y); } // add the animation to the list of avoidables _avoidAnims.add(anim); // keep an eye on it so that we can remove it when it's finished anim.addAnimationObserver(_avoidAnimObs); } // documentation inherited public void paintBehind (Graphics2D gfx, Rectangle dirty) { super.paintBehind(gfx, dirty); // render the background renderBackground(gfx, dirty); } /** * Fills the background of the board with the background color. */ protected void renderBackground (Graphics2D gfx, Rectangle dirty) { gfx.setColor(getBackground()); gfx.fill(dirty); } // documentation inherited public void paintBetween (Graphics2D gfx, Rectangle dirty) { super.paintBetween(gfx, dirty); // PerformanceMonitor.tick(this, "paint"); renderBoard(gfx, dirty); } // documentation inherited protected void paintInFront (Graphics2D gfx, Rectangle dirty) { super.paintInFront(gfx, dirty); // if the action is paused, indicate as much if (_pauseLabel != null) { Dimension d = _pauseLabel.getSize(); _pauseLabel.render(gfx, _vbounds.x + (_vbounds.width - d.width) / 2, _vbounds.y + (_vbounds.height - d.height) / 2); } } /** * Fires a {@link #ACTION_CLEARED} command iff we have no remaining * interesting sprites or animations. */ protected void maybeFireCleared () { if (DEBUG_ACTION) { Log.info("Maybe firing cleared " + getActionCount() + ":" + isShowing()); } if (getActionCount() == 0) { // we're probably in the middle of a tick() in an // animationDidFinish() call and we want everyone to finish // processing their business before we go clearing the action, // so we queue this up to be run after the tick is complete _ctx.getClient().getRunQueue().postRunnable(new Runnable() { public void run () { _pctrl.boardActionCleared(); } }); } } /** * Renders the board contents to the given graphics context. * Sub-classes should implement this method to draw all of their * game-specific business. */ protected abstract void renderBoard (Graphics2D gfx, Rectangle dirty); /** Our client context. */ protected PuzzleContext _ctx; /** Our puzzle controller. */ protected PuzzleController _pctrl; /** The board data to be displayed. */ protected Board _board; /** The board's bounding rectangle. */ protected Rectangle _bounds; /** The action animations on the board. */ protected ArrayList _actionAnims = new ArrayList(); /** The action sprites on the board. */ protected ArrayList _actionSprites = new ArrayList(); /** The animations that other animations may wish to avoid. */ protected ArrayList _avoidAnims = new ArrayList(); /** Our background image. */ protected Mirage _background; /** A label to show when the puzzle is paused. */ protected Label _pauseLabel; /** The distance in pixels that score animations float. */ protected int _scoreDist = DEFAULT_SCORE_DISTANCE; /** Listens to our action animations and clears them when they're done. */ protected AnimationAdapter _actionAnimObs = new AnimationAdapter() { public void animationCompleted (Animation anim, long when) { animationFinished(anim); } }; /** Automatically removes avoid animations when they're done. */ protected AnimationAdapter _avoidAnimObs = new AnimationAdapter() { public void animationCompleted (Animation anim, long when) { if (!_avoidAnims.remove(anim)) { Log.warning("Couldn't remove avoid animation?! " + anim + "."); } } }; /** The puzzle fonts. */ protected static Font[] _fonts; /** Temporary action debugging. */ protected static boolean DEBUG_ACTION = false; // action state constants protected static final int ACTION_GOING = 0; protected static final int CLEAR_PENDING = 1; protected static final int ACTION_CLEARED = 2; /** The default vertical distance to float score animations. */ protected static final int DEFAULT_SCORE_DISTANCE = 30; /** The mid-sized font used as the default size for score * animations. */ protected static final int MEDIUM_FONT_SIZE = 1; /** The puzzle font sizes. */ protected static final double[] FONT_SIZES = { 24d, 30d, 36d, 42d, 52d, 68d }; static { // create the puzzle fonts Font ofont = UIManager.getFont("Label.serifFont"); if (ofont == null) { ofont = new Font("Helvetica", Font.PLAIN, 16); } ofont = ofont.deriveFont((float)FONT_SIZES[0]); _fonts = new Font[FONT_SIZES.length]; for (int ii = 0; ii < _fonts.length; ii++) { double scale = FONT_SIZES[ii]/FONT_SIZES[0]; _fonts[ii] = ofont.deriveFont( AffineTransform.getScaleInstance(scale * 1.1d, scale)); } } }
package com.hazelcast.wan; import com.hazelcast.config.Config; import com.hazelcast.config.WanReplicationConfig; import com.hazelcast.config.WanReplicationRef; import com.hazelcast.config.WanTargetClusterConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.instance.HazelcastInstanceFactory; import com.hazelcast.map.merge.HigherHitsMapMergePolicy; import com.hazelcast.map.merge.LatestUpdateMapMergePolicy; import com.hazelcast.map.merge.PassThroughMergePolicy; import com.hazelcast.map.merge.PutIfAbsentMapMergePolicy; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ProblematicTest; import com.hazelcast.test.annotation.SlowTest; import org.junit.*; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import static org.junit.Assert.*; @RunWith(HazelcastSerialClassRunner.class) @Category(SlowTest.class) public class WanReplicationTest extends HazelcastTestSupport{ private HazelcastInstanceFactory factory = new HazelcastInstanceFactory(); private HazelcastInstance[] clusterA = new HazelcastInstance[2]; private HazelcastInstance[] clusterB = new HazelcastInstance[2]; private HazelcastInstance[] clusterC = new HazelcastInstance[2]; private Config configA; private Config configB; private Config configC; private Random random = new Random(); @Before public void setup() throws Exception { configA = new Config(); configA.getGroupConfig().setName("A"); configA.getNetworkConfig().setPort(5701); configB = new Config(); configB.getGroupConfig().setName("B"); configB.getNetworkConfig().setPort(5801); configC = new Config(); configC.getGroupConfig().setName("C"); configC.getNetworkConfig().setPort(5901); } private void initCluster(HazelcastInstance[] cluster, Config config){ for(int i=0; i<cluster.length; i++){ cluster[i]= factory.newHazelcastInstance(config); } } private void initClusterA(){ initCluster(clusterA, configA); } private void initClusterB(){ initCluster(clusterB, configB); } private void initClusterC(){ initCluster(clusterC, configC); } private void initAllClusters(){ initClusterA(); initClusterB(); initClusterC(); } private HazelcastInstance getNode(HazelcastInstance[] cluster){ return cluster[random.nextInt(cluster.length) ]; } private List getClusterEndPoints(Config config, int count){ List ends = new ArrayList<String>(); int port = config.getNetworkConfig().getPort(); for(int i=0; i<count; i++){ ends.add(new String("127.0.0.1:"+port++ ) ); } return ends; } private WanTargetClusterConfig targetCluster(Config config, int count){ WanTargetClusterConfig target = new WanTargetClusterConfig(); target.setGroupName(config.getGroupConfig().getName()); target.setReplicationImpl(WanNoDelayReplication.class.getName()); target.setEndpoints(getClusterEndPoints(config, count)); return target; } private void setupReplicateFrom(Config fromConfig, Config toConfig, int clusterSz, String setupName, String policy){ WanReplicationConfig wanConfig = new WanReplicationConfig(); wanConfig.setName(setupName); wanConfig.addTargetClusterConfig(targetCluster(toConfig, clusterSz)); WanReplicationRef wanRef = new WanReplicationRef(); wanRef.setName(setupName); wanRef.setMergePolicy(policy); fromConfig.addWanReplicationConfig(wanConfig); fromConfig.getMapConfig("default").setWanReplicationRef(wanRef); } private void createDataIn(HazelcastInstance[] cluster, String mapName, int start, int end){ HazelcastInstance node = getNode(cluster); IMap m = node.getMap(mapName); for(; start<end; start++) m.put(start, node.getConfig().getGroupConfig().getName()+start); } private void removeDataIn(HazelcastInstance[] cluster, String mapName, int start, int end){ HazelcastInstance node = getNode(cluster); IMap m = node.getMap(mapName); for(; start<end; start++) m.remove(start); } private boolean checkKeysIn(HazelcastInstance[] cluster, String mapName, int start, int end){ HazelcastInstance node = getNode(cluster); IMap m = node.getMap(mapName); for(; start<end; start++) if(!m.containsKey(start)) return false; return true; } private boolean checkDataInFrom(HazelcastInstance[] targetCluster, String mapName, int start, int end, HazelcastInstance[] sourceCluster){ HazelcastInstance node = getNode(targetCluster); String sourceGroupName = getNode(sourceCluster).getConfig().getGroupConfig().getName(); IMap m = node.getMap(mapName); for(; start<end; start++){ Object v = m.get(start); if(v==null || !v.equals(sourceGroupName+start)) return false; } return true; } private boolean checkKeysNotIn(HazelcastInstance[] cluster, String mapName, int start, int end){ HazelcastInstance node = getNode(cluster); IMap m = node.getMap(mapName); for(; start<end; start++) if(m.containsKey(start)) return false; return true; } private void assertDataSize(final HazelcastInstance[] cluster, String mapName, int size){ HazelcastInstance node = getNode(cluster); IMap m = node.getMap(mapName); assertEquals(size, m.size()); } private void assertKeysIn(final HazelcastInstance[] cluster, final String mapName, final int start, final int end){ assertTrueEventually(new AssertTask() { public void run() { assertTrue(checkKeysIn(cluster, mapName, start, end) ); } }); } private void assertDataInFrom(final HazelcastInstance[] cluster, final String mapName, final int start, final int end, final HazelcastInstance[] sourceCluster){ assertTrueEventually(new AssertTask() { public void run() { assertTrue(checkDataInFrom(cluster, mapName, start, end, sourceCluster) ); } }); } private void assertKeysNotIn(final HazelcastInstance[] cluster, final String mapName, final int start, final int end){ assertTrueEventually(new AssertTask() { public void run() { assertTrue(checkKeysNotIn(cluster, mapName, start, end) ); } }); } // V topo config 1 passive replicar, 2 producers @Test @Category(ProblematicTest.class) public void VTopo_1passiveReplicar_2producers_Test_PassThroughMergePolicy(){ setupReplicateFrom(configA, configC, clusterC.length, "atoc", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configB, configC, clusterC.length, "btoc", PassThroughMergePolicy.class.getName()); initAllClusters(); createDataIn(clusterA, "map", 0, 1000); createDataIn(clusterB, "map", 1000, 2000); assertDataInFrom(clusterC, "map", 0, 1000, clusterA); assertDataInFrom(clusterC, "map", 1000, 2000, clusterB); createDataIn(clusterB, "map", 0, 1); assertDataInFrom(clusterC, "map", 0, 1, clusterB); removeDataIn(clusterA, "map", 0, 500); removeDataIn(clusterB, "map", 1500, 2000); assertKeysNotIn(clusterC, "map", 0, 500); assertKeysNotIn(clusterC, "map", 1500, 2000); assertKeysIn(clusterC, "map", 500, 1500); removeDataIn(clusterA, "map", 500, 1000); removeDataIn(clusterB, "map", 1000, 1500); assertKeysNotIn(clusterC, "map", 0, 2000); assertDataSize(clusterC, "map", 0); } @Test @Category(ProblematicTest.class) public void Vtopo_TTL_Replication_Issue254(){ setupReplicateFrom(configA, configC, clusterC.length, "atoc", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configB, configC, clusterC.length, "btoc", PassThroughMergePolicy.class.getName()); configA.getMapConfig("default").setTimeToLiveSeconds(2); configB.getMapConfig("default").setTimeToLiveSeconds(2); configC.getMapConfig("default").setTimeToLiveSeconds(2); initAllClusters(); createDataIn(clusterA, "map", 0, 10); assertDataInFrom(clusterC, "map", 0, 10, clusterA); createDataIn(clusterB, "map", 10, 20); assertDataInFrom(clusterC, "map", 10, 20, clusterB); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } assertKeysNotIn(clusterA, "map", 0, 10); assertKeysNotIn(clusterB, "map", 10, 20); assertKeysNotIn(clusterC, "map", 0, 20); } //"Issue @Test @Category(ProblematicTest.class) public void VTopo_1activeActiveReplicar_2producers_Test_PassThroughMergePolicy(){ setupReplicateFrom(configA, configC, clusterC.length, "atoc", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configB, configC, clusterC.length, "btoc", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configC, configA, clusterA.length, "ctoa", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configC, configB, clusterB.length, "ctob", PassThroughMergePolicy.class.getName()); initAllClusters(); printAllReplicarConfig(); createDataIn(clusterA, "map", 0, 1000); createDataIn(clusterB, "map", 1000, 2000); assertDataInFrom(clusterC, "map", 0, 1000, clusterA); assertDataInFrom(clusterC, "map", 1000, 2000, clusterB); assertDataInFrom(clusterA, "map", 1000, 2000, clusterB); assertDataInFrom(clusterB, "map", 0, 1000, clusterA); } @Test @Category(ProblematicTest.class) public void VTopo_1passiveReplicar_2producers_Test_PutIfAbsentMapMergePolicy(){ setupReplicateFrom(configA, configC, clusterC.length, "atoc", PutIfAbsentMapMergePolicy.class.getName()); setupReplicateFrom(configB, configC, clusterC.length, "btoc", PutIfAbsentMapMergePolicy.class.getName()); initAllClusters(); createDataIn(clusterA, "map", 0, 1000); createDataIn(clusterB, "map", 1000, 2000); assertDataInFrom(clusterC, "map", 0, 1000, clusterA); assertDataInFrom(clusterC, "map", 1000, 2000, clusterB); createDataIn(clusterB, "map", 0, 1000); assertDataInFrom(clusterC, "map", 0, 1000, clusterA); assertDataSize(clusterC, "map", 2000); removeDataIn(clusterA, "map", 0, 1000); removeDataIn(clusterB, "map", 1000, 2000); assertKeysNotIn(clusterC, "map", 0, 2000); assertDataSize(clusterC, "map", 0); } @Test @Category(ProblematicTest.class) public void VTopo_1passiveReplicar_2producers_Test_LatestUpdateMapMergePolicy (){ setupReplicateFrom(configA, configC, clusterC.length, "atoc", LatestUpdateMapMergePolicy.class.getName()); setupReplicateFrom(configB, configC, clusterC.length, "btoc", LatestUpdateMapMergePolicy.class.getName()); initAllClusters(); createDataIn(clusterA, "map", 0, 1000); assertDataInFrom(clusterC, "map", 0, 1000, clusterA); createDataIn(clusterB, "map", 0, 1000); assertDataInFrom(clusterC, "map", 0, 1000, clusterB); assertDataSize(clusterC, "map", 1000); removeDataIn(clusterA, "map", 0, 500); assertKeysNotIn(clusterC, "map", 0, 500); removeDataIn(clusterB, "map", 500, 1000); assertKeysNotIn(clusterC, "map", 500, 1000); assertDataSize(clusterC, "map", 0); } //"Issue #1373 this test passes when run in isolation")//TODO @Test @Category(ProblematicTest.class) public void VTopo_1passiveReplicar_2producers_Test_HigherHitsMapMergePolicy(){ setupReplicateFrom(configA, configC, clusterC.length, "atoc", HigherHitsMapMergePolicy.class.getName()); setupReplicateFrom(configB, configC, clusterC.length, "btoc", HigherHitsMapMergePolicy.class.getName()); initAllClusters(); createDataIn(clusterA, "map", 0, 1000); assertDataInFrom(clusterC, "map", 0, 1000, clusterA); createDataIn(clusterB, "map", 0, 1000); assertDataInFrom(clusterC, "map", 0, 1000, clusterA); createDataIn(clusterB, "map", 0, 1000); createDataIn(clusterB, "map", 0, 1000); createDataIn(clusterB, "map", 0, 1000); assertDataInFrom(clusterC, "map", 0, 1000, clusterB); } //("Issue #1368 multi replicar topology cluster A replicates to B and C") @Test @Category(ProblematicTest.class) public void VTopo_2passiveReplicar_1producer_Test(){ setupReplicateFrom(configA, configB, clusterB.length, "atob", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configA, configC, clusterC.length, "atoc", PassThroughMergePolicy.class.getName()); initAllClusters(); createDataIn(clusterA, "map", 0, 1000); assertKeysIn(clusterB, "map", 0, 1000); assertKeysIn(clusterC, "map", 0, 1000); removeDataIn(clusterA, "map", 0, 1000); assertKeysNotIn(clusterB, "map", 0, 1000); assertKeysNotIn(clusterC, "map", 0, 1000); assertDataSize(clusterB, "map", 0); assertDataSize(clusterC, "map", 0); } @Test @Category(ProblematicTest.class) public void linkTopo_ActiveActiveReplication_Test(){ setupReplicateFrom(configA, configB, clusterB.length, "atob", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configB, configA, clusterA.length, "btoa", PassThroughMergePolicy.class.getName()); initClusterA(); initClusterB(); createDataIn(clusterA, "map", 0, 1000); assertDataInFrom(clusterB, "map", 0, 1000, clusterA); createDataIn(clusterB, "map", 1000, 2000); assertDataInFrom(clusterA, "map", 1000, 2000, clusterB); removeDataIn(clusterA, "map", 1500, 2000); assertKeysNotIn(clusterB, "map", 1500, 2000); removeDataIn(clusterB, "map", 0, 500); assertKeysNotIn(clusterA, "map", 0, 500); assertKeysIn(clusterA, "map", 500, 1500); assertKeysIn(clusterB, "map", 500, 1500); assertDataSize(clusterA, "map", 1000); assertDataSize(clusterB, "map", 1000); } @Test @Category(ProblematicTest.class) public void linkTopo_ActiveActiveReplication_Threading_Test() throws InterruptedException, BrokenBarrierException { setupReplicateFrom(configA, configB, clusterB.length, "atob", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configB, configA, clusterA.length, "btoa", PassThroughMergePolicy.class.getName()); initClusterA(); initClusterB(); CyclicBarrier gate = new CyclicBarrier(3); startGatedThread(new GatedThread(gate) { public void go() { createDataIn(clusterA, "map", 0, 1000); } }); startGatedThread(new GatedThread(gate) { public void go() { createDataIn(clusterB, "map", 500, 1500); } }); gate.await(); assertDataInFrom(clusterB, "map", 0, 500, clusterA); assertDataInFrom(clusterA, "map", 1000, 1500, clusterB); assertKeysIn(clusterA, "map", 500, 1000); gate = new CyclicBarrier(3); startGatedThread(new GatedThread(gate) { public void go() { removeDataIn(clusterA, "map", 0, 1000); } }); startGatedThread(new GatedThread(gate) { public void go() { removeDataIn(clusterB, "map", 500, 1500); } }); gate.await(); assertKeysNotIn(clusterA, "map", 0, 1500); assertKeysNotIn(clusterB, "map", 0, 1500); assertDataSize(clusterA, "map", 0); assertDataSize(clusterB, "map", 0); } @Test @Category(ProblematicTest.class) public void linkTopo_ActiveActiveReplication_2clusters_Test_HigherHitsMapMergePolicy(){ setupReplicateFrom(configA, configB, clusterB.length, "atob", HigherHitsMapMergePolicy.class.getName()); setupReplicateFrom(configB, configA, clusterA.length, "btoa", HigherHitsMapMergePolicy.class.getName()); initClusterA(); initClusterB(); createDataIn(clusterA, "map", 0, 1000); assertDataInFrom(clusterB, "map", 0, 1000, clusterA); createDataIn(clusterB, "map", 0, 500); assertDataInFrom(clusterA, "map", 0, 500, clusterB); } //("Issue #1372 is a chain of replicars a valid topology")//TODO @Test @Category(ProblematicTest.class) public void chainTopo_2passiveReplicars_1producer(){ setupReplicateFrom(configA, configB, clusterB.length, "atob", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configB, configC, clusterC.length, "btoc", PassThroughMergePolicy.class.getName()); initAllClusters(); createDataIn(clusterA, "map", 0, 1000); assertKeysIn(clusterB, "map", 0, 1000); assertDataSize(clusterB, "map", 1000); assertKeysIn(clusterC, "map", 0, 1000); assertDataSize(clusterC, "map", 1000); } //("Issue #1372 is a ring topology valid")//TODO @Test @Category(ProblematicTest.class) public void replicationRing(){ setupReplicateFrom(configA, configB, clusterB.length,"atob", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configB, configC, clusterC.length,"btoc", PassThroughMergePolicy.class.getName()); setupReplicateFrom(configC, configA, clusterA.length,"ctoa", PassThroughMergePolicy.class.getName()); initAllClusters(); createDataIn(clusterA, "map", 0, 1000); assertKeysIn(clusterB, "map", 0, 1000); assertDataSize(clusterB, "map", 1000); assertKeysIn(clusterC, "map", 0, 1000); assertDataSize(clusterC, "map", 1000); } private void printReplicaConfig(Config c){ Map m = c.getWanReplicationConfigs(); Set<Entry> s = m.entrySet(); for(Entry e : s ){ System.out.println(e.getKey() + " ==> " + e.getValue()); } } private void printAllReplicarConfig(){ System.out.println(); System.out.println("==configA=="); printReplicaConfig(configA); System.out.println("==configB=="); printReplicaConfig(configB); System.out.println("==configC=="); printReplicaConfig(configC); System.out.println(); } abstract public class GatedThread extends Thread{ private final CyclicBarrier gate; public GatedThread(CyclicBarrier gate){ this.gate = gate; } public void run(){ try { gate.await(); go(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } abstract public void go(); } void startGatedThread(GatedThread t){ t.start(); } }
package org.helianto.core.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.persistence.Version; /** * Features suggest information to be shared among entities. * * @author mauriciofernandesdecastro */ @javax.persistence.Entity @Table(name="core_feature", uniqueConstraints = {@UniqueConstraint(columnNames={"contextId", "featureCode"})} ) public class Feature implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Version private int version; @ManyToOne @JoinColumn(name="contextId") private Operator context; @Column(length=32) private String featureCode; @Column(length=128) private String featureName; @Column(length=1024) private String featureDesc; private Character featureType = 'S'; /** * @deprecated */ @Column(length=32) private int osConstraints; @Column(length=128) private String constraints; /** * Constructor. */ public Feature() { super(); } /** * Constructor. * * @param context * @param featureCode */ public Feature(Operator context, String featureCode) { this(); setContext(context); setFeatureCode(featureCode); } /** * Constructor. * * @param context * @param featureCode * @param featureType */ public Feature(Operator context, String featureCode, Character featureType) { this(context, featureCode); setFeatureType(featureType); } /** * Constructor. * * @param context * @param featureCode * @param featureType * @param featureName */ public Feature(Operator context, String featureCode, Character featureType, String featureName) { this(context, featureCode, featureType); setFeatureName(featureName); } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public Operator getContext() { return context; } public void setContext(Operator context) { this.context = context; } public String getFeatureCode() { return featureCode; } public void setFeatureCode(String featureCode) { this.featureCode = featureCode; } public String getFeatureName() { return featureName; } public void setFeatureName(String featureName) { this.featureName = featureName; } public String getFeatureDesc() { return featureDesc; } public void setFeatureDesc(String featureDesc) { this.featureDesc = featureDesc; } public Character getFeatureType() { return featureType; } public void setFeatureType(Character featureType) { this.featureType = featureType; } public int getOsConstraints() { return osConstraints; } public void setOsConstraints(int osConstraints) { this.osConstraints = osConstraints; } public String getConstraints() { return constraints; } public void setConstraints(String constraints) { this.constraints = constraints; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((context == null) ? 0 : context.hashCode()); result = prime * result + ((featureCode == null) ? 0 : featureCode.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; Feature other = (Feature) obj; if (context == null) { if (other.context != null) return false; } else if (!context.equals(other.context)) return false; if (featureCode == null) { if (other.featureCode != null) return false; } else if (!featureCode.equals(other.featureCode)) return false; return true; } }