answer
stringlengths
17
10.2M
package st.gaw.db; import java.util.Map; public class MapEntry<K, V> implements Map.Entry<K, V> { private final K mKey; private V mVal; public MapEntry(K key, V val) { if (null==key) throw new NullPointerException(); mKey = key; mVal = val; } @Override public K getKey() { return mKey; } @Override public V getValue() { return mVal; } @Override public boolean equals(Object o) { if (this==o) return true; if (!(o instanceof MapEntry)) return false; return mKey.equals(((MapEntry<?, ?>) o).mKey); } @Override public int hashCode() { return mKey.hashCode(); } @Override public V setValue(V newVal) { mVal = newVal; return mVal; } @Override public String toString() { return mKey.toString()+':'+(null==mVal ? null : mVal.toString()); } }
// VisitechReader.java package loci.formats.in; import java.io.*; import java.util.*; import loci.formats.*; public class VisitechReader extends FormatReader { // -- Fields -- /** Files in this dataset. */ private Vector files; // -- Constructor -- public VisitechReader() { super("Visitech XYS", new String[] {"xys", "html"}); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(byte[]) */ public boolean isThisType(byte[] block) { return false; } /* @see loci.formats.IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); FormatTools.checkPlaneNumber(this, no); FormatTools.checkBufferSize(this, buf.length); int plane = core.sizeX[series] * core.sizeY[series] * FormatTools.getBytesPerPixel(core.pixelType[series]); int div = core.sizeZ[series] * core.sizeT[series]; int fileIndex = (series * core.sizeC[series]) + no / div; int planeIndex = no % div; String file = (String) files.get(fileIndex); RandomAccessStream s = new RandomAccessStream(file); s.seek(374); while (s.read() != (byte) 0xf0); s.skipBytes(1); if (s.readInt() == 0) s.skipBytes(4 + ((plane + 164) * planeIndex)); else { if (planeIndex == 0) s.seek(s.getFilePointer() - 4); else s.skipBytes((plane + 164) * planeIndex - 4); } s.read(buf); s.close(); return buf; } /* @see loci.formats.IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { if (files == null) return new String[0]; return (String[]) files.toArray(new String[0]); } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { super.close(); files = null; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); // first, make sure we have the HTML file if (!id.toLowerCase().endsWith("html")) { Location file = new Location(id).getAbsoluteFile(); String path = file.exists() ? file.getPath() : id; int ndx = path.lastIndexOf(File.separator); String base = path.substring(ndx + 1, path.indexOf(" ", ndx)); String suffix = " Report.html"; currentId = null; initFile(file.exists() ? new Location(file.getParent(), base + suffix).getAbsolutePath() : base + suffix); return; } // parse the HTML file in = new RandomAccessStream(id); String s = in.readString((int) in.length()); // strip out "style", "a", and "script" tags s = s.replaceAll("<[bB][rR]>", "\n"); s = s.replaceAll("<[sS][tT][yY][lL][eE]\\p{ASCII}*?" + "[sS][tT][yY][lL][eE]>", ""); s = s.replaceAll("<[sS][cC][rR][iI][pP][tT]\\p{ASCII}*?" + "[sS][cC][rR][iI][pP][tT]>", ""); StringTokenizer st = new StringTokenizer(s, "\n"); String token = null, key = null, value = null; int numSeries = 0; while (st.hasMoreTokens()) { token = st.nextToken().trim(); if ((token.startsWith("<") && !token.startsWith("</")) || token.indexOf("pixels") != -1) { token = token.replaceAll("<.*?>", ""); int ndx = token.indexOf(":"); if (ndx != -1) { key = token.substring(0, ndx).trim(); value = token.substring(ndx + 1).trim(); if (key.equals("Number of steps")) { core.sizeZ[0] = Integer.parseInt(value); } else if (key.equals("Image bit depth")) { int bits = Integer.parseInt(value); while ((bits % 8) != 0) bits++; switch (bits) { case 16: core.pixelType[0] = FormatTools.UINT16; break; case 32: core.pixelType[0] = FormatTools.UINT32; break; default: core.pixelType[0] = FormatTools.UINT8; } } else if (key.equals("Image dimensions")) { int n = value.indexOf(","); core.sizeX[0] = Integer.parseInt(value.substring(1, n).trim()); core.sizeY[0] = Integer.parseInt(value.substring(n + 1, value.length() - 1).trim()); } else if (key.startsWith("Channel Selection")) { core.sizeC[0]++; } else if (key.startsWith("Microscope XY")) { numSeries++; } addMeta(key, value); } if (token.indexOf("pixels") != -1) { core.sizeC[0]++; core.imageCount[0] += Integer.parseInt(token.substring(0, token.indexOf(" "))); } else if (token.startsWith("Time Series")) { int idx = token.indexOf(";") + 1; String ss = token.substring(idx, token.indexOf(" ", idx)).trim(); core.sizeT[0] = Integer.parseInt(ss); } } } if (core.sizeT[0] == 0) { core.sizeT[0] = core.imageCount[0] / (core.sizeZ[0] * core.sizeC[0]); if (core.sizeT[0] == 0) core.sizeT[0] = 1; } if (core.imageCount[0] == 0) { core.imageCount[0] = core.sizeZ[0] * core.sizeC[0] * core.sizeT[0]; } if (numSeries > 1) { int x = core.sizeX[0]; int y = core.sizeY[0]; int z = core.sizeZ[0]; int c = core.sizeC[0] / numSeries; int t = core.sizeT[0]; int count = z * c * t; int ptype = core.pixelType[0]; core = new CoreMetadata(numSeries); Arrays.fill(core.sizeX, x); Arrays.fill(core.sizeY, y); Arrays.fill(core.sizeZ, z); Arrays.fill(core.sizeC, c); Arrays.fill(core.sizeT, t); Arrays.fill(core.imageCount, count); Arrays.fill(core.pixelType, ptype); } Arrays.fill(core.rgb, false); Arrays.fill(core.currentOrder, "XYZTC"); Arrays.fill(core.interleaved, false); Arrays.fill(core.littleEndian, true); Arrays.fill(core.indexed, false); Arrays.fill(core.falseColor, false); Arrays.fill(core.metadataComplete, true); // find pixels files - we think there is one channel per file files = new Vector(); int ndx = currentId.lastIndexOf(File.separator) + 1; String base = currentId.substring(ndx, currentId.lastIndexOf(" ")); File f = new File(currentId).getAbsoluteFile(); if (numSeries == 0) numSeries = 1; for (int i=0; i<core.sizeC[0]*numSeries; i++) { files.add((f.exists() ? f.getParent() + File.separator : "") + base + " " + (i + 1) + ".xys"); } files.add(currentId); MetadataStore store = getMetadataStore(); store.setImage(null, null, null, null); FormatTools.populatePixels(store, this); for (int i=0; i<core.sizeC[0]; i++) { store.setLogicalChannel(i, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); } } }
// TransformLink.java package loci.visbio.view; import java.rmi.RemoteException; import java.util.Vector; import loci.visbio.VisBioFrame; import loci.visbio.data.*; import loci.visbio.state.Dynamic; import loci.visbio.util.VisUtil; import visad.*; import visad.util.Util; /** Represents a link between a data transform and a display. */ public class TransformLink implements DisplayListener, Dynamic, Runnable, TransformListener { // -- Fields -- /** Associated transform handler. */ protected TransformHandler handler; /** Data transform linked to the display. */ protected DataTransform trans; /** Associated handler for managing this link's color settings. */ protected ColorHandler colorHandler; /** Data reference linking data to the display. */ protected DataReferenceImpl ref; /** Data renderer for toggling data's visibility and other parameters. */ protected DataRenderer rend; /** Separate thread for managing full-resolution burn-in. */ protected Thread burnThread; /** Whether a full-resolution burn-in should occur immediately. */ protected boolean burnNow; /** Next clock time a full-resolution burn-in should occur. */ protected long burnTime; /** Whether this link is still active. */ protected boolean alive = true; /** Status message, to be displayed in bottom left corner. */ protected VisADException status; /** * Range values for current cursor location, * to be displayed in bottom left corner. */ protected VisADException[] cursor; /** Whether a TRANSFORM_DONE event should clear the status message. */ protected boolean clearWhenDone; // -- Fields - initial state -- /** Whether data transform is visible onscreen. */ protected boolean visible; // -- Constructor -- /** Constructs an uninitialized transform link. */ public TransformLink(TransformHandler h) { handler = h; } /** * Creates a link between the given data transform and * the specified transform handler's display. */ public TransformLink(TransformHandler h, DataTransform t) { handler = h; trans = t; if (trans instanceof ImageTransform) { colorHandler = new ColorHandler(this); } visible = true; initState(null); } // -- TransformLink API methods -- /** Gets the link's transform handler. */ public TransformHandler getHandler() { return handler; } /** Gets the link's data transform. */ public DataTransform getTransform() { return trans; } /** Gets the link's color handler. */ public ColorHandler getColorHandler() { return colorHandler; } /** Gets the link's reference. */ public DataReferenceImpl getReference() { return ref; } /** Gets the link's renderer. */ public DataRenderer getRenderer() { return rend; } /** Links this transform into the display. */ public void link() { try { handler.getWindow().getDisplay().addReferences(rend, ref); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } /** Unlinks this transform from the display. */ public void unlink() { try { handler.getWindow().getDisplay().removeReference(ref); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } /** Frees resources being consumed by this transform link. */ public void destroy() { alive = false; } /** Toggles visibility of the transform. */ public void setVisible(boolean vis) { rend.toggle(vis); } /** Gets visibility of the transform. */ public boolean isVisible() { return rend == null ? visible : rend.getEnabled(); } /** Sets status messages displayed in display's bottom left-hand corner. */ public void setMessage(String msg) { if (trans.isImmediate()) return; // no messages in immediate mode status = msg == null ? null : new VisADException(trans.getName() + ": " + msg); doMessages(false); } // -- TransformLink API methods - state logic -- /** Writes the current state. */ public void saveState(DisplayWindow window, String attrName) { VisBioFrame bio = handler.getWindow().getVisBio(); DataManager dm = (DataManager) bio.getManager(DataManager.class); Vector dataList = dm.getDataList(); int ndx = dataList.indexOf(trans); window.setAttr(attrName + "_dataIndex", "" + ndx); if (colorHandler != null) colorHandler.saveState(attrName); window.setAttr(attrName + "_visible", "" + isVisible()); } /** Restores the current state. */ public void restoreState(DisplayWindow window, String attrName) { VisBioFrame bio = handler.getWindow().getVisBio(); DataManager dm = (DataManager) bio.getManager(DataManager.class); Vector dataList = dm.getDataList(); int dataIndex = Integer.parseInt(window.getAttr(attrName + "_dataIndex")); trans = (DataTransform) dataList.elementAt(dataIndex); if (colorHandler != null) colorHandler.restoreState(attrName); visible = window.getAttr(attrName + "_visible").equalsIgnoreCase("true"); } // -- DisplayListener API methods -- /** Handles VisAD display events. */ public void displayChanged(DisplayEvent e) { // ensure status messages stay visible int id = e.getId(); if (id == DisplayEvent.FRAME_DONE) { computeCursor(); doMessages(true); } else if (e.getId() == DisplayEvent.TRANSFORM_DONE) { if (clearWhenDone) { setMessage(null); clearWhenDone = false; } else doMessages(false); } // pass along DisplayEvents to linked transform trans.displayChanged(e); } // -- Dynamic API methods -- /** Tests whether two dynamic objects are equivalent. */ public boolean matches(Dynamic dyn) { if (!isCompatible(dyn)) return false; TransformLink link = (TransformLink) dyn; return getTransform().matches(link.getTransform()) && isVisible() == link.isVisible(); } /** * Tests whether the given dynamic object can be used as an argument to * initState, for initializing this dynamic object. */ public boolean isCompatible(Dynamic dyn) { return dyn instanceof TransformLink; } /** * Modifies this object's state to match that of the given object. * If the argument is null, the object is initialized according to * its current state instead. */ public void initState(Dynamic dyn) { if (dyn != null && !isCompatible(dyn)) return; if (burnThread != null) { alive = false; try { burnThread.join(); } catch (InterruptedException exc) { } alive = true; } TransformLink link = (TransformLink) dyn; if (link != null) { if (trans != null) trans.removeTransformListener(this); trans = link.getTransform(); if (colorHandler != null) colorHandler.initState(link.getColorHandler()); visible = link.isVisible(); } else if (colorHandler != null) colorHandler.initState(null); // remove old data reference DisplayImpl display = handler.getWindow().getDisplay(); if (ref != null) { try { display.removeReference(ref); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } // build data reference try { ref = new DataReferenceImpl(trans.getName()); rend = display.getDisplayRenderer().makeDefaultRenderer(); rend.toggle(visible); display.addDisplayListener(this); } catch (VisADException exc) { exc.printStackTrace(); } // listen for changes to this transform trans.addTransformListener(this); // initialize thread for handling full-resolution burn-in operations burnThread = new Thread(this); burnThread.start(); } /** * Called when this object is being discarded in favor of * another object with a matching state. */ public void discard() { destroy(); } // -- Runnable API methods -- /** Executes full-resolution burn-in operations. */ public void run() { while (true) { // wait until a new burn-in is requested if (!alive) break; while (System.currentTimeMillis() > burnTime && !burnNow) { try { Thread.sleep(50); } catch (InterruptedException exc) { } } burnNow = false; // wait until appointed burn-in time (which could change during the wait) if (!alive) break; long time; while ((time = System.currentTimeMillis()) < burnTime) { long wait = burnTime - time; if (wait >= 1000) { long seconds = wait / 1000; setMessage(seconds + " second" + (seconds == 1 ? "" : "s") + " until burn in"); try { Thread.sleep(1000); } catch (InterruptedException exc) { } } else { try { Thread.sleep(wait); } catch (InterruptedException exc) { } } } // burn-in full resolution data if (!alive) break; computeData(false); } } // -- TransformListener API methods -- /** Called when a data transform's parameters are updated. */ public void transformChanged(TransformEvent e) { doTransform(TransformHandler.MINIMUM_BURN_DELAY); } // -- Internal TransformLink API methods -- /** Updates displayed data based on current dimensional position. */ protected void doTransform() { doTransform(handler.getBurnDelay()); } /** Updates displayed data based on current dimensional position. */ protected void doTransform(long delay) { if (trans.isImmediate()) computeData(false); else { computeData(true); // request a new burn-in in delay milliseconds burnTime = System.currentTimeMillis() + delay; if (delay < 100) burnNow = true; } } /** * Computes the reference data at the current position, * utilizing thumbnails as appropriate. */ protected synchronized void computeData(boolean thumbs) { int[] pos = handler.getPos(trans); ThumbnailHandler th = trans.getThumbHandler(); Data thumb = th == null ? null : th.getThumb(pos); if (thumbs) setData(thumb); else { setMessage("loading full-resolution data"); Data d = getImageData(pos); if (th != null && thumb == null) { // fill in missing thumbnail th.setThumb(pos, th.makeThumb(d)); } setMessage("burning in full-resolution data"); clearWhenDone = true; setData(d); if (colorHandler != null) colorHandler.reAutoScale(); } } /** Gets the transform's data at the given dimensional position. */ protected Data getImageData(int[] pos) { return trans.getData(pos, 2); } /** Assigns the given data object to the data reference. */ protected void setData(Data d) { setData(d, ref); } /** Assigns the given data object to the given data reference. */ protected void setData(Data d, DataReference dataRef) { if (d instanceof FlatField && trans instanceof ImageTransform) { // special case: use ImageTransform's suggested MathType instead FlatField ff = (FlatField) d; FunctionType ftype = ((ImageTransform) trans).getType(); try { d = VisUtil.switchType(ff, ftype); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } try { dataRef.setData(d); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } /** Computes range values at the current cursor location. */ protected void computeCursor() { // check for active cursor cursor = null; DisplayImpl display = handler.getWindow().getDisplay(); DisplayRenderer dr = display.getDisplayRenderer(); Vector cursorStringVector = dr.getCursorStringVector(); if (cursorStringVector == null || cursorStringVector.size() == 0) return; // get cursor value double[] cur = dr.getCursor(); if (cur == null || cur.length == 0 || cur[0] != cur[0]) return; // get range values at the given cursor location if (!(trans instanceof ImageTransform)) return; ImageTransform it = (ImageTransform) trans; // retrieve data object to be probed Data data = ref.getData(); if (!(data instanceof FunctionImpl)) return; FunctionImpl func = (FunctionImpl) data; // get cursor's domain coordinates RealType xType = it.getXType(); RealType yType = it.getYType(); double[] domain = VisUtil.cursorToDomain(display, new RealType[] {xType, yType, null}, cur); // evaluate function at the cursor location double[] rangeValues = null; try { RealTuple tuple = new RealTuple(new Real[] { new Real(xType, domain[0]), new Real(yType, domain[1]) }); Data result = func.evaluate(tuple, Data.NEAREST_NEIGHBOR, Data.NO_ERRORS); if (result instanceof Real) { Real r = (Real) result; rangeValues = new double[] {r.getValue()}; } else if (result instanceof RealTuple) { RealTuple rt = (RealTuple) result; int dim = rt.getDimension(); rangeValues = new double[dim]; for (int j=0; j<dim; j++) { Real r = (Real) rt.getComponent(j); rangeValues[j] = r.getValue(); } } else return; } catch (VisADException exc) { return; } catch (RemoteException exc) { return; } // compile range value messages if (rangeValues == null) return; RealType[] range = it.getRangeTypes(); if (range.length < rangeValues.length) return; cursor = new VisADException[rangeValues.length]; String prefix = trans.getName() + ": "; for (int i=0; i<rangeValues.length; i++) { cursor[i] = new VisADException(prefix + range[i].getName() + " = " + rangeValues[i]); } } // -- Helper methods -- /** * Assigns the current status and cursor messages to the data renderer * and redraws the display, optionally using the Swing event thread. */ private void doMessages(boolean swing) { Vector oldList = rend.getExceptionVector(); Vector newList = new Vector(); if (cursor != null) { for (int i=0; i<cursor.length; i++) newList.add(cursor[i]); } if (status != null) newList.add(status); boolean equal = true; if (oldList == null) equal = false; else { int len = oldList.size(); if (newList.size() != len) equal = false; else { for (int i=0; i<len; i++) { VisADException oldExc = (VisADException) oldList.elementAt(i); VisADException newExc = (VisADException) newList.elementAt(i); if (!oldExc.getMessage().equals(newExc.getMessage())) { equal = false; break; } } } } if (equal) return; // no change; rend.clearExceptions(); int len = newList.size(); for (int i=0; i<len; i++) { rend.addException((VisADException) newList.elementAt(i)); } if (swing) { Util.invoke(false, new Runnable() { public void run() { VisUtil.redrawMessages(handler.getWindow().getDisplay()); } }); } else VisUtil.redrawMessages(handler.getWindow().getDisplay()); } }
package scal.io.liger; import android.content.Context; import android.os.Environment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.android.vending.expansion.zipfile.APKExpansionSupport; import com.android.vending.expansion.zipfile.ZipResourceFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Set; import scal.io.liger.model.ExpansionIndexItem; /** * @author Matt Bogner * @author Josh Steiner */ public class ZipHelper { public static final String TAG = "ZipHelper"; public static String getExpansionZipFilename(Context ctx, String mainOrPatch, int version) { String packageName = ctx.getPackageName(); String filename = mainOrPatch + "." + version + "." + packageName + ".obb"; return filename; } public static String getExpansionZipDirectory(Context ctx, String mainOrPatch, int version) { // basically a wrapper for getExpansionFileFolder, but defaults to files directory String filePath = getExpansionFileFolder(ctx, mainOrPatch, version); if (filePath == null) { return getFileFolderName(ctx); } else { return filePath; } } public static String getObbFolderName(Context ctx) { String packageName = ctx.getPackageName(); File root = Environment.getExternalStorageDirectory(); return root.toString() + "/Android/obb/" + packageName + "/"; } public static String getFileFolderName(Context ctx) { // TODO Why doesn't this use ctx.getExternalFilesDir(null) (like JsonHelper)? String packageName = ctx.getPackageName(); File root = Environment.getExternalStorageDirectory(); return root.toString() + "/Android/data/" + packageName + "/files/"; } public static String getFileFolderName(Context context, String fileName) { // need to account for patch files if (fileName.contains(Constants.PATCH)) { fileName.replace(Constants.PATCH, Constants.MAIN); } ExpansionIndexItem expansionIndexItem = IndexManager.loadInstalledFileIndex(context).get(fileName); if (expansionIndexItem == null) { Log.e("DIRECTORIES", "FAILED TO LOCATE EXPANSION INDEX ITEM FOR " + fileName); return null; } File root = Environment.getExternalStorageDirectory(); return root.toString() + File.separator + expansionIndexItem.getExpansionFilePath(); } public static String getFileFolderName(Context context, String fileName, ExpansionIndexItem item) { // need to account for patch files if (fileName.contains(Constants.PATCH)) { fileName.replace(Constants.PATCH, Constants.MAIN); } File root = Environment.getExternalStorageDirectory(); return root.toString() + File.separator + item.getExpansionFilePath(); } // supressing messages for less text during polling public static String getExpansionFileFolder(Context ctx, String mainOrPatch, int version) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // check and/or attempt to create obb folder String checkPath = getObbFolderName(ctx); File checkDir = new File(checkPath); if (checkDir.isDirectory() || checkDir.mkdirs()) { File checkFile = new File(checkPath + getExpansionZipFilename(ctx, mainOrPatch, version)); if (checkFile.exists()) { Log.d("DIRECTORIES", "FOUND " + mainOrPatch + " " + version + " IN OBB DIRECTORY: " + checkFile.getPath()); return checkPath; } } // check and/or attempt to create files folder checkPath = getFileFolderName(ctx); checkDir = new File(checkPath); if (checkDir.isDirectory() || checkDir.mkdirs()) { File checkFile = new File(checkPath + getExpansionZipFilename(ctx, mainOrPatch, version)); if (checkFile.exists()) { Log.d("DIRECTORIES", "FOUND " + mainOrPatch + " " + version + " IN FILES DIRECTORY: " + checkFile.getPath()); return checkPath; } } } Log.e("DIRECTORIES", + mainOrPatch + " " + version + " NOT FOUND IN OBB DIRECTORY OR FILES DIRECTORY"); return null; } // for additional expansion files, check files folder for specified file public static String getExpansionFileFolder(Context ctx, String fileName) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // check and/or attempt to create files folder String checkPath = getFileFolderName(ctx, fileName); if (checkPath == null) { return null; } File checkDir = new File(checkPath); if (checkDir.isDirectory() || checkDir.mkdirs()) { File checkFile = new File(checkPath + fileName); if (checkFile.exists()) { Log.d("DIRECTORIES", "FOUND " + fileName + " IN DIRECTORY: " + checkFile.getPath()); return checkPath; } } } Log.e("DIRECTORIES", fileName + " NOT FOUND"); return null; } public static String getExpansionFileFolder(Context ctx, String fileName, ExpansionIndexItem item) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // check and/or attempt to create files folder String checkPath = getFileFolderName(ctx, fileName, item); if (checkPath == null) { return null; } File checkDir = new File(checkPath); if (checkDir.isDirectory() || checkDir.mkdirs()) { File checkFile = new File(checkPath + fileName); if (checkFile.exists()) { Log.d("DIRECTORIES", "FOUND " + fileName + " IN DIRECTORY: " + checkFile.getPath()); return checkPath; } } } Log.e("DIRECTORIES", fileName + " NOT FOUND"); return null; } public static ZipResourceFile getResourceFile(Context context) { try { // resource file contains main file and patch file ArrayList<String> paths = getExpansionPaths(context); ZipResourceFile resourceFile = APKExpansionSupport.getResourceZipFile(paths.toArray(new String[paths.size()])); return resourceFile; } catch (IOException ioe) { Log.e(" *** TESTING *** ", "Could not open resource file (main version " + Constants.MAIN_VERSION + ", patch version " + Constants.PATCH_VERSION + ")"); return null; } } public static InputStream getFileInputStream(String path, Context context, String language) { String localizedFilePath = path; // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (path.lastIndexOf("-" + language + path.substring(path.lastIndexOf("."))) < 0) { localizedFilePath = path.substring(0, path.lastIndexOf(".")) + "-" + language + path.substring(path.lastIndexOf(".")); } Log.d("LANGUAGE", "getFileInputStream() - TRYING LOCALIZED PATH: " + localizedFilePath); } InputStream fileStream = getFileInputStream(localizedFilePath, context); // if there is no result with the localized path, retry with default path if (fileStream == null) { if (localizedFilePath.contains("-")) { localizedFilePath = localizedFilePath.substring(0, localizedFilePath.lastIndexOf("-")) + localizedFilePath.substring(localizedFilePath.lastIndexOf(".")); Log.d("LANGUAGE", "getFileInputStream() - NO RESULT WITH LOCALIZED PATH, TRYING DEFAULT PATH: " + localizedFilePath); fileStream = ZipHelper.getFileInputStream(localizedFilePath, context); } } else { return fileStream; } if (fileStream == null) { Log.d("LANGUAGE", "getFileInputStream() - NO RESULT WITH DEFAULT PATH: " + localizedFilePath); } else { return fileStream; } return null; } public static @Nullable InputStream getFileInputStreamForExpansionAndPath(@NonNull ExpansionIndexItem expansion, @NonNull String path, @NonNull Context context) { return getFileInputStreamFromFile(IndexManager.buildFileAbsolutePath(expansion, Constants.MAIN), path, context); } public static InputStream getThumbnailInputStreamForItem(ExpansionIndexItem item, Context context) { ZipResourceFile resourceFile = null; try { resourceFile = APKExpansionSupport.getResourceZipFile(new String[]{IndexManager.buildFileAbsolutePath(item, Constants.MAIN)}); return resourceFile.getInputStream(item.getThumbnailPath()); } catch (IOException e) { e.printStackTrace(); } return null; } private static ArrayList<String> expansionPaths; /** * @return an absolute path to an expansion file with the given expansionId, or null if no * match could be made. */ public static @Nullable String getExpansionPathForExpansionId(Context context, String expansionId) { String targetExpansionPath = null; ArrayList<String> expansionPaths = getExpansionPaths(context); for (String expansionPath : expansionPaths) { if (expansionPath.contains(expansionId)) { targetExpansionPath = expansionPath; break; } } return targetExpansionPath; } public static void clearCache() { expansionPaths = null; } /** * @return a list of absolute paths to all available expansion files. */ private static ArrayList<String> getExpansionPaths(Context context) { if (expansionPaths == null) { expansionPaths = new ArrayList<>(); expansionPaths.add(getExpansionFileFolder(context, Constants.MAIN, Constants.MAIN_VERSION) + getExpansionZipFilename(context, Constants.MAIN, Constants.MAIN_VERSION)); if (Constants.PATCH_VERSION > 0) { // if the main file is newer than the patch file, do not apply a patch file if (Constants.PATCH_VERSION < Constants.MAIN_VERSION) { Log.d("ZIP", "PATCH VERSION " + Constants.PATCH_VERSION + " IS OUT OF DATE (MAIN VERSION IS " + Constants.MAIN_VERSION + ")"); } else { Log.d("ZIP", "APPLYING PATCH VERSION " + Constants.PATCH_VERSION + " (MAIN VERSION IS " + Constants.MAIN_VERSION + ")"); expansionPaths.add(getExpansionFileFolder(context, Constants.PATCH, Constants.PATCH_VERSION) + getExpansionZipFilename(context, Constants.PATCH, Constants.PATCH_VERSION)); } } // add 3rd party stuff HashMap<String, ExpansionIndexItem> expansionIndex = IndexManager.loadInstalledOrderIndex(context); // need to sort patch order keys, numbers may not be consecutive ArrayList<String> orderNumbers = new ArrayList<String>(expansionIndex.keySet()); Collections.sort(orderNumbers); for (String orderNumber : orderNumbers) { ExpansionIndexItem item = expansionIndex.get(orderNumber); if (item == null) { Log.d("ZIP", "EXPANSION FILE ENTRY MISSING AT PATCH ORDER NUMBER " + orderNumber); } else { // construct name String pathName = IndexManager.buildFilePath(item); String fileName = IndexManager.buildFileName(item, Constants.MAIN); File checkFile = new File(pathName + fileName); // should be able to do this locally // if (DownloadHelper.checkExpansionFiles(context, fileName)) { if (checkFile.exists()) { Log.d("ZIP", "EXPANSION FILE " + checkFile.getPath() + " FOUND, ADDING TO ZIP"); expansionPaths.add(checkFile.getPath()); if ((item.getPatchFileVersion() != null) && (item.getExpansionFileVersion() != null) && (Integer.parseInt(item.getPatchFileVersion()) > 0) && (Integer.parseInt(item.getPatchFileVersion()) >= Integer.parseInt(item.getExpansionFileVersion()))) { // construct name String patchName = IndexManager.buildFileName(item, Constants.PATCH); checkFile = new File(pathName + patchName); // should be able to do this locally // if (DownloadHelper.checkExpansionFiles(context, patchName)) { if (checkFile.exists()) { Log.d("ZIP", "EXPANSION FILE " + checkFile.getPath() + " FOUND, ADDING TO ZIP"); expansionPaths.add(checkFile.getPath()); } else { Log.e("ZIP", "EXPANSION FILE " + patchName + " NOT FOUND, CANNOT ADD TO ZIP"); } } } else { Log.e("ZIP", "EXPANSION FILE " + fileName + " NOT FOUND, CANNOT ADD TO ZIP"); } } } } return expansionPaths; } /** * @return the {@link scal.io.liger.model.ExpansionIndexItem} which is likely to contain the * given path. * * This method is useful as an optimization step until StoryPathLibrarys hold reference * to the ExpansionIndexItem from which they were created, if applicable. The inspection * is performed by searching for installed ExpansionIndexItem expansionId values * within the given path parameter, and does not involve inspection of the files belonging to * each ExpansionIndexItem. * */ public static @Nullable ExpansionIndexItem guessExpansionIndexItemForPath(String path, Context context) { HashMap<String, ExpansionIndexItem> expansions = IndexManager.loadInstalledIdIndex(context); Set<String> expansionIds = expansions.keySet(); for(String expansionId : expansionIds) { if (path.contains(expansionId)) { return expansions.get(expansionId); } } return null; } /** * @return an {@link java.io.InputStream} corresponding to the given path which must reside within * one of the installed index items. On disk this corresponds to a zip archive packaged as an .obb file. * */ @Deprecated public static InputStream getFileInputStream(String path, Context context) { // resource file contains main file and patch file ArrayList<String> allExpansionPaths = getExpansionPaths(context); ArrayList<String> targetExpansionPaths = new ArrayList<>(); // try to extract expansion id from target path // assumes format org.storymaker.app/learning_guide/content_metadata-en.json String[] parts = path.split("/"); for (String expansionPath : allExpansionPaths) { if (expansionPath.contains(parts[1])) { Log.d("PATCHING", "FOUND MATCH FOR " + parts[1] + " IN PATH " + expansionPath); targetExpansionPaths.add(expansionPath); } } // this shouldn't happen... if (targetExpansionPaths.size() == 0) { Log.d("PATCHING", "NO MATCHES FOR " + parts[1] + ", USING ALL PATHS"); targetExpansionPaths = allExpansionPaths; } StringBuilder paths = new StringBuilder(); for (String expansionPath : targetExpansionPaths) { paths.append(expansionPath); paths.append(", "); } paths.delete(paths.length()-2, paths.length()); Log.d(TAG, String.format("Searching for %s in %s", path, paths)); return getFileInputStreamFromFiles(targetExpansionPaths, path, context); } public static InputStream getFileInputStreamFromFile(String zipPath, String filePath, Context context) { ArrayList<String> zipPaths = new ArrayList<String>(); zipPaths.add(zipPath); return getFileInputStreamFromFiles(zipPaths, filePath, context); } public static InputStream getFileInputStreamFromFiles(ArrayList<String> zipPaths, String filePath, Context context) { try { ZipResourceFile resourceFile = APKExpansionSupport.getResourceZipFile(zipPaths.toArray(new String[zipPaths.size()])); if (resourceFile == null) { return null; } // file path must be relative to the root of the resource file InputStream resourceStream = resourceFile.getInputStream(filePath); if (resourceStream == null) { Log.d(" *** TESTING *** ", "Could not find file " + filePath + " within resource file (main version " + Constants.MAIN_VERSION + ", patch version " + Constants.PATCH_VERSION + ")"); } else { Log.d(" *** TESTING *** ", "Found file " + filePath + " within resource file (main version " + Constants.MAIN_VERSION + ", patch version " + Constants.PATCH_VERSION + ")"); } return resourceStream; } catch (IOException ioe) { Log.e(" *** TESTING *** ", "Could not find file " + filePath + " within resource file (main version " + Constants.MAIN_VERSION + ", patch version " + Constants.PATCH_VERSION + ")"); return null; } } /** * Copy the expansion asset at path to a temporary file within tempPath. If * a temp file exists for the given arguments it will be deleted and remade. */ @Deprecated public static File getTempFile(String path, String tempPath, Context context) { String extension = path.substring(path.lastIndexOf(".")); File tempFile = new File(tempPath + File.separator + "TEMP" + extension); try { if (tempFile.exists()) { tempFile.delete(); Log.d(" *** TESTING *** ", "Deleted temp file " + tempFile.getPath()); } tempFile.createNewFile(); Log.d(" *** TESTING *** ", "Made temp file " + tempFile.getPath()); } catch (IOException ioe) { Log.e(" *** TESTING *** ", "Failed to clean up existing temp file " + tempFile.getPath() + ", " + ioe.getMessage()); return null; } InputStream zipInput = getFileInputStream(path, context); if (zipInput == null) { Log.e(" *** TESTING *** ", "Failed to open input stream for " + path + " in .zip file"); return null; } try { FileOutputStream tempOutput = new FileOutputStream(tempFile); byte[] buf = new byte[1024]; int i; while((i = zipInput.read(buf)) > 0) { tempOutput.write(buf, 0, i); } tempOutput.close(); zipInput.close(); Log.d(" *** TESTING *** ", "Wrote temp file " + tempFile.getPath()); } catch (IOException ioe) { Log.e(" *** TESTING *** ", "Failed to write to temp file " + tempFile.getPath() + ", " + ioe.getMessage()); return null; } Log.e(" *** TESTING *** ", "Created temp file " + tempFile.getPath()); return tempFile; } }
public class ConfigCellInfo { private final int DEFAULT_STATE = 0; private int myRow; private int myCol; private String myState; private int myIntState; public ConfigCellInfo(int row, int col, String state){ myRow = row; myCol = col; myState = state; myIntState = DEFAULT_STATE; } public int getRow(){ return myRow; } public int getCol(){ return myCol; } public String getStringState(){ return myState; } public void setIntState(int intState){ myIntState = intState; } public int getIntState(){ return myIntState; } }
package DefPackage; import java.util.ArrayList; import javafx.application.Application; import javafx.application.Platform; import javafx.event.Event; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.text.*; import javafx.scene.control.TextArea; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextInputControl; import java.util.Optional; import java.util.HashMap; import java.util.Map; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.shape.Rectangle; /** * * @author attelahtinen */ public class Gui extends Application { double paivays = 1; boolean erMesVis = false; Ruokailija ruokailijat = new Ruokailija(); Ruoka_annos mainCourse = new Ruoka_annos(); Ruoka_annos veggieCourse = new Ruoka_annos(); Ruoka_annos dessertCourse = new Ruoka_annos(); Palaute palaute = new Palaute(); TextArea resText = new TextArea(""); Tili sodexoTili = new Tili(); ObservableList<Ruokalaji> paaruuat = FXCollections.observableArrayList(); ObservableList<Ruokalaji> lisukkeet = FXCollections.observableArrayList(); ObservableList<Ruokalaji> jalkkarit = FXCollections.observableArrayList(); ObservableList<Ruokalaji> kasvisruuat = FXCollections.observableArrayList(); @Override public void start(Stage primaryStage) { // Oliot ja muuttujat Map<Double,Double> fbHistory = new HashMap(); double rahaMeno; Tilaus tilaus = new Tilaus(); sodexoTili.Pano(1000.0); Label saldoNum = new Label (""+sodexoTili.getSaldo()); Label saldoNum2 = new Label (""+sodexoTili.getSaldo()); ArrayList<Ruoka_annos> tanaan = new ArrayList(); ArrayList<Ruoka_annos> huomenna = new ArrayList(); Label errorMes = new Label("This is text"); TextField estCust = new TextField(); TextField veggie = new TextField(); TextField dessert = new TextField(); ArrayList <TextField> lukumaarat = new ArrayList(); lukumaarat.add(estCust); lukumaarat.add(veggie); lukumaarat.add(dessert); Ruokalaji kanaKastike = new Ruokalaji("Kanakastike", 2.0, 1.5, 3.5); Ruokalaji riisi = new Ruokalaji("Riisi", 0.6, 0.1, 1.0); Ruokalaji ohukaiset = new Ruokalaji("Ohukaiset ja hillo", 0.6, 0.3, 4.2); Ruokalaji linssiPata = new Ruokalaji("Linssipata", 1.8, 1.1, 2.4); Ruokalaji peruna = new Ruokalaji("Peruna", 0.6, 0.2, 1.2); Ruokalaji lihaPulla = new Ruokalaji("Lihapullat", 2.0, 1.5, 3.5); Ruokalaji papuKastike = new Ruokalaji("Papukastike", 1.8, 1.0, 2.0); Ruokalaji marjaPiirakka = new Ruokalaji("Marjapiirakka", 0.6, 0.2, 3.0); Ruokalaji veriPalttu = new Ruokalaji("Veripalttu", 2.0, 1.7, 1.0); Ruokalaji tilliLiha = new Ruokalaji("Tilliliha", 2.0, 1.4, 0.6); Ruokalaji tacoVuoka = new Ruokalaji("Tacojauhelihavuoka", 2.0, 1.6, 3.0); paaruuat.addAll(kanaKastike, lihaPulla, veriPalttu, tilliLiha, tacoVuoka); lisukkeet.addAll(riisi, peruna); jalkkarit.addAll(ohukaiset, marjaPiirakka); kasvisruuat.addAll(linssiPata, papuKastike); BorderPane borderpane = new BorderPane(); borderpane.setStyle("-fx-background-color: linear-gradient(from 0% 0% to 70% 70%, #6EBBFF, #DEF0FF)"); Scene orderScene = new Scene(borderpane, 650, 600); BorderPane resultBorder = new BorderPane(); resultBorder.setStyle("-fx-background-color: linear-gradient(from 0% 0% to 70% 70%, #38A2FF, #DEF0FF)"); Scene resultScene = new Scene(resultBorder,650,600); // Tekstialue vasen AnchorPane textBox = new AnchorPane(); textBox.setPadding(new Insets(10, 10, 10, 10)); textBox.setPrefSize(300.0, 300.0); TextArea textA = new TextArea("Welcome!\n"); textBox.getChildren().add(textA); AnchorPane.setRightAnchor(textA, 10.0); AnchorPane.setTopAnchor(textA, 15.0); borderpane.setRight(textBox); textA.setPrefSize(230, 300); textA.setMaxSize(230, 400); // Alareuna Buttons buttons = new Buttons(); Label tyytyvaisyys = new Label ("Tyytyväisyys"); Label fbToday = new Label("Tänään: "+fbHistory.get(paivays)); Label fbWeek = new Label ("Viimeisin viikko: #muokkaa"); VBox feedbacks = new VBox(); feedbacks.getChildren().addAll(tyytyvaisyys,fbToday,fbWeek); VBox saldoBox = new VBox(); Label saldoText = new Label ("Saldo:"); saldoBox.getChildren().addAll(saldoText,saldoNum); saldoBox.setAlignment(Pos.CENTER_LEFT); Button makeOrder = new Button(); Button startService = new Button(); makeOrder.setText("Tee tilaus"); startService.setText("Aloita ruokailu"); makeOrder.setDisable(true); startService.setDisable(true); makeOrder.setOnAction((ActionEvent event) -> { textA.appendText("Tilaus päivälle "+Math.round(paivays)+" tehty!\n"); erMesVis = !erMesVis; errorMes.setVisible(erMesVis); ruokailijat.setRuokailija(Integer.parseInt(estCust.getText())); ruokailijat.setKasvis(Integer.parseInt(veggie.getText())); ruokailijat.setJalkkari(Integer.parseInt(dessert.getText())); startService.setDisable(false); double minus = tilaus.teeTilaus(ruokailijat.getRuokailija(), ruokailijat.getKasvis(),ruokailijat.getJalkkari(), mainCourse, veggieCourse, dessertCourse); sodexoTili.Otto(minus); saldoNum.setText(""+sodexoTili.getSaldo()); saldoNum2.setText(""+sodexoTili.getSaldo()); textA.appendText("Saldo väheni " + minus + " eurolla\n"); }); startService.setOnAction((ActionEvent e) -> { paivays++; primaryStage.setScene(resultScene); resText.appendText(calcFeedback(mainCourse, 200, ruokailijat.getRuokailija())+"\n"); resText.appendText(calcFeedback(veggieCourse, 50, ruokailijat.getKasvis())+"\n"); resText.appendText(calcDessert()); saldoNum.setText(""+sodexoTili.getSaldo()); saldoNum2.setText(""+sodexoTili.getSaldo()); }); HBox hbox = new HBox(); hbox.setSpacing(20); hbox.setPadding(new Insets(0,10,0,10)); hbox.setStyle("-fx-background-color: #B0DAFF;"); hbox.getChildren().addAll(makeOrder, startService); hbox.setAlignment(Pos.CENTER_LEFT); BorderPane footer = new BorderPane(); footer.setStyle("-fx-background-color: #B0DAFF;"); footer.setPadding(new Insets(10, 10, 10, 10)); footer.setLeft(feedbacks); footer.setCenter(hbox); //buttons.modButtons(textA) footer.setRight(saldoBox); borderpane.setBottom(footer); StackPane header = new StackPane(); header.setPadding(new Insets(15, 15, 15, 15)); ImageView logo = new ImageView(new Image("file:sorekso.png")); logo.setPreserveRatio(true); logo.setFitWidth(350); Label label1 = new Label("Simulator 1.0"); label1.setTextFill(Color.web("#2A3C93")); label1.setFont(Font.font("Cambria", FontWeight.SEMI_BOLD, 18)); header.getChildren().addAll(logo,label1); StackPane.setAlignment(label1, Pos.BOTTOM_RIGHT); StackPane.setAlignment(logo, Pos.TOP_CENTER); borderpane.setTop(header); // VALINNAT //Choice boxes (dropdownit) VBox selectors = new VBox(); //selectors.setPrefWidth(180); ChoiceBox paaruoka = new ChoiceBox (FXCollections.observableArrayList (paaruuat)); paaruoka.setPrefWidth(100); paaruoka.getSelectionModel().selectedIndexProperty().addListener((obs, oldSelect, newSelect) ->{ mainCourse.setPaaruoka(paaruuat.get(newSelect.intValue())); textA.appendText("Valinta: "+ mainCourse.getPaaruoka().toString()+"\n"); }); ChoiceBox lisuke1 = new ChoiceBox(FXCollections.observableArrayList (lisukkeet)); lisuke1.setPrefWidth(100); lisuke1.getSelectionModel().selectedIndexProperty().addListener((obs, oldSelect, newSelect) ->{ mainCourse.setLisuke(lisukkeet.get(newSelect.intValue())); textA.appendText("Valinta: "+ mainCourse.getLisuke().toString()+"\n"); }); ChoiceBox kasvisruoka = new ChoiceBox(FXCollections.observableArrayList (kasvisruuat)); kasvisruoka.setPrefWidth(100); kasvisruoka.getSelectionModel().selectedIndexProperty().addListener((obs, oldSelect, newSelect) ->{ veggieCourse.setPaaruoka(kasvisruuat.get(newSelect.intValue())); textA.appendText("Valinta: "+ veggieCourse.getPaaruoka().toString()+"\n"); }); ChoiceBox lisuke2 = new ChoiceBox(FXCollections.observableArrayList (lisukkeet)); lisuke2.setPrefWidth(100); lisuke2.getSelectionModel().selectedIndexProperty().addListener((obs, oldSelect, newSelect) ->{ veggieCourse.setLisuke(lisukkeet.get(newSelect.intValue())); textA.appendText("Valinta: "+ veggieCourse.getLisuke().toString()+"\n"); }); ChoiceBox jalkkari = new ChoiceBox(FXCollections.observableArrayList (jalkkarit)); jalkkari.setPrefWidth(100); jalkkari.getSelectionModel().selectedIndexProperty().addListener((obs, oldSelect, newSelect) ->{ dessertCourse.setJalkkari(jalkkarit.get(newSelect.intValue())); textA.appendText("Valinta: "+ dessertCourse.getJalkkari().toString()+"\n"); }); ArrayList <ChoiceBox> boxes = new ArrayList(); boxes.add(paaruoka); boxes.add(lisuke1); boxes.add(kasvisruoka); boxes.add(lisuke2); boxes.add(jalkkari); selectors.getChildren().addAll(paaruoka,lisuke1,kasvisruoka,lisuke2,jalkkari); selectors.setPadding(new Insets(20,20,20,20)); selectors.setSpacing(10); selectors.setAlignment(Pos.CENTER_RIGHT); VBox query = new VBox(); query.setPadding(new Insets(20,20,20,20)); query.getChildren().addAll(createFields(textA, lukumaarat),selectors); query.setSpacing(20); borderpane.setLeft(query); // Tee tilaus -painike VBox middle = new VBox(); errorMes.setTextFill(Color.RED); errorMes.setVisible(erMesVis); checkValues(makeOrder, boxes); middle.getChildren().addAll(errorMes); middle.setSpacing(50); middle.setAlignment(Pos.CENTER); borderpane.setCenter(middle); primaryStage.setTitle("Opiskelijaravintola"); primaryStage.setScene(orderScene); primaryStage.setMinWidth(650); primaryStage.setMinHeight(600); /*primaryStage.setOnCloseRequest(e -> { close(e); });*/ primaryStage.show(); StackPane resStack = new StackPane(); VBox resMid = new VBox(); Button backToOrder = new Button(); //TextFlow resultField = new TextFlow(resText); backToOrder.setText("Seuraava päivä >>"); backToOrder.setOnAction((ActionEvent e) -> { textA.appendText("Valitse päivän "+Math.round(paivays)+" ruokalista!\n"); paaruoka.getSelectionModel().clearSelection(); lisuke1.getSelectionModel().clearSelection(); kasvisruoka.getSelectionModel().clearSelection(); lisuke2.getSelectionModel().clearSelection(); jalkkari.getSelectionModel().clearSelection(); errorMes.setVisible(false); startService.setDisable(true); saldoNum.setText(""+sodexoTili.getSaldo()); saldoNum2.setText(""+sodexoTili.getSaldo()); primaryStage.setScene(orderScene); }); Rectangle rect = new Rectangle(300,300); rect.setFill(Color.web("#DEF0FF")); resStack.getChildren().addAll(rect, resText); resStack.setAlignment(Pos.CENTER); resMid.getChildren().addAll(resStack, backToOrder); resMid.setSpacing(30); resMid.setAlignment(Pos.CENTER); StackPane header2 = new StackPane(); header2.setPadding(new Insets(15, 15, 15, 15)); ImageView logo2 = new ImageView(new Image("file:sorekso.png")); logo2.setPreserveRatio(true); logo2.setFitWidth(350); Label label2 = new Label("Simulator 1.0"); label2.setTextFill(Color.web("#2A3C93")); label2.setFont(Font.font("Cambria", FontWeight.SEMI_BOLD, 18)); header2.getChildren().addAll(logo2,label2); StackPane.setAlignment(label2, Pos.BOTTOM_RIGHT); StackPane.setAlignment(logo2, Pos.TOP_CENTER); Label tyytyvaisyys2 = new Label ("Tyytyväisyys"); Label fbToday2 = new Label("Tänään: "+fbHistory.get(paivays)); Label fbWeek2 = new Label ("Viimeisin viikko: #muokkaa"); VBox feedbacks2 = new VBox(); feedbacks2.getChildren().addAll(tyytyvaisyys2,fbToday2,fbWeek2); VBox saldoBox2 = new VBox(); Label saldoText2 = new Label ("Saldo:"); saldoBox2.getChildren().addAll(saldoText2,saldoNum2); saldoBox2.setAlignment(Pos.CENTER_LEFT); BorderPane footer2 = new BorderPane(); footer2.setStyle("-fx-background-color: #B0DAFF;"); footer2.setPadding(new Insets(10, 10, 10, 10)); footer2.setLeft(feedbacks2); footer2.setRight(saldoBox2); resultBorder.setBottom(footer2); resultBorder.setTop(header2); resultBorder.setCenter(resMid); } public GridPane createFields(TextArea textA, ArrayList<TextField> lukumaarat) { GridPane grid = new GridPane(); Label label1 = new Label("Ruokalijat: "); label1.setFont(Font.font("Cambria", 16)); Label label2 = new Label("Kasvis: "); label2.setFont(Font.font("Cambria", 16)); Label label3 = new Label("Jälkiruoka: "); label3.setFont(Font.font("Cambria", 16)); /*estCust.setOnKeyPressed((KeyEvent event) -> { if (checkTextFields(lukumaarat)) { ruokailijat.setRuokailija(Integer.parseInt(estCust.getText())); } });*/ lukumaarat.get(0).setAlignment(Pos.CENTER); lukumaarat.get(0).setPrefSize(60, 20); /*veggie.setOnKeyPressed((KeyEvent event) -> { if (checkTextFields(lukumaarat)) { ruokailijat.setKasvis(Integer.parseInt(veggie.getText())); } });*/ lukumaarat.get(1).setAlignment(Pos.CENTER); lukumaarat.get(1).setPrefSize(60, 20); /*dessert.setOnKeyPressed((KeyEvent event) -> { if (checkTextFields(lukumaarat)) { ruokailijat.setJalkkari(Integer.parseInt(dessert.getText())); } });*/ lukumaarat.get(2).setAlignment(Pos.CENTER); lukumaarat.get(2).setPrefSize(60, 20); grid.setVgap(10); grid.setHgap(10); grid.add(label1, 0, 1); grid.add(label2, 0, 2); grid.add(label3, 0, 3); grid.add(lukumaarat.get(0), 1, 1); grid.add(lukumaarat.get(1), 1, 2); grid.add(lukumaarat.get(2), 1, 3); return grid; } public void close(Event e) { Alert exitAlert = new Alert(AlertType.CONFIRMATION); exitAlert.setTitle("Exit?"); exitAlert.setContentText("Do you really want to exit?"); Optional<ButtonType> result = exitAlert.showAndWait(); if (result.get() == ButtonType.OK){ Platform.exit(); System.exit(0); } else { e.consume(); } } public void checkValues(Button makeOrder, ArrayList<ChoiceBox> boxes){ for (ChoiceBox z : boxes) { z.setOnAction(e -> { if (checkDropdowns(boxes)) { makeOrder.setDisable(false); } }); } } public boolean checkDropdowns(ArrayList<ChoiceBox> boxes){ for (ChoiceBox y : boxes) { if (y.getValue().equals(null)) {return false;} } return true; } public boolean checkTextFields (ArrayList <TextField> lukumaarat){ for (TextField x : lukumaarat) { if (x.getText().isEmpty()) { } } return true; } public String calcFeedback(Ruoka_annos course, int lkm, int annokset){ Kysynta mika = new Kysynta(); int taso = palaute.taso(course,dessertCourse); double kysynta = mika.kysynta(course); int halukkaat = mika.halukkaat(lkm, kysynta); int ostajat = mika.ostajat(halukkaat, annokset); double tulos = mika.tulos(course, ostajat); int riittava = mika.riittava(halukkaat, annokset); sodexoTili.Pano(tulos); resText.appendText("Rahaa tuli tänään "+ tulos + " euroa\n"); return palaute.palaute(taso, riittava); } public String calcDessert(){ Kysynta mika = new Kysynta(); double kysynta = mika.jalkkariKysynta(dessertCourse); int halukkaat = mika.halukkaat(200, kysynta); int ostajat = mika.ostajat(halukkaat, ruokailijat.getJalkkari()); double tulos = mika.tulos(dessertCourse, ostajat); sodexoTili.Pano(tulos); return "Jälkkäri tuotti "+ tulos+ " euroa\n"; } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
import java.util.Timer; import java.util.TimerTask; /** * Main Class for integration with Git */ public class GitIntegration { private final static Timer timer = new Timer(); public static void main(String[] arg) { // Timer runs all tasks in a single background thread, so its behaviour is similar to .NET events timer.scheduleAtFixedRate(new GitPollTask(), 0, 3000); while(true) { /* do nothing, the job is done in background thread */ } } private static class GitPollTask extends TimerTask { @Override public void run() { try { Thread.sleep(4000); System.out.println("hit next interval"); } catch(InterruptedException ex) { // do nothing } } } }
package com.raizlabs.events; import java.util.HashSet; /** * Class which represents an Event with arguments of type T. * @author Dylan James * * @param <T> */ public class Event<T> { private HashSet<EventListener<T>> listeners; private HashSet<EventListener<T>> listenersToAdd; private HashSet<EventListener<T>> listenersToRemove; private boolean raisingEvent; /** * Creates a new RZEvent */ public Event() { listeners = new HashSet<EventListener<T>>(); listenersToAdd = new HashSet<EventListener<T>>(); listenersToRemove = new HashSet<EventListener<T>>(); raisingEvent = false; } /** * Adds an RZEventListener to be notified when this event happens. * @param listener The listener to be notified. */ public void addListener(EventListener<T> listener) { if (listener != null) { synchronized (this) { // If the event is currently being raised, we can't modify the collection // Add it to the toAdd collection if (raisingEvent) { listenersToAdd.add(listener); } else { listeners.add(listener); } } } } /** * Removes an RZEventListener so it will no longer be notified of * this event. * @param listener The RZEventListener to be removed. * @return True if the listener was removed, false if it wasn't found. */ public boolean removeListener(EventListener<T> listener) { synchronized (this) { // If the event is currently being raised, we can't modify the collection // Add it to the toRemove collection if (raisingEvent) { listenersToRemove.add(listener); return listeners.contains(listener); } else { return listeners.remove(listener); } } } /** * Raises this event and notifies its listeners. * @param sender The object raising the even. * @param args The arguments to the event which will be passed to the listeners. */ public void raiseEvent(Object sender, T args) { synchronized (this) { raisingEvent = true; listenersToAdd.clear(); listenersToRemove.clear(); for (EventListener<T> listener : listeners) { // Don't raise the event if the listener is flagged to be removed. if (!listenersToRemove.contains(listener)) { listener.onEvent(sender, args); } } for (EventListener<T> listener : listenersToAdd) { listeners.add(listener); } for (EventListener<T> listener : listenersToRemove) { listeners.remove(listener); } raisingEvent = false; } } /** * Clears all listeners from this event. */ public void clear() { synchronized (this) { // If the event is currently being raised, we can't modify the collection // Add all of the current listeners to the toRemove collection if (raisingEvent) { for (EventListener<T> listener : listeners) { listenersToRemove.add(listener); } } else { listeners.clear(); } } } }
package org.drooms.api; import org.apache.commons.lang3.tuple.ImmutablePair; /** * Represents a connection (a route) between two immediately adjacent * {@link Node}s in a {@link Playground}. Worms can move from one {@link Node} * to anoter only by using an {@link Edge}. The connection is always * bi-directional. */ public class Edge { private final ImmutablePair<Node, Node> nodes; /** * Make two nodes immediately adjacent. * * @param firstNode * One node. * @param secondNode * The other. */ public Edge(final Node firstNode, final Node secondNode) { if (firstNode == null || secondNode == null) { throw new IllegalArgumentException("Neither nodes can be null."); } else if (firstNode.equals(secondNode)) { throw new IllegalArgumentException( "Edges between the same node make no sense."); } if (firstNode.compareTo(secondNode) < 0) { this.nodes = ImmutablePair.of(firstNode, secondNode); } else { this.nodes = ImmutablePair.of(secondNode, firstNode); } } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Edge)) { return false; } final Edge other = (Edge) obj; if (this.nodes == null) { if (other.nodes != null) { return false; } } else if (!this.nodes.equals(other.nodes)) { return false; } return true; } /** * Retrieve nodes in this edge. * * @return A pair of nodes. First node is always the least of the two. (See * {@link Node#compareTo(Node)}.) */ public ImmutablePair<Node, Node> getNodes() { return this.nodes; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.nodes == null) ? 0 : this.nodes.hashCode()); return result; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Edge [nodes=").append(this.nodes).append("]"); return builder.toString(); } }
package com.exedio.cope; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import bak.pcj.list.IntList; import com.exedio.dsmf.Driver; import com.exedio.dsmf.SQLRuntimeException; import com.exedio.dsmf.Schema; abstract class AbstractDatabase implements Database { protected static final int TWOPOW8 = 1<<8; protected static final int TWOPOW16 = 1<<16; protected static final int TWOPOW24 = 1<<24; private static final String NO_SUCH_ROW = "no such row"; private final List tables = new ArrayList(); private final HashMap uniqueConstraintsByID = new HashMap(); private final HashMap itemColumnsByIntegrityConstraintName = new HashMap(); private boolean buildStage = true; final Driver driver; private final boolean prepare; private final boolean log; private final boolean butterflyPkSource; private final boolean fulltextIndex; final ConnectionPool connectionPool; private final java.util.Properties forcedNames; final java.util.Properties tableOptions; final int limitSupport; final long blobLengthFactor; final boolean oracle; // TODO remove protected AbstractDatabase(final Driver driver, final Properties properties) { this.driver = driver; this.prepare = !properties.getDatabaseDontSupportPreparedStatements(); this.log = properties.getDatabaseLog(); this.butterflyPkSource = properties.getPkSourceButterfly(); this.fulltextIndex = properties.getFulltextIndex(); this.connectionPool = new ConnectionPool(properties); this.forcedNames = properties.getDatabaseForcedNames(); this.tableOptions = properties.getDatabaseTableOptions(); this.limitSupport = properties.getDatabaseDontSupportLimit() ? LIMIT_SUPPORT_NONE : getLimitSupport(); this.blobLengthFactor = getBlobLengthFactor(); this.oracle = getClass().getName().equals("com.exedio.cope.OracleDatabase"); switch(limitSupport) { case LIMIT_SUPPORT_NONE: case LIMIT_SUPPORT_CLAUSE_AFTER_SELECT: case LIMIT_SUPPORT_CLAUSE_AFTER_WHERE: case LIMIT_SUPPORT_CLAUSES_AROUND: break; default: throw new RuntimeException(Integer.toString(limitSupport)); } //System.out.println("using database "+getClass()); } public final Driver getDriver() { return driver; } public final java.util.Properties getTableOptions() { return tableOptions; } public final ConnectionPool getConnectionPool() { return connectionPool; } public final void addTable(final Table table) { if(!buildStage) throw new RuntimeException(); tables.add(table); } public final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint) { if(!buildStage) throw new RuntimeException(); final Object collision = uniqueConstraintsByID.put(constraintID, constraint); if(collision!=null) throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision); } public final void addIntegrityConstraint(final ItemColumn column) { if(!buildStage) throw new RuntimeException(); if(itemColumnsByIntegrityConstraintName.put(column.integrityConstraintName, column)!=null) throw new RuntimeException("there is more than one integrity constraint with name "+column.integrityConstraintName); } protected final Statement createStatement() { return createStatement(true); } protected final Statement createStatement(final boolean qualifyTable) { return new Statement(this, prepare, qualifyTable, isDefiningColumnTypes()); } protected final Statement createStatement(final Query query) { return new Statement(this, prepare, query, isDefiningColumnTypes()); } public void createDatabase() { buildStage = false; makeSchema().create(); } public void createDatabaseConstraints() { buildStage = false; makeSchema().createConstraints(); } //private static int checkTableTime = 0; public void checkDatabase(final Connection connection) { buildStage = false; //final long time = System.currentTimeMillis(); final Statement bf = createStatement(true); bf.append("select count(*) from ").defineColumnInteger(); boolean first = true; for(Iterator i = tables.iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); final Table table = (Table)i.next(); bf.append(table.protectedID); } bf.append(" where "); first = true; for(Iterator i = tables.iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(" and "); final Table table = (Table)i.next(); final Column primaryKey = table.primaryKey; bf.append(primaryKey). append('='). appendParameter(Type.NOT_A_PK); for(Iterator j = table.getColumns().iterator(); j.hasNext(); ) { final Column column = (Column)j.next(); bf.append(" and "). append(column); if(column instanceof BlobColumn || (oracle && column instanceof StringColumn && ((StringColumn)column).maximumLength>=4000)) { bf.append("is not null"); } else { bf.append('='). appendParameter(column, column.getCheckValue()); } } } executeSQLQuery(connection, bf, new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); } }, false ); } public void dropDatabase() { buildStage = false; makeSchema().drop(); } public void dropDatabaseConstraints() { buildStage = false; makeSchema().dropConstraints(); } public void tearDownDatabase() { buildStage = false; makeSchema().tearDown(); } public void tearDownDatabaseConstraints() { buildStage = false; makeSchema().tearDownConstraints(); } public void checkEmptyDatabase(final Connection connection) { buildStage = false; //final long time = System.currentTimeMillis(); for(Iterator i = tables.iterator(); i.hasNext(); ) { final Table table = (Table)i.next(); final int count = countTable(connection, table); if(count>0) throw new RuntimeException("there are "+count+" items left for table "+table.id); } //final long amount = (System.currentTimeMillis()-time); //checkEmptyTableTime += amount; //System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime); } public final ArrayList search(final Connection connection, final Query query, final boolean doCountOnly) { buildStage = false; final int limitStart = query.limitStart; final int limitCount = query.limitCount; final boolean limitActive = limitStart>0 || limitCount!=Query.UNLIMITED_COUNT; final ArrayList queryJoins = query.joins; final Statement bf = createStatement(query); if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSES_AROUND) appendLimitClause(bf, limitStart, limitCount); bf.append("select"); if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSE_AFTER_SELECT) appendLimitClause(bf, limitStart, limitCount); bf.append(' '); final Selectable[] selectables = query.selectables; final Column[] selectColumns = new Column[selectables.length]; final Type[] selectTypes = new Type[selectables.length]; if(doCountOnly) { bf.append("count(*)"); } else { for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++) { final Selectable selectable = selectables[selectableIndex]; final Column selectColumn; final Type selectType; final Table selectTable; final Column selectPrimaryKey; if(selectable instanceof Function) { final Function selectAttribute = (Function)selectable; selectType = selectAttribute.getType(); if(selectableIndex>0) bf.append(','); if(selectable instanceof FunctionAttribute) { selectColumn = ((FunctionAttribute)selectAttribute).getColumn(); bf.append((FunctionAttribute)selectable, (Join)null).defineColumn(selectColumn); if(selectable instanceof ItemAttribute) { final StringColumn typeColumn = ((ItemAttribute)selectAttribute).getTypeColumn(); if(typeColumn!=null) bf.append(',').append(typeColumn).defineColumn(typeColumn); } } else { selectColumn = null; final View view = (View)selectable; bf.append(view, (Join)null).defineColumn(view); } } else { selectType = (Type)selectable; selectTable = selectType.getTable(); selectPrimaryKey = selectTable.primaryKey; selectColumn = selectPrimaryKey; if(selectableIndex>0) bf.append(','); bf.appendPK(selectType, (Join)null).defineColumn(selectColumn); if(selectColumn.primaryKey) { final StringColumn selectTypeColumn = selectColumn.getTypeColumn(); if(selectTypeColumn!=null) { bf.append(','). append(selectTypeColumn).defineColumn(selectTypeColumn); } else selectTypes[selectableIndex] = selectType.getOnlyPossibleTypeOfInstances(); } else selectTypes[selectableIndex] = selectType.getOnlyPossibleTypeOfInstances(); } selectColumns[selectableIndex] = selectColumn; } } bf.append(" from "). appendTypeDefinition((Join)null, query.type); if(queryJoins!=null) { for(Iterator i = queryJoins.iterator(); i.hasNext(); ) { final Join join = (Join)i.next(); bf.append(' '). append(join.getKindString()). append(" join "). appendTypeDefinition(join, join.type); final Condition joinCondition = join.condition; if(joinCondition!=null) { bf.append(" on "); joinCondition.append(bf); } bf.appendTypeJoinCondition(joinCondition!=null ? " and " : " on ", join, join.type); } } if(query.condition!=null) { bf.append(" where "); query.condition.append(bf); } bf.appendTypeJoinCondition(query.condition!=null ? " and " : " where ", (Join)null, query.type); if(!doCountOnly) { final Function[] orderBy = query.orderBy; if(orderBy!=null) { final boolean[] orderAscending = query.orderAscending; for(int i = 0; i<orderBy.length; i++) { bf.appendOrderBy(). append(orderBy[i], (Join)null); if(!orderAscending[i]) bf.append(" desc"); } } if(query.deterministicOrder) // TODO skip this, if orderBy already orders by some unique function { bf.appendOrderBy(); query.type.getPkSource().appendDeterministicOrderByExpression(bf, query.type); } if(limitActive && limitSupport==LIMIT_SUPPORT_CLAUSE_AFTER_WHERE) appendLimitClause(bf, limitStart, limitCount); } if(!doCountOnly && limitActive && limitSupport==LIMIT_SUPPORT_CLAUSES_AROUND) appendLimitClause2(bf, limitStart, limitCount); final Type[] types = selectTypes; final Model model = query.model; final ArrayList result = new ArrayList(); if(limitStart<0) throw new RuntimeException(); if(selectables.length!=selectColumns.length) throw new RuntimeException(); if(selectables.length!=types.length) throw new RuntimeException(); //System.out.println(bf.toString()); query.addStatementInfo(executeSQLQuery(connection, bf, new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { if(doCountOnly) { resultSet.next(); result.add(new Integer(resultSet.getInt(1))); if(resultSet.next()) throw new RuntimeException(); return; } if(limitStart>0 && limitSupport==LIMIT_SUPPORT_NONE) { // TODO: ResultSet.relative // Would like to use // resultSet.relative(limitStart+1); // but this throws a java.sql.SQLException: // Invalid operation for forward only resultset : relative for(int i = limitStart; i>0; i resultSet.next(); } int i = ((limitCount==Query.UNLIMITED_COUNT||(limitSupport!=LIMIT_SUPPORT_NONE)) ? Integer.MAX_VALUE : limitCount ); if(i<=0) throw new RuntimeException(String.valueOf(limitCount)); while(resultSet.next() && (--i)>=0) { int columnIndex = 1; final Object[] resultRow = (selectables.length > 1) ? new Object[selectables.length] : null; final Row dummyRow = new Row(); for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++) { final Selectable selectable = selectables[selectableIndex]; final Object resultCell; if(selectable instanceof FunctionAttribute) { selectColumns[selectableIndex].load(resultSet, columnIndex++, dummyRow); final FunctionAttribute selectAttribute = (FunctionAttribute)selectable; if(selectable instanceof ItemAttribute) { final StringColumn typeColumn = ((ItemAttribute)selectAttribute).getTypeColumn(); if(typeColumn!=null) typeColumn.load(resultSet, columnIndex++, dummyRow); } resultCell = selectAttribute.get(dummyRow); } else if(selectable instanceof View) { final View selectFunction = (View)selectable; resultCell = selectFunction.load(resultSet, columnIndex++); } else { final Number pk = (Number)resultSet.getObject(columnIndex++); //System.out.println("pk:"+pk); if(pk==null) { // can happen when using right outer joins resultCell = null; } else { final Type type = types[selectableIndex]; final Type currentType; if(type==null) { final String typeID = resultSet.getString(columnIndex++); currentType = model.findTypeByID(typeID); if(currentType==null) throw new RuntimeException("no type with type id "+typeID); } else currentType = type; resultCell = currentType.getItemObject(pk.intValue()); } } if(resultRow!=null) resultRow[selectableIndex] = resultCell; else result.add(resultCell); } if(resultRow!=null) result.add(Collections.unmodifiableList(Arrays.asList(resultRow))); } } }, query.makeStatementInfo)); return result; } private void log(final long start, final long end, final String sqlText) { final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS"); System.out.println(df.format(new Date(start)) + " " + (end-start) + "ms: " + sqlText); } public void load(final Connection connection, final PersistentState state) { buildStage = false; final Statement bf = createStatement(state.type.getSupertype()!=null); bf.append("select "); boolean first = true; for(Type type = state.type; type!=null; type = type.getSupertype()) { for(Iterator i = type.getTable().getColumns().iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); if(!(column instanceof BlobColumn)) { if(first) first = false; else bf.append(','); bf.append(column).defineColumn(column); } } } if(first) { // no columns in type bf.appendPK(state.type, (Join)null); } bf.append(" from "); first = true; for(Type type = state.type; type!=null; type = type.getSupertype()) { if(first) first = false; else bf.append(','); bf.append(type.getTable().protectedID); } bf.append(" where "); first = true; for(Type type = state.type; type!=null; type = type.getSupertype()) { if(first) first = false; else bf.append(" and "); bf.appendPK(type, (Join)null). append('='). appendParameter(state.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail // Here this also checks for Model#findByID, // that the item has the type given in the ID. final StringColumn typeColumn = type.getTable().typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn). append('='). appendParameter(state.type.id); } } //System.out.println(bf.toString()); executeSQLQuery(connection, bf, state, false); } public void store(final Connection connection, final State state, final boolean present) throws UniqueViolationException { store(connection, state, state.type, present); } private void store(final Connection connection, final State state, final Type type, final boolean present) throws UniqueViolationException { buildStage = false; final Type supertype = type.getSupertype(); if(supertype!=null) store(connection, state, supertype, present); final Table table = type.getTable(); final List columns = table.getColumns(); final Statement bf = createStatement(); final StringColumn typeColumn = table.typeColumn; if(present) { bf.append("update "). append(table.protectedID). append(" set "); boolean first = true; for(Iterator i = columns.iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); if(!(column instanceof BlobColumn)) { if(first) first = false; else bf.append(','); bf.append(column.protectedID). append('='). appendParameter(column, state.store(column)); } } if(first) // no columns in table return; bf.append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(state.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return "0 rows affected" and executeSQLUpdate // will fail if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(state.type.id); } } else { bf.append("insert into "). append(table.protectedID). append("("). append(table.primaryKey.protectedID); if(typeColumn!=null) { bf.append(','). append(typeColumn.protectedID); } for(Iterator i = columns.iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); if(!(column instanceof BlobColumn)) { bf.append(','). append(column.protectedID); } } bf.append(")values("). appendParameter(state.pk); if(typeColumn!=null) { bf.append(','). appendParameter(state.type.id); } for(Iterator i = columns.iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); if(!(column instanceof BlobColumn)) { bf.append(','). appendParameter(column, state.store(column)); } } bf.append(')'); } //System.out.println("storing "+bf.toString()); final List uqs = type.declaredUniqueConstraints; executeSQLUpdate(connection, bf, 1, uqs.size()==1?(UniqueConstraint)uqs.iterator().next():null); } public void delete(final Connection connection, final Item item) { buildStage = false; final Type type = item.type; final int pk = item.pk; for(Type currentType = type; currentType!=null; currentType = currentType.getSupertype()) { final Table currentTable = currentType.getTable(); final Statement bf = createStatement(); bf.append("delete from "). append(currentTable.protectedID). append(" where "). append(currentTable.primaryKey.protectedID). append('='). appendParameter(pk); //System.out.println("deleting "+bf.toString()); try { executeSQLUpdate(connection, bf, 1); } catch(UniqueViolationException e) { throw new RuntimeException(e); } } } public final byte[] load(final Connection connection, final BlobColumn column, final Item item) { // TODO reuse code in load blob methods buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select "). append(column.protectedID).defineColumn(column). append(" from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } final LoadBlobResultSetHandler handler = new LoadBlobResultSetHandler(supportsGetBytes()); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class LoadBlobResultSetHandler implements ResultSetHandler { final boolean supportsGetBytes; LoadBlobResultSetHandler(final boolean supportsGetBytes) { this.supportsGetBytes = supportsGetBytes; } byte[] result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); result = supportsGetBytes ? resultSet.getBytes(1) : loadBlob(resultSet.getBlob(1)); } private static final byte[] loadBlob(final Blob blob) throws SQLException { if(blob==null) return null; return DataAttribute.copy(blob.getBinaryStream(), blob.length()); } } public final void load(final Connection connection, final BlobColumn column, final Item item, final OutputStream data, final DataAttribute attribute) { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select "). append(column.protectedID).defineColumn(column). append(" from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } executeSQLQuery(connection, bf, new ResultSetHandler(){ public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Blob blob = resultSet.getBlob(1); if(blob!=null) { InputStream source = null; try { source = blob.getBinaryStream(); attribute.copy(source, data, blob.length(), item); } catch(IOException e) { throw new RuntimeException(e); } finally { if(source!=null) { try { source.close(); } catch(IOException e) {} } } } } }, false); } public final long loadLength(final Connection connection, final BlobColumn column, final Item item) { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("select length("). append(column.protectedID).defineColumnInteger(). append(") from "). append(table.protectedID). append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return no rows and the result set handler // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } final LoadBlobLengthResultSetHandler handler = new LoadBlobLengthResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private class LoadBlobLengthResultSetHandler implements ResultSetHandler { long result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Object o = resultSet.getObject(1); if(o!=null) { long value = ((Number)o).longValue(); final long factor = blobLengthFactor; if(factor!=1) { if(value%factor!=0) throw new RuntimeException("not dividable "+value+'/'+factor); value /= factor; } result = value; } else result = -1; } } public final void store( final Connection connection, final BlobColumn column, final Item item, final InputStream data, final DataAttribute attribute) throws IOException { buildStage = false; final Table table = column.table; final Statement bf = createStatement(); bf.append("update "). append(table.protectedID). append(" set "). append(column.protectedID). append('='); if(data!=null) bf.appendParameterBlob(column, data, attribute, item); else bf.append("NULL"); bf.append(" where "). append(table.primaryKey.protectedID). append('='). appendParameter(item.pk); // Additionally check correctness of type column // If type column is inconsistent, the database // will return "0 rows affected" and executeSQLUpdate // will fail final StringColumn typeColumn = table.typeColumn; if(typeColumn!=null) { bf.append(" and "). append(typeColumn.protectedID). append('='). appendParameter(item.type.id); } //System.out.println("storing "+bf.toString()); try { executeSQLUpdate(connection, bf, 1, null); } catch(UniqueViolationException e) { throw new RuntimeException(e); } } static interface ResultSetHandler { public void run(ResultSet resultSet) throws SQLException; } private final static int convertSQLResult(final Object sqlInteger) { // IMPLEMENTATION NOTE // Whether the returned object is an Integer, a Long or a BigDecimal, // depends on the database used and for oracle on whether // OracleStatement.defineColumnType is used or not, so we support all // here. return ((Number)sqlInteger).intValue(); } //private static int timeExecuteQuery = 0; protected final StatementInfo executeSQLQuery( final Connection connection, final Statement statement, final ResultSetHandler resultSetHandler, final boolean makeStatementInfo) { java.sql.Statement sqlStatement = null; ResultSet resultSet = null; try { final String sqlText = statement.getText(); final long logStart = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; final long logPrepared; final long logExecuted; if(!prepare) { sqlStatement = connection.createStatement(); defineColumnTypes(statement.columnTypes, sqlStatement); logPrepared = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; resultSet = sqlStatement.executeQuery(sqlText); logExecuted = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; resultSetHandler.run(resultSet); } else { final PreparedStatement prepared = connection.prepareStatement(sqlText); sqlStatement = prepared; int parameterIndex = 1; for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++) setObject(sqlText, prepared, parameterIndex, i.next()); defineColumnTypes(statement.columnTypes, sqlStatement); logPrepared = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; resultSet = prepared.executeQuery(); logExecuted = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; resultSetHandler.run(resultSet); } final long logResultRead = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; if(resultSet!=null) { resultSet.close(); resultSet = null; } if(sqlStatement!=null) { sqlStatement.close(); sqlStatement = null; } final long logEnd = (log||makeStatementInfo) ? System.currentTimeMillis() : 0; if(log) log(logStart, logEnd, sqlText); if(makeStatementInfo) return makeStatementInfo(statement, connection, logStart, logPrepared, logExecuted, logResultRead, logEnd); else return null; } catch(SQLException e) { throw new SQLRuntimeException(e, statement.toString()); } finally { if(resultSet!=null) { try { resultSet.close(); } catch(SQLException e) { // exception is already thrown } } if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } private final void executeSQLUpdate(final Connection connection, final Statement statement, final int expectedRows) throws UniqueViolationException { executeSQLUpdate(connection, statement, expectedRows, null); } private final void executeSQLUpdate( final Connection connection, final Statement statement, final int expectedRows, final UniqueConstraint onlyThreatenedUniqueConstraint) throws UniqueViolationException { java.sql.Statement sqlStatement = null; try { final String sqlText = statement.getText(); final long logStart = log ? System.currentTimeMillis() : 0; final int rows; if(!prepare) { sqlStatement = connection.createStatement(); rows = sqlStatement.executeUpdate(sqlText); } else { final PreparedStatement prepared = connection.prepareStatement(sqlText); sqlStatement = prepared; int parameterIndex = 1; for(Iterator i = statement.parameters.iterator(); i.hasNext(); parameterIndex++) setObject(sqlText, prepared, parameterIndex, i.next()); rows = prepared.executeUpdate(); } final long logEnd = log ? System.currentTimeMillis() : 0; if(log) log(logStart, logEnd, sqlText); //System.out.println("("+rows+"): "+statement.getText()); if(rows!=expectedRows) throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows+" on statement "+sqlText); } catch(SQLException e) { final UniqueViolationException wrappedException = wrapException(e, onlyThreatenedUniqueConstraint); if(wrappedException!=null) throw wrappedException; else throw new SQLRuntimeException(e, statement.toString()); } finally { if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } private static final void setObject(String s, final PreparedStatement statement, final int parameterIndex, final Object value) throws SQLException { //try{ statement.setObject(parameterIndex, value); //}catch(SQLException e){ throw new SQLRuntimeException(e, "setObject("+parameterIndex+","+value+")"+s); } } protected static final String EXPLAIN_PLAN = "explain plan"; protected StatementInfo makeStatementInfo( final Statement statement, final Connection connection, final long start, final long prepared, final long executed, final long resultRead, final long end) { final StatementInfo result = new StatementInfo(statement.getText()); result.addChild(new StatementInfo("timing "+(end-start)+'/'+(prepared-start)+'/'+(executed-prepared)+'/'+(resultRead-executed)+'/'+(end-resultRead)+" (total/prepare/execute/readResult/close in ms)")); return result; } protected abstract String extractUniqueConstraintName(SQLException e); protected final static String ANY_CONSTRAINT = "--ANY private final UniqueViolationException wrapException( final SQLException e, final UniqueConstraint onlyThreatenedUniqueConstraint) { final String uniqueConstraintID = extractUniqueConstraintName(e); if(uniqueConstraintID!=null) { final UniqueConstraint constraint; if(ANY_CONSTRAINT.equals(uniqueConstraintID)) constraint = onlyThreatenedUniqueConstraint; else { constraint = (UniqueConstraint)uniqueConstraintsByID.get(uniqueConstraintID); if(constraint==null) throw new SQLRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID +"<, has only "+uniqueConstraintsByID.keySet()); } return new UniqueViolationException(constraint, null, e); } return null; } /** * Trims a name to length for being a suitable qualifier for database entities, * such as tables, columns, indexes, constraints, partitions etc. */ protected static final String trimString(final String longString, final int maxLength) { if(maxLength<=0) throw new RuntimeException("maxLength must be greater zero"); if(longString.length()==0) throw new RuntimeException("longString must not be empty"); if(longString.length()<=maxLength) return longString; int longStringLength = longString.length(); final int[] trimPotential = new int[maxLength]; final ArrayList words = new ArrayList(); { final StringBuffer buf = new StringBuffer(); for(int i=0; i<longString.length(); i++) { final char c = longString.charAt(i); if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } if(buf.length()<maxLength) buf.append(c); else longStringLength } if(buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } } final int expectedTrimPotential = longStringLength - maxLength; //System.out.println("expected trim potential = "+expectedTrimPotential); int wordLength; int remainder = 0; for(wordLength = trimPotential.length-1; wordLength>=0; wordLength { //System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]); remainder = trimPotential[wordLength] - expectedTrimPotential; if(remainder>=0) break; } final StringBuffer result = new StringBuffer(longStringLength); for(Iterator i = words.iterator(); i.hasNext(); ) { final String word = (String)i.next(); //System.out.println("word "+word+" remainder:"+remainder); if((word.length()>wordLength) && remainder>0) { result.append(word.substring(0, wordLength+1)); remainder } else if(word.length()>wordLength) result.append(word.substring(0, wordLength)); else result.append(word); } if(result.length()!=maxLength) throw new RuntimeException(result.toString()+maxLength); return result.toString(); } public String makeName(final String longName) { return makeName(null, longName); } public String makeName(final String prefix, final String longName) { final String query = prefix==null ? longName : prefix+'.'+longName; final String forcedName = forcedNames.getProperty(query); if(forcedName!=null) return forcedName; return trimString(longName, 25); } public boolean supportsCheckConstraints() { return true; } public boolean supportsGetBytes() { return true; } public boolean supportsEmptyStrings() { return true; } public boolean supportsRightOuterJoins() { return true; } public boolean fakesSupportReadCommitted() { return false; } public int getBlobLengthFactor() { return 1; } public abstract String getIntegerType(int precision); public abstract String getDoubleType(int precision); public abstract String getStringType(int maxLength); public abstract String getDayType(); abstract int getLimitSupport(); protected static final int LIMIT_SUPPORT_NONE = 26; protected static final int LIMIT_SUPPORT_CLAUSE_AFTER_SELECT = 63; protected static final int LIMIT_SUPPORT_CLAUSE_AFTER_WHERE = 93; protected static final int LIMIT_SUPPORT_CLAUSES_AROUND = 134; /** * Appends a clause to the statement causing the database limiting the query result. * This method is never called for <code>start==0 && count=={@link Query#UNLIMITED_COUNT}</code>. * NOTE: Don't forget the space before the keyword 'limit'! * @param start the number of rows to be skipped * or zero, if no rows to be skipped. * Is never negative. * @param count the number of rows to be returned * or {@link Query#UNLIMITED_COUNT} if all rows to be returned. * Is always positive (greater zero). */ abstract void appendLimitClause(Statement bf, int start, int count); /** * Same as {@link #appendLimitClause(Statement, int, int}. * Is used for {@link #LIMIT_SUPPORT_CLAUSES_AROUND} only, * for the postfix. */ abstract void appendLimitClause2(Statement bf, int start, int count); abstract void appendMatchClauseFullTextIndex(Statement bf, StringFunction function, String value); /** * Search full text. */ public final void appendMatchClause(final Statement bf, final StringFunction function, final String value) { if(fulltextIndex) appendMatchClauseFullTextIndex(bf, function, value); else appendMatchClauseByLike(bf, function, value); } protected final void appendMatchClauseByLike(final Statement bf, final StringFunction function, final String value) { bf.append(function, (Join)null). append(" like "). appendParameter(function, '%'+value+'%'); } private int countTable(final Connection connection, final Table table) { final Statement bf = createStatement(); bf.append("select count(*) from ").defineColumnInteger(). append(table.protectedID); final CountResultSetHandler handler = new CountResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class CountResultSetHandler implements ResultSetHandler { int result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); result = convertSQLResult(resultSet.getObject(1)); } } public final PkSource makePkSource(final Table table) { return butterflyPkSource ? (PkSource)new ButterflyPkSource(table) : new SequentialPkSource(table); } public final int[] getMinMaxPK(final Connection connection, final Table table) { buildStage = false; final Statement bf = createStatement(); final String primaryKeyProtectedID = table.primaryKey.protectedID; bf.append("select min("). append(primaryKeyProtectedID).defineColumnInteger(). append("),max("). append(primaryKeyProtectedID).defineColumnInteger(). append(") from "). append(table.protectedID); final NextPKResultSetHandler handler = new NextPKResultSetHandler(); executeSQLQuery(connection, bf, handler, false); return handler.result; } private static class NextPKResultSetHandler implements ResultSetHandler { int[] result; public void run(final ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new SQLException(NO_SUCH_ROW); final Object oLo = resultSet.getObject(1); if(oLo!=null) { result = new int[2]; result[0] = convertSQLResult(oLo); final Object oHi = resultSet.getObject(2); result[1] = convertSQLResult(oHi); } } } public final Schema makeSchema() { final Schema result = new Schema(driver, connectionPool); for(Iterator i = tables.iterator(); i.hasNext(); ) ((Table)i.next()).makeSchema(result); completeSchema(result); return result; } protected void completeSchema(final Schema schema) { } public final Schema makeVerifiedSchema() { final Schema result = makeSchema(); result.verify(); return result; } /** * @deprecated for debugging only, should never be used in committed code */ protected static final void printMeta(final ResultSet resultSet) throws SQLException { final ResultSetMetaData metaData = resultSet.getMetaData();; final int columnCount = metaData.getColumnCount(); for(int i = 1; i<=columnCount; i++) System.out.println(" } /** * @deprecated for debugging only, should never be used in committed code */ protected static final void printRow(final ResultSet resultSet) throws SQLException { final ResultSetMetaData metaData = resultSet.getMetaData();; final int columnCount = metaData.getColumnCount(); for(int i = 1; i<=columnCount; i++) System.out.println(" } /** * @deprecated for debugging only, should never be used in committed code */ static final ResultSetHandler logHandler = new ResultSetHandler() { public void run(final ResultSet resultSet) throws SQLException { final int columnCount = resultSet.getMetaData().getColumnCount(); System.out.println("columnCount:"+columnCount); final ResultSetMetaData meta = resultSet.getMetaData(); for(int i = 1; i<=columnCount; i++) { System.out.println(meta.getColumnName(i)+"|"); } while(resultSet.next()) { for(int i = 1; i<=columnCount; i++) { System.out.println(resultSet.getObject(i)+"|"); } } } }; public boolean isDefiningColumnTypes() { return false; } public void defineColumnTypes(IntList columnTypes, java.sql.Statement statement) throws SQLException { // default implementation does nothing, may be overwritten by subclasses } }
package org.archive.extract; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.archive.format.gzip.GZIPFormatException; import org.archive.resource.Resource; import org.archive.resource.ResourceConstants; import org.archive.resource.ResourceParseException; import org.archive.resource.ResourceProducer; public class ResourceExtractor implements ResourceConstants, Tool { private final static Logger LOG = Logger.getLogger(ResourceExtractor.class.getName()); Charset UTF8 = Charset.forName("utf-8"); public final static String TOOL_NAME = "extractor"; public static final String TOOL_DESCRIPTION = "A tool for extracting metadata from WARC, ARC, and WAT files"; private OutputStream out; private Configuration conf; public void setConf(Configuration conf) { this.conf = conf; } public Configuration getConf() { return conf; } // private static final Logger LOG = // Logger.getLogger(ResourceExtractor.class.getName()); private static int USAGE(int exitCode) { System.err.println("Usage:\n"); System.err.println("extractor [OPT] SRC"); System.err.println("\tSRC is the local path, HTTP or HDFS URL to an " + "arc, warc, arc.gz, or warc.gz."); System.err.println("\tOPT can be one of:"); System.err.println("\t\t-cdx\tProduce output in NEW-SURT-Wayback CDX format"); System.err.println("\t\t\t (note that column 1 is NOT standard Wayback canonicalized)\n"); System.err.println("\t\t-wat\tembed JSON output in a compressed WARC" + "wrapper, for storage, or sharing."); return exitCode; } public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new ResourceExtractor(), args); System.exit(res); } public int run(String[] args) throws IndexOutOfBoundsException, FileNotFoundException, IOException, ResourceParseException, URISyntaxException { // TODO: parse CLI arguments better if(args.length < 1) { return USAGE(1); } if(args.length > 2) { return USAGE(1); } int max = Integer.MAX_VALUE; OutputStream os = this.out == null ? System.out : this.out; Logger.getLogger("org.archive").setLevel(Level.WARNING); ExtractorOutput out; int arg = 0; if(args.length > 0) { if(args[0].equals("-nostrict")) { ProducerUtils.STRICT_GZ = false; arg++; } } String path = args[arg]; if(args.length == arg + 2) { if(args[arg].equals("-cdx")) { path = args[arg+1]; out = new RealCDXExtractorOutput(new PrintWriter(new OutputStreamWriter(os, Charset.forName("UTF-8")))); } else if(args[arg].equals("-wat")) { path = args[arg+1]; out = new WATExtractorOutput(os); } else { String filter = args[arg+1]; out = new JSONViewExtractorOutput(os, filter); } } else { out = new DumpingExtractorOutput(os); } ResourceProducer producer = ProducerUtils.getProducer(path); if(producer == null) { return USAGE(1); } ResourceFactoryMapper mapper = new ExtractingResourceFactoryMapper(); ExtractingResourceProducer exProducer = new ExtractingResourceProducer(producer, mapper); Logger.getLogger("org.archive").setLevel(Level.WARNING); int count = 0; int incr = 1; while(count < max) { try { Resource r = exProducer.getNext(); if(r == null) { break; } count += incr; out.output(r); } catch(GZIPFormatException e) { if(ProducerUtils.STRICT_GZ) { LOG.severe(String.format("%s: %s",exProducer.getContext(),e.getMessage())); throw e; } e.printStackTrace(); } catch(ResourceParseException e) { LOG.severe(String.format("%s: %s",exProducer.getContext(),e.getMessage())); throw e; } } return 0; } /** * @return the out */ public OutputStream getOut() { return out; } /** * @param out the out to set */ public void setOut(OutputStream out) { this.out = out; } }
/* Jeu * @author MARECAL Thomas * @author MARTIN Florian * @author QUENTIN Thibaut * Groupe I2 * @version 1 du 17/06/2014 */ import metier.*; import util.TexteUtil; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.ArrayList; public class Jeu { public final static int NB_TUILE = 4; public final static String FICHIER_CARTES = "ressources/cartes"; public final static int NB_CUBE_ROUGE = 13; public final static int NB_CUBE_JAUNE = 11; public final static int NB_CUBE_VERT = 9; public final static int NB_CUBE_BLEU = 7; public final static int NB_CUBE_GRIS = 5; private Tuile[] tuiles ; private Joueur[] joueurs ; private Pioche<Carte> piocheCartes ; private Pioche<Cube> piocheCubes ; private Defausse defausse ; private int dernierJoueur; public Jeu () { //Pour l'initialisation de la pioche de cartes String fichier = ""; try { //Chargement du fichier Scanner sc = new Scanner( new File( FICHIER_CARTES)); if ( sc.hasNext()) fichier = sc.nextLine(); sc.close(); } catch ( FileNotFoundException e) { System.out.println("Le fichier n'existe pas."); System.exit(1); } this("Joueur Gauche", "Joueur Droite", new String[0], fichier, new String[0]); piocheCartes.melanger(); piocheCubes.melanger(); //Placement des cubes sur les tuiles for ( int i = 0; i < NB_TUILE; i++) placerCubes( i); } public Jeu ( String nomJoueur1, String nomJoueur2, String[] etatTuiles, String etatPioche, String[] etatJoueur) { tuiles = new Tuile[NB_TUILE]; joueurs = new Joueur[2]; joueurs[0] = new Joueur( nomJoueur1, 'G'); joueurs[1] = new Joueur( nomJoueur2, 'D'); piocheCartes = new Pioche<Carte>(); piocheCubes = new Pioche<Cube> (); defausse = new Defausse(); initialiserTuiles( etatTuiles); initialiserPiocheCartes( etatPioche); initialiserJoueurs( etatJoueur); initialiserPiocheCubes( NB_CUBE_ROUGE, NB_CUBE_JAUNE, NB_CUBE_VERT, NB_CUBE_BLEU, NB_CUBE_GRIS); } private void initialiserTuiles() { for ( int i = 0; i < NB_TUILE; i++) if ( i%2 == 0) tuiles[i] = new Tuile( i+1, Tuile.TYPES_PAYSAGE[0]); else tuiles[i] = new Tuile( i+1, Tuile.TYPES_PAYSAGE[1]); } //Exemple : R01V11B09 renverra une liste avec une carte Rouge 1, Verte 11, Bleu 9 private ArrayList<Carte> creerCartes( String chaine) { int valeur = 0; String carte = "", couleur = ""; Pattern p; Matcher m; ArrayList<Carte> cs = new ArrayList<Carte>(); p = Pattern.compile("[RVBGJ](0[1-9]|1[0-3])"); m = p.matcher( chaine); while ( m.find()) { carte = m.group(); switch ( carte.charAt(0)){ case 'R': couleur = "ROUGE"; break; case 'G': couleur = "GRIS"; break; case 'B': couleur = "BLEU"; break; case 'V': couleur = "VERT"; break; case 'J': couleur = "JAUNE"; break; default: couleur = "DEFAUT"; } valeur = Integer.parseInt( carte.substring(1)); cs.add( new Carte( couleur, valeur)) } } // Initialisation des tuiles dans un etat donnee private void initialiserTuiles( String[] etatTuiles ) { if( etatTuiles.length<NB_TUILE ) initialiserTuiles(); int deb, fin; ArrayList<Carte> gauche, droite; ArrayList<Cube> cubes; Pattern p; Matcher m; for( int i=0; i<etatTuiles.length; i++ ) { // Decoupe de la chaine en 4 sous chaines // Cote gauche deb = 0; fin = etatTuiles[i].indexOf( deb, "|" ); String carteGauche = etatTuiles[i].substring( deb, fin ); // Paysage deb = fin; fin = etatTuiles[i].indexOf( deb, "|" ); String paysage = etatTuiles[i].substring( deb, fin ); // Cote droit deb = fin; fin = etatTuiles[i].indexOf( deb, "|" ); String carteDroite = etatTuiles[i].substring( deb, fin ); // Cubes deb = fin; String cubes = etatTuiles[i].substring( deb ); this.tuiles[i] = new Tuile( i+1, paysage ); // Ajout des cubes p = Pattern.compile( "[RVBGJ][0-" + NB_TUILE + "]" ); m = p.matcher( cubes ); int nbCube=0; String couleur=""; while( m.find() ) { switch ( cubes.charAt(0)){ case 'R': couleur = "ROUGE"; break; case 'G': couleur = "GRIS"; break; case 'B': couleur = "BLEU"; break; case 'V': couleur = "VERT"; break; case 'J': couleur = "JAUNE"; break; default: couleur = "DEFAUT"; } nbCube = Integer.parseInt( cubes.charAt(1) ); for( int j=0; j<nbCube; j++ ) this.tuiles[i].ajouterCube( new Cube( couleur ) ); } // Ajout des cartes cote gauche gauche = this.creerCartes( cartesGauche ); for( Carte c : gauche ) this.tuiles[i].ajouterCarte( 'G', c ); // Ajout des cartes cote droit droite = this.creerCartes( cartesDroite ); for( Carte c : droite ) this.tuiles[i].ajouterCarte( 'D', c ); } } private void initialiserPiocheCartes ( String cartes) { ArrayList<Carte> cs = creerCartes ( cartes); while ( !cs.isEmpty() ) piocheCartes.ajouter( cs.remove(0)); } private void initialiserJoueurs() { for ( int i = 0; i < Joueur.NB_CARTE_MAX; i++){ joueurs[0].ajouterCarte( piocheCartes.piocher()); joueurs[1].ajouterCarte( piocheCartes.piocher()); } } private void initialiserPiocheCubes ( int rouge, int jaune, int vert, int bleu, int gris) { //Cubes rouges for ( int i = 0; i < rouge; i++ ) piocheCubes.ajouter( new Cube("ROUGE")); //Cubes jaunes for ( int i = 0; i < jaune; i++ ) piocheCubes.ajouter( new Cube("JAUNE")); //Cubes verts for ( int i = 0; i < vert; i++ ) piocheCubes.ajouter( new Cube("VERT")); //Cubes bleu for ( int i = 0; i < bleu; i++ ) piocheCubes.ajouter( new Cube("BLEU")); //Cubes gris for ( int i = 0; i < gris; i++ ) piocheCubes.ajouter( new Cube("GRIS")); } public void placerCubes ( int indTuile) { for ( int i = 0; i < tuiles[indTuile].getNombre(); i++) tuiles[indTuile].ajouterCube( piocheCubes.piocher()); } public boolean jouerCarte( char coteJ, char cote, int indCarte, int indTuile ) { if( coteJ == 'D' ) { if(joueurs[1].jouerCarte( indCarte, cote, this.tuiles[indTuile] )) { joueurs[1].ajouterCarte( piocheCartes.piocher()); return true; } } else { if(joueurs[0].jouerCarte( indCarte, cote, this.tuiles[indTuile] )) { joueurs[0].ajouterCarte( piocheCartes.piocher()); return true; } } return false; } public boolean continuer() { if( !this.joueurs[1].aGagne() && !this.joueurs[0].aGagne() ) return true; return false; } public String toString() { String s=""; String s2 = ""; for( int i=0; i<this.tuiles.length; i++ ) s += this.tuiles[i].toString() + "\n\n"; for ( int i = 0; i < Joueur.NB_CARTE_MAX; i++) s2 += TexteUtil.centrer( ""+(i+1), 6); s += " for ( int i = 0; i < joueurs.length; i++) { s += TexteUtil.centrer( joueurs[i].getNom() , 55) + "\n" + TexteUtil.centrer(" " + s2 , 55) + "\n" + TexteUtil.centrer("Cartes : " + joueurs[i].afficherMain (), 55) + "\n" + TexteUtil.centrer("Cubes : " + joueurs[i].afficherCube (), 55) + "\n" + TexteUtil.centrer("Trophees:" + joueurs[i].afficherTrophe(), 55) + "\n\n"; } return s; } public String compterTuiles () { String s = ""; for(Tuile t : tuiles) { switch(t.gagnant()) { case 'G': s += joueurs[0].getNom() + " gagne " + t.getNombre() + " cubes"; t.oterCubes(joueurs[0]); t.oterCartes(defausse); break; case 'D': s += joueurs[1].getNom() + " gagne " + t.getNombre() + " cubes"; t.oterCubes(joueurs[1]); t.oterCartes(defausse); break; case 'N': s += joueurs[dernierJoueur].getNom() + " gagne " + t.getNombre() + " cubes"; t.oterCubes(joueurs[dernierJoueur]); t.oterCartes(defausse); break; default: break; } } return s; } public Joueur getJoueur () { return joueurs[dernierJoueur]; } public void changerJoueur () { dernierJoueur = 1 -dernierJoueur; } public static void main (String[] a) { Jeu j = new Jeu(); System.out.println(j); while(j.continuer()) { try { char cote; int carte , tuile; Scanner sc = new Scanner(System.in); do { System.out.println(j.getJoueur().getNom() + " : Jouez une carte"); do { System.out.println("Choisissez l'index de la carte : "); carte = sc.nextInt(); }while(carte < 1 || carte > Joueur.NB_CARTE_MAX); do { System.out.println("Choisissez la tuile : "); tuile = sc.nextInt(); }while(tuile < 1 || tuile > NB_TUILE); sc.nextLine(); do { System.out.println("Choisissez le cote ou vous voulez jouer : "); cote = sc.nextLine().charAt(0); }while(cote != 'D' && cote != 'G'); }while(!j.jouerCarte(j.getJoueur().getCote(), cote, carte-1, tuile-1));//2eme argument \E0 demander au joueur System.out.println(j.compterTuiles()); System.out.println(j); j.changerJoueur(); } catch(Exception e) { System.out.println(e); } } } }
package com.jianzhi_inc.dandelion.bdpush; import android.util.Log; import com.baidu.android.pushservice.PushConstants; import com.baidu.android.pushservice.PushManager; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; public class BDPush extends CordovaPlugin { public final static String ACTION_BIND = "bind"; public final static String ACTION_UNBIND = "unbind"; //public final static String CALLBACK_BIND_SUCCESS = "bind_success"; private static String apiKey; public static CallbackContext currentCallbackContext; /** TAG to Log */ public static final String TAG = BDPush.class.getSimpleName(); @Override protected void pluginInitialize() { super.pluginInitialize(); if(null == apiKey) { apiKey = preferences.getString("BD_PUSH_API_KEY", ""); } } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.i(TAG, action + " is called, param [" + args.toString() + "]"); if(ACTION_BIND.equals(action)) { return bindBDPush(args, callbackContext); } if(ACTION_UNBIND.equals(action)) { return unbindBDPush(args, callbackContext); } return super.execute(action, args, callbackContext); } private boolean bindBDPush(JSONArray args, CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PushManager.startWork(webView.getContext(), PushConstants.LOGIN_TYPE_API_KEY, apiKey); currentCallbackContext = callbackContext; } }); return true; } private boolean unbindBDPush(JSONArray args, CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { if(PushManager.isConnected(webView.getContext())) { PushManager.stopWork(webView.getContext()); currentCallbackContext = callbackContext; } } }); return true; } }
package avrora; /** * The <code>Version</code> class represents a version number, including the major version, the commit number, * as well as the date and time of the last commit. * * @author Ben L. Titzer */ public class Version { /** * The <code>prefix</code> field stores the string that the prefix of the version (if any) for this * version. */ public final String prefix = "Beta "; /** * The <code>major</code> field stores the string that represents the major version number (the release * number). */ public final String major = "1.6"; /** * The <code>commit</code> field stores the commit number (i.e. the number of code revisions committed to * CVS since the last release). */ public final int commit = 1; /** * The <code>getVersion()</code> method returns a reference to a <code>Version</code> object * that represents the version of the code base. * @return a <code>Version</code> object representing the current version */ public static Version getVersion() { return new Version(); } /** * The <code>toString()</code> method converts this version to a string. * @return a string representation of this version */ public String toString() { return prefix + major + '.' + commit; } }
package backend; import java.util.ArrayList; import backend.Season; public class Series { public String title; public ArrayList<Season> s; public String length; public int id; public int episodeCount; public int seasonCount; public Series(String b,String l,int i, int e,int s) { title=b; length=l; id=i; episodeCount=e; seasonCount=s; } public Season getSeason(int season) { return s.get(season); } }
package com.example.drinkingapp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; public class DrinkCounter extends Activity { private int drink_count = 0; // int start_color = 0xFF7b9aad; int start_color = 0x884D944D; int offset = 10; private DatabaseHandler db; private double hours; private int color; private double bac; // TODO:Temporary, move to a class that makes more sense private final Double CALORIES_PER_DRINK = 120.0; private final Double CALORIES_PER_CHICKEN = 264.0; private final Double CALORIES_PER_PIZZA = 285.0; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.drink_tracking); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } db = new DatabaseHandler(this); View view = findViewById(R.id.drink_layout); calculateBac(); calculateColor(); view.setBackgroundColor(color); setContentView(view); } @Override protected void onResume() { super.onResume(); View view = findViewById(R.id.drink_layout); calculateBac(); calculateColor(); view.setBackgroundColor(color); } private void calculateHours() { Date date = new Date(); SimpleDateFormat year_fmt = new SimpleDateFormat("yyyy", Locale.US); SimpleDateFormat month_fmt = new SimpleDateFormat("MM", Locale.US); SimpleDateFormat day_fmt = new SimpleDateFormat("dd", Locale.US); int year = Integer.parseInt(year_fmt.format(date)); int month = Integer.parseInt(month_fmt.format(date)); int day = Integer.parseInt(day_fmt.format(date)); ArrayList<DatabaseStore> drink_count_vals = (ArrayList<DatabaseStore>) db .getVarValuesForDay("drink_count", month, day, year); color = start_color; if (drink_count_vals != null) { drink_count = drink_count_vals.size(); drink_count_vals = DatabaseStore.sortByTime(drink_count_vals); // calculate the hours drinking if (drink_count_vals.size() > 0) { DatabaseStore start = drink_count_vals.get(0); Integer start_time = start.hour * 60 + start.minute; DatabaseStore last = drink_count_vals.get(drink_count_vals .size() - 1); Integer last_time = last.hour * 60 + last.minute; hours = (last_time - start_time) / 60.0; } // color = start_color - (0x00000900 * drink_count); } } public void doneDrinking(View view) { finish(); } public void calculateColor() { if (bac < 0.06) { color = start_color; } else if (bac < 0.15) { color = 0X88E68A2E; } else if (bac < 0.24) { color = 0X88A30000; } else { color = 0XCC000000; } } private void calculateBac() { Date date = new Date(); SimpleDateFormat year_fmt = new SimpleDateFormat("yyyy", Locale.US); SimpleDateFormat month_fmt = new SimpleDateFormat("MM", Locale.US); SimpleDateFormat day_fmt = new SimpleDateFormat("dd", Locale.US); int year = Integer.parseInt(year_fmt.format(date)); int month = Integer.parseInt(month_fmt.format(date)); int day = Integer.parseInt(day_fmt.format(date)); ArrayList<DatabaseStore> drink_count_vals = (ArrayList<DatabaseStore>) db .getVarValuesForDay("drink_count", month, day, year); if (drink_count_vals != null) { calculateHours(); // get the users gender ArrayList<DatabaseStore> stored_gender = (ArrayList<DatabaseStore>) db .getAllVarValue("gender"); // If user did not set gender use "Female" as default String gender = "Female"; if (stored_gender != null) { gender = stored_gender.get(0).value; } // fetch the users weight ArrayList<DatabaseStore> stored_weight = (ArrayList<DatabaseStore>) db .getAllVarValue("weight"); Integer weight_lbs = 120; if (stored_weight != null) { weight_lbs = Integer.parseInt(stored_weight.get(0).value); } double metabolism_constant = 0; double gender_constant = 0; double weight_kilograms = weight_lbs * 0.453592; if (gender.equals("Male")) { metabolism_constant = 0.015; gender_constant = 0.58; } else { metabolism_constant = 0.017; gender_constant = 0.49; } bac = ((0.806 * drink_count * 1.2) / (gender_constant * weight_kilograms)) - (metabolism_constant * hours); } else { bac = 0; } } @SuppressLint("NewApi") public void hadDrink(View view) { drink_count++; if (drink_count == 1){ db.addValueTomorrow("drank_last_night", "True"); } db.addValue("drink_count", drink_count); calculateBac(); db.addValue("bac", String.valueOf(bac)); calculateColor(); View parent_view = findViewById(R.id.drink_layout); parent_view.setBackgroundColor(color); // TextView check = new TextView(this); // check.setText(String.valueOf(bac)); // FrameLayout layout = (FrameLayout)findViewById(R.id.drink_layout); // layout.addView(check); //calculate number of chickens that equate the number of calories Double drink_cals = drink_count * CALORIES_PER_DRINK; int number_chickens = (int) Math .ceil(drink_cals / CALORIES_PER_CHICKEN); db.updateOrAdd("number_chickens", number_chickens); //calculate the number of slices of pizza that equate to the //number of drinks consumed that day. int number_pizza = (int) Math.ceil(drink_cals / CALORIES_PER_PIZZA); db.updateOrAdd("number_pizza", number_pizza); TextView check = new TextView(this); check.setText(String.valueOf(number_chickens)); FrameLayout layout = (FrameLayout) findViewById(R.id.drink_layout); layout.addView(check); } }
/** * @Company Google * * Given two string arrays, A and B, return an array of length B where each value at index i corresponds to the number of strings * in A that are less than the string in B at index i. The string comparator is defined as follows: * * String A is greater than String B if the first lexicographical order character in A is more frequent than the first lexicographical order in B. * The lexicographical is the ordering of the alphabet. * * Ex. 'aabbbccc' is greater than 'bcccc' since there are 2 a's vs 1 b * 'aaa' is less than 'cc' since there are 3 a's vs 2 c's * * Problem Ex. * Input: [ 'abc', 'aab', 'aaa' ], [ 'aazz', 'abc', 'aaaaaaa' ] * Output: [ 1, 0, 3 ] * * 'aazz' has a value of 2 which is greater than 'abc' * 'abc' has a value of 1 which is greater than nothing in array A * 'aaaaaaa' has a value of 7 which is greater than 'abc', 'aab', 'aaa' */ public int[] numOfLargerStrings(String[] a, String[] b) { String[] aStrs = a.split("\\s"); String[] bStrs = b.split("\\s"); int[] values = new int[aStrs.length]; int[] result = new int[bStrs.length]; int i = 0; // Count the frequency value for each string. while (i < aStrs.length || i < bStrs.length) { if (i < aStrs.length) values[i] = lexicographicalValue(aStrs[i]); if (i < bStrs.length) result[i] = lexicographicalValue(bStrs[i]); i ++; } // Count the number of strings in a that are less than the string in b. for (int j = 0; j < bStrs.length; j ++) { int count = 0; for (int k = 0; k < aStrs.length; k ++) { if (aStrs[k] < bStrs[j]) count++; } result[i] = count; } return result; } /** * Helper function to count the lexicographical value of the string. */ public int lexicographicalValue(String str) { char[] arr = str.toCharArray(); Arrays.sort(arr); int count = 0; for (char c : arr) { if (c == arr[0]) count ++; else break; } return count; }
package com.orbekk.same; import org.eclipse.jetty.server.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.googlecode.jsonrpc4j.JsonRpcServer; import com.orbekk.net.HttpUtil; public class ClientApp { private Logger logger = LoggerFactory.getLogger(getClass()); private Server server; private static final int timeout = 1000; public ClientService getClient(int port, String networkName, String masterUrl) { logger.info("Starting client with port:{}, networkName:{}, masterUrl:{}", new Object[]{port, networkName, masterUrl}); ConnectionManagerImpl connections = new ConnectionManagerImpl(timeout, timeout); State state = new State(networkName); Broadcaster broadcaster = BroadcasterImpl.getDefaultBroadcastRunner(); MasterServiceImpl master = new MasterServiceImpl(state, connections, broadcaster); ClientServiceImpl client = new ClientServiceImpl(state, connections); JsonRpcServer jsonServer = new JsonRpcServer(client, ClientService.class); server = new Server(port); RpcHandler rpcHandler = new RpcHandler(jsonServer, client); server.setHandler(rpcHandler); try { server.start(); } catch (Exception e) { logger.error("Could not start jetty server: {}", e); } while (client.getUrl() == null) { HttpUtil.sendHttpRequest(masterUrl + "ping?port=" + port); try { Thread.sleep(500); } catch (InterruptedException e) { // Ignore interrupt in wait loop. } } client.joinNetwork(masterUrl + "MasterService.json"); return client; } public void run(int port, String networkName, String masterUrl) { getClient(port, networkName, masterUrl); try { server.join(); } catch (InterruptedException e) { logger.warn("Interrupted.", e); } } public static void main(String[] args) { if (args.length < 3) { System.err.println("Usage: port networkName masterUrl"); System.exit(1); } int port = Integer.parseInt(args[0]); String networkName = args[1]; String masterUrl = args[2]; (new ClientApp()).run(port, networkName, masterUrl); } }
package de.fhg.ids.comm.ws.protocol; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import org.asynchttpclient.ws.WebSocket; import org.eclipse.jetty.websocket.api.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.MessageLite; import de.fhg.aisec.ids.messages.Idscp.ConnectorMessage; import de.fhg.aisec.ids.messages.AttestationProtos.IdsAttestationType; import de.fhg.ids.comm.ws.protocol.error.ErrorHandler; import de.fhg.ids.comm.ws.protocol.fsm.FSM; import de.fhg.ids.comm.ws.protocol.fsm.Transition; import de.fhg.ids.comm.ws.protocol.metadata.MetadataConsumerHandler; import de.fhg.ids.comm.ws.protocol.metadata.MetadataHandler; import de.fhg.ids.comm.ws.protocol.metadata.MetadataProviderHandler; import de.fhg.ids.comm.ws.protocol.rat.RemoteAttestationConsumerHandler; import de.fhg.ids.comm.ws.protocol.rat.RemoteAttestationProviderHandler; public class ProtocolMachine { /** The session to send and receive messages */ private WebSocket ws; private Session sess; private String ttpURL = "http://10.1.2.19:31337/configurations/check"; private String socket = "/var/run/tpm2d/control.sock"; private Logger LOG = LoggerFactory.getLogger(ProtocolMachine.class); /** C'tor */ public ProtocolMachine() { } /** * Returns a finite state machine (FSM) implementing the IDSP protocol. * * The FSM will be in its initial state and ready to accept messages via <code>FSM.feedEvent()</code>. * It will send responses over the session according to its FSM definition. * * @return a FSM implementing the IDSP protocol. */ public FSM initIDSConsumerProtocol(WebSocket websocket, IdsAttestationType type) { this.ws = websocket; FSM fsm = new FSM(); URI ttp = null; try { ttp = new URI(ttpURL); } catch (URISyntaxException e1) { LOG.debug("TTP URI Syntax exception"); e1.printStackTrace(); } // all handler RemoteAttestationConsumerHandler ratConsumerHandler = new RemoteAttestationConsumerHandler(fsm, type, ttp, socket); ErrorHandler errorHandler = new ErrorHandler(); MetadataConsumerHandler metaHandler = new MetadataConsumerHandler(); // standard protocol states fsm.addState(ProtocolState.IDSCP_START); fsm.addState(ProtocolState.IDSCP_ERROR); fsm.addState(ProtocolState.IDSCP_END); switch(type) { case BASIC: case ALL: case ADVANCED: // do remote attestation // rat states fsm.addState(ProtocolState.IDSCP_RAT_AWAIT_REQUEST); fsm.addState(ProtocolState.IDSCP_RAT_AWAIT_RESPONSE); fsm.addState(ProtocolState.IDSCP_RAT_AWAIT_RESULT); fsm.addState(ProtocolState.IDSCP_RAT_AWAIT_LEAVE); //Metadata exchange fsm.addState(ProtocolState.IDSCP_META_REQUEST); fsm.addState(ProtocolState.IDSCP_META_RESPONSE); /* Remote Attestation Protocol */ fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_START, ProtocolState.IDSCP_START, ProtocolState.IDSCP_RAT_AWAIT_REQUEST, (e) -> {return replyProto(ratConsumerHandler.enterRatRequest(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_REQUEST, ProtocolState.IDSCP_RAT_AWAIT_REQUEST, ProtocolState.IDSCP_RAT_AWAIT_RESPONSE, (e) -> {return replyProto(ratConsumerHandler.sendTPM2Ddata(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_RESPONSE, ProtocolState.IDSCP_RAT_AWAIT_RESPONSE, ProtocolState.IDSCP_RAT_AWAIT_RESULT, (e) -> {return replyProto(ratConsumerHandler.sendResult(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_RESULT, ProtocolState.IDSCP_RAT_AWAIT_RESULT, ProtocolState.IDSCP_RAT_AWAIT_LEAVE, (e) -> {return replyProto(ratConsumerHandler.leaveRatRequest(e));} )); /* Metadata Exchange Protocol */ fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_LEAVE, ProtocolState.IDSCP_RAT_AWAIT_LEAVE, ProtocolState.IDSCP_META_REQUEST, (e) -> {return replyProto(metaHandler.request(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.META_REQUEST, ProtocolState.IDSCP_META_REQUEST, ProtocolState.IDSCP_META_RESPONSE, (e) -> {return replyProto(metaHandler.response(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.META_RESPONSE, ProtocolState.IDSCP_META_RESPONSE, ProtocolState.IDSCP_END, (e) -> {return true;} )); /* error protocol */ // in case of error go back to IDSC_START state fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_START, ProtocolState.IDSCP_START, (e) -> { return errorHandler.handleError(e, ProtocolState.IDSCP_START, true);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_RAT_AWAIT_REQUEST, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_RAT_AWAIT_REQUEST, true);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_RAT_AWAIT_RESPONSE, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_RAT_AWAIT_RESPONSE, true);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_RAT_AWAIT_RESULT, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_RAT_AWAIT_RESULT, true);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_RAT_AWAIT_LEAVE, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_RAT_AWAIT_LEAVE, true);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_META_REQUEST, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_META_REQUEST, true);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_META_RESPONSE, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_META_RESPONSE, true);} )); break; case ZERO: /* NO Remote Attestation Protocol at all */ fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_START, ProtocolState.IDSCP_START, ProtocolState.IDSCP_END, (e) -> {return replyProto(ratConsumerHandler.sendNoAttestation(e));} )); break; default: /* attestation type is missing so do error routine */ fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_START, ProtocolState.IDSCP_START, ProtocolState.IDSCP_START, (e) -> { return errorHandler.handleError(e, ProtocolState.IDSCP_START, true);} )); break; } /* Add listener to log state transitions*/ fsm.addSuccessfulChangeListener((f,e) -> {LOG.debug("Consumer State change: " + e.getKey() + " -> " + f.getState());}); /* Run the FSM */ fsm.setInitialState(ProtocolState.IDSCP_START); return fsm; } public FSM initIDSProviderProtocol(Session sess, IdsAttestationType type) { this.sess = sess; FSM fsm = new FSM(); URI ttp = null; try { ttp = new URI(ttpURL); } catch (URISyntaxException e1) { LOG.debug("TTP URI Syntax exception"); e1.printStackTrace(); } // all handler RemoteAttestationProviderHandler ratProviderHandler = new RemoteAttestationProviderHandler(fsm, type, ttp, socket); ErrorHandler errorHandler = new ErrorHandler(); MetadataProviderHandler metaHandler = new MetadataProviderHandler(); // standard protocol states fsm.addState(ProtocolState.IDSCP_START); fsm.addState(ProtocolState.IDSCP_ERROR); fsm.addState(ProtocolState.IDSCP_END); switch(type) { case BASIC: case ALL: case ADVANCED: // do remote attestation // rat states fsm.addState(ProtocolState.IDSCP_RAT_AWAIT_REQUEST); fsm.addState(ProtocolState.IDSCP_RAT_AWAIT_RESPONSE); fsm.addState(ProtocolState.IDSCP_RAT_AWAIT_RESULT); fsm.addState(ProtocolState.IDSCP_RAT_AWAIT_LEAVE); //metadata exchange states fsm.addState(ProtocolState.IDSCP_META_REQUEST); fsm.addState(ProtocolState.IDSCP_META_RESPONSE); /* Remote Attestation Protocol */ fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_REQUEST, ProtocolState.IDSCP_START, ProtocolState.IDSCP_RAT_AWAIT_RESPONSE, (e) -> {return replyProto(ratProviderHandler.enterRatRequest(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_RESPONSE, ProtocolState.IDSCP_RAT_AWAIT_RESPONSE, ProtocolState.IDSCP_RAT_AWAIT_RESULT, (e) -> {return replyProto(ratProviderHandler.sendTPM2Ddata(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_RESULT, ProtocolState.IDSCP_RAT_AWAIT_RESULT, ProtocolState.IDSCP_RAT_AWAIT_LEAVE, (e) -> {return replyProto(ratProviderHandler.sendResult(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_LEAVE, ProtocolState.IDSCP_RAT_AWAIT_LEAVE, ProtocolState.IDSCP_META_REQUEST, (e) -> {return replyProto(ratProviderHandler.leaveRatRequest(e));} )); /* Metadata Exchange Protocol */ fsm.addTransition(new Transition(ConnectorMessage.Type.META_REQUEST, ProtocolState.IDSCP_META_REQUEST, ProtocolState.IDSCP_META_RESPONSE, (e) -> {return replyProto(metaHandler.request(e));} )); fsm.addTransition(new Transition(ConnectorMessage.Type.META_RESPONSE, ProtocolState.IDSCP_META_RESPONSE, ProtocolState.IDSCP_END, (e) -> {return true;} )); /* error protocol */ // in case of error go back to IDSC_START state fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_START, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_START, false);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_RAT_AWAIT_REQUEST, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_RAT_AWAIT_REQUEST, false);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_RAT_AWAIT_RESPONSE, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_RAT_AWAIT_RESPONSE, false);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_RAT_AWAIT_RESULT, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_RAT_AWAIT_RESULT, false);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_RAT_AWAIT_LEAVE, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_RAT_AWAIT_LEAVE, false);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_META_REQUEST, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_META_REQUEST, false);} )); fsm.addTransition(new Transition(ConnectorMessage.Type.ERROR, ProtocolState.IDSCP_META_RESPONSE, ProtocolState.IDSCP_START, (e) -> {return errorHandler.handleError(e, ProtocolState.IDSCP_META_RESPONSE, false);} )); break; case ZERO: /* NO Remote Attestation Protocol at all */ fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_START, ProtocolState.IDSCP_START, ProtocolState.IDSCP_END, (e) -> {return true;} )); break; default: /* attestation type is missing so do error routine */ fsm.addTransition(new Transition(ConnectorMessage.Type.RAT_START, ProtocolState.IDSCP_START, ProtocolState.IDSCP_START, (e) -> { return errorHandler.handleError(e, ProtocolState.IDSCP_START, false);} )); break; } /* Add listener to log state transitions*/ fsm.addSuccessfulChangeListener((f,e) -> {LOG.debug("Provider State change: " + e.getKey() + " -> " + f.getState());}); /* Run the FSM */ fsm.setInitialState(ProtocolState.IDSCP_START); return fsm; } boolean replyProto(MessageLite message) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); //System.out.println("message to send: \n" + message.toString() + "\n"); try { message.writeTo(bos); } catch (IOException e) { e.printStackTrace(); } return reply(bos.toByteArray()); } /** * Sends a response over the websocket session. * * @param text * @return true if successful, false if not. */ boolean reply(byte[] text) { if (ws!=null) { //System.out.println("Sending out " + text.length + " bytes"); ws.sendMessage(text); } else if (sess!=null) { try { ByteBuffer bb = ByteBuffer.wrap(text); //System.out.println("Sending out ByteBuffer with " + bb.array().length + " bytes"); sess.getRemote().sendBytes(bb); } catch (IOException e) { e.printStackTrace(); } } return true; } }
package io.jchat.android.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import io.jchat.android.R; public class SideBar extends View { private OnTouchingLetterChangedListener onTouchingLetterChangedListener; public static String[] b; private int choose = -1; private Paint paint = new Paint(); private TextView mTextDialog; private float mRatio; private float mDensity; private float mTop; private float mBottom; private int mIndex; public void setTextView(TextView mTextDialog) { this.mTextDialog = mTextDialog; } public SideBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public SideBar(Context context, AttributeSet attrs) { super(context, attrs); } public SideBar(Context context) { super(context); } public void setIndex(String[] sections) { b = sections; postInvalidate(); } protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (null != b) { int height = getHeight(); int width = getWidth(); int singleHeight = (int) (20 * mDensity); mTop = height / 2 + 10 * mDensity; mBottom = height / 2 - 10 * mDensity * b.length; for (int i = 0; i < b.length; i++) { paint.setColor(getResources().getColor(R.color.jmui_jpush_blue)); paint.setTypeface(Typeface.DEFAULT_BOLD); paint.setAntiAlias(true); paint.setTextSize((int) (30 * mRatio)); if (i == choose) { paint.setColor(getResources().getColor(R.color.white)); paint.setFakeBoldText(true); } float xPos = width / 2 - paint.measureText(b[i]) / 2; float yPos; if (b.length / 2 > i) { yPos = height / 2 - singleHeight * (b.length / 2 - i); } else { yPos = height / 2 + singleHeight * (i - b.length / 2); } canvas.drawText(b[i], xPos, yPos, paint); paint.reset(); } } } @Override public boolean dispatchTouchEvent(MotionEvent event) { if (null == b) { return true; } final int action = event.getAction(); final float y = event.getY(); final int oldChoose = choose; final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener; int actualHeight = (int)(b.length * 20 * mDensity); final int c = (int) Math.ceil((y - mBottom) * b.length / actualHeight) ; // y*bb. switch (action) { case MotionEvent.ACTION_UP: setBackgroundDrawable(new ColorDrawable(0x00000000)); choose = -1; invalidate(); if (mTextDialog != null) { mTextDialog.setVisibility(View.INVISIBLE); } break; default: // setBackgroundResource(R.drawable.sidebar_background); // setBackgroundColor(Color.TRANSPARENT); if (oldChoose != c) { if (c >= 0 && c < b.length) { if (listener != null) { listener.onTouchingLetterChanged(b[c]); } if (mTextDialog != null) { mTextDialog.setText(b[c]); mTextDialog.setVisibility(View.VISIBLE); } choose = c; invalidate(); } } break; } return true; } /** * * * @param onTouchingLetterChangedListener */ public void setOnTouchingLetterChangedListener( OnTouchingLetterChangedListener onTouchingLetterChangedListener) { this.onTouchingLetterChangedListener = onTouchingLetterChangedListener; } /** * * * @author coder */ public interface OnTouchingLetterChangedListener { public void onTouchingLetterChanged(String s); } public void setRatioAndDensity(float ratio, float density) { this.mRatio = ratio; this.mDensity = density; } }
package eu.theunitry.fabula.calculate; public class UNCalculate{ private int result; public int calculate(int g1, int g2, char operator) { switch (operator) { case '+': this.sum(g1, g2); break; case '-': this.subtract(g1, g2); break; case '*': this.multiply(g1, g2); break; case '/': this.divide(g1, g2); break; } return result; } private void sum(int g1, int g2) { result = g1 + g2; } public void subtract(int g1, int g2) { result = g1 - g2; } public void multiply(int g1, int g2) { result = g1 * g2; } public void divide(int g1, int g2) { result = g1 / g2; } }
package org.gem.calc; import java.io.File; import java.rmi.RemoteException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.collections.Closure; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opensha.commons.data.Site; import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc; import org.opensha.commons.data.function.DiscretizedFuncAPI; import org.opensha.commons.geo.Location; import org.opensha.commons.geo.LocationList; import org.opensha.commons.geo.LocationUtils; import org.opensha.commons.param.DoubleParameter; import org.opensha.sha.calc.HazardCurveCalculator; import org.opensha.sha.earthquake.EqkRupForecastAPI; import org.opensha.sha.earthquake.ProbEqkRupture; import org.opensha.sha.earthquake.ProbEqkSource; import org.opensha.sha.earthquake.rupForecastImpl.GEM1.GEM1ERF; import org.opensha.sha.imr.ScalarIntensityMeasureRelationshipAPI; import org.opensha.sha.imr.param.OtherParams.StdDevTypeParam; import org.opensha.sha.imr.param.SiteParams.DepthTo2pt5kmPerSecParam; import org.opensha.sha.imr.param.SiteParams.Vs30_Param; import org.opensha.sha.util.TectonicRegionType; import static org.apache.commons.collections.CollectionUtils.forAllDo; import org.gem.calc.DisaggregationResult; public class DisaggregationCalculator { private static Log logger = LogFactory.getLog(DisaggregationCalculator.class); /** * Dataset for the full disagg matrix (for HDF5 ouput). */ public static final String FULLDISAGGMATRIX = "fulldisaggmatrix"; private final Double[] latBinLims; private final Double[] lonBinLims; private final Double[] magBinLims; private final Double[] epsilonBinLims; private static final TectonicRegionType[] tectonicRegionTypes = TectonicRegionType.values(); /** * Dimensions for matrices produced by this calculator, based on the length * of the bin limits passed to the constructor. */ private final long[] dims; /** * Used for checking that bin edge lists are not null; */ private static final Closure notNull = new Closure() { public void execute(Object o) { if (o == null) { throw new IllegalArgumentException("Bin edges should not be null"); } } }; /** * Used for checking that bin edge lists have a length greater than or equal * to 2. */ private static final Closure lenGE2 = new Closure() { public void execute(Object o) { if (o instanceof Object[]) { Object[] oArray = (Object[]) o; if (oArray.length < 2) { throw new IllegalArgumentException("Bin edge arrays must have a length >= 2"); } } } }; private static final Closure isSorted = new Closure() { public void execute(Object o) { if (o instanceof Object[]) { Object[] oArray = (Object[]) o; Object[] sorted = Arrays.copyOf(oArray, oArray.length); Arrays.sort(sorted); if (!Arrays.equals(sorted, oArray)) { throw new IllegalArgumentException("Bin edge arrays must be arranged in ascending order"); } } } }; public DisaggregationCalculator( Double[] latBinEdges, Double[] lonBinEdges, Double[] magBinEdges, Double[] epsilonBinEdges) { List binEdges = Arrays.asList(latBinEdges, lonBinEdges, magBinEdges, epsilonBinEdges); // Validation for the bin edges: forAllDo(binEdges, notNull); forAllDo(binEdges, lenGE2); forAllDo(binEdges, isSorted); this.latBinLims = latBinEdges; this.lonBinLims = lonBinEdges; this.magBinLims = magBinEdges; this.epsilonBinLims = epsilonBinEdges; this.dims = new long[5]; this.dims[0] = this.latBinLims.length - 1; this.dims[1] = this.lonBinLims.length - 1; this.dims[2] = this.magBinLims.length - 1; this.dims[3] = this.epsilonBinLims.length - 1; this.dims[4] = tectonicRegionTypes.length; } /** * Simplified computeMatrix method for convenient calls from the Python * code. */ public DisaggregationResult computeMatrix( double lat, double lon, GEM1ERF erf, Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> imrMap, double poe, List<Double> imls, double vs30Value, double depthTo2pt5KMPS) { Site site = new Site(new Location(lat, lon)); site.addParameter(new DoubleParameter(Vs30_Param.NAME, vs30Value)); site.addParameter(new DoubleParameter(DepthTo2pt5kmPerSecParam.NAME, depthTo2pt5KMPS)); DiscretizedFuncAPI hazardCurve = new ArbitrarilyDiscretizedFunc(); // initialize the hazard curve with the number of points == the number of IMLs for (double d : imls) { hazardCurve.set(d, 1.0); } try { HazardCurveCalculator hcc = new HazardCurveCalculator(); hcc.getHazardCurve(hazardCurve, site, imrMap, erf); } catch (RemoteException e) { throw new RuntimeException(e); } logger.debug("Hazard Curve is: " + hazardCurve.toString()); double minMag = (Double) erf.getParameter(GEM1ERF.MIN_MAG_NAME).getValue(); return computeMatrix(site, erf, imrMap, poe, hazardCurve, minMag); } public DisaggregationResult computeMatrix( Site site, EqkRupForecastAPI erf, Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> imrMap, double poe, DiscretizedFuncAPI hazardCurve, double minMag) { assertPoissonian(erf); assertNonZeroStdDev(imrMap); double disaggMatrix[][][][][] = new double[(int) dims[0]] [(int) dims[1]] [(int) dims[2]] [(int) dims[3]] [(int) dims[4]]; // value by which to normalize the final matrix double totalAnnualRate = 0.0; double logGMV = getGMV(hazardCurve, poe); for (int srcCnt = 0; srcCnt < erf.getNumSources(); srcCnt++) { ProbEqkSource source = erf.getSource(srcCnt); double totProb = source.computeTotalProbAbove(minMag); double totRate = -Math.log(1 - totProb); TectonicRegionType trt = source.getTectonicRegionType(); ScalarIntensityMeasureRelationshipAPI imr = imrMap.get(trt); imr.setSite(site); imr.setIntensityMeasureLevel(logGMV); for(int rupCnt = 0; rupCnt < source.getNumRuptures(); rupCnt++) { ProbEqkRupture rupture = source.getRupture(rupCnt); imr.setEqkRupture(rupture); Location location = closestLocation(rupture.getRuptureSurface().getLocationList(), site.getLocation()); double lat, lon, mag, epsilon; lat = location.getLatitude(); lon = location.getLongitude(); mag = rupture.getMag(); epsilon = imr.getEpsilon(); if (!allInRange(lat, lon, mag, epsilon)) { // one or more of the parameters is out of range; // skip this rupture continue; } int[] binIndices = getBinIndices(lat, lon, mag, epsilon, trt); double annualRate = totRate * imr.getExceedProbability() * rupture.getProbability(); disaggMatrix[binIndices[0]][binIndices[1]][binIndices[2]][binIndices[3]][binIndices[4]] += annualRate; totalAnnualRate += annualRate; } // end rupture loop } // end source loop disaggMatrix = normalize(disaggMatrix, totalAnnualRate); DisaggregationResult daResult = new DisaggregationResult(); daResult.setGMV(Math.exp(logGMV)); daResult.setMatrix(disaggMatrix); return daResult; } public boolean allInRange( double lat, double lon, double mag, double epsilon) { return inRange(this.latBinLims, lat) && inRange(this.lonBinLims, lon) && inRange(this.magBinLims, mag) && inRange(this.epsilonBinLims, epsilon); } public static void assertPoissonian(EqkRupForecastAPI erf) { for (int i = 0; i < erf.getSourceList().size(); i++) { ProbEqkSource source = erf.getSource(i); if (!source.isPoissonianSource()) { throw new RuntimeException( "Sources must be Poissonian. (Non-Poissonian source are not currently supported.)"); } } } public static void assertNonZeroStdDev( Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> imrMap) { for (ScalarIntensityMeasureRelationshipAPI imr : imrMap.values()) { String stdDevType = (String) imr.getParameter(StdDevTypeParam.NAME).getValue(); if (stdDevType.equalsIgnoreCase(StdDevTypeParam.STD_DEV_TYPE_NONE)) { throw new RuntimeException( "Attenuation relationship must have a non-zero standard deviation."); } } } public static boolean inRange(Double[] bins, Double value) { return value >= bins[0] && value < bins[bins.length - 1]; } /** * Figure out which bins each input parameter fits into. The returned array * of indices represent the 5 dimensional coordinates in the disaggregation * matrix. * @param lat * @param lon * @param mag * @param epsilon * @param trt */ public int[] getBinIndices( double lat, double lon, double mag, double epsilon, TectonicRegionType trt) { int[] result = new int[5]; result[0] = digitize(this.latBinLims, lat); result[1] = digitize(this.lonBinLims, lon); result[2] = digitize(this.magBinLims, mag); result[3] = digitize(this.epsilonBinLims, epsilon); result[4] = Arrays.asList(TectonicRegionType.values()).indexOf(trt); return result; } public static int digitize(Double[] bins, Double value) { for (int i = 0; i < bins.length - 1; i++) { if (value >= bins[i] && value < bins[i + 1]) { return i; } } throw new IllegalArgumentException( "Value '" + value + "' is outside the expected range"); } /** * Given a LocationList and a Location target, get the Location in the * LocationList which is closest to the target Location. * @param list * @param target * @return closest Location (in the input ListLocation) to the target */ public static Location closestLocation(LocationList list, Location target) { Location closest = null; double minDistance = Double.MAX_VALUE; for (Location loc : list) { double horzDist = LocationUtils.horzDistance(loc, target); double vertDist = LocationUtils.vertDistance(loc, target); double distance = Math.sqrt(Math.pow(horzDist, 2) + Math.pow(vertDist, 2)); if (distance < minDistance) { minDistance = distance; closest = loc; } } return closest; } /** * Extract a GMV (Ground Motion Value) for a given curve and PoE * (Probability of Exceedance) value. * * IML (Intensity Measure Level) values make up the X-axis of the curve. * IMLs are arranged in ascending order. The lower the IML value, the * higher the PoE value (Y value) on the curve. Thus, it is assumed that * hazard curves will always have a negative slope. * * If the input poe value is > the max Y value in the curve, extrapolate * and return the X value corresponding to the max Y value (the first Y * value). * If the input poe value is < the min Y value in the curve, extrapolate * and return the X value corresponding to the min Y value (the last Y * value). * Otherwise, interpolate an X value in the curve given the input PoE. * @param hazardCurve * @param poe Probability of Exceedance value * @return GMV corresponding to the input poe */ public static Double getGMV(DiscretizedFuncAPI hazardCurve, double poe) { if (poe > hazardCurve.getY(0)) { return hazardCurve.getX(0); } else if (poe < hazardCurve.getY(hazardCurve.getNum() - 1)) { return hazardCurve.getX(hazardCurve.getNum() - 1); } else { return hazardCurve.getFirstInterpolatedX(poe); } } /** * Normalize a 5D matrix by the given value. * @param matrix * @param normFactor */ public static double[][][][][] normalize(double[][][][][] matrix, double normFactor) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { for (int k = 0; k < matrix[i][j].length; k++) { for (int l = 0; l < matrix[i][j][k].length; l++) { for (int m = 0; m < matrix[i][j][k][l].length; m++) { matrix[i][j][k][l][m] /= normFactor; } } } } } return matrix; } }
package com.dianping.cat.report.page.state; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.dianping.cat.consumer.state.model.entity.Machine; import com.dianping.cat.consumer.state.model.entity.Message; import com.dianping.cat.consumer.state.model.entity.ProcessDomain; import com.dianping.cat.consumer.state.model.entity.StateReport; import com.dianping.cat.consumer.state.model.transform.BaseVisitor; import com.dianping.cat.helper.CatString; public class StateShow extends BaseVisitor { private Machine m_total = new Machine(); private Map<Long, Message> m_messages = new LinkedHashMap<Long, Message>(); private Map<String, ProcessDomain> m_processDomains = new LinkedHashMap<String, ProcessDomain>(); private String m_currentIp; private String m_ip; public StateShow(String ip) { m_ip = ip; } public List<Message> getMessages() { List<Message> all = new ArrayList<Message>(m_messages.values()); List<Message> result = new ArrayList<Message>(); long current = System.currentTimeMillis(); for (Message message : all) { if (message.getId() < current) { result.add(message); } } return result; } public Map<Long, Message> getMessagesMap() { return m_messages; } public List<ProcessDomain> getProcessDomains() { List<ProcessDomain> temp = new ArrayList<ProcessDomain>(m_processDomains.values()); Collections.sort(temp, new DomainCompartor()); return temp; } public Machine getTotal() { return m_total; } public boolean isIp(String ip) { boolean result = false; // try { // if (ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) { // String s[] = ip.split("\\."); // if (Integer.parseInt(s[0]) <= 255) { // if (Integer.parseInt(s[1]) <= 255) { // if (Integer.parseInt(s[2]) <= 255) { // if (Integer.parseInt(s[3]) <= 255) { // result = true; // } catch (Exception e) { // //ignore try { char first = ip.charAt(0); char next = ip.charAt(1); if (first >= '0' && first <= '9') { if (next >= '0' && next <= '9') { return true; } } } catch (Exception e) { } return result; } public int getTotalSize() { Set<String> ips = new HashSet<String>(); for (ProcessDomain domain : m_processDomains.values()) { Set<String> temp = domain.getIps(); for (String str : temp) { if (isIp(str)) { ips.add(str); } } } return ips.size(); } private Machine mergerMachine(Machine total, Machine machine) { total.setAvgTps(total.getAvgTps() + machine.getAvgTps()); total.setTotal(total.getTotal() + machine.getTotal()); total.setTotalLoss(total.getTotalLoss() + machine.getTotalLoss()); total.setDump(total.getDump() + machine.getDump()); total.setDumpLoss(total.getDumpLoss() + machine.getDumpLoss()); total.setSize(total.getSize() + machine.getSize()); total.setDelaySum(total.getDelaySum() + machine.getDelaySum()); total.setDelayCount(total.getDelayCount() + machine.getDelayCount()); total.setBlockTotal(total.getBlockTotal() + machine.getBlockTotal()); total.setBlockLoss(total.getBlockLoss() + machine.getBlockLoss()); total.setBlockTime(total.getBlockTime() + machine.getBlockTime()); total.setPigeonTimeError(total.getPigeonTimeError() + machine.getPigeonTimeError()); total.setNetworkTimeError(total.getNetworkTimeError() + machine.getNetworkTimeError()); if (machine.getMaxTps() > total.getMaxTps()) { total.setMaxTps(machine.getMaxTps()); } long count = total.getDelayCount(); double sum = total.getDelaySum(); if (count > 0) { total.setDelayAvg(sum / count); } return total; } private void mergerMessage(Message total, Message message) { total.setDelayCount(total.getDelayCount() + message.getDelayCount()); total.setDelaySum(total.getDelaySum() + message.getDelaySum()); total.setDump(total.getDump() + message.getDump()); total.setDumpLoss(total.getDumpLoss() + message.getDumpLoss()); total.setSize(total.getSize() + message.getSize()); total.setTotal(total.getTotal() + message.getTotal()); total.setTotalLoss(total.getTotalLoss() + message.getTotalLoss()); total.setBlockTotal(total.getBlockTotal() + message.getBlockTotal()); total.setBlockLoss(total.getBlockLoss() + message.getBlockLoss()); total.setBlockTime(total.getBlockTime() + message.getBlockTime()); total.setPigeonTimeError(total.getPigeonTimeError() + message.getPigeonTimeError()); total.setNetworkTimeError(total.getNetworkTimeError() + message.getNetworkTimeError()); } @Override public void visitMachine(Machine machine) { String ip = machine.getIp(); m_currentIp = ip; if (m_total == null) { m_total = new Machine(); m_total.setIp(ip); } if (m_ip.equals(CatString.ALL) || m_ip.equalsIgnoreCase(ip)) { m_total = mergerMachine(m_total, machine); super.visitMachine(machine); } } @Override public void visitMessage(Message message) { Message temp = m_messages.get(message.getId()); if (temp == null) { m_messages.put(message.getId(), message); } else { mergerMessage(temp, message); } } @Override public void visitProcessDomain(ProcessDomain processDomain) { if (m_ip.equals(m_currentIp) || m_ip.equals(CatString.ALL)) { ProcessDomain temp = m_processDomains.get(processDomain.getName()); if (temp == null) { m_processDomains.put(processDomain.getName(), processDomain); } else { temp.getIps().addAll(processDomain.getIps()); } } } @Override public void visitStateReport(StateReport stateReport) { super.visitStateReport(stateReport); } public static class DomainCompartor implements Comparator<ProcessDomain> { @Override public int compare(ProcessDomain o1, ProcessDomain o2) { return o1.getName().compareTo(o2.getName()); } } }
package org.chromium.chrome.browser; import org.chromium.base.CalledByNative; import org.chromium.base.ObserverList; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.components.bookmarks.BookmarkType; import java.util.ArrayList; import java.util.List; /** * Provides the communication channel for Android to fetch and manipulate the * bookmark model stored in native. */ public class BookmarksBridge { private final Profile mProfile; private boolean mIsDoingExtensiveChanges; private long mNativeBookmarksBridge; private boolean mIsNativeBookmarkModelLoaded; private final List<DelayedBookmarkCallback> mDelayedBookmarkCallbacks = new ArrayList<DelayedBookmarkCallback>(); private final ObserverList<BookmarkModelObserver> mObservers = new ObserverList<BookmarkModelObserver>(); /** * Interface for callback object for fetching bookmarks and folder hierarchy. */ public interface BookmarksCallback { /** * Callback method for fetching bookmarks for a folder and the folder hierarchy. * @param folderId The folder id to which the bookmarks belong. * @param bookmarksList List holding the fetched bookmarks and details. */ @CalledByNative("BookmarksCallback") void onBookmarksAvailable(BookmarkId folderId, List<BookmarkItem> bookmarksList); /** * Callback method for fetching the folder hierarchy. * @param folderId The folder id to which the bookmarks belong. * @param bookmarksList List holding the fetched folder details. */ @CalledByNative("BookmarksCallback") void onBookmarksFolderHierarchyAvailable(BookmarkId folderId, List<BookmarkItem> bookmarksList); } /** * Base empty implementation observer class that provides listeners to be notified of changes * to the bookmark model. It's mandatory to implement one method, bookmarkModelChanged. Other * methods are optional and if they aren't overridden, the default implementation of them will * eventually call bookmarkModelChanged. Unless noted otherwise, all the functions won't be * called during extensive change. */ public abstract static class BookmarkModelObserver { /** * Invoked when a node has moved. * @param oldParent The parent before the move. * @param oldIndex The index of the node in the old parent. * @param newParent The parent after the move. * @param newIndex The index of the node in the new parent. */ public void bookmarkNodeMoved( BookmarkItem oldParent, int oldIndex, BookmarkItem newParent, int newIndex) { bookmarkModelChanged(); } /** * Invoked when a node has been added. * @param parent The parent of the node being added. * @param index The index of the added node. */ public void bookmarkNodeAdded(BookmarkItem parent, int index) { bookmarkModelChanged(); } /** * Invoked when a node has been removed, the item may still be starred though. This can * be called during extensive change, and have the flag argument indicating it. * @param parent The parent of the node that was removed. * @param oldIndex The index of the removed node in the parent before it was removed. * @param node The node that was removed. * @param isDoingExtensiveChanges whether extensive changes are happening. */ public void bookmarkNodeRemoved(BookmarkItem parent, int oldIndex, BookmarkItem node, boolean isDoingExtensiveChanges) { if (isDoingExtensiveChanges) return; bookmarkNodeRemoved(parent, oldIndex, node); } /** * Invoked when a node has been removed, the item may still be starred though. * * @param parent The parent of the node that was removed. * @param oldIndex The index of the removed node in the parent before it was removed. * @param node The node that was removed. */ public void bookmarkNodeRemoved(BookmarkItem parent, int oldIndex, BookmarkItem node) { bookmarkModelChanged(); } /** * Invoked when the title or url of a node changes. * @param node The node being changed. */ public void bookmarkNodeChanged(BookmarkItem node) { bookmarkModelChanged(); } /** * Invoked when the children (just direct children, not descendants) of a node have been * reordered in some way, such as sorted. * @param node The node whose children are being reordered. */ public void bookmarkNodeChildrenReordered(BookmarkItem node) { bookmarkModelChanged(); } /** * Called when the native side of bookmark is loaded and now in usable state. */ public void bookmarkModelLoaded() { bookmarkModelChanged(); } /** * Called when there are changes to the bookmark model that don't trigger any of the other * callback methods or it wasn't handled by other callback methods. * Examples: * - On partner bookmarks change. * - On extensive change finished. * - Falling back from other methods that are not overridden in this class. */ public abstract void bookmarkModelChanged(); } /** * Handler to fetch the bookmarks, titles, urls and folder hierarchy. * @param profile Profile instance corresponding to the active profile. */ public BookmarksBridge(Profile profile) { mProfile = profile; mNativeBookmarksBridge = nativeInit(profile); mIsDoingExtensiveChanges = nativeIsDoingExtensiveChanges(mNativeBookmarksBridge); } /** * Destroys this instance so no further calls can be executed. */ public void destroy() { if (mNativeBookmarksBridge != 0) { nativeDestroy(mNativeBookmarksBridge); mNativeBookmarksBridge = 0; mIsNativeBookmarkModelLoaded = false; mDelayedBookmarkCallbacks.clear(); } mObservers.clear(); } /** * Load an empty partner bookmark shim for testing. The root node for bookmark will be an * empty node. */ @VisibleForTesting public void loadEmptyPartnerBookmarkShimForTesting() { nativeLoadEmptyPartnerBookmarkShimForTesting(mNativeBookmarksBridge); } /** * Add an observer to bookmark model changes. * @param observer The observer to be added. */ public void addObserver(BookmarkModelObserver observer) { mObservers.addObserver(observer); } /** * Remove an observer of bookmark model changes. * @param observer The observer to be removed. */ public void removeObserver(BookmarkModelObserver observer) { mObservers.removeObserver(observer); } /** * @return Whether or not the underlying bookmark model is loaded. */ public boolean isBookmarkModelLoaded() { return mIsNativeBookmarkModelLoaded; } /** * @return A BookmarkItem instance for the given BookmarkId. */ public BookmarkItem getBookmarkById(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; return nativeGetBookmarkByID(mNativeBookmarksBridge, id.getId(), id.getType()); } /** * @return All the permanent nodes. */ public List<BookmarkId> getPermanentNodeIDs() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetPermanentNodeIDs(mNativeBookmarksBridge, result); return result; } /** * @return The top level folder's parents, which are root node, mobile node, and other node. */ public List<BookmarkId> getTopLevelFolderParentIDs() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetTopLevelFolderParentIDs(mNativeBookmarksBridge, result); return result; } /** * @param getSpecial Whether special top folders should be returned. * @param getNormal Whether normal top folders should be returned. * @return The top level folders. Note that special folders come first and normal top folders * will be in the alphabetical order. Special top folders are managed bookmark and * partner bookmark. Normal top folders are desktop permanent folder, and the * sub-folders of mobile permanent folder and others permanent folder. */ public List<BookmarkId> getTopLevelFolderIDs(boolean getSpecial, boolean getNormal) { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetTopLevelFolderIDs(mNativeBookmarksBridge, getSpecial, getNormal, result); return result; } /** * @return The uncategorized bookmark IDs. They are direct descendant bookmarks of mobile and * other folders. */ public List<BookmarkId> getUncategorizedBookmarkIDs() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetUncategorizedBookmarkIDs(mNativeBookmarksBridge, result); return result; } /** * Populates folderList with BookmarkIds of folders users can move bookmarks * to and all folders have corresponding depth value in depthList. Folders * having depths of 0 will be shown as top-layered folders. These include * "Desktop Folder" itself as well as all children of "mobile" and "other". * Children of 0-depth folders have depth of 1, and so on. * * The result list will be sorted alphabetically by title. "mobile", "other", * root node, managed folder, partner folder are NOT included as results. */ public void getAllFoldersWithDepths(List<BookmarkId> folderList, List<Integer> depthList) { assert mIsNativeBookmarkModelLoaded; nativeGetAllFoldersWithDepths(mNativeBookmarksBridge, folderList, depthList); } /** * @return The BookmarkId for Mobile folder node */ public BookmarkId getMobileFolderId() { assert mIsNativeBookmarkModelLoaded; return nativeGetMobileFolderId(mNativeBookmarksBridge); } /** * @return Id representing the special "other" folder from bookmark model. */ public BookmarkId getOtherFolderId() { assert mIsNativeBookmarkModelLoaded; return nativeGetOtherFolderId(mNativeBookmarksBridge); } /** * @return BokmarkId representing special "desktop" folder, namely "bookmark bar". */ @VisibleForTesting public BookmarkId getDesktopFolderId() { assert mIsNativeBookmarkModelLoaded; return nativeGetDesktopFolderId(mNativeBookmarksBridge); } /** * Reads sub-folder IDs, sub-bookmark IDs, or both of the given folder. * * @param getFolders Whether sub-folders should be returned. * @param getBookmarks Whether sub-bookmarks should be returned. * @return Child IDs of the given folder, with the specified type. */ public List<BookmarkId> getChildIDs(BookmarkId id, boolean getFolders, boolean getBookmarks) { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetChildIDs(mNativeBookmarksBridge, id.getId(), id.getType(), getFolders, getBookmarks, result); return result; } /** * Gets the child of a folder at the specific position. * @param folderId Id of the parent folder * @param index Posision of child among all children in folder * @return BookmarkId of the child, which will be null if folderId does not point to a folder or * index is invalid. */ public BookmarkId getChildAt(BookmarkId folderId, int index) { assert mIsNativeBookmarkModelLoaded; return nativeGetChildAt(mNativeBookmarksBridge, folderId.getId(), folderId.getType(), index); } /** * @return All bookmark IDs ordered by descending creation date. */ public List<BookmarkId> getAllBookmarkIDsOrderedByCreationDate() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetAllBookmarkIDsOrderedByCreationDate(mNativeBookmarksBridge, result); return result; } /** * Set title of the given bookmark. */ public void setBookmarkTitle(BookmarkId id, String title) { assert mIsNativeBookmarkModelLoaded; nativeSetBookmarkTitle(mNativeBookmarksBridge, id.getId(), id.getType(), title); } /** * Set URL of the given bookmark. */ public void setBookmarkUrl(BookmarkId id, String url) { assert mIsNativeBookmarkModelLoaded; nativeSetBookmarkUrl(mNativeBookmarksBridge, id.getId(), id.getType(), url); } /** * @return Whether the given bookmark exist in the current bookmark model, e.g., not deleted. */ public boolean doesBookmarkExist(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; return nativeDoesBookmarkExist(mNativeBookmarksBridge, id.getId(), id.getType()); } /** * Fetches the bookmarks of the given folder. This is an always-synchronous version of another * getBookmarksForForder function. * * @param folderId The parent folder id. * @return Bookmarks of the given folder. */ public List<BookmarkItem> getBookmarksForFolder(BookmarkId folderId) { assert mIsNativeBookmarkModelLoaded; List<BookmarkItem> result = new ArrayList<BookmarkItem>(); nativeGetBookmarksForFolder(mNativeBookmarksBridge, folderId, null, result); return result; } /** * Fetches the bookmarks of the current folder. Callback will be * synchronous if the bookmark model is already loaded and async if it is loaded in the * background. * @param folderId The current folder id. * @param callback Instance of a callback object. */ public void getBookmarksForFolder(BookmarkId folderId, BookmarksCallback callback) { if (mIsNativeBookmarkModelLoaded) { nativeGetBookmarksForFolder(mNativeBookmarksBridge, folderId, callback, new ArrayList<BookmarkItem>()); } else { mDelayedBookmarkCallbacks.add(new DelayedBookmarkCallback(folderId, callback, DelayedBookmarkCallback.GET_BOOKMARKS_FOR_FOLDER, this)); } } /** * Fetches the folder hierarchy of the given folder. Callback will be * synchronous if the bookmark model is already loaded and async if it is loaded in the * background. * @param folderId The current folder id. * @param callback Instance of a callback object. */ public void getCurrentFolderHierarchy(BookmarkId folderId, BookmarksCallback callback) { if (mIsNativeBookmarkModelLoaded) { nativeGetCurrentFolderHierarchy(mNativeBookmarksBridge, folderId, callback, new ArrayList<BookmarkItem>()); } else { mDelayedBookmarkCallbacks.add(new DelayedBookmarkCallback(folderId, callback, DelayedBookmarkCallback.GET_CURRENT_FOLDER_HIERARCHY, this)); } } /** * Deletes a specified bookmark node. * @param bookmarkId The ID of the bookmark to be deleted. */ public void deleteBookmark(BookmarkId bookmarkId) { nativeDeleteBookmark(mNativeBookmarksBridge, bookmarkId); } /** * Move the bookmark to the new index within same folder or to a different folder. * @param bookmarkId The id of the bookmark that is being moved. * @param newParentId The parent folder id. * @param index The new index for the bookmark. */ public void moveBookmark(BookmarkId bookmarkId, BookmarkId newParentId, int index) { nativeMoveBookmark(mNativeBookmarksBridge, bookmarkId, newParentId, index); } /** * Add a new folder to the given parent folder * * @param parent Folder where to add. Must be a normal editable folder, instead of a partner * bookmark folder or a managed bookomark folder or root node of the entire * bookmark model. * @param index The position to locate the new folder * @param title The title text of the new folder * @return Id of the added node. If adding failed (index is invalid, string is null, parent is * not editable), returns null. */ public BookmarkId addFolder(BookmarkId parent, int index, String title) { assert parent.getType() == BookmarkType.NORMAL; assert index >= 0; assert title != null; return nativeAddFolder(mNativeBookmarksBridge, parent, index, title); } /** * Add a new bookmark to a specific position below parent * * @param parent Folder where to add. Must be a normal editable folder, instead of a partner * bookmark folder or a managed bookomark folder or root node of the entire * bookmark model. * @param index The position where the bookmark will be placed in parent folder * @param title Title of the new bookmark * @param url Url of the new bookmark * @return Id of the added node. If adding failed (index is invalid, string is null, parent is * not editable), returns null. */ public BookmarkId addBookmark(BookmarkId parent, int index, String title, String url) { assert parent.getType() == BookmarkType.NORMAL; assert index >= 0; assert title != null; assert url != null; return nativeAddBookmark(mNativeBookmarksBridge, parent, index, title, url); } /** * Undo the last undoable action on the top of the bookmark undo stack */ public void undo() { nativeUndo(mNativeBookmarksBridge); } /** * Start grouping actions for a single undo operation * Note: This only works with BookmarkModel, not partner bookmarks. */ public void startGroupingUndos() { nativeStartGroupingUndos(mNativeBookmarksBridge); } /** * End grouping actions for a single undo operation * Note: This only works with BookmarkModel, not partner bookmarks. */ public void endGroupingUndos() { nativeEndGroupingUndos(mNativeBookmarksBridge); } public static boolean isEditBookmarksEnabled() { return nativeIsEditBookmarksEnabled(); } public static boolean isEnhancedBookmarksEnabled(Profile profile) { return nativeIsEnhancedBookmarksFeatureEnabled(profile); } @CalledByNative private void bookmarkModelLoaded() { mIsNativeBookmarkModelLoaded = true; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkModelLoaded(); } if (!mDelayedBookmarkCallbacks.isEmpty()) { for (int i = 0; i < mDelayedBookmarkCallbacks.size(); i++) { mDelayedBookmarkCallbacks.get(i).callCallbackMethod(); } mDelayedBookmarkCallbacks.clear(); } } @CalledByNative private void bookmarkModelDeleted() { destroy(); } @CalledByNative private void bookmarkNodeMoved( BookmarkItem oldParent, int oldIndex, BookmarkItem newParent, int newIndex) { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeMoved(oldParent, oldIndex, newParent, newIndex); } } @CalledByNative private void bookmarkNodeAdded(BookmarkItem parent, int index) { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeAdded(parent, index); } } @CalledByNative private void bookmarkNodeRemoved(BookmarkItem parent, int oldIndex, BookmarkItem node) { for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeRemoved(parent, oldIndex, node, mIsDoingExtensiveChanges); } } @CalledByNative private void bookmarkNodeChanged(BookmarkItem node) { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeChanged(node); } } @CalledByNative private void bookmarkNodeChildrenReordered(BookmarkItem node) { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeChildrenReordered(node); } } @CalledByNative private void extensiveBookmarkChangesBeginning() { mIsDoingExtensiveChanges = true; } @CalledByNative private void extensiveBookmarkChangesEnded() { mIsDoingExtensiveChanges = false; bookmarkModelChanged(); } @CalledByNative private void bookmarkModelChanged() { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkModelChanged(); } } @CalledByNative private static BookmarkItem createBookmarkItem(long id, int type, String title, String url, boolean isFolder, long parentId, int parentIdType, boolean isEditable, boolean isManaged) { return new BookmarkItem(new BookmarkId(id, type), title, url, isFolder, new BookmarkId(parentId, parentIdType), isEditable, isManaged); } @CalledByNative private static void addToList(List<BookmarkItem> bookmarksList, BookmarkItem bookmark) { bookmarksList.add(bookmark); } @CalledByNative private static void addToBookmarkIdList(List<BookmarkId> bookmarkIdList, long id, int type) { bookmarkIdList.add(new BookmarkId(id, type)); } @CalledByNative private static void addToBookmarkIdListWithDepth(List<BookmarkId> folderList, long id, int type, List<Integer> depthList, int depth) { folderList.add(new BookmarkId(id, type)); depthList.add(depth); } @CalledByNative private static BookmarkId createBookmarkId(long id, int type) { return new BookmarkId(id, type); } private native BookmarkItem nativeGetBookmarkByID(long nativeBookmarksBridge, long id, int type); private native void nativeGetPermanentNodeIDs(long nativeBookmarksBridge, List<BookmarkId> bookmarksList); private native void nativeGetTopLevelFolderParentIDs(long nativeBookmarksBridge, List<BookmarkId> bookmarksList); private native void nativeGetTopLevelFolderIDs(long nativeBookmarksBridge, boolean getSpecial, boolean getNormal, List<BookmarkId> bookmarksList); private native void nativeGetUncategorizedBookmarkIDs(long nativeBookmarksBridge, List<BookmarkId> bookmarksList); private native void nativeGetAllFoldersWithDepths(long nativeBookmarksBridge, List<BookmarkId> folderList, List<Integer> depthList); private native BookmarkId nativeGetMobileFolderId(long nativeBookmarksBridge); private native BookmarkId nativeGetOtherFolderId(long nativeBookmarksBridge); private native BookmarkId nativeGetDesktopFolderId(long nativeBookmarksBridge); private native void nativeGetChildIDs(long nativeBookmarksBridge, long id, int type, boolean getFolders, boolean getBookmarks, List<BookmarkId> bookmarksList); private native BookmarkId nativeGetChildAt(long nativeBookmarksBridge, long id, int type, int index); private native void nativeGetAllBookmarkIDsOrderedByCreationDate(long nativeBookmarksBridge, List<BookmarkId> result); private native void nativeSetBookmarkTitle(long nativeBookmarksBridge, long id, int type, String title); private native void nativeSetBookmarkUrl(long nativeBookmarksBridge, long id, int type, String url); private native boolean nativeDoesBookmarkExist(long nativeBookmarksBridge, long id, int type); private native void nativeGetBookmarksForFolder(long nativeBookmarksBridge, BookmarkId folderId, BookmarksCallback callback, List<BookmarkItem> bookmarksList); private native void nativeGetCurrentFolderHierarchy(long nativeBookmarksBridge, BookmarkId folderId, BookmarksCallback callback, List<BookmarkItem> bookmarksList); private native BookmarkId nativeAddFolder(long nativeBookmarksBridge, BookmarkId parent, int index, String title); private native void nativeDeleteBookmark(long nativeBookmarksBridge, BookmarkId bookmarkId); private native void nativeMoveBookmark(long nativeBookmarksBridge, BookmarkId bookmarkId, BookmarkId newParentId, int index); private native BookmarkId nativeAddBookmark(long nativeBookmarksBridge, BookmarkId parent, int index, String title, String url); private native void nativeUndo(long nativeBookmarksBridge); private native void nativeStartGroupingUndos(long nativeBookmarksBridge); private native void nativeEndGroupingUndos(long nativeBookmarksBridge); private static native boolean nativeIsEnhancedBookmarksFeatureEnabled(Profile profile); private native void nativeLoadEmptyPartnerBookmarkShimForTesting(long nativeBookmarksBridge); private native long nativeInit(Profile profile); private native boolean nativeIsDoingExtensiveChanges(long nativeBookmarksBridge); private native void nativeDestroy(long nativeBookmarksBridge); private static native boolean nativeIsEditBookmarksEnabled(); /** * Simple object representing the bookmark item. */ public static class BookmarkItem { private final String mTitle; private final String mUrl; private final BookmarkId mId; private final boolean mIsFolder; private final BookmarkId mParentId; private final boolean mIsEditable; private final boolean mIsManaged; private BookmarkItem(BookmarkId id, String title, String url, boolean isFolder, BookmarkId parentId, boolean isEditable, boolean isManaged) { mId = id; mTitle = title; mUrl = url; mIsFolder = isFolder; mParentId = parentId; mIsEditable = isEditable; mIsManaged = isManaged; } /** @return Title of the bookmark item. */ public String getTitle() { return mTitle; } /** @return Url of the bookmark item. */ public String getUrl() { return mUrl; } /** @return Id of the bookmark item. */ public BookmarkId getId() { return mId; } /** @return Whether item is a folder or a bookmark. */ public boolean isFolder() { return mIsFolder; } /** @return Parent id of the bookmark item. */ public BookmarkId getParentId() { return mParentId; } /** @return Whether this bookmark can be edited. */ public boolean isEditable() { return mIsEditable; } /** @return Whether this is a managed bookmark. */ public boolean isManaged() { return mIsManaged; } } /** * Details about callbacks that need to be called once the bookmark model has loaded. */ private static class DelayedBookmarkCallback { private static final int GET_BOOKMARKS_FOR_FOLDER = 0; private static final int GET_CURRENT_FOLDER_HIERARCHY = 1; private final BookmarksCallback mCallback; private final BookmarkId mFolderId; private final int mCallbackMethod; private final BookmarksBridge mHandler; private DelayedBookmarkCallback(BookmarkId folderId, BookmarksCallback callback, int method, BookmarksBridge handler) { mFolderId = folderId; mCallback = callback; mCallbackMethod = method; mHandler = handler; } /** * Invoke the callback method. */ private void callCallbackMethod() { switch (mCallbackMethod) { case GET_BOOKMARKS_FOR_FOLDER: mHandler.getBookmarksForFolder(mFolderId, mCallback); break; case GET_CURRENT_FOLDER_HIERARCHY: mHandler.getCurrentFolderHierarchy(mFolderId, mCallback); break; default: assert false; break; } } } }
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.ArrayWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class PopularityLeague extends Configured implements Tool { public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new PopularityLeague(), args); System.exit(res); } public static class IntArrayWritable extends ArrayWritable { public IntArrayWritable() { super(IntWritable.class); } public IntArrayWritable(Integer[] numbers) { super(IntWritable.class); IntWritable[] ints = new IntWritable[numbers.length]; for (int i = 0; i < numbers.length; i++) { ints[i] = new IntWritable(numbers[i]); } set(ints); } } @Override public int run(String[] args) throws Exception { Configuration conf = this.getConf(); FileSystem fs = FileSystem.get(conf); Path linkCountsTmpPath = new Path("/mp2/tmp/linkCounts"); Path ranksTmpPath = new Path("/mp2/tmp/linkRanks"); Path inputPaths = new Path(args[0]); Path resultPath = new Path(args[1]); // clean all directories fs.delete(linkCountsTmpPath, true); fs.delete(ranksTmpPath, true); fs.delete(resultPath, true); // Link Count Job Configuration Job linkJob = Job.getInstance(conf, "Popularity League"); linkJob.setOutputKeyClass(IntWritable.class); linkJob.setOutputValueClass(IntWritable.class); linkJob.setMapperClass(LinkCountMap.class); linkJob.setReducerClass(LinkCountReduce.class); FileInputFormat.setInputPaths(linkJob, inputPaths); FileOutputFormat.setOutputPath(linkJob, linkCountsTmpPath); linkJob.setJarByClass(PopularityLeague.class); linkJob.waitForCompletion(true); // Link Ranking Job Configuration Job rankJob = Job.getInstance(conf, "Popularity League"); rankJob.setOutputKeyClass(IntWritable.class); rankJob.setOutputValueClass(IntWritable.class); rankJob.setMapOutputKeyClass(NullWritable.class); rankJob.setMapOutputValueClass(IntArrayWritable.class); rankJob.setMapperClass(TopLinksMap.class); rankJob.setReducerClass(TopLinksReduce.class); rankJob.setNumReduceTasks(1); FileInputFormat.setInputPaths(rankJob, linkCountsTmpPath); FileOutputFormat.setOutputPath(rankJob, ranksTmpPath); rankJob.setInputFormatClass(KeyValueTextInputFormat.class); rankJob.setOutputFormatClass(TextOutputFormat.class); rankJob.setJarByClass(PopularityLeague.class); rankJob.waitForCompletion(true); // League Job Configuration Job leagueJob = Job.getInstance(conf, "Popularity League"); leagueJob.setOutputKeyClass(IntWritable.class); leagueJob.setOutputValueClass(IntWritable.class); leagueJob.setMapOutputKeyClass(NullWritable.class); leagueJob.setMapOutputValueClass(IntArrayWritable.class); leagueJob.setMapperClass(LeagueRankMap.class); leagueJob.setReducerClass(LeagueRankReduce.class); leagueJob.setNumReduceTasks(1); FileInputFormat.setInputPaths(leagueJob, ranksTmpPath); FileOutputFormat.setOutputPath(leagueJob, resultPath); leagueJob.setInputFormatClass(KeyValueTextInputFormat.class); leagueJob.setOutputFormatClass(TextOutputFormat.class); leagueJob.setJarByClass(PopularityLeague.class); return leagueJob.waitForCompletion(true) ? 0 : 1; } public static String readHDFSFile(String path, Configuration conf) throws IOException{ Path pt = new Path(path); FileSystem fs = FileSystem.get(pt.toUri(), conf); FSDataInputStream file = fs.open(pt); BufferedReader buffIn = new BufferedReader(new InputStreamReader(file)); StringBuilder everything = new StringBuilder(); String line; while( (line = buffIn.readLine()) != null) { everything.append(line); everything.append("\n"); } return everything.toString(); } public static class LinkCountMap extends Mapper<Object, Text, IntWritable, IntWritable> { @Override public void map(Object key, Text line, Context ctxt) throws IOException, InterruptedException { String[] input = line.toString().split(":"); Integer pageId = Integer.parseInt(input[0].replace(':', ' ').trim()); String[] pageLinks = input[1].split(" "); // Flip the format upside down so that each *linked to* // page has a corresponding page that *links* to it. // This method completely excludes orphaned links but since // this is a popularity contest we don't care, and even better, // it makes the reducer dataset smaller for (String linkIdStr : pageLinks) { if (linkIdStr.trim().isEmpty()) continue; Integer linkId = Integer.parseInt(linkIdStr.trim()); ctxt.write(new IntWritable(linkId), new IntWritable(1)); } } } public static class LinkCountReduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> { // we simply need to aggregate the number of counts // this is more of a map than a reduce.. the mapper already reduced // by excluding orphaned pages @Override public void reduce(IntWritable key, Iterable<IntWritable> values, Context ctxt) throws IOException, InterruptedException { Integer linkBackCount = 0; for (IntWritable linkId : values) { linkBackCount += linkId.get(); } ctxt.write(key, new IntWritable(linkBackCount)); } } public static class TopLinksMap extends Mapper<Text, Text, NullWritable, IntArrayWritable> { private TreeSet<Pair<Integer, Integer>> rankMap = new TreeSet<Pair<Integer, Integer>>(); @Override public void map(Text key, Text value, Context ctxt) throws IOException, InterruptedException { Integer count = Integer.parseInt(value.toString()); Integer pageId = Integer.parseInt(key.toString()); // treeset will sort on Key (pair[0]) so count *then* pageId rankMap.add(new Pair<Integer, Integer>(count, pageId)); } @Override protected void cleanup(Context ctxt) throws IOException, InterruptedException { for (Pair<Integer, Integer> itm : rankMap) { Integer[] entry = { itm.first, itm.second }; IntArrayWritable entryArr = new IntArrayWritable(entry); ctxt.write(NullWritable.get(), entryArr); } } } public static class TopLinksReduce extends Reducer<NullWritable, IntArrayWritable, IntWritable, IntWritable> { private TreeSet<Pair<Integer, Integer>> rankMap = new TreeSet<Pair<Integer, Integer>>(); @Override public void reduce(NullWritable key, Iterable<IntArrayWritable> values, Context ctxt) throws IOException, InterruptedException { for (IntArrayWritable val : values) { IntWritable[] rankEntry = (IntWritable[]) val.toArray(); Integer linkBackCount = rankEntry[0].get(); Integer pageId = rankEntry[1].get(); // now that we have a shorter list we want to sort by pageId rankMap.add(new Pair<Integer, Integer>(linkBackCount, pageId)); } for (Pair<Integer, Integer> rankEntry : rankMap.descendingSet()) { IntWritable count = new IntWritable(rankEntry.first); IntWritable pageId = new IntWritable(rankEntry.second); ctxt.write(pageId, count); } } } public static class LeagueRankMap extends Mapper<Text, Text, NullWritable, IntArrayWritable> { ArrayList<Integer> leagues = new ArrayList<Integer>(); private TreeSet<Pair<Integer, Integer>> rankMap = new TreeSet<Pair<Integer, Integer>>(); @Override protected void setup(Context ctxt) throws IOException, InterruptedException { // i. build leagues list Configuration conf = ctxt.getConfiguration(); String leaguePath = conf.get("league"); String[] leagueStrings = readHDFSFile(leaguePath, conf).split("\n"); for (String leagueId : leagueStrings) { if (leagueId.trim().isEmpty()) continue; leagues.add(Integer.parseInt(leagueId.trim())); } } @Override public void map(Text key, Text value, Context ctxt) throws IOException, InterruptedException { // ii. build page link-back ranks from previous reduce, key: pageId, value: linkback count // filtering out everything except league values Integer pageId = Integer.parseInt(key.toString()); Integer count = Integer.parseInt(value.toString()); if (leagues.contains(pageId)) rankMap.add(new Pair<Integer, Integer>(count, pageId)); } @Override protected void cleanup(Context ctxt) throws IOException, InterruptedException { for (Pair<Integer, Integer> rank : rankMap) { Integer[] entry = { rank.first, rank.second }; IntArrayWritable entryArr = new IntArrayWritable(entry); ctxt.write(NullWritable.get(), entryArr); } } } public static class LeagueRankReduce extends Reducer<NullWritable, IntArrayWritable, IntWritable, IntWritable> { private TreeSet<Pair<Integer, Integer>> rankMap = new TreeSet<Pair<Integer, Integer>>(); @Override public void reduce(NullWritable key, Iterable<IntArrayWritable> values, Context ctxt) throws IOException, InterruptedException { // iv. get our full list for processing for (IntArrayWritable val : values) { IntWritable[] rankEntry = (IntWritable[]) val.toArray(); Integer pageId = rankEntry[1].get(); Integer linkBackCount = rankEntry[0].get(); rankMap.add(new Pair<Integer, Integer>(linkBackCount, pageId)); } // v. do the rank calculation & sort via rankMap where pair = {count, pageId} // note that rankMap.descendingSet() will return ranks from highest link count // to lowest link count TreeSet<Pair<Integer, Integer>> pageRankMap = new TreeSet<Pair<Integer, Integer>>(); for (Pair<Integer, Integer> entry : rankMap) { // if we take the subset of a sorted set in desc. order from this // element to the bottom, the size of such set represents how many // elements we have that are lower than this one. // When we are at the bottom we will be getting the subset from // this to this so it will be zero // TODO this doesn't account for two entries with the same count // but otherwise.. it's a nice solution // Integer rank = rankMap.size() - rankMap.subSet(entry, rankMap.last()).size() - 1; Integer pageId = entry.second; Integer rank = 0; // we only need to check on this element and down since the list is already // sorted by count descending for (Pair<Integer, Integer> itrEntry : rankMap) { if (itrEntry.first < entry.first) rank += 1; } ctxt.write(new IntWritable(pageId), new IntWritable(rank)); } } } } class Pair<A extends Comparable<? super A>, B extends Comparable<? super B>> implements Comparable<Pair<A, B>> { public final A first; public final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public static <A extends Comparable<? super A>, B extends Comparable<? super B>> Pair<A, B> of(A first, B second) { return new Pair<A, B>(first, second); } @Override public int compareTo(Pair<A, B> o) { int cmp = o == null ? 1 : (this.first).compareTo(o.first); return cmp == 0 ? (this.second).compareTo(o.second) : cmp; } @Override public int hashCode() { return 31 * hashcode(first) + hashcode(second); } private static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; if (this == obj) return true; return equal(first, ((Pair<?, ?>) obj).first) && equal(second, ((Pair<?, ?>) obj).second); } private boolean equal(Object o1, Object o2) { return o1 == o2 || (o1 != null && o1.equals(o2)); } @Override public String toString() { return "(" + first + ", " + second + ')'; } }
package org.chromium.chrome.browser; import org.chromium.base.CalledByNative; import org.chromium.base.ObserverList; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.components.bookmarks.BookmarkType; import java.util.ArrayList; import java.util.List; /** * Provides the communication channel for Android to fetch and manipulate the * bookmark model stored in native. */ public class BookmarksBridge { private final Profile mProfile; private boolean mIsDoingExtensiveChanges; private long mNativeBookmarksBridge; private boolean mIsNativeBookmarkModelLoaded; private final List<DelayedBookmarkCallback> mDelayedBookmarkCallbacks = new ArrayList<DelayedBookmarkCallback>(); private final ObserverList<BookmarkModelObserver> mObservers = new ObserverList<BookmarkModelObserver>(); /** * Interface for callback object for fetching bookmarks and folder hierarchy. */ public interface BookmarksCallback { /** * Callback method for fetching bookmarks for a folder and the folder hierarchy. * @param folderId The folder id to which the bookmarks belong. * @param bookmarksList List holding the fetched bookmarks and details. */ @CalledByNative("BookmarksCallback") void onBookmarksAvailable(BookmarkId folderId, List<BookmarkItem> bookmarksList); /** * Callback method for fetching the folder hierarchy. * @param folderId The folder id to which the bookmarks belong. * @param bookmarksList List holding the fetched folder details. */ @CalledByNative("BookmarksCallback") void onBookmarksFolderHierarchyAvailable(BookmarkId folderId, List<BookmarkItem> bookmarksList); } /** * Base empty implementation observer class that provides listeners to be notified of changes * to the bookmark model. It's mandatory to implement one method, bookmarkModelChanged. Other * methods are optional and if they aren't overridden, the default implementation of them will * eventually call bookmarkModelChanged. Unless noted otherwise, all the functions won't be * called during extensive change. */ public abstract static class BookmarkModelObserver { /** * Invoked when a node has moved. * @param oldParent The parent before the move. * @param oldIndex The index of the node in the old parent. * @param newParent The parent after the move. * @param newIndex The index of the node in the new parent. */ public void bookmarkNodeMoved( BookmarkItem oldParent, int oldIndex, BookmarkItem newParent, int newIndex) { bookmarkModelChanged(); } /** * Invoked when a node has been added. * @param parent The parent of the node being added. * @param index The index of the added node. */ public void bookmarkNodeAdded(BookmarkItem parent, int index) { bookmarkModelChanged(); } /** * Invoked when a node has been removed, the item may still be starred though. This can * be called during extensive change, and have the flag argument indicating it. * @param parent The parent of the node that was removed. * @param oldIndex The index of the removed node in the parent before it was removed. * @param node The node that was removed. * @param isDoingExtensiveChanges whether extensive changes are happening. */ public void bookmarkNodeRemoved(BookmarkItem parent, int oldIndex, BookmarkItem node, boolean isDoingExtensiveChanges) { if (isDoingExtensiveChanges) return; bookmarkNodeRemoved(parent, oldIndex, node); } /** * Invoked when a node has been removed, the item may still be starred though. * * @param parent The parent of the node that was removed. * @param oldIndex The index of the removed node in the parent before it was removed. * @param node The node that was removed. */ public void bookmarkNodeRemoved(BookmarkItem parent, int oldIndex, BookmarkItem node) { bookmarkModelChanged(); } /** * Invoked when the title or url of a node changes. * @param node The node being changed. */ public void bookmarkNodeChanged(BookmarkItem node) { bookmarkModelChanged(); } /** * Invoked when the children (just direct children, not descendants) of a node have been * reordered in some way, such as sorted. * @param node The node whose children are being reordered. */ public void bookmarkNodeChildrenReordered(BookmarkItem node) { bookmarkModelChanged(); } /** * Called when the native side of bookmark is loaded and now in usable state. */ public void bookmarkModelLoaded() { bookmarkModelChanged(); } /** * Called when there are changes to the bookmark model that don't trigger any of the other * callback methods or it wasn't handled by other callback methods. * Examples: * - On partner bookmarks change. * - On extensive change finished. * - Falling back from other methods that are not overridden in this class. */ public abstract void bookmarkModelChanged(); } /** * Handler to fetch the bookmarks, titles, urls and folder hierarchy. * @param profile Profile instance corresponding to the active profile. */ public BookmarksBridge(Profile profile) { mProfile = profile; mNativeBookmarksBridge = nativeInit(profile); mIsDoingExtensiveChanges = nativeIsDoingExtensiveChanges(mNativeBookmarksBridge); } /** * Destroys this instance so no further calls can be executed. */ public void destroy() { if (mNativeBookmarksBridge != 0) { nativeDestroy(mNativeBookmarksBridge); mNativeBookmarksBridge = 0; mIsNativeBookmarkModelLoaded = false; mDelayedBookmarkCallbacks.clear(); } mObservers.clear(); } /** * Load an empty partner bookmark shim for testing. The root node for bookmark will be an * empty node. */ @VisibleForTesting public void loadEmptyPartnerBookmarkShimForTesting() { nativeLoadEmptyPartnerBookmarkShimForTesting(mNativeBookmarksBridge); } /** * Add an observer to bookmark model changes. * @param observer The observer to be added. */ public void addObserver(BookmarkModelObserver observer) { mObservers.addObserver(observer); } /** * Remove an observer of bookmark model changes. * @param observer The observer to be removed. */ public void removeObserver(BookmarkModelObserver observer) { mObservers.removeObserver(observer); } /** * @return Whether or not the underlying bookmark model is loaded. */ public boolean isBookmarkModelLoaded() { return mIsNativeBookmarkModelLoaded; } /** * @return A BookmarkItem instance for the given BookmarkId. */ public BookmarkItem getBookmarkById(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; return nativeGetBookmarkByID(mNativeBookmarksBridge, id.getId(), id.getType()); } /** * @return All the permanent nodes. */ public List<BookmarkId> getPermanentNodeIDs() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetPermanentNodeIDs(mNativeBookmarksBridge, result); return result; } /** * @return The top level folder's parents, which are root node, mobile node, and other node. */ public List<BookmarkId> getTopLevelFolderParentIDs() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetTopLevelFolderParentIDs(mNativeBookmarksBridge, result); return result; } /** * @param getSpecial Whether special top folders should be returned. * @param getNormal Whether normal top folders should be returned. * @return The top level folders. Note that special folders come first and normal top folders * will be in the alphabetical order. Special top folders are managed bookmark and * partner bookmark. Normal top folders are desktop permanent folder, and the * sub-folders of mobile permanent folder and others permanent folder. */ public List<BookmarkId> getTopLevelFolderIDs(boolean getSpecial, boolean getNormal) { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetTopLevelFolderIDs(mNativeBookmarksBridge, getSpecial, getNormal, result); return result; } /** * @return The uncategorized bookmark IDs. They are direct descendant bookmarks of mobile and * other folders. */ public List<BookmarkId> getUncategorizedBookmarkIDs() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetUncategorizedBookmarkIDs(mNativeBookmarksBridge, result); return result; } /** * Populates folderList with BookmarkIds of folders users can move bookmarks * to and all folders have corresponding depth value in depthList. Folders * having depths of 0 will be shown as top-layered folders. These include * "Desktop Folder" itself as well as all children of "mobile" and "other". * Children of 0-depth folders have depth of 1, and so on. * * The result list will be sorted alphabetically by title. "mobile", "other", * root node, managed folder, partner folder are NOT included as results. */ public void getAllFoldersWithDepths(List<BookmarkId> folderList, List<Integer> depthList) { assert mIsNativeBookmarkModelLoaded; nativeGetAllFoldersWithDepths(mNativeBookmarksBridge, folderList, depthList); } /** * @return The BookmarkId for Mobile folder node */ public BookmarkId getMobileFolderId() { assert mIsNativeBookmarkModelLoaded; return nativeGetMobileFolderId(mNativeBookmarksBridge); } /** * @return Id representing the special "other" folder from bookmark model. */ public BookmarkId getOtherFolderId() { assert mIsNativeBookmarkModelLoaded; return nativeGetOtherFolderId(mNativeBookmarksBridge); } /** * @return BokmarkId representing special "desktop" folder, namely "bookmark bar". */ @VisibleForTesting public BookmarkId getDesktopFolderId() { assert mIsNativeBookmarkModelLoaded; return nativeGetDesktopFolderId(mNativeBookmarksBridge); } /** * Reads sub-folder IDs, sub-bookmark IDs, or both of the given folder. * * @param getFolders Whether sub-folders should be returned. * @param getBookmarks Whether sub-bookmarks should be returned. * @return Child IDs of the given folder, with the specified type. */ public List<BookmarkId> getChildIDs(BookmarkId id, boolean getFolders, boolean getBookmarks) { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetChildIDs(mNativeBookmarksBridge, id.getId(), id.getType(), getFolders, getBookmarks, result); return result; } /** * Gets the child of a folder at the specific position. * @param folderId Id of the parent folder * @param index Posision of child among all children in folder * @return BookmarkId of the child, which will be null if folderId does not point to a folder or * index is invalid. */ public BookmarkId getChildAt(BookmarkId folderId, int index) { assert mIsNativeBookmarkModelLoaded; return nativeGetChildAt(mNativeBookmarksBridge, folderId.getId(), folderId.getType(), index); } /** * @return All bookmark IDs ordered by descending creation date. */ public List<BookmarkId> getAllBookmarkIDsOrderedByCreationDate() { assert mIsNativeBookmarkModelLoaded; List<BookmarkId> result = new ArrayList<BookmarkId>(); nativeGetAllBookmarkIDsOrderedByCreationDate(mNativeBookmarksBridge, result); return result; } /** * Set title of the given bookmark. */ public void setBookmarkTitle(BookmarkId id, String title) { assert mIsNativeBookmarkModelLoaded; nativeSetBookmarkTitle(mNativeBookmarksBridge, id.getId(), id.getType(), title); } /** * Set URL of the given bookmark. */ public void setBookmarkUrl(BookmarkId id, String url) { assert mIsNativeBookmarkModelLoaded; nativeSetBookmarkUrl(mNativeBookmarksBridge, id.getId(), id.getType(), url); } /** * @return Whether the given bookmark exist in the current bookmark model, e.g., not deleted. */ public boolean doesBookmarkExist(BookmarkId id) { assert mIsNativeBookmarkModelLoaded; return nativeDoesBookmarkExist(mNativeBookmarksBridge, id.getId(), id.getType()); } /** * Fetches the bookmarks of the given folder. This is an always-synchronous version of another * getBookmarksForForder function. * * @param folderId The parent folder id. * @return Bookmarks of the given folder. */ public List<BookmarkItem> getBookmarksForFolder(BookmarkId folderId) { assert mIsNativeBookmarkModelLoaded; List<BookmarkItem> result = new ArrayList<BookmarkItem>(); nativeGetBookmarksForFolder(mNativeBookmarksBridge, folderId, null, result); return result; } /** * Fetches the bookmarks of the current folder. Callback will be * synchronous if the bookmark model is already loaded and async if it is loaded in the * background. * @param folderId The current folder id. * @param callback Instance of a callback object. */ public void getBookmarksForFolder(BookmarkId folderId, BookmarksCallback callback) { if (mIsNativeBookmarkModelLoaded) { nativeGetBookmarksForFolder(mNativeBookmarksBridge, folderId, callback, new ArrayList<BookmarkItem>()); } else { mDelayedBookmarkCallbacks.add(new DelayedBookmarkCallback(folderId, callback, DelayedBookmarkCallback.GET_BOOKMARKS_FOR_FOLDER, this)); } } /** * Fetches the folder hierarchy of the given folder. Callback will be * synchronous if the bookmark model is already loaded and async if it is loaded in the * background. * @param folderId The current folder id. * @param callback Instance of a callback object. */ public void getCurrentFolderHierarchy(BookmarkId folderId, BookmarksCallback callback) { if (mIsNativeBookmarkModelLoaded) { nativeGetCurrentFolderHierarchy(mNativeBookmarksBridge, folderId, callback, new ArrayList<BookmarkItem>()); } else { mDelayedBookmarkCallbacks.add(new DelayedBookmarkCallback(folderId, callback, DelayedBookmarkCallback.GET_CURRENT_FOLDER_HIERARCHY, this)); } } /** * Deletes a specified bookmark node. * @param bookmarkId The ID of the bookmark to be deleted. */ public void deleteBookmark(BookmarkId bookmarkId) { nativeDeleteBookmark(mNativeBookmarksBridge, bookmarkId); } /** * Move the bookmark to the new index within same folder or to a different folder. * @param bookmarkId The id of the bookmark that is being moved. * @param newParentId The parent folder id. * @param index The new index for the bookmark. */ public void moveBookmark(BookmarkId bookmarkId, BookmarkId newParentId, int index) { nativeMoveBookmark(mNativeBookmarksBridge, bookmarkId, newParentId, index); } /** * Add a new folder to the given parent folder * * @param parent Folder where to add. Must be a normal editable folder, instead of a partner * bookmark folder or a managed bookomark folder or root node of the entire * bookmark model. * @param index The position to locate the new folder * @param title The title text of the new folder * @return Id of the added node. If adding failed (index is invalid, string is null, parent is * not editable), returns null. */ public BookmarkId addFolder(BookmarkId parent, int index, String title) { assert parent.getType() == BookmarkType.BOOKMARK_TYPE_NORMAL; assert index >= 0; assert title != null; return nativeAddFolder(mNativeBookmarksBridge, parent, index, title); } /** * Add a new bookmark to a specific position below parent * * @param parent Folder where to add. Must be a normal editable folder, instead of a partner * bookmark folder or a managed bookomark folder or root node of the entire * bookmark model. * @param index The position where the bookmark will be placed in parent folder * @param title Title of the new bookmark * @param url Url of the new bookmark * @return Id of the added node. If adding failed (index is invalid, string is null, parent is * not editable), returns null. */ public BookmarkId addBookmark(BookmarkId parent, int index, String title, String url) { assert parent.getType() == BookmarkType.BOOKMARK_TYPE_NORMAL; assert index >= 0; assert title != null; assert url != null; return nativeAddBookmark(mNativeBookmarksBridge, parent, index, title, url); } /** * Undo the last undoable action on the top of the bookmark undo stack */ public void undo() { nativeUndo(mNativeBookmarksBridge); } /** * Start grouping actions for a single undo operation * Note: This only works with BookmarkModel, not partner bookmarks. */ public void startGroupingUndos() { nativeStartGroupingUndos(mNativeBookmarksBridge); } /** * End grouping actions for a single undo operation * Note: This only works with BookmarkModel, not partner bookmarks. */ public void endGroupingUndos() { nativeEndGroupingUndos(mNativeBookmarksBridge); } public static boolean isEditBookmarksEnabled() { return nativeIsEditBookmarksEnabled(); } public static boolean isEnhancedBookmarksEnabled(Profile profile) { return nativeIsEnhancedBookmarksFeatureEnabled(profile); } @CalledByNative private void bookmarkModelLoaded() { mIsNativeBookmarkModelLoaded = true; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkModelLoaded(); } if (!mDelayedBookmarkCallbacks.isEmpty()) { for (int i = 0; i < mDelayedBookmarkCallbacks.size(); i++) { mDelayedBookmarkCallbacks.get(i).callCallbackMethod(); } mDelayedBookmarkCallbacks.clear(); } } @CalledByNative private void bookmarkModelDeleted() { destroy(); } @CalledByNative private void bookmarkNodeMoved( BookmarkItem oldParent, int oldIndex, BookmarkItem newParent, int newIndex) { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeMoved(oldParent, oldIndex, newParent, newIndex); } } @CalledByNative private void bookmarkNodeAdded(BookmarkItem parent, int index) { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeAdded(parent, index); } } @CalledByNative private void bookmarkNodeRemoved(BookmarkItem parent, int oldIndex, BookmarkItem node) { for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeRemoved(parent, oldIndex, node, mIsDoingExtensiveChanges); } } @CalledByNative private void bookmarkNodeChanged(BookmarkItem node) { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeChanged(node); } } @CalledByNative private void bookmarkNodeChildrenReordered(BookmarkItem node) { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkNodeChildrenReordered(node); } } @CalledByNative private void extensiveBookmarkChangesBeginning() { mIsDoingExtensiveChanges = true; } @CalledByNative private void extensiveBookmarkChangesEnded() { mIsDoingExtensiveChanges = false; bookmarkModelChanged(); } @CalledByNative private void bookmarkModelChanged() { if (mIsDoingExtensiveChanges) return; for (BookmarkModelObserver observer : mObservers) { observer.bookmarkModelChanged(); } } @CalledByNative private static BookmarkItem createBookmarkItem(long id, int type, String title, String url, boolean isFolder, long parentId, int parentIdType, boolean isEditable, boolean isManaged) { return new BookmarkItem(new BookmarkId(id, type), title, url, isFolder, new BookmarkId(parentId, parentIdType), isEditable, isManaged); } @CalledByNative private static void addToList(List<BookmarkItem> bookmarksList, BookmarkItem bookmark) { bookmarksList.add(bookmark); } @CalledByNative private static void addToBookmarkIdList(List<BookmarkId> bookmarkIdList, long id, int type) { bookmarkIdList.add(new BookmarkId(id, type)); } @CalledByNative private static void addToBookmarkIdListWithDepth(List<BookmarkId> folderList, long id, int type, List<Integer> depthList, int depth) { folderList.add(new BookmarkId(id, type)); depthList.add(depth); } @CalledByNative private static BookmarkId createBookmarkId(long id, int type) { return new BookmarkId(id, type); } private native BookmarkItem nativeGetBookmarkByID(long nativeBookmarksBridge, long id, int type); private native void nativeGetPermanentNodeIDs(long nativeBookmarksBridge, List<BookmarkId> bookmarksList); private native void nativeGetTopLevelFolderParentIDs(long nativeBookmarksBridge, List<BookmarkId> bookmarksList); private native void nativeGetTopLevelFolderIDs(long nativeBookmarksBridge, boolean getSpecial, boolean getNormal, List<BookmarkId> bookmarksList); private native void nativeGetUncategorizedBookmarkIDs(long nativeBookmarksBridge, List<BookmarkId> bookmarksList); private native void nativeGetAllFoldersWithDepths(long nativeBookmarksBridge, List<BookmarkId> folderList, List<Integer> depthList); private native BookmarkId nativeGetMobileFolderId(long nativeBookmarksBridge); private native BookmarkId nativeGetOtherFolderId(long nativeBookmarksBridge); private native BookmarkId nativeGetDesktopFolderId(long nativeBookmarksBridge); private native void nativeGetChildIDs(long nativeBookmarksBridge, long id, int type, boolean getFolders, boolean getBookmarks, List<BookmarkId> bookmarksList); private native BookmarkId nativeGetChildAt(long nativeBookmarksBridge, long id, int type, int index); private native void nativeGetAllBookmarkIDsOrderedByCreationDate(long nativeBookmarksBridge, List<BookmarkId> result); private native void nativeSetBookmarkTitle(long nativeBookmarksBridge, long id, int type, String title); private native void nativeSetBookmarkUrl(long nativeBookmarksBridge, long id, int type, String url); private native boolean nativeDoesBookmarkExist(long nativeBookmarksBridge, long id, int type); private native void nativeGetBookmarksForFolder(long nativeBookmarksBridge, BookmarkId folderId, BookmarksCallback callback, List<BookmarkItem> bookmarksList); private native void nativeGetCurrentFolderHierarchy(long nativeBookmarksBridge, BookmarkId folderId, BookmarksCallback callback, List<BookmarkItem> bookmarksList); private native BookmarkId nativeAddFolder(long nativeBookmarksBridge, BookmarkId parent, int index, String title); private native void nativeDeleteBookmark(long nativeBookmarksBridge, BookmarkId bookmarkId); private native void nativeMoveBookmark(long nativeBookmarksBridge, BookmarkId bookmarkId, BookmarkId newParentId, int index); private native BookmarkId nativeAddBookmark(long nativeBookmarksBridge, BookmarkId parent, int index, String title, String url); private native void nativeUndo(long nativeBookmarksBridge); private native void nativeStartGroupingUndos(long nativeBookmarksBridge); private native void nativeEndGroupingUndos(long nativeBookmarksBridge); private static native boolean nativeIsEnhancedBookmarksFeatureEnabled(Profile profile); private native void nativeLoadEmptyPartnerBookmarkShimForTesting(long nativeBookmarksBridge); private native long nativeInit(Profile profile); private native boolean nativeIsDoingExtensiveChanges(long nativeBookmarksBridge); private native void nativeDestroy(long nativeBookmarksBridge); private static native boolean nativeIsEditBookmarksEnabled(); /** * Simple object representing the bookmark item. */ public static class BookmarkItem { private final String mTitle; private final String mUrl; private final BookmarkId mId; private final boolean mIsFolder; private final BookmarkId mParentId; private final boolean mIsEditable; private final boolean mIsManaged; private BookmarkItem(BookmarkId id, String title, String url, boolean isFolder, BookmarkId parentId, boolean isEditable, boolean isManaged) { mId = id; mTitle = title; mUrl = url; mIsFolder = isFolder; mParentId = parentId; mIsEditable = isEditable; mIsManaged = isManaged; } /** @return Title of the bookmark item. */ public String getTitle() { return mTitle; } /** @return Url of the bookmark item. */ public String getUrl() { return mUrl; } /** @return Id of the bookmark item. */ public BookmarkId getId() { return mId; } /** @return Whether item is a folder or a bookmark. */ public boolean isFolder() { return mIsFolder; } /** @return Parent id of the bookmark item. */ public BookmarkId getParentId() { return mParentId; } /** @return Whether this bookmark can be edited. */ public boolean isEditable() { return mIsEditable; } /** @return Whether this is a managed bookmark. */ public boolean isManaged() { return mIsManaged; } } /** * Details about callbacks that need to be called once the bookmark model has loaded. */ private static class DelayedBookmarkCallback { private static final int GET_BOOKMARKS_FOR_FOLDER = 0; private static final int GET_CURRENT_FOLDER_HIERARCHY = 1; private final BookmarksCallback mCallback; private final BookmarkId mFolderId; private final int mCallbackMethod; private final BookmarksBridge mHandler; private DelayedBookmarkCallback(BookmarkId folderId, BookmarksCallback callback, int method, BookmarksBridge handler) { mFolderId = folderId; mCallback = callback; mCallbackMethod = method; mHandler = handler; } /** * Invoke the callback method. */ private void callCallbackMethod() { switch (mCallbackMethod) { case GET_BOOKMARKS_FOR_FOLDER: mHandler.getBookmarksForFolder(mFolderId, mCallback); break; case GET_CURRENT_FOLDER_HIERARCHY: mHandler.getCurrentFolderHierarchy(mFolderId, mCallback); break; default: assert false; break; } } } }
package spelling; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; /** * @author UC San Diego Intermediate MOOC team * */ public class NearbyWords implements SpellingSuggest { // THRESHOLD to determine how many words to look through when looking // for spelling suggestions (stops prohibitively long searching) // For use in the Optional Optimization in Part 2. private static final int THRESHOLD = 1000; Dictionary dict; public NearbyWords (Dictionary dict) { this.dict = dict; } /** Return the list of Strings that are one modification away * from the input string. * @param s The original String * @param wordsOnly controls whether to return only words or any String * @return list of Strings which are nearby the original string */ public List<String> distanceOne(String s, boolean wordsOnly ) { List<String> retList = new ArrayList<String>(); insertions(s, retList, wordsOnly); subsitution(s, retList, wordsOnly); deletions(s, retList, wordsOnly); return retList; } /** Add to the currentList Strings that are one character mutation away * from the input string. * @param s The original String * @param currentList is the list of words to append modified words * @param wordsOnly controls whether to return only words or any String * @return */ public void subsitution(String s, List<String> currentList, boolean wordsOnly) { // for each letter in the s and for all possible replacement characters for(int index = 0; index < s.length(); index++){ for(int charCode = (int)'a'; charCode <= (int)'z'; charCode++) { // use StringBuffer for an easy interface to permuting the // letters in the String StringBuffer sb = new StringBuffer(s); sb.setCharAt(index, (char)charCode); // if the item isn't in the list, isn't the original string, and // (if wordsOnly is true) is a real word, add to the list if(!currentList.contains(sb.toString()) && (!wordsOnly||dict.isWord(sb.toString())) && !s.equals(sb.toString())) { currentList.add(sb.toString()); } } } } /** Add to the currentList Strings that are one character insertion away * from the input string. * @param s The original String * @param currentList is the list of words to append modified words * @param wordsOnly controls whether to return only words or any String * @return */ public void insertions(String s, List<String> currentList, boolean wordsOnly ) { // TODO: Implement this method for(int index = 0; index <= s.length(); index++){ for(int charCode = (int)'a'; charCode <= (int)'z'; charCode++) { // use StringBuffer for an easy interface to permuting the // letters in the String StringBuffer sb = new StringBuffer(s); sb.insert(index, (char)charCode); // if the item isn't in the list, isn't the original string, and // (if wordsOnly is true) is a real word, add to the list if(!currentList.contains(sb.toString()) && (!wordsOnly||dict.isWord(sb.toString())) && !s.equals(sb.toString())) { currentList.add(sb.toString()); } } } } /** Add to the currentList Strings that are one character deletion away * from the input string. * @param s The original String * @param currentList is the list of words to append modified words * @param wordsOnly controls whether to return only words or any String * @return */ public void deletions(String s, List<String> currentList, boolean wordsOnly ) { // DONE: Implement this method StringBuffer sb = new StringBuffer(s); for(int index = 0; index < s.length(); index++){ sb.deleteCharAt(index); if(!currentList.contains(sb.toString()) && (!wordsOnly||dict.isWord(sb.toString())) && !s.equals(sb.toString())) { currentList.add(sb.toString()); } sb = new StringBuffer(s); } } /** Add to the currentList Strings that are one character deletion away * from the input string. * @param word The misspelled word * @param numSuggestions is the maximum number of suggestions to return * @return the list of spelling suggestions */ @Override public List<String> suggestions(String word, int numSuggestions) { // initial variables List<String> queue = new LinkedList<String>(); // String to explore HashSet<String> visited = new HashSet<String>(); // to avoid exploring the same // string multiple times List<String> retList = new LinkedList<String>(); // words to return String curr; List<String> neighbors = new LinkedList<String>(); // List to hold neighbor words boolean words = true; // only return words // insert first node queue.add(word); visited.add(word); while (!queue.isEmpty() && retList.size() < numSuggestions) { curr = queue.remove(0); neighbors = distanceOne(curr, words); for (String permutation : neighbors) { if (!visited.contains(permutation)) { visited.add(permutation); queue.add(queue.size(), permutation); if (dict.isWord(permutation)) { retList.add(permutation); } } } } // TODO: Implement the remainder of this method, see assignment for algorithm return retList; } public static void main(String[] args) { // basic testing code to get started String word = "crest"; // Pass NearbyWords any Dictionary implementation you prefer Dictionary d = new DictionaryHashSet(); DictionaryLoader.loadDictionary(d, "data/dict.txt"); NearbyWords w = new NearbyWords(d); List<String> l = w.distanceOne(word, true); System.out.println("One away word Strings for for \""+word+"\" are:"); System.out.println(l+"\n"); word = "tailo"; List<String> suggest = w.suggestions(word, 10); System.out.println("Spelling Suggestions for \""+word+"\" are:"); System.out.println(suggest); } }
package com.example.gridviewapp; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GridView gridview= (GridView) findViewById(R.id.grid_view); gridview.setAdapter(new ImageAdapter(MainActivity.this)); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent , View v, int poistion, long id) { // TODO Auto-generated method stub Intent i = new Intent(MainActivity.this,SingleActivity.class); i.putExtra("id", poistion); startActivity(i); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package org.jboss.as.cli.handlers; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.CancellationException; import org.jboss.as.cli.CommandArgument; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandFormatException; import org.jboss.as.cli.CommandHandler; import org.jboss.as.cli.CommandLineException; import org.jboss.as.cli.OperationCommand; import org.jboss.as.cli.Util; import org.jboss.as.cli.operation.impl.DefaultCallbackHandler; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.dmr.ModelNode; /** * The operation request handler. * * @author Alexey Loubyansky */ public class OperationRequestHandler implements CommandHandler, OperationCommand { @Override public boolean isBatchMode(CommandContext ctx) { return true; } /* (non-Javadoc) * @see org.jboss.as.cli.CommandHandler#handle(org.jboss.as.cli.CommandContext) */ @Override public void handle(CommandContext ctx) throws CommandLineException { ModelControllerClient client = ctx.getModelControllerClient(); if(client == null) { throw new CommandFormatException("You are disconnected at the moment." + " Type 'connect' to connect to the server" + " or 'help' for the list of supported commands."); } ModelNode request = (ModelNode) ctx.get("OP_REQ"); if(request == null) { throw new CommandLineException("Parsed request isn't available."); } if(ctx.getConfig().isValidateOperationRequests()) { validateRequest(ctx, request); } try { final ModelNode result = client.execute(request); if(Util.isSuccess(result)) { ctx.printLine(result.toString()); } else { throw new CommandLineException(result.toString()); } } catch(NoSuchElementException e) { throw new CommandLineException("ModelNode request is incomplete", e); } catch (CancellationException e) { throw new CommandLineException("The result couldn't be retrieved (perhaps the task was cancelled", e); } catch (IOException e) { ctx.disconnectController(); throw new CommandLineException("Communication error", e); } catch (RuntimeException e) { throw new CommandLineException("Failed to execute operation.", e); } } @Override public boolean isAvailable(CommandContext ctx) { return true; } @Override public ModelNode buildRequest(CommandContext ctx) throws CommandFormatException { return ((DefaultCallbackHandler)ctx.getParsedCommandLine()).toOperationRequest(ctx); } @Override public CommandArgument getArgument(CommandContext ctx, String name) { return null; } @Override public boolean hasArgument(CommandContext ctx, String name) { return false; } @Override public boolean hasArgument(CommandContext ctx, int index) { return false; } @Override public List<CommandArgument> getArguments(CommandContext ctx) { return Collections.emptyList(); } private void validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException { final ModelControllerClient client = ctx.getModelControllerClient(); if(client == null) { throw new CommandFormatException("No connection to the controller."); } final Set<String> keys = request.keys(); if(!keys.contains(Util.OPERATION)) { throw new CommandFormatException("Request is missing the operation name."); } final String operationName = request.get(Util.OPERATION).asString(); if(!keys.contains(Util.ADDRESS)) { throw new CommandFormatException("Request is missing the address part."); } final ModelNode address = request.get(Util.ADDRESS); if(keys.size() == 2) { // no props return; } final ModelNode opDescrReq = new ModelNode(); opDescrReq.get(Util.ADDRESS).set(address); opDescrReq.get(Util.OPERATION).set(Util.READ_OPERATION_DESCRIPTION); opDescrReq.get(Util.NAME).set(operationName); final ModelNode outcome; try { outcome = client.execute(opDescrReq); } catch(Exception e) { throw new CommandFormatException("Failed to perform " + Util.READ_OPERATION_DESCRIPTION + " to validate the request: " + e.getLocalizedMessage()); } if (!Util.isSuccess(outcome)) { throw new CommandFormatException("Failed to get the list of the operation properties: \"" + Util.getFailureDescription(outcome) + '\"'); } if(!outcome.has(Util.RESULT)) { throw new CommandFormatException("Failed to perform " + Util.READ_OPERATION_DESCRIPTION + " to validate the request: result is not available."); } final ModelNode result = outcome.get(Util.RESULT); if(!result.hasDefined(Util.REQUEST_PROPERTIES)) { if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) { throw new CommandFormatException("Operation '" + operationName + "' does not expect any property."); } } else { final Set<String> definedProps = result.get(Util.REQUEST_PROPERTIES).keys(); if(definedProps.isEmpty()) { if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) { throw new CommandFormatException("Operation '" + operationName + "' does not expect any property."); } } int skipped = 0; for(String prop : keys) { if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) { ++skipped; continue; } if(!definedProps.contains(prop)) { if(!Util.OPERATION_HEADERS.equals(prop)) { throw new CommandFormatException("'" + prop + "' is not found among the supported properties: " + definedProps); } } } } } }
package yuku.alkitab.yes2; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import yuku.afw.D; import yuku.alkitab.base.model.Ari; import yuku.alkitab.base.model.Book; import yuku.alkitab.base.model.PericopeBlock; import yuku.alkitab.base.model.SingleChapterVerses; import yuku.alkitab.base.model.Version; import yuku.alkitab.base.storage.BibleReader; import yuku.alkitab.yes2.io.RandomInputStream; import yuku.alkitab.yes2.io.Yes2VerseTextDecoder; import yuku.alkitab.yes2.model.SectionIndex; import yuku.alkitab.yes2.model.Yes2Book; import yuku.alkitab.yes2.section.BooksInfoSection; import yuku.alkitab.yes2.section.PericopesSection; import yuku.alkitab.yes2.section.TextSection; import yuku.alkitab.yes2.section.VersionInfoSection; import yuku.bintex.BintexReader; import yuku.bintex.ValueMap; import yuku.snappy.codec.Snappy; public class Yes2Reader implements BibleReader { private static final String TAG = Yes2Reader.class.getSimpleName(); private RandomInputStream file_; private SectionIndex sectionIndex_; // cached in memory private VersionInfoSection versionInfo_; private PericopesSection pericopesSection_; private TextSectionReader textSectionReader_; static class Yes2SingleChapterVerses extends SingleChapterVerses { private final String[] verses; public Yes2SingleChapterVerses(String[] verses) { this.verses = verses; } @Override public String getVerse(int verse_0) { return verses[verse_0]; } @Override public int getVerseCount() { return verses.length; } } static class SnappyInputStream extends InputStream { private final Snappy snappy; private final RandomInputStream file; private final long baseOffset; private final int[] compressed_block_sizes; private final int[] compressed_block_offsets; private int current_block_index; private int current_block_skip; private byte[] compressed_buf; private int uncompressed_block_index = -1; private byte[] uncompressed_buf; private int uncompressed_len; public SnappyInputStream(RandomInputStream file, long baseOffset, int block_size, int[] compressed_block_sizes, int[] compressed_block_offsets) { this.snappy = new Snappy.Factory().newInstance(); this.file = file; this.baseOffset = baseOffset; this.compressed_block_sizes = compressed_block_sizes; this.compressed_block_offsets = compressed_block_offsets; if (compressed_buf == null || compressed_buf.length < snappy.maxCompressedLength(block_size)) { compressed_buf = new byte[snappy.maxCompressedLength(block_size)]; } if (uncompressed_buf == null || uncompressed_buf.length != block_size) { uncompressed_buf = new byte[block_size]; } } public void prepareForRead(int current_block_index, int current_block_skip) throws IOException { this.current_block_index = current_block_index; this.current_block_skip = current_block_skip; prepareBuffer(); } private void prepareBuffer() throws IOException { int block_index = current_block_index; // if uncompressed_block_index is already equal to the requested block_index // then we do not need to re-decompress again if (uncompressed_block_index != block_index) { file.seek(baseOffset + compressed_block_offsets[block_index]); file.read(compressed_buf, 0, compressed_block_sizes[block_index]); uncompressed_len = snappy.decompress(compressed_buf, 0, uncompressed_buf, 0, compressed_block_sizes[block_index]); if (uncompressed_len < 0) { throw new IOException("Error in decompressing: " + uncompressed_len); } uncompressed_block_index = block_index; } } @Override public int read() throws IOException { int can_read = uncompressed_len - current_block_skip; if (can_read == 0) { if (current_block_index >= compressed_block_sizes.length) { return -1; // EOF } else { // need to move to the next block current_block_index++; current_block_skip = 0; prepareBuffer(); } } int res = /* need to convert to uint8: */ 0xff & uncompressed_buf[current_block_skip]; current_block_skip++; return res; } @Override public int read(byte[] buffer, int offset, int length) throws IOException { int res = 0; int want_read = length; while (want_read > 0) { int can_read = uncompressed_len - current_block_skip; if (can_read == 0) { if (current_block_index >= compressed_block_sizes.length) { // EOF if (res == 0) return -1; // we didn't manage to read any return res; } else { // need to move to the next block current_block_index++; current_block_skip = 0; prepareBuffer(); can_read = uncompressed_len; } } int will_read = want_read > can_read? can_read: want_read; System.arraycopy(uncompressed_buf, current_block_skip, buffer, offset, will_read); current_block_skip += will_read; offset += will_read; want_read -= will_read; res += will_read; } return res; } } /** * This class simplify many operations regarding reading the verse texts from the yes file. * This stores the offset to the beginning of text section content * and also understands the text section attributes (compression, encryption etc.) */ static class TextSectionReader { private RandomInputStream file_; private final Yes2VerseTextDecoder decoder_; private final long sectionContentOffset_; private int block_size = 0; // 0 means no compression private SnappyInputStream snappyInputStream; private int[] compressed_block_sizes; private int[] compressed_block_offsets; public TextSectionReader(RandomInputStream file, Yes2VerseTextDecoder decoder, ValueMap sectionAttributes, long sectionContentOffset) throws Exception { file_ = file; decoder_ = decoder; sectionContentOffset_ = sectionContentOffset; if (sectionAttributes != null) { String compressionName = sectionAttributes.getString("compression.name"); if ("snappy-blocks".equals(compressionName)) { int compressionVersion = sectionAttributes.getInt("compression.version", 0); if (compressionVersion > 1) { throw new Exception("Compression " + compressionName + " version " + compressionVersion + " is not supported"); } ValueMap compressionInfo = sectionAttributes.getSimpleMap("compression.info"); block_size = compressionInfo.getInt("block_size"); compressed_block_sizes = compressionInfo.getIntArray("compressed_block_sizes"); { // convert compressed_block_sizes into offsets compressed_block_offsets = new int[compressed_block_sizes.length + 1]; int c = 0; for (int i = 0, len = compressed_block_sizes.length; i < len; i++) { compressed_block_offsets[i] = c; c += compressed_block_sizes[i]; } compressed_block_offsets[compressed_block_sizes.length] = c; } snappyInputStream = new SnappyInputStream(file_, sectionContentOffset, block_size, compressed_block_sizes, compressed_block_offsets); } else { throw new Exception("Compression " + compressionName + " is not supported"); } } } public Yes2SingleChapterVerses loadVerseText(Yes2Book yes2Book, int chapter_1, boolean dontSeparateVerses, boolean lowercase) throws Exception { int contentOffset = yes2Book.offset; contentOffset += yes2Book.chapter_offsets[chapter_1 - 1]; BintexReader br; if (block_size != 0) { // compressed! int block_index = contentOffset / block_size; int block_skip = contentOffset % block_size; if (D.EBUG) { Log.d(TAG, "want to read contentOffset=" + contentOffset + " but compressed"); Log.d(TAG, "so going to block " + block_index + " where compressed offset is " + compressed_block_offsets[block_index]); Log.d(TAG, "skipping " + block_skip + " uncompressed bytes"); } snappyInputStream.prepareForRead(block_index, block_skip); br = new BintexReader(snappyInputStream); } else { file_.seek(sectionContentOffset_ + contentOffset); br = new BintexReader(file_); } int verse_count = yes2Book.verse_counts[chapter_1 - 1]; if (dontSeparateVerses) { return new Yes2SingleChapterVerses(new String[] { decoder_.makeIntoSingleString(br, verse_count, lowercase), }); } else { return new Yes2SingleChapterVerses(decoder_.separateIntoVerses(br, verse_count, lowercase)); } } } public Yes2Reader(RandomInputStream input) { this.file_ = input; } /** Read section index */ private synchronized void loadSectionIndex() throws Exception { if (sectionIndex_ != null) { // we have read it previously. return; } file_.seek(0); { // check header byte[] buf = new byte[8]; file_.read(buf); if (!Arrays.equals(buf, new byte[] { (byte) 0x98, 0x58, 0x0d, 0x0a, 0x00, 0x5d, (byte) 0xe0, 0x02 /* yes version 2 */})) { throw new RuntimeException("YES2: Header is incorrect. Found: " + Arrays.toString(buf)); //$NON-NLS-1$ } } file_.seek(12); // start of sectionIndex sectionIndex_ = SectionIndex.read(file_); } private synchronized void loadVersionInfo() throws Exception { if (seekToSection("versionInfo")) { versionInfo_ = new VersionInfoSection.Reader().read(file_); } } private synchronized boolean seekToSection(String sectionName) throws Exception { loadSectionIndex(); if (sectionIndex_ == null) { Log.e(TAG, "@@seekToSection Could not load section index"); return false; } if (sectionIndex_.seekToSectionContent(sectionName, file_)) { return true; } else { Log.e(TAG, "@@seekToSection Could not seek to section: " + sectionName); return false; } } @Override public String getShortName() { try { loadVersionInfo(); return versionInfo_.shortName; } catch (Exception e) { Log.e(TAG, "yes load version info error", e); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } @Override public String getLongName() { try { loadVersionInfo(); return versionInfo_.longName; } catch (Exception e) { Log.e(TAG, "yes load version info error", e); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } public String getDescription() { try { loadVersionInfo(); return versionInfo_.description; } catch (Exception e) { Log.e(TAG, "yes load version info error", e); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } } @Override public Book[] loadBooks() { try { loadVersionInfo(); if (seekToSection(BooksInfoSection.SECTION_NAME)) { BooksInfoSection section = new BooksInfoSection.Reader().read(file_); List<Yes2Book> books = section.yes2Books; return books.toArray(new Yes2Book[books.size()]); } Log.e(TAG, "no section named " + BooksInfoSection.SECTION_NAME); //$NON-NLS-1$ return null; } catch (Exception e) { Log.e(TAG, "loadBooks error", e); //$NON-NLS-1$ return null; } } @Override public Yes2SingleChapterVerses loadVerseText(Book book, int chapter_1, boolean dontSeparateVerses, boolean lowercase) { Yes2Book yes2Book = (Yes2Book) book; try { if (chapter_1 <= 0 || chapter_1 > yes2Book.chapter_count) { return null; } if (textSectionReader_ == null) { ValueMap sectionAttributes = sectionIndex_.getSectionAttributes(TextSection.SECTION_NAME, file_); long sectionContentOffset = sectionIndex_.getAbsoluteOffsetForSectionContent(TextSection.SECTION_NAME); // init text decoder Yes2VerseTextDecoder decoder; int textEncoding = versionInfo_.textEncoding; if (textEncoding == 1) { decoder = new Yes2VerseTextDecoder.Ascii(); } else if (textEncoding == 2) { decoder = new Yes2VerseTextDecoder.Utf8(); } else { Log.e(TAG, "Text encoding " + textEncoding + " not supported! Fallback to ascii."); //$NON-NLS-1$ //$NON-NLS-2$ decoder = new Yes2VerseTextDecoder.Ascii(); } textSectionReader_ = new TextSectionReader(file_, decoder, sectionAttributes, sectionContentOffset); } return textSectionReader_.loadVerseText(yes2Book, chapter_1, dontSeparateVerses, lowercase); } catch (Exception e) { Log.e(TAG, "loadVerseText error", e); //$NON-NLS-1$ return null; } } @Override public int loadPericope(Version version, int bookId, int chapter_1, int[] aris, PericopeBlock[] blocks, int max) { try { loadVersionInfo(); if (versionInfo_.hasPericopes == 0) { return 0; } if (pericopesSection_ == null) { // not yet loaded! if (seekToSection(PericopesSection.SECTION_NAME)) { pericopesSection_ = new PericopesSection.Reader().read(file_); } else { return 0; } } if (pericopesSection_ == null) { Log.e(TAG, "Didn't succeed in loading pericopes section"); return 0; } int ariMin = Ari.encode(bookId, chapter_1, 0); int ariMax = Ari.encode(bookId, chapter_1 + 1, 0); return pericopesSection_.getPericopesForAris(ariMin, ariMax, aris, blocks, max); } catch (Exception e) { Log.e(TAG, "General exception in loading pericope block", e); //$NON-NLS-1$ return 0; } } }
// associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // furnished to do so, subject to the following conditions: // substantial portions of the Software. // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // To compile: javac -cp MalmoJavaJar.jar JavaExamples_run_mission.java // To run: java -cp MalmoJavaJar.jar:. JavaExamples_run_mission (on Linux) // java -cp MalmoJavaJar.jar;. JavaExamples_run_mission (on Windows) // To run from the jar file without compiling: java -cp MalmoJavaJar.jar:JavaExamples_run_mission.jar -Djava.library.path=. JavaExamples_run_mission (on Linux) // java -cp MalmoJavaJar.jar;JavaExamples_run_mission.jar -Djava.library.path=. JavaExamples_run_mission (on Windows) import com.microsoft.msr.malmo.*; public class JavaExamples_run_mission { static { System.loadLibrary("MalmoJava"); // attempts to load MalmoJava.dll (on Windows) or libMalmoJava.so (on Linux) } public static void main(String argv[]) { AgentHost agent_host = new AgentHost(); try { StringVector args = new StringVector(); args.add("JavaExamples_run_mission"); for( String arg : argv ) args.add( arg ); agent_host.parse( args ); } catch( Exception e ) { System.err.println( "ERROR: " + e.getMessage() ); System.err.println( agent_host.getUsage() ); System.exit(1); } if( agent_host.receivedArgument("help") ) { System.out.println( agent_host.getUsage() ); System.exit(0); } MissionSpec my_mission = new MissionSpec(); my_mission.timeLimitInSeconds(10); my_mission.requestVideo( 320, 240 ); my_mission.rewardForReachingPosition(19.5f,0.0f,19.5f,100.0f,1.1f); MissionRecordSpec my_mission_record = new MissionRecordSpec("./saved_data.tgz"); my_mission_record.recordCommands(); my_mission_record.recordMP4(20, 400000); my_mission_record.recordRewards(); my_mission_record.recordObservations(); try { agent_host.startMission( my_mission, my_mission_record ); } catch (Exception e) { System.err.println( "Error starting mission: " + e.getMessage() ); System.exit(1); } WorldState world_state; System.out.print( "Waiting for the mission to start" ); do { System.out.print( "." ); try { Thread.sleep(100); } catch(InterruptedException ex) { System.err.println( "User interrupted while waiting for mission to start." ); return; } world_state = agent_host.getWorldState(); for( int i = 0; i < world_state.getErrors().size(); i++ ) System.err.println( "Error: " + world_state.getErrors().get(i).getText() ); } while( !world_state.getIsMissionRunning() ); System.out.println( "" ); // main loop: do { agent_host.sendCommand( "move 1" ); agent_host.sendCommand( "turn " + Math.random() ); try { Thread.sleep(500); } catch(InterruptedException ex) { System.err.println( "User interrupted while mission was running." ); return; } world_state = agent_host.getWorldState(); System.out.print( "video,observations,rewards received: " ); System.out.print( world_state.getNumberOfVideoFramesSinceLastState() + "," ); System.out.print( world_state.getNumberOfObservationsSinceLastState() + "," ); System.out.println( world_state.getNumberOfRewardsSinceLastState() ); for( int i = 0; i < world_state.getRewards().size(); i++ ) { TimestampedReward reward = world_state.getRewards().get(i); System.out.println( "Summed reward: " + reward.getValue() ); } for( int i = 0; i < world_state.getErrors().size(); i++ ) { TimestampedString error = world_state.getErrors().get(i); System.err.println( "Error: " + error.getText() ); } } while( world_state.getIsMissionRunning() ); System.out.println( "Mission has stopped." ); } }
package ch.openech.mj.swing; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.prefs.Preferences; import javax.swing.Action; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.SwingUtilities; import ch.openech.mj.application.ApplicationContext; import ch.openech.mj.edit.Editor; import ch.openech.mj.edit.Editor.EditorListener; import ch.openech.mj.edit.form.IForm; import ch.openech.mj.page.Page; import ch.openech.mj.page.PageContext; import ch.openech.mj.page.PageLink; import ch.openech.mj.page.RefreshablePage; import ch.openech.mj.swing.component.EditablePanel; import ch.openech.mj.swing.component.History; import ch.openech.mj.swing.component.History.HistoryListener; import ch.openech.mj.swing.toolkit.SwingClientToolkit; import ch.openech.mj.swing.toolkit.SwingClientToolkit.SwingLink; import ch.openech.mj.swing.toolkit.SwingEditorDialog; import ch.openech.mj.swing.toolkit.SwingEditorLayout; import ch.openech.mj.swing.toolkit.SwingInternalFrame; import ch.openech.mj.swing.toolkit.SwingSwitchLayout; import ch.openech.mj.toolkit.IComponent; public class SwingTab extends EditablePanel implements IComponent, PageContext { final SwingFrame frame; final Action previousAction, nextAction, refreshAction, upAction, downAction; final Action closeTabAction; final JMenuItem menuItemToolBarVisible; private final SwingToolBar toolBar; private final SwingMenuBar menuBar; private final SwingSwitchLayout switchLayout; private final History<String> history; private final SwingPageContextHistoryListener historyListener; private Page page; private List<String> pageLinks; private int indexInPageLinks; private Editor<?> editor; public SwingTab(SwingFrame frame) { super(); this.frame = frame; historyListener = new SwingPageContextHistoryListener(); history = new History<String>(historyListener); previousAction = new PreviousPageAction(); nextAction = new NextPageAction(); refreshAction = new RefreshAction(); upAction = new UpAction(); downAction = new DownAction(); closeTabAction = new CloseTabAction(); toolBar = new SwingToolBar(this); menuBar = new SwingMenuBar(this); menuItemToolBarVisible = new MenuItemToolBarVisible(); JPanel outerPanel = new JPanel(new BorderLayout()); outerPanel.add(menuBar, BorderLayout.NORTH); JPanel panel = new JPanel(new BorderLayout()); outerPanel.add(panel, BorderLayout.CENTER); panel.add(toolBar, BorderLayout.NORTH); switchLayout = new SwingSwitchLayout(); panel.add(switchLayout, BorderLayout.CENTER); setContent(outerPanel); } public Page getVisiblePage() { return page; } public Editor<?> getEditor() { return editor; } void onHistoryChanged() { updateActions(); menuBar.onHistoryChanged(); toolBar.onHistoryChanged(); frame.onHistoryChanged(); } protected void updateActions() { if (getVisiblePage() != null && editor == null) { previousAction.setEnabled(hasPast()); nextAction.setEnabled(hasFuture()); refreshAction.setEnabled(getVisiblePage() instanceof RefreshablePage); upAction.setEnabled(!top()); downAction.setEnabled(!bottom()); } else { previousAction.setEnabled(false); nextAction.setEnabled(false); refreshAction.setEnabled(false); upAction.setEnabled(false); downAction.setEnabled(false); } } protected class PreviousPageAction extends SwingResourceAction { @Override public void actionPerformed(ActionEvent e) { previous(); } } protected class NextPageAction extends SwingResourceAction { @Override public void actionPerformed(ActionEvent e) { next(); } } protected class RefreshAction extends SwingResourceAction { @Override public void actionPerformed(ActionEvent e) { refresh(); } } public void refresh() { if (getVisiblePage() instanceof RefreshablePage) { ((RefreshablePage)getVisiblePage()).refresh(); } } private class UpAction extends SwingResourceAction { @Override public void actionPerformed(ActionEvent e) { up(); } } private class DownAction extends SwingResourceAction { @Override public void actionPerformed(ActionEvent e) { down(); } } private class CloseTabAction extends SwingResourceAction { @Override public void actionPerformed(ActionEvent e) { frame.closeTab(); } } private class MenuItemToolBarVisible extends JCheckBoxMenuItem implements ItemListener { private final Preferences preferences = Preferences.userNodeForPackage(MenuItemToolBarVisible.class).node(MenuItemToolBarVisible.class.getSimpleName()); public MenuItemToolBarVisible() { super("Navigation sichtbar"); addItemListener(this); setSelected(preferences.getBoolean("visible", true)); toolBar.setVisible(isSelected()); } @Override public void itemStateChanged(ItemEvent e) { toolBar.setVisible(isSelected()); preferences.putBoolean("visible", isSelected()); } } // PageContext private class SwingPageContextHistoryListener implements HistoryListener { @Override public void onHistoryChanged() { page = PageLink.createPage(SwingTab.this, history.getPresent()); show(page); SwingTab.this.onHistoryChanged(); } private void show(Page page) { switchLayout.show((IComponent) page.getComponent()); registerMouseListener((Component) page.getComponent()); SwingClientToolkit.focusFirstComponent(page.getComponent()); } } private void registerMouseListener(Component component) { if (component instanceof SwingLink) { // TODO // ((SwingLink) component).setMouseListener(mouseListener); } if (component instanceof Container) { for (Component c : ((Container) component).getComponents()) { registerMouseListener(c); } } } public void add(String pageLink) { history.add(pageLink); } public void replace(String pageLink) { history.replace(pageLink); } public String getPresent() { return history.getPresent(); } public boolean hasFuture() { return history.hasFuture(); } public boolean hasPast() { return history.hasPast(); } public void next() { history.next(); } public void previous() { history.previous(); } public void dropFuture() { history.dropFuture(); } public PageContext addTab() { return frame.addTab(); } public void closeTab() { if (hasPast()) { previous(); dropFuture(); } else { frame.closeTab(this); } } @Override public void show(final String pageLink) { if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { show(pageLink); }; }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } else { if (pageLinks != null && !pageLinks.contains(pageLink)) { pageLinks = null; } add(pageLink); } } @Override public void show(Editor<?> editor) { this.editor = editor; IForm<?> form = editor.startEditor(); SwingEditorLayout layout = new SwingEditorLayout(form.getComponent(), editor.getActions()); final SwingInternalFrame dialog = new SwingInternalFrame(this, layout, editor.getTitle()); dialog.setCloseListener(new SwingEditorDialog.CloseListener() { @Override public boolean close() { SwingTab.this.editor.checkedClose(); return SwingTab.this.editor == null; } }); editor.setEditorListener(new EditorListener() { @Override public void saved(Object saveResult) { dialog.closeDialog(); dialog.dispose(); SwingTab.this.editor = null; if (saveResult instanceof String) { show((String) saveResult); } } @Override public void canceled() { dialog.closeDialog(); dialog.dispose(); SwingTab.this.editor = null; } }); dialog.openDialog(); SwingClientToolkit.focusFirstComponent(form.getComponent()); } @Override public void show(List<String> pageLinks, int index) { this.pageLinks = pageLinks; this.indexInPageLinks = index; show(pageLinks.get(indexInPageLinks)); } public boolean top() { return pageLinks == null || indexInPageLinks == 0; } public boolean bottom() { return pageLinks == null || indexInPageLinks == pageLinks.size() - 1; } public void up() { replace(pageLinks.get(--indexInPageLinks)); } public void down() { replace(pageLinks.get(++indexInPageLinks)); } @Override public ApplicationContext getApplicationContext() { return SwingLauncher.getApplicationContext(); } }
package com.datdo.mobilib.base; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.os.Bundle; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import com.datdo.mobilib.event.MblCommonEvents; import com.datdo.mobilib.event.MblEventCenter; import com.datdo.mobilib.event.MblEventListener; import com.datdo.mobilib.util.MblUtils; /** * <pre> * Plug an object of this class into an activity to make this library works. * </pre> */ public class MblActivityPlugin { // current status private int mOrientation; // wrapper views private MblDecorView mDecorView; // for background/foreground detecting private static long sLastOnPause = 0; private static Runnable sBackgroundStatusCheckTask = new Runnable() { @Override public void run() { MblEventCenter.postEvent(this, MblCommonEvents.GO_TO_BACKGROUND); } }; private static final long DEFAULT_MAX_ALLOWED_TRASITION_BETWEEN_ACTIVITY = 2000; protected long mMaxAllowedTrasitionBetweenActivity = DEFAULT_MAX_ALLOWED_TRASITION_BETWEEN_ACTIVITY; /** * Extends Activity#onCreate(Bundle) * @param activity targeted activity * @param savedInstanceState */ public void onCreate(Activity activity, Bundle savedInstanceState) { Context context = MblUtils.getCurrentContext(); if (context == null || !(context instanceof Activity)) { MblUtils.setCurrentContext(activity); } activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); mOrientation = activity.getResources().getConfiguration().orientation; } /** * Extends Activity#onResume() * @param activity targeted activity */ public void onResume(Activity activity) { MblUtils.setCurrentContext(activity); MblUtils.getMainThreadHandler().removeCallbacks(sBackgroundStatusCheckTask); long now = getNow(); if (now - sLastOnPause > mMaxAllowedTrasitionBetweenActivity) { MblEventCenter.postEvent(this, MblCommonEvents.GO_TO_FOREGROUND); } MblEventCenter.postEvent(this, MblCommonEvents.ACTIVITY_RESUMED, activity); } /** * Extends Activity#onPause() */ public void onPause() { MblUtils.hideKeyboard(); sLastOnPause = getNow(); MblUtils.getMainThreadHandler().postDelayed(sBackgroundStatusCheckTask, mMaxAllowedTrasitionBetweenActivity); } /** * Extends Activity#onConfigurationChanged(Configuration) * @param activity targeted activity * @param newConfig */ public void onConfigurationChanged(Activity activity, Configuration newConfig) { if (newConfig.orientation != mOrientation) { mOrientation = newConfig.orientation; waitForWindowOrientationReallyChanged(activity, new Runnable() { @Override public void run() { MblEventCenter.postEvent(this, MblCommonEvents.ORIENTATION_CHANGED); } }); } } private void waitForWindowOrientationReallyChanged(final Activity activity, final Runnable callback) { if (MblUtils.isPortraitDisplay() != isPortraitWindow(activity)) { MblUtils.getMainThreadHandler().postDelayed(new Runnable() { @Override public void run() { waitForWindowOrientationReallyChanged(activity, callback); } }, 10); } else { callback.run(); } } public boolean isPortraitWindow(Activity activity) { View root = activity.getWindow().getDecorView(); return root.getWidth() <= root.getHeight(); } private long getNow() { return System.currentTimeMillis(); } /** * Determine whether targeted activity is top activity in current task * @param activity * @return */ public boolean isTopActivity(Activity activity) { return MblUtils.getCurrentContext() == activity; } private View createDecorViewAndAddContent(Activity activity, int layoutResId, LayoutParams params) { View content = activity.getLayoutInflater().inflate(layoutResId, null); return createDecorViewAndAddContent(activity, content, params); } private View createDecorViewAndAddContent(Activity activity, View layout, LayoutParams params) { if (params == null) { params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } layout.setLayoutParams(params); MblDecorView decorView = new MblDecorView(activity); decorView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); decorView.addView(layout); mDecorView = decorView; return decorView; } /** * Create wrapping content view for {@link Activity#setContentView(int)} * @param activity targeted activity * @param layoutResID * @return wrapping content view */ public View getContentView(Activity activity, int layoutResID) { return createDecorViewAndAddContent(activity, layoutResID, null); } /** * Create wrapping content view for {@link Activity#setContentView(View)} * @param activity targeted activity * @param view * @return wrapping content view */ public View getContentView(Activity activity, View view) { return createDecorViewAndAddContent(activity, view, null); } /** * Create wrapping content view for {@link Activity#setContentView(View, LayoutParams)} * @param activity targeted activity * @param view * @param params * @return wrapping content view */ public View getContentView(Activity activity, View view, LayoutParams params) { return createDecorViewAndAddContent(activity, view, params); } /** * Extends Activity#onDestroy() * @param activity targeted activity */ public void onDestroy(Activity activity) { if (activity instanceof MblEventListener) { MblEventCenter.removeListenerFromAllEvents((MblEventListener) activity); } MblUtils.cleanupView(mDecorView); } /** * Get root view of activity * @param activity targeted activity * @return root view */ public MblDecorView getDecorView(Activity activity) { return mDecorView; } public void setMaxAllowedTrasitionBetweenActivity(Activity activity, long duration) { mMaxAllowedTrasitionBetweenActivity = duration; } /** * @see #setMaxAllowedTrasitionBetweenActivity(Activity, long) */ public void resetDefaultMaxAllowedTrasitionBetweenActivity(Activity activity) { mMaxAllowedTrasitionBetweenActivity = DEFAULT_MAX_ALLOWED_TRASITION_BETWEEN_ACTIVITY; } }
package com.sedmelluq.discord.lavaplayer.source.bandcamp; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManager; import com.sedmelluq.discord.lavaplayer.tools.DataFormatTools; import com.sedmelluq.discord.lavaplayer.tools.ExceptionTools; import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; import com.sedmelluq.discord.lavaplayer.tools.JsonBrowser; import com.sedmelluq.discord.lavaplayer.tools.io.HttpClientTools; import com.sedmelluq.discord.lavaplayer.track.AudioItem; import com.sedmelluq.discord.lavaplayer.track.AudioReference; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import static com.sedmelluq.discord.lavaplayer.tools.FriendlyException.Severity.FAULT; import static com.sedmelluq.discord.lavaplayer.tools.FriendlyException.Severity.SUSPICIOUS; /** * Audio source manager that implements finding Bandcamp tracks based on URL. */ public class BandcampAudioSourceManager implements AudioSourceManager { private static final String TRACK_URL_REGEX = "^https?:\\/\\/(?:[^.]+\\.|)bandcamp\\.com\\/track\\/([a-zA-Z0-9-_]+)(?:\\?.*|)\\/?$"; private static final String ALBUM_URL_REGEX = "^https?:\\/\\/(?:[^.]+\\.|)bandcamp\\.com\\/album\\/([a-zA-Z0-9-_]+)(?:\\?.*|)\\/?$"; private static final Pattern trackUrlPattern = Pattern.compile(TRACK_URL_REGEX); private static final Pattern albumUrlPattern = Pattern.compile(ALBUM_URL_REGEX); private final HttpClientBuilder httpClientBuilder; /** * Create an instance. */ public BandcampAudioSourceManager() { httpClientBuilder = HttpClientTools.createSharedCookiesHttpBuilder(); } @Override public String getSourceName() { return "bandcamp"; } @Override public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) { if (trackUrlPattern.matcher(reference.identifier).matches()) { return loadTrack(reference.identifier); } else if (albumUrlPattern.matcher(reference.identifier).matches()) { return loadAlbum(reference.identifier); } return null; } private AudioItem loadTrack(String trackUrl) { return extractFromPage(trackUrl, (httpClient, text) -> { String bandUrl = readBandUrl(text); JsonBrowser trackListInfo = readTrackListInformation(text); String artist = trackListInfo.get("artist").text(); return extractTrack(trackListInfo.get("trackinfo").index(0), bandUrl, artist); }); } private AudioItem loadAlbum(String albumUrl) { return extractFromPage(albumUrl, (httpClient, text) -> { String bandUrl = readBandUrl(text); JsonBrowser trackListInfo = readTrackListInformation(text); String artist = trackListInfo.get("artist").text(); List<AudioTrack> tracks = new ArrayList<>(); for (JsonBrowser trackInfo : trackListInfo.get("trackinfo").values()) { tracks.add(extractTrack(trackInfo, bandUrl, artist)); } JsonBrowser albumInfo = readAlbumInformation(text); return new BasicAudioPlaylist(albumInfo.get("album_title").text(), tracks, null); }); } private AudioTrack extractTrack(JsonBrowser trackInfo, String bandUrl, String artist) { return new BandcampAudioTrack(new AudioTrackInfo( trackInfo.get("title").text(), artist, (long) (trackInfo.get("duration").as(Double.class) * 1000.0), bandUrl + trackInfo.get("title_link").text(), false ), this); } private String readBandUrl(String text) { String bandUrl = DataFormatTools.extractBetween(text, "var band_url = \"", "\";"); if (bandUrl == null) { throw new FriendlyException("Band information not found on the Bandcamp page.", SUSPICIOUS, null); } return bandUrl; } private JsonBrowser readAlbumInformation(String text) throws IOException { String albumInfoJson = DataFormatTools.extractBetween(text, "var EmbedData = ", "};"); if (albumInfoJson == null) { throw new FriendlyException("Album information not found on the Bandcamp page.", SUSPICIOUS, null); } albumInfoJson = albumInfoJson.replace("\" + \"", "") + "};"; return JsonBrowser.parse(albumInfoJson); } JsonBrowser readTrackListInformation(String text) throws IOException { String trackInfoJson = DataFormatTools.extractBetween(text, "var TralbumData = ", "};"); if (trackInfoJson == null) { throw new FriendlyException("Track information not found on the Bandcamp page.", SUSPICIOUS, null); } trackInfoJson = trackInfoJson.replace("\" + \"", "") + "};"; return JsonBrowser.parse(trackInfoJson + "};"); } private AudioItem extractFromPage(String url, AudioItemExtractor extractor) { try (CloseableHttpClient httpClient = httpClientBuilder.build()) { return extractFromPageWithClient(httpClient, url, extractor); } catch (Exception e) { throw ExceptionTools.wrapUnfriendlyExceptions("Loading information for a Bandcamp track failed.", FAULT, e); } } private AudioItem extractFromPageWithClient(CloseableHttpClient httpClient, String url, AudioItemExtractor extractor) throws Exception { String responseText; try (CloseableHttpResponse response = httpClient.execute(new HttpGet(url))) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 404) { return new AudioReference(null, null); } else if (statusCode != 200) { throw new IOException("Invalid status code " + statusCode + " for track page."); } responseText = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); } return extractor.extract(httpClient, responseText); } @Override public boolean isTrackEncodable(AudioTrack track) { return true; } @Override public void encodeTrack(AudioTrack track, DataOutput output) throws IOException { // No special values to encode } @Override public AudioTrack decodeTrack(AudioTrackInfo trackInfo, DataInput input) throws IOException { return new BandcampAudioTrack(trackInfo, this); } @Override public void shutdown() { // Nothing to do } /** * @return A new HttpClient instance. All instances returned from this method use the same cookie jar. */ public CloseableHttpClient createHttpClient() { return httpClientBuilder.build(); } private interface AudioItemExtractor { AudioItem extract(CloseableHttpClient httpClient, String text) throws Exception; } }
package pl.edu.icm.coansys.metaextr.textr; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.HeightFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.UppercaseWordRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.AtCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LetterRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LineWidthMeanFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.DotRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.WordCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.YPositionFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LineHeightMeanFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LineRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.DigitCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LineXPositionMeanFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.UppercaseRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.WidthRelativeFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.DigitRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.CommaRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.UppercaseCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LowercaseCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.XPositionRelativeFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LetterCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.XPositionFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.CommaCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.WordCountRelativeFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.CharCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.WidthFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.DotCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.WordWidthMeanFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.HeightRelativeFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.UppercaseWordCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.AtRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LineCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.YPositionRelativeFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.ProportionsFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LowercaseRelativeCountFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.CharCountRelativeFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LineXWidthPositionDiffFeature; import pl.edu.icm.coansys.metaextr.metadata.zoneclassification.features.LineXPositionDiffFeature; import pl.edu.icm.coansys.metaextr.textr.ZoneClassifier; import com.thoughtworks.xstream.XStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.Arrays; import java.util.zip.ZipException; import javax.xml.parsers.ParserConfigurationException; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.xml.sax.SAXException; import pl.edu.icm.coansys.metaextr.AnalysisException; import pl.edu.icm.coansys.metaextr.TransformationException; import pl.edu.icm.coansys.metaextr.classification.features.FeatureCalculator; import pl.edu.icm.coansys.metaextr.classification.features.FeatureVectorBuilder; import pl.edu.icm.coansys.metaextr.classification.features.SimpleFeatureVectorBuilder; import pl.edu.icm.coansys.metaextr.classification.hmm.HMMService; import pl.edu.icm.coansys.metaextr.classification.hmm.HMMServiceImpl; import pl.edu.icm.coansys.metaextr.classification.hmm.HMMZoneClassifier; import pl.edu.icm.coansys.metaextr.classification.hmm.probability.HMMProbabilityInfo; import pl.edu.icm.coansys.metaextr.textr.model.BxDocument; import pl.edu.icm.coansys.metaextr.textr.model.BxPage; import pl.edu.icm.coansys.metaextr.textr.model.BxZone; import pl.edu.icm.coansys.metaextr.textr.model.BxZoneLabel; import pl.edu.icm.coansys.metaextr.textr.tools.UnclassifiedZonesPreprocessor; /** * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class HMMZoneClassifierTest extends AbstractDocumentProcessorTest { protected static final double testSuccessPercentage = 90; protected static final String hmmProbabilitiesFile = "/pl/edu/icm/coansys/metaextr/textr/hmmZoneProbabilities.xml"; protected static final String[] zipResources = {"/pl/edu/icm/coansys/metaextr/textr/margSmallSample.zip"}; private HMMService hmmService = new HMMServiceImpl(); private ZoneClassifier zoneClassifier; int allZones = 0; int badZones = 0; @Before public void setUp() { this.startProcessFlattener = new UnclassifiedZonesPreprocessor(); InputStream is = this.getClass().getResourceAsStream(hmmProbabilitiesFile); XStream xstream = new XStream(); HMMProbabilityInfo<BxZoneLabel> hmmProbabilities = (HMMProbabilityInfo<BxZoneLabel>) xstream.fromXML(is); FeatureVectorBuilder<BxZone, BxPage> vBuilder = new SimpleFeatureVectorBuilder<BxZone, BxPage>(); vBuilder.setFeatureCalculators(Arrays.<FeatureCalculator<BxZone, BxPage>>asList( new ProportionsFeature(), new HeightFeature(), new WidthFeature(), new XPositionFeature(), new YPositionFeature(), new HeightRelativeFeature(), new WidthRelativeFeature(), new XPositionRelativeFeature(), new YPositionRelativeFeature(), new LineCountFeature(), new LineRelativeCountFeature(), new LineHeightMeanFeature(), new LineWidthMeanFeature(), new LineXPositionMeanFeature(), new LineXPositionDiffFeature(), new LineXWidthPositionDiffFeature(), new WordCountFeature(), new WordCountRelativeFeature(), new CharCountFeature(), new CharCountRelativeFeature(), new DigitCountFeature(), new DigitRelativeCountFeature(), new LetterCountFeature(), new LetterRelativeCountFeature(), new LowercaseCountFeature(), new LowercaseRelativeCountFeature(), new UppercaseCountFeature(), new UppercaseRelativeCountFeature(), new UppercaseWordCountFeature(), new UppercaseWordRelativeCountFeature(), new AtCountFeature(), new AtRelativeCountFeature(), new CommaCountFeature(), new CommaRelativeCountFeature(), new DotCountFeature(), new DotRelativeCountFeature(), new WordWidthMeanFeature() )); zoneClassifier = new HMMZoneClassifier(hmmService, hmmProbabilities, vBuilder); } @Ignore("XMLe zawarte w margSmallExample.zip sa nie dokonca prawidlowe." + "Po zmianie reading orderu, RO w plikach wzoracowych i przetwarzanych" + "jest inny. W moim odczuciu kolejnosc ustalana przez nowy RO jest" + "lepsza ") @Test public void hmmZonesClassifierTest() throws URISyntaxException, ZipException, IOException, ParserConfigurationException, SAXException, AnalysisException, TransformationException { testAllFilesFromZip(Arrays.asList(zipResources), testSuccessPercentage); System.out.println("all zones: "+this.allZones); System.out.println("bad zones: "+this.badZones); } @Override protected boolean compareDocuments(BxDocument testDoc, BxDocument expectedDoc) { boolean ret = true; for (int i = 0; i < testDoc.getPages().size(); i++) { BxPage testPage = testDoc.getPages().get(i); BxPage expectedPage = expectedDoc.getPages().get(i); for (int j = 0; j < testPage.getZones().size(); j++) { BxZone testZone = testPage.getZones().get(j); BxZone expectedZone = expectedPage.getZones().get(j); this.allZones++; if (!testZone.getLabel().equals(expectedZone.getLabel())) { this.badZones++; ret = false; } } } return ret; } @Override protected BxDocument process(BxDocument doc) throws AnalysisException { zoneClassifier.classifyZones(doc); return doc; } }
package com.elasticinbox.core.cassandra.persistence; import static me.prettyprint.hector.api.factory.HFactory.createCounterColumn; import static me.prettyprint.hector.api.factory.HFactory.createCounterSliceQuery; import static com.elasticinbox.core.cassandra.CassandraDAOFactory.CF_COUNTERS; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import me.prettyprint.cassandra.serializers.CompositeSerializer; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.beans.Composite; import me.prettyprint.hector.api.beans.CounterSlice; import me.prettyprint.hector.api.beans.HCounterColumn; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SliceCounterQuery; import com.elasticinbox.core.cassandra.CassandraDAOFactory; import com.elasticinbox.core.model.LabelConstants; import com.elasticinbox.core.model.LabelCounters; import com.elasticinbox.core.model.ReservedLabels; public final class LabelCounterPersistence { /** Counter type for Label counters */ public final static String CN_TYPE_LABEL = "l"; /** Label counter subtype for total bytes */ public final static char CN_SUBTYPE_BYTES = 'b'; /** Label counter subtype for total messages */ public final static char CN_SUBTYPE_MESSAGES = 'm'; /** Label counter subtype for unread messages */ public final static char CN_SUBTYPE_UNREAD = 'u'; private final static Keyspace keyspace = CassandraDAOFactory.getKeyspace(); private final static StringSerializer strSe = StringSerializer.get(); private final static Logger logger = LoggerFactory.getLogger(LabelCounterPersistence.class); /** * Get counters for all label in the given mailbox * * @param mailbox * @return */ public static Map<Integer, LabelCounters> getAll(final String mailbox) { Composite startRange = new Composite(); startRange.addComponent(0, CN_TYPE_LABEL, Composite.ComponentEquality.EQUAL); Composite endRange = new Composite(); endRange.addComponent(0, CN_TYPE_LABEL, Composite.ComponentEquality.GREATER_THAN_EQUAL); SliceCounterQuery<String, Composite> sliceQuery = createCounterSliceQuery(keyspace, strSe, new CompositeSerializer()); sliceQuery.setColumnFamily(CF_COUNTERS); sliceQuery.setKey(mailbox); sliceQuery.setRange(startRange, endRange, false, LabelConstants.MAX_LABEL_ID); QueryResult<CounterSlice<Composite>> r = sliceQuery.execute(); return compositeColumnsToCounters(mailbox, r.get().getColumns()); } /** * Get counters for the specified label in the given mailbox * * @param mailbox * @param labelId * @return */ public static LabelCounters get(final String mailbox, final Integer labelId) { Composite startRange = new Composite(); startRange.addComponent(0, CN_TYPE_LABEL, Composite.ComponentEquality.EQUAL); startRange.addComponent(1, labelId.toString(), Composite.ComponentEquality.EQUAL); Composite endRange = new Composite(); endRange.addComponent(0, CN_TYPE_LABEL, Composite.ComponentEquality.EQUAL); endRange.addComponent(1, labelId.toString(), Composite.ComponentEquality.GREATER_THAN_EQUAL); SliceCounterQuery<String, Composite> sliceQuery = createCounterSliceQuery(keyspace, strSe, new CompositeSerializer()); sliceQuery.setColumnFamily(CF_COUNTERS); sliceQuery.setKey(mailbox); sliceQuery.setRange(startRange, endRange, false, 5); QueryResult<CounterSlice<Composite>> r = sliceQuery.execute(); Map<Integer, LabelCounters> counters = compositeColumnsToCounters(mailbox, r.get().getColumns()); LabelCounters labelCounters = counters.containsKey(labelId) ? counters.get(labelId) : new LabelCounters(); logger.debug("Fetched counters for single label {} with {}", labelId, labelCounters); return labelCounters; } /** * Increment or decrement of the label counters. Use negative values for * decrement. * * @param mutator * @param mailbox * @param labelIds * @param labelCounters */ public static void add(Mutator<String> mutator, final String mailbox, final Set<Integer> labelIds, final LabelCounters labelCounters) { // batch add of counters for each of the labels for (Integer labelId : labelIds) { logger.debug("Updating counters for label {} with {}", labelId, labelCounters); // update total bytes only for ALL_MAILS label (i.e. total mailbox usage) if ((labelId == ReservedLabels.ALL_MAILS.getId()) && (labelCounters.getTotalBytes() != 0)) { HCounterColumn<Composite> col = countersToCompositeColumn( labelId, CN_SUBTYPE_BYTES, labelCounters.getTotalBytes()); mutator.addCounter(mailbox, CF_COUNTERS, col); } if (labelCounters.getTotalMessages() != 0) { HCounterColumn<Composite> col = countersToCompositeColumn( labelId, CN_SUBTYPE_MESSAGES, labelCounters.getTotalMessages()); mutator.addCounter(mailbox, CF_COUNTERS, col); } if (labelCounters.getUnreadMessages() != 0) { HCounterColumn<Composite> col = countersToCompositeColumn( labelId, CN_SUBTYPE_UNREAD, labelCounters.getUnreadMessages()); mutator.addCounter(mailbox, CF_COUNTERS, col); } } } public static void subtract(Mutator<String> mutator, final String mailbox, final Set<Integer> labelIds, final LabelCounters labelCounters) { // perform addition of inverse (i.e. subtraction) add(mutator, mailbox, labelIds, labelCounters.getInverse()); } public static void add(Mutator<String> mutator, final String mailbox, final Integer labelId, final LabelCounters labelCounters) { Set<Integer> labelIds = new HashSet<Integer>(1); labelIds.add(labelId); add(mutator, mailbox, labelIds, labelCounters); } public static void subtract(Mutator<String> mutator, final String mailbox, final Integer labelId, final LabelCounters labelCounters) { Set<Integer> labelIds = new HashSet<Integer>(1); labelIds.add(labelId); subtract(mutator, mailbox, labelIds, labelCounters); } /** * Delete label counters * * @param mutator * @param mailbox * @param labelId */ public static void delete(Mutator<String> mutator, final String mailbox, final Integer labelId) { // reset all counters (since delete won't work in most cases) LabelCounters labelCounters = get(mailbox, labelId); // if counter super-column for this label exists if (labelCounters != null) { subtract(mutator, mailbox, labelId, labelCounters); // delete counters HCounterColumn<Composite> c; c = countersToCompositeColumn(labelId, CN_SUBTYPE_MESSAGES, labelCounters.getTotalMessages()); mutator.addDeletion(mailbox, CF_COUNTERS, c.getName(), new CompositeSerializer()); c = countersToCompositeColumn(labelId, CN_SUBTYPE_UNREAD, labelCounters.getTotalMessages()); mutator.addDeletion(mailbox, CF_COUNTERS, c.getName(), new CompositeSerializer()); // delete bytes only if ALL_MAILS if (labelId == ReservedLabels.ALL_MAILS.getId()) { c = countersToCompositeColumn(labelId, CN_SUBTYPE_BYTES, labelCounters.getTotalMessages()); mutator.addDeletion(mailbox, CF_COUNTERS, c.getName(), new CompositeSerializer()); } } } /** * Delete all label counters * * @param mailbox */ public static void deleteAll(Mutator<String> mutator, final String mailbox) { // reset all counters (since delete won't work in most cases) Map<Integer, LabelCounters> counters = getAll(mailbox); for (Integer labelId : counters.keySet()) { LabelCounters labelCounters = counters.get(labelId); subtract(mutator, mailbox, labelId, labelCounters); } // delete all label counters mutator.delete(mailbox, CF_COUNTERS, null, strSe); } /** * Build composite counter column * * @param labelId * @param subtype * @param count * @return */ private static HCounterColumn<Composite> countersToCompositeColumn( final Integer labelId, final char subtype, final Long count) { Composite composite = new Composite(); composite.addComponent(CN_TYPE_LABEL, strSe); composite.addComponent(labelId.toString(), strSe); composite.addComponent(Character.toString(subtype), strSe); return createCounterColumn(composite, count, new CompositeSerializer()); } /** * Convert Hector Composite Columns to {@link LabelCounters} * * @param columnList * @return */ private static Map<Integer, LabelCounters> compositeColumnsToCounters( final String mailbox, final List<HCounterColumn<Composite>> columnList) { Map<Integer, LabelCounters> result = new HashMap<Integer, LabelCounters>(LabelConstants.MAX_RESERVED_LABEL_ID); LabelCounters labelCounters = new LabelCounters(); int prevLabelId = 0; // remember previous labelid which is always start form 0 for (HCounterColumn<Composite> c : columnList) { int labelId = Integer.parseInt(c.getName().get(1, strSe)); char subtype = c.getName().get(2, strSe).charAt(0); // since columns are ordered by labels, we can // flush label counters to result map as we traverse if (prevLabelId != labelId) { logger.debug("Fetched counters for label {} with {}", prevLabelId, labelCounters); result.put(prevLabelId, labelCounters); labelCounters = new LabelCounters(); prevLabelId = labelId; } long cValue = 0; // never return negative counter value if (c.getValue() >= 0) { cValue = c.getValue(); } else { logger.warn("Negative counter value found for label {}/{}: ", mailbox, labelId); } switch (subtype) { case CN_SUBTYPE_BYTES: labelCounters.setTotalBytes(cValue); break; case CN_SUBTYPE_MESSAGES: labelCounters.setTotalMessages(cValue); break; case CN_SUBTYPE_UNREAD: labelCounters.setUnreadMessages(cValue); break; } } // flush remaining counters for the last label result.put(prevLabelId, labelCounters); return result; } }
package net.nemerosa.ontrack.migration.postgresql; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; import javax.sql.DataSource; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.Collectors; @Component public class Migration { private final Logger logger = LoggerFactory.getLogger(Migration.class); private final MigrationProperties migrationProperties; private final NamedParameterJdbcTemplate h2; private final NamedParameterJdbcTemplate postgresql; private final TransactionTemplate txTemplate; @Autowired public Migration(@Qualifier("h2") DataSource h2Datasource, @Qualifier("postgresql") DataSource postgresqlDatasource, MigrationProperties migrationProperties) { this.migrationProperties = migrationProperties; h2 = new NamedParameterJdbcTemplate(h2Datasource); postgresql = new NamedParameterJdbcTemplate(postgresqlDatasource); PlatformTransactionManager txManager = new DataSourceTransactionManager(postgresqlDatasource); txTemplate = new TransactionTemplate(txManager); } public void run() { // Cleanup? if (migrationProperties.isCleanup()) { cleanup(); } /** * Global data */ // CONFIGURATIONS copy("CONFIGURATIONS", "ID", "TYPE", "NAME", "CONTENT::JSONB"); // SETTINGS copy("SETTINGS", "CATEGORY", "NAME", "VALUE"); // PREDEFINED_PROMOTION_LEVELS copy("PREDEFINED_PROMOTION_LEVELS", "ID", "ORDERNB", "NAME", "DESCRIPTION", "IMAGETYPE", "IMAGEBYTES"); // PREDEFINED_VALIDATION_STAMPS copy("PREDEFINED_VALIDATION_STAMPS", "ID", "NAME", "DESCRIPTION", "IMAGETYPE", "IMAGEBYTES"); // STORAGE copy("STORAGE", "STORE", "NAME", "DATA::JSONB"); /** * Entities */ // PROJECTS copy("PROJECTS", "ID", "NAME", "DESCRIPTION", "DISABLED"); // BRANCHES copy("BRANCHES", "ID", "PROJECTID", "NAME", "DESCRIPTION", "DISABLED"); // PROMOTION_LEVELS copy("PROMOTION_LEVELS", "ID", "BRANCHID", "ORDERNB", "NAME", "DESCRIPTION", "IMAGETYPE", "IMAGEBYTES"); // VALIDATION_STAMPS copy("VALIDATION_STAMPS", "ID", "BRANCHID", "OWNER", "PROMOTION_LEVEL", "ORDERNB", "NAME", "DESCRIPTION", "IMAGETYPE", "IMAGEBYTES"); // BUILDS copy("BUILDS", "ID", "BRANCHID", "NAME", "DESCRIPTION", "CREATION", "CREATOR"); // PROMOTION_RUNS copy("PROMOTION_RUNS", "ID", "BUILDID", "PROMOTIONLEVELID", "CREATION", "CREATOR", "DESCRIPTION"); // VALIDATION_RUNS copy("VALIDATION_RUNS", "ID", "BUILDID", "VALIDATIONSTAMPID"); // VALIDATION_RUN_STATUSES copy("VALIDATION_RUN_STATUSES", "ID", "VALIDATIONRUNID", "VALIDATIONRUNSTATUSID", "CREATION", "CREATOR", "DESCRIPTION"); /** * Branch templating */ // BRANCH_TEMPLATE_DEFINITIONS copy("BRANCH_TEMPLATE_DEFINITIONS", "BRANCHID", "ABSENCEPOLICY", "SYNCINTERVAL", "SYNCHRONISATIONSOURCEID", "SYNCHRONISATIONSOURCECONFIG::JSONB"); // BRANCH_TEMPLATE_DEFINITION_PARAMS copy("BRANCH_TEMPLATE_DEFINITION_PARAMS", "BRANCHID", "NAME", "DESCRIPTION", "EXPRESSION"); // BRANCH_TEMPLATE_INSTANCES copy("BRANCH_TEMPLATE_INSTANCES", "BRANCHID", "TEMPLATEBRANCHID"); // BRANCH_TEMPLATE_INSTANCE_PARAMS copy("BRANCH_TEMPLATE_INSTANCE_PARAMS", "BRANCHID", "NAME", "VALUE"); /** * Entity data */ // ENTITY_DATA copy("ENTITY_DATA", "ID", "PROJECT", "BRANCH", "PROMOTION_LEVEL", "VALIDATION_STAMP", "BUILD", "PROMOTION_RUN", "VALIDATION_RUN", "NAME", "VALUE::JSONB"); // PROPERTIES copyProperties(); // SHARED_BUILD_FILTERS copy("SHARED_BUILD_FILTERS", "BRANCHID", "NAME", "TYPE", "DATA::JSONB"); // EVENTS if (migrationProperties.isSkipEvents()) { logger.warn("Skipping events migration"); } else { copyEvents(); } /** * ACL */ // ACCOUNTS copy("ACCOUNTS", "ID", "NAME", "FULLNAME", "EMAIL", "MODE", "PASSWORD", "ROLE"); // ACCOUNT_GROUPS copy("ACCOUNT_GROUPS", "ID", "NAME", "DESCRIPTION"); // ACCOUNT_GROUP_LINK copy("ACCOUNT_GROUP_LINK", "ACCOUNT", "ACCOUNTGROUP"); // ACCOUNT_GROUP_MAPPING copy("ACCOUNT_GROUP_MAPPING", "ID", "GROUPID", "MAPPING", "SOURCE"); // GLOBAL_AUTHORIZATIONS copy("GLOBAL_AUTHORIZATIONS", "ACCOUNT", "ROLE"); // GROUP_GLOBAL_AUTHORIZATIONS copy("GROUP_GLOBAL_AUTHORIZATIONS", "ACCOUNTGROUP", "ROLE"); // GROUP_PROJECT_AUTHORIZATIONS copy("GROUP_PROJECT_AUTHORIZATIONS", "ACCOUNTGROUP", "PROJECT", "ROLE"); // PROJECT_AUTHORIZATIONS copy("PROJECT_AUTHORIZATIONS", "ACCOUNT", "PROJECT", "ROLE"); // PREFERENCES copy("PREFERENCES", "ACCOUNTID", "TYPE", "CONTENT"); // BUILD_FILTERS copy("BUILD_FILTERS", "ACCOUNTID", "BRANCHID", "NAME", "TYPE", "DATA::JSONB"); // Subversion // Subversion tables do not need to be migrated - they will be filled on demand // Update of sequences updateSequences(); } private void copyProperties() { String[] columns = new String[]{"ID", "PROJECT", "BRANCH", "PROMOTION_LEVEL", "VALIDATION_STAMP", "BUILD", "PROMOTION_RUN", "VALIDATION_RUN", "TYPE", "SEARCHKEY", "JSON::JSONB"}; String h2Query = String.format("SELECT * FROM %s", "PROPERTIES"); String insert = Arrays.asList(columns).stream().map(column -> StringUtils.substringBefore(column, "::")).collect(Collectors.joining(",")); String values = Arrays.asList(columns).stream().map(column -> ":" + column).collect(Collectors.joining(",")); String postgresqlUpdate = String.format("INSERT INTO %s (%s) VALUES (%s)", "TMP_PROPERTIES", insert, values); tx(() -> { // Makes sure TMP_PROPERTIES is dropped postgresql.getJdbcOperations().execute("DROP TABLE IF EXISTS TMP_PROPERTIES"); // Creates temporary table logger.info("Creating TMP_PROPERTIES..."); postgresql.getJdbcOperations().execute("CREATE TABLE TMP_PROPERTIES " + "( " + " ID INTEGER PRIMARY KEY, " + " TYPE CHARACTER VARYING(150), " + " PROJECT INTEGER, " + " BRANCH INTEGER, " + " PROMOTION_LEVEL INTEGER, " + " VALIDATION_STAMP INTEGER, " + " BUILD INTEGER, " + " PROMOTION_RUN INTEGER, " + " VALIDATION_RUN INTEGER, " + " SEARCHKEY CHARACTER VARYING(200), " + " JSON JSONB " + ");"); }); int count = intx(() -> { // Copy to tmp space logger.info("Migrating PROPERTIES to TMP_PROPERTIES (no check)..."); List<Map<String, Object>> sources = h2.queryForList(h2Query, Collections.emptyMap()); @SuppressWarnings("unchecked") Map<String, ?>[] array = sources.toArray(new Map[sources.size()]); postgresql.batchUpdate(postgresqlUpdate, array); return sources.size(); }); tx(() -> { // Copying the tmp logger.info("Copying TMP_PROPERTIES into PROPERTIES..."); postgresql.getJdbcOperations().execute("INSERT INTO PROPERTIES SELECT * FROM TMP_PROPERTIES"); // Deletes tmp table logger.info("Deleting TMP_PROPERTIES..."); postgresql.getJdbcOperations().execute("DROP TABLE TMP_PROPERTIES;"); }); logger.info("{} count = {}...", "PROPERTIES", count); } private void copyEvents() { String h2Query = "SELECT * FROM EVENTS"; String[] columns = new String[]{"ID", "PROJECT", "BRANCH", "PROMOTION_LEVEL", "VALIDATION_STAMP", "BUILD", "PROMOTION_RUN", "VALIDATION_RUN", "EVENT_TYPE", "REF", "EVENT_VALUES", "EVENT_TIME", "EVENT_USER"}; String insert = Arrays.asList(columns).stream().map(column -> StringUtils.substringBefore(column, "::")).collect(Collectors.joining(",")); // String values = Arrays.asList(columns).stream().map(column -> ":" + column).collect(Collectors.joining(",")); String postgresqlUpdate = String.format( "INSERT INTO TMP_EVENTS (%s) VALUES (%s)", insert, StringUtils.repeat("?", ",", columns.length) ); tx(() -> { // Makes sure TMP_EVENTS is dropped postgresql.getJdbcOperations().execute("DROP TABLE IF EXISTS TMP_EVENTS"); // Creates temporary `events` table, without any contraint logger.info("Creating TMP_EVENTS..."); postgresql.getJdbcOperations().execute("CREATE TABLE TMP_EVENTS " + "( " + " ID INTEGER PRIMARY KEY, " + " EVENT_TYPE CHARACTER VARYING(120), " + " PROJECT INTEGER, " + " BRANCH INTEGER, " + " PROMOTION_LEVEL INTEGER, " + " VALIDATION_STAMP INTEGER, " + " BUILD INTEGER, " + " PROMOTION_RUN INTEGER, " + " VALIDATION_RUN INTEGER, " + " REF CHARACTER VARYING(20), " + " EVENT_VALUES CHARACTER VARYING(500), " + " EVENT_TIME CHARACTER VARYING(24), " + " EVENT_USER CHARACTER VARYING(40) " + ");"); }); int count = intx(() -> { logger.info("Migrating EVENTS to TMP_{} (no check)...", "EVENTS"); List<Map<String, Object>> sources = h2.queryForList(h2Query, Collections.emptyMap()); int size = sources.size(); postgresql.getJdbcOperations().execute( postgresqlUpdate, (PreparedStatementCallback<Void>) ps -> { int index = 0; for (Map<String, Object> source : sources) { index++; if (index % 1000 == 0) { logger.info("Migrating EVENTS to TMP_EVENTS (no check) {}/{}", index, size); } int i = 1; ps.setInt(i++, (Integer) source.get("ID")); ps.setObject(i++, source.get("PROJECT")); ps.setObject(i++, source.get("BRANCH")); ps.setObject(i++, source.get("PROMOTION_LEVEL")); ps.setObject(i++, source.get("VALIDATION_STAMP")); ps.setObject(i++, source.get("BUILD")); ps.setObject(i++, source.get("PROMOTION_RUN")); ps.setObject(i++, source.get("VALIDATION_RUN")); ps.setString(i++, (String) source.get("EVENT_TYPE")); ps.setString(i++, (String) source.get("REF")); ps.setString(i++, (String) source.get("EVENT_VALUES")); ps.setString(i++, (String) source.get("EVENT_TIME")); ps.setString(i++, (String) source.get("EVENT_USER")); ps.addBatch(); } ps.executeBatch(); return null; } ); return size; }); tx(() -> { // Copying the tmp logger.info("Copying TMP_EVENTS into EVENTS..."); postgresql.getJdbcOperations().execute("INSERT INTO EVENTS SELECT * FROM TMP_EVENTS"); // Deletes tmp table logger.info("Deleting TMP_EVENTS..."); postgresql.getJdbcOperations().execute("DROP TABLE TMP_EVENTS;"); }); logger.info("{} count = {}...", "EVENTS", count); } private void updateSequences() { logger.info("Resetting the sequences..."); String[] tables = { "ACCOUNT_GROUP_MAPPING", "ACCOUNT_GROUPS", "ACCOUNTS", "BRANCHES", "BUILDS", "CONFIGURATIONS", "ENTITY_DATA", "EVENTS", "EXT_SVN_REPOSITORY", "PREDEFINED_PROMOTION_LEVELS", "PREDEFINED_VALIDATION_STAMPS", "PROJECTS", "PROMOTION_LEVELS", "PROMOTION_RUNS", "PROPERTIES", "VALIDATION_RUN_STATUSES", "VALIDATION_RUNS", "VALIDATION_STAMPS", }; tx(() -> Arrays.asList(tables).stream().forEach(table -> { Integer max = postgresql.queryForObject( String.format("SELECT MAX(ID) AS ID FROM %s", table), Collections.emptyMap(), Integer.class ); int value = max != null ? max + 1 : 1; postgresql.update( String.format("ALTER SEQUENCE %s_ID_SEQ RESTART WITH %d", table, value), Collections.emptyMap() ); logger.info("Resetting sequence for {} to {}.", table, value); })); } private void cleanup() { logger.info("Cleanup of target database..."); String[] tables = { "ACCOUNTS", "ACCOUNT_GROUPS", "CONFIGURATIONS", "EXT_SVN_REPOSITORY", "PREDEFINED_PROMOTION_LEVELS", "PREDEFINED_VALIDATION_STAMPS", "PROJECTS", "EVENTS", "SETTINGS", "STORAGE", }; tx(() -> { for (String table : tables) { postgresql.update(String.format("DELETE FROM %s", table), Collections.emptyMap()); } }); } private void tx(Runnable task) { txTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { try { task.run(); } catch (Exception ex) { String message = ex.getMessage(); if (StringUtils.contains(message, "Block not found") && migrationProperties.isSkipBlobErrors()) { logger.warn("Ignoring BLOB read error: {}", message); } else { throw ex; } } } }); } private <T> T intx(Supplier<T> supplier) { return txTemplate.execute(status -> supplier.get()); } private void copy(String table, String... columns) { String h2Query = String.format("SELECT * FROM %s", table); String insert = Arrays.asList(columns).stream().map(column -> StringUtils.substringBefore(column, "::")).collect(Collectors.joining(",")); String values = Arrays.asList(columns).stream().map(column -> ":" + column).collect(Collectors.joining(",")); String postgresqlUpdate = String.format("INSERT INTO %s (%s) VALUES (%s)", table, insert, values); tx(() -> simpleMigration( table, h2Query, Collections.emptyMap(), postgresqlUpdate )); } private void simpleMigration(String name, String h2Query, Map<String, Object> h2Params, String postgresqlUpdate) { logger.info("Migrating {}...", name); List<Map<String, Object>> sources = h2.queryForList(h2Query, h2Params); int count = sources.size(); @SuppressWarnings("unchecked") Map<String, ?>[] array = sources.toArray(new Map[sources.size()]); postgresql.batchUpdate(postgresqlUpdate, array); logger.info("{} count = {}...", name, count); } }
package com.cloudant.client.api; import com.cloudant.client.api.views.Key; import com.cloudant.client.internal.util.DeserializationTypes; import com.cloudant.client.internal.util.IndexDeserializer; import com.cloudant.client.internal.util.SecurityDeserializer; import com.cloudant.client.internal.util.ShardDeserializer; import com.cloudant.client.org.lightcouch.CouchDbException; import com.cloudant.client.org.lightcouch.CouchDbProperties; import com.cloudant.http.HttpConnectionInterceptor; import com.cloudant.http.HttpConnectionRequestInterceptor; import com.cloudant.http.HttpConnectionResponseInterceptor; import com.cloudant.http.interceptors.CookieInterceptor; import com.cloudant.http.interceptors.ProxyAuthInterceptor; import com.cloudant.http.interceptors.SSLCustomizerInterceptor; import com.cloudant.http.interceptors.TimeoutCustomizationInterceptor; import com.google.gson.GsonBuilder; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import javax.net.ssl.SSLSocketFactory; public class ClientBuilder { /** * Default max of 6 connections **/ public static final int DEFAULT_MAX_CONNECTIONS = 6; /** * Connection timeout defaults to 5 minutes **/ public static final long DEFAULT_CONNECTION_TIMEOUT = 5l; /** * Read timeout defaults to 5 minutes **/ public static final long DEFAULT_READ_TIMEOUT = 5l; private static final Logger logger = Logger.getLogger(ClientBuilder.class.getName()); private List<HttpConnectionRequestInterceptor> requestInterceptors = new ArrayList <HttpConnectionRequestInterceptor>(); private List<HttpConnectionResponseInterceptor> responseInterceptors = new ArrayList <HttpConnectionResponseInterceptor>(); private String password; private String username; private URL url; private GsonBuilder gsonBuilder; /** * Defaults to {@link #DEFAULT_MAX_CONNECTIONS} **/ private int maxConnections = DEFAULT_MAX_CONNECTIONS; private URL proxyURL; private String proxyUser; private String proxyPassword; private boolean isSSLAuthenticationDisabled; private SSLSocketFactory authenticatedModeSSLSocketFactory; private long connectTimeout = DEFAULT_CONNECTION_TIMEOUT; private TimeUnit connectTimeoutUnit = TimeUnit.MINUTES; private long readTimeout = DEFAULT_READ_TIMEOUT; private TimeUnit readTimeoutUnit = TimeUnit.MINUTES; public static ClientBuilder account(String account) { logger.config("Account: " + account); try { URL url = new URL(String.format("https://%s.cloudant.com", account)); return ClientBuilder.url(url); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not generate url from account name.", e); } } public static ClientBuilder url(URL url) { return new ClientBuilder(url); } private ClientBuilder(URL url) { logger.config("URL: " + url); String urlProtocol = url.getProtocol(); String urlHost = url.getHost(); //Check if port exists int urlPort = url.getPort(); if (urlPort < 0) { urlPort = url.getDefaultPort(); } if (url.getUserInfo() != null) { //Get username and password and replace credential variables this.username = url.getUserInfo().substring(0, url .getUserInfo() .indexOf(":")); this.password = url.getUserInfo().substring(url .getUserInfo() .indexOf(":") + 1); } try { //Remove user credentials from url this.url = new URL(urlProtocol + ": + urlHost + ":" + urlPort); } catch (MalformedURLException e) { throw new RuntimeException(e); } } /** * Build the {@link CloudantClient} instance based on the endpoint used to construct this * client builder and the options that have been set on it before calling this method. * * @return the {@link CloudantClient} instance for the specified end point and options */ public CloudantClient build() { logger.config("Building client using URL: " + url); //Build properties and couchdb client CouchDbProperties props = new CouchDbProperties(url); //Create cookie interceptor if (this.username != null && this.password != null) { //make interceptor if both username and password are not null //Create cookie interceptor and set in HttpConnection interceptors CookieInterceptor cookieInterceptor = new CookieInterceptor(username, password); props.addRequestInterceptors(cookieInterceptor); props.addResponseInterceptors(cookieInterceptor); logger.config("Added cookie interceptor"); } else { //If username or password is null, throw an exception if (username != null || password != null) { //Username and password both have to contain values throw new CouchDbException("Either a username and password must be provided, or " + "both values must be null. Please check the credentials and try again."); } } //If setter methods for read and connection timeout are not called, default values are used. logger.config(String.format("Connect timeout: %s %s", connectTimeout, connectTimeoutUnit)); logger.config(String.format("Read timeout: %s %s", readTimeout, readTimeoutUnit)); props.addRequestInterceptors(new TimeoutCustomizationInterceptor(connectTimeout, connectTimeoutUnit, readTimeout, readTimeoutUnit)); //Set connect options props.setMaxConnections(maxConnections); props.setProxyURL(proxyURL); if (proxyUser != null) { //if there was proxy auth information create an interceptor for it props.addRequestInterceptors(new ProxyAuthInterceptor(proxyUser, proxyPassword)); logger.config("Added proxy auth interceptor"); } if (isSSLAuthenticationDisabled) { props.addRequestInterceptors(SSLCustomizerInterceptor .SSL_AUTH_DISABLED_INTERCEPTOR); logger.config("SSL authentication is disabled"); } if (authenticatedModeSSLSocketFactory != null) { props.addRequestInterceptors(new SSLCustomizerInterceptor( authenticatedModeSSLSocketFactory )); logger.config("Added custom SSL socket factory"); } //Set http connection interceptors if (requestInterceptors != null) { for (HttpConnectionRequestInterceptor requestInterceptor : requestInterceptors) { props.addRequestInterceptors(requestInterceptor); logger.config("Added request interceptor: " + requestInterceptor.getClass() .getName()); } } if (responseInterceptors != null) { for (HttpConnectionResponseInterceptor responseInterceptor : responseInterceptors) { props.addResponseInterceptors(responseInterceptor); logger.config("Added response interceptor: " + responseInterceptor.getClass() .getName()); } } //if no gsonBuilder has been provided, create a new one if (gsonBuilder == null) { gsonBuilder = new GsonBuilder(); logger.config("Using default GSON builder"); } else { logger.config("Using custom GSON builder"); } //always register additional TypeAdapaters for derserializing some Cloudant specific // types before constructing the CloudantClient gsonBuilder.registerTypeAdapter(DeserializationTypes.SHARDS, new ShardDeserializer()) .registerTypeAdapter(DeserializationTypes.INDICES, new IndexDeserializer()) .registerTypeAdapter(DeserializationTypes.PERMISSIONS_MAP, new SecurityDeserializer()) .registerTypeAdapter(Key.ComplexKey.class, new Key.ComplexKeyDeserializer()); return new CloudantClient(props, gsonBuilder); } /** * Sets a username or API key for the client connection. * * @param username the user or API key for the session * @return this ClientBuilder object for setting additional options */ public ClientBuilder username(String username) { this.username = username; return this; } /** * Sets the password for the client connection. The password is the one for the username or * API key set by the {@link #username(String)} method. * * @param password user password or API key passphrase * @return this ClientBuilder object for setting additional options */ public ClientBuilder password(String password) { this.password = password; return this; } /** * Set a custom GsonBuilder to use when serializing and de-serializing JSON in requests and * responses between the CloudantClient and the server. * <P> * Note: the supplied GsonBuilder will be augmented with some internal TypeAdapters. * </P> * * @param gsonBuilder the custom GsonBuilder to use * @return this ClientBuilder object for setting additional options */ public ClientBuilder gsonBuilder(GsonBuilder gsonBuilder) { this.gsonBuilder = gsonBuilder; return this; } /** * Set the maximum number of connections to maintain in the connection pool. * <P> * Note: this setting only applies if using the optional OkHttp dependency. If OkHttp is not * present then the JVM configuration is used for pooling. Consult the JVM documentation for * the {@code http.maxConnections} property for further details. * </P> * Defaults to {@link #DEFAULT_MAX_CONNECTIONS} * * @param maxConnections the maximum number of simultaneous connections to open to the server * @return this ClientBuilder object for setting additional options */ public ClientBuilder maxConnections(int maxConnections) { this.maxConnections = maxConnections; return this; } /** * Sets a proxy url for the client connection. * * @param proxyURL the URL of the proxy server * @return this ClientBuilder object for setting additional options */ public ClientBuilder proxyURL(URL proxyURL) { this.proxyURL = proxyURL; return this; } /** * Sets an optional proxy username for the client connection. * * @param proxyUser username for the proxy server * @return this ClientBuilder object for setting additional options */ public ClientBuilder proxyUser(String proxyUser) { this.proxyUser = proxyUser; return this; } /** * Sets an optional proxy password for the proxy user specified by * {@link #proxyUser(String)}. * * @param proxyPassword password for the proxy server user * @return this ClientBuilder object for setting additional options */ public ClientBuilder proxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; return this; } public ClientBuilder disableSSLAuthentication() { if (authenticatedModeSSLSocketFactory == null) { this.isSSLAuthenticationDisabled = true; } else { throw new IllegalStateException("Cannot disable SSL authentication when a " + "custom SSLSocketFactory has been set."); } return this; } public ClientBuilder customSSLSocketFactory(SSLSocketFactory factory) { if (!isSSLAuthenticationDisabled) { this.authenticatedModeSSLSocketFactory = factory; } else { throw new IllegalStateException("Cannot use a custom SSLSocketFactory when " + "SSL authentication is disabled."); } return this; } /** * This method adds {@link HttpConnectionInterceptor}s to be used on the CloudantClient * connection. Interceptors can be used to modify the HTTP requests and responses between the * CloudantClient and the server. * <P> * An example interceptor use might be to apply a custom authorization mechanism. For * instance to use BasicAuth instead of CookieAuth it is possible to use a * {@link com.cloudant.http.interceptors.BasicAuthInterceptor} that adds the BasicAuth * {@code Authorization} header to the request: * </P> * <pre> * {@code * CloudantClient client = ClientBuilder.account("yourCloudantAccount") * .interceptors(new BasicAuthInterceptor("yourUsername:yourPassword")) * .build() * } * </pre> * * @param interceptors one or more HttpConnectionInterceptor objects * @return this ClientBuilder object for setting additional options * @see HttpConnectionInterceptor */ public ClientBuilder interceptors(HttpConnectionInterceptor... interceptors) { for (HttpConnectionInterceptor interceptor : interceptors) { if (interceptor instanceof HttpConnectionRequestInterceptor) { requestInterceptors.add((HttpConnectionRequestInterceptor) interceptor); } if (interceptor instanceof HttpConnectionResponseInterceptor) { responseInterceptors.add((HttpConnectionResponseInterceptor) interceptor); } } return this; } /** * Sets the specified timeout value when opening the client connection. If the timeout * expires before the connection can be established, a * {@link java.net.SocketTimeoutException} is raised. * <P> * Example creating a {@link CloudantClient} with a connection timeout of 2 seconds: * </P> * <pre> * {@code * CloudantClient client = ClientBuilder.account("yourCloudantAccount") * .username("yourUsername") * .password("yourPassword") * .connectTimeout(2, TimeUnit.SECONDS) * .build(); * } * </pre> * Defaults to {@link #DEFAULT_CONNECTION_TIMEOUT} with {@link TimeUnit#MINUTES}. * * @param connectTimeout duration of the read timeout * @param connectTimeoutUnit unit of measurement of the read timeout parameter * @return this ClientBuilder object for setting additional options * @see java.net.HttpURLConnection#setConnectTimeout(int) **/ public ClientBuilder connectTimeout(long connectTimeout, TimeUnit connectTimeoutUnit) { this.connectTimeout = connectTimeout; this.connectTimeoutUnit = connectTimeoutUnit; return this; } /** * Sets the specified timeout value when reading from a {@link java.io.InputStream} with an * established client connection. If the timeout expires before there is data available for * read, a {@link java.net.SocketTimeoutException} is raised. * <P> * Example creating a {@link CloudantClient} with a read timeout of 2 seconds: * </P> * <pre> * {@code * CloudantClient client = ClientBuilder.account("yourCloudantAccount") * .username("yourUsername") * .password("yourPassword") * .readTimeout(2, TimeUnit.SECONDS) * .build(); * } * </pre> * Defaults to {@link #DEFAULT_READ_TIMEOUT} with {@link TimeUnit#MINUTES}. * * @param readTimeout duration of the read timeout * @param readTimeoutUnit unit of measurement of the read timeout parameter * @return this ClientBuilder object for setting additional options * @see java.net.HttpURLConnection#setReadTimeout(int) **/ public ClientBuilder readTimeout(long readTimeout, TimeUnit readTimeoutUnit) { this.readTimeout = readTimeout; this.readTimeoutUnit = readTimeoutUnit; return this; } }
package org.ai4fm.proofprocess.isabelle.core.parse; import isabelle.Markup; import isabelle.Pretty; import isabelle.XML.Elem; import isabelle.XML.Text; import isabelle.XML.Tree; import isabelle.scala.ScalaCollections; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.ai4fm.proofprocess.Term; import org.ai4fm.proofprocess.isabelle.CompositeTerm; import org.ai4fm.proofprocess.isabelle.DisplayTerm; import org.ai4fm.proofprocess.isabelle.IsaTerm; import org.ai4fm.proofprocess.isabelle.IsabelleProofProcessFactory; import org.ai4fm.proofprocess.isabelle.TermKind; import scala.Tuple2; import scala.collection.Iterator; /** * @author Andrius Velykis */ public class TermParser { private static IsabelleProofProcessFactory FACTORY = IsabelleProofProcessFactory.eINSTANCE; private static Set<String> IGNORE_MARKUPS = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList( Markup.BREAK()))); public static List<Term> parseGoals(Tree source) { List<Term> goals = new ArrayList<Term>(); // get all XML elements for <subgoal> for (Elem subgoalElem : getElems(ScalaCollections.singletonList(source), Markup.SUBGOAL())) { // expect a single <term> XML element inside Elem termElem = getSingleElem(subgoalElem.body(), Markup.TERM()); Term ppTerm = parseTerm(termElem); goals.add(ppTerm); } return goals; } private static List<Elem> getElems(scala.collection.immutable.List<Tree> source, String markup) { List<Elem> elems = new ArrayList<Elem>(); collectElems(source, markup, elems); return elems; } private static void collectElems(scala.collection.immutable.List<Tree> source, String markup, List<Elem> elems) { for (Iterator<Tree> it = source.iterator(); it.hasNext();) { Tree obj = it.next(); if (obj instanceof Elem) { Elem elem = (Elem) obj; if (markup.equals(elem.markup().name())) { // found elem with correct markup elems.add(elem); } else { // recurse deeper collectElems(elem.body(), markup, elems); } } } } private static Elem getSingleElem(scala.collection.immutable.List<Tree> body, String markup) { List<Elem> elems = getElems(body, markup); if (elems.size() == 1) { // if single element found, return it return elems.get(0); } // invalid cases if (elems.isEmpty()) { throw new IllegalArgumentException("No <" + markup + "> found: " + body); } throw new IllegalArgumentException("Multiple <" + markup + "> found: " + body); } private static Term parseTerm(Elem termElem) { // do the parsing - ensuring its TERM if (!Markup.TERM().equals(termElem.markup().name())) { throw new IllegalArgumentException("Expected <term>, found: " + termElem); } CompositeTermParser parser = new CompositeTermParser(); parser.parse(termElem.body()); Term term = parser.rootTerm; if (term == null) { throw new IllegalStateException("Invalid term: " + termElem); } return term; } private static class CompositeTermParser { private final Stack<DisplayTerm> termStack = new Stack<DisplayTerm>(); private Term rootTerm; public void parse(scala.collection.immutable.List<Tree> source) { for (Iterator<Tree> it = source.iterator(); it.hasNext();) { Tree e = it.next(); if (e instanceof Text) { String content = ((Text) e).content(); DisplayTerm top = termStack.peek(); if (top instanceof IsaTerm) { IsaTerm isaTerm = (IsaTerm) top; if (isaTerm.getName() == null) { isaTerm.setName(content); } else { // usually happens for CONST entities, they have a fully-qualified name // and a "display" text inside // System.out.println("Term name already set. Text: " + content + ";\nTerm: " + isaTerm); } } else { // usually happens for CompositeTerms, when parentheses are used, // e.g. composite would have ["(", IsaTerm, ")"]. // System.out.println("Text element inside a non-term. Text: " + content + ";\nTerm: " + top); } } else if (e instanceof Elem) { Elem elem = (Elem) e; Markup markup = elem.markup(); if (Markup.BLOCK().equals(markup.name()) && elem.body().size() == 1) { // single element inside a block - continue on the inner element, // skipping the outer BLOCK parse(elem.body()); } else if (ignoreElem(markup.name())){ // Some elements are in result XML for pretty-printing // only, and should be ignored in parsing altogether, e.g. <break>. // Do nothing for this elem - continue onto the next one continue; } else { DisplayTerm term = parseElem(markup); // render the element for display term.setDisplay(renderDisplay(elem)); addToParent(term, source); // push the term onto stack, and continue in its body termStack.push(term); parse(elem.body()); termStack.pop(); } } else { throw new IllegalStateException("Unsupported XML element: " + e); } } } private boolean ignoreElem(String markup) { return IGNORE_MARKUPS.contains(markup); } private void addToParent(DisplayTerm term, scala.collection.immutable.List<Tree> source) { if (termStack.isEmpty()) { // this is the root term, others will be added to it rootTerm = term; } else { // the top should be composite - add to it DisplayTerm top = termStack.peek(); if (top instanceof CompositeTerm) { // add the term to the parent composite ((CompositeTerm) top).getTerms().add(term); } else { // TODO this happens for <fixed><free> System.out.println("Invalid top of the stack: " + top + ";\nterm: " + term + ";\nsource: " + source); } } } private DisplayTerm parseElem(Markup elemMarkup) { if (Markup.BLOCK().equals(elemMarkup.name())) { // TODO render the display? return FACTORY.createCompositeTerm(); } if (Markup.ENTITY().equals(elemMarkup.name())) { IsaTerm isaTerm = FACTORY.createIsaTerm(); Map<String, String> props = propsMap(elemMarkup.properties()); isaTerm.setName(props.get(Markup.NAME())); String kindStr = props.get(Markup.KIND()); if (Markup.CONSTANT().equals(kindStr)) { isaTerm.setKind(TermKind.CONST); } else { throw new IllegalStateException("Unknown entity kind: " + kindStr); } return isaTerm; } TermKind termKind = getTermKind(elemMarkup.name()); if (termKind != null) { IsaTerm isaTerm = FACTORY.createIsaTerm(); isaTerm.setKind(termKind); return isaTerm; } throw new IllegalStateException("Unsupported markup: " + elemMarkup); } private TermKind getTermKind(String markup) { if (Markup.BOUND().equals(markup)) { return TermKind.BOUND; } if (Markup.VAR().equals(markup)) { return TermKind.VAR; } if (Markup.FIXED().equals(markup)) { return TermKind.FIXED; } if (Markup.FREE().equals(markup)) { return TermKind.FREE; } return null; } private Map<String, String> propsMap( scala.collection.immutable.List<Tuple2<String, String>> props) { Map<String, String> propsMap = new HashMap<String, String>(); for (Iterator<Tuple2<String, String>> it = props.iterator(); it.hasNext();) { Tuple2<String, String> prop = it.next(); propsMap.put(prop._1(), prop._2()); } return propsMap; } private String renderDisplay(Elem elem) { return Pretty.str_of(ScalaCollections.<Tree>singletonList(elem)); } } }
// FILE: c:/projects/jetel/org/jetel/exception/NoMoreDataException.java package org.jetel.exception; import org.jetel.graph.GraphElement; /** A class that represents general Jetel exception * * @see Exception * @author D.Pavlis */ public class ComponentNotReadyException extends Exception { // Attributes GraphElement graphElement; // Associations // Operations public ComponentNotReadyException(String message){ super(message); } public ComponentNotReadyException(Exception ex){ super(ex); } public ComponentNotReadyException(GraphElement element,Exception ex){ super(ex); this.graphElement=element; } public ComponentNotReadyException(GraphElement element,String message,Exception ex){ super(message,ex); this.graphElement=element; } public ComponentNotReadyException(GraphElement element,String message){ super(message); this.graphElement=element; } public GraphElement getGraphElement(){ return graphElement; } public String toString() { StringBuffer message = new StringBuffer(80); if (graphElement!=null){ message.append("Element [").append(graphElement.getId()).append(':'); if (graphElement.getName()!=null) message.append(graphElement.getName()); message.append("]-"); } message.append(super.getMessage()); return message.toString(); } } /* end class NoMoreDataException */
package org.caleydo.view.stratomex.command.handler; import org.caleydo.view.stratomex.GLStratomex; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.handlers.HandlerUtil; public class OpenStratomexHandler extends AbstractHandler implements IHandler { /** * Counter variable for determination of the secondary view ID. Needed for * multiple instances of the same view type. */ private static int SECONDARY_ID = 0; @Override public Object execute(ExecutionEvent event) throws ExecutionException { try { HandlerUtil .getActiveWorkbenchWindow(event) .getActivePage() .showView(GLStratomex.VIEW_TYPE, Integer.toString(SECONDARY_ID++), IWorkbenchPage.VIEW_ACTIVATE); } catch (PartInitException e) { e.printStackTrace(); } return null; } }
package org.eclipse.ec4e.codelens; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import org.eclipse.codelens.editors.IEditorCodeLensContext; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.ec4e.IDEEditorConfigManager; import org.eclipse.ec4e.search.CountSectionPatternVisitor; import org.eclipse.ec4j.core.EditorConfigLoader; import org.eclipse.ec4j.core.Resources; import org.eclipse.ec4j.core.model.Section; import org.eclipse.ec4j.core.parser.EditorConfigParser; import org.eclipse.ec4j.core.parser.Location; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.provisional.codelens.AbstractSyncCodeLensProvider; import org.eclipse.jface.text.provisional.codelens.ICodeLens; import org.eclipse.jface.text.provisional.codelens.ICodeLensContext; import org.eclipse.ui.texteditor.ITextEditor; public class EditorConfigCodeLensProvider extends AbstractSyncCodeLensProvider { @Override protected ICodeLens[] provideSyncCodeLenses(ICodeLensContext context, IProgressMonitor monitor) { ITextEditor textEditor = ((IEditorCodeLensContext) context).getTextEditor(); IFile file = EditorConfigCodeLensControllerProvider.getFile(textEditor); if (file == null) { return null; } IDocument document = context.getViewer().getDocument(); EditorConfigLoader loader = IDEEditorConfigManager.getInstance().getSession().getLoader(); SectionsHandler handler = new SectionsHandler(loader.getRegistry(), loader.getVersion()); EditorConfigParser parser = EditorConfigParser.builder().tolerant().build(); try { parser.parse(Resources.ofString(file.getFullPath().toString(), document.get()), handler); } catch (IOException e) { /* Will not happen with Resources.ofString() */ throw new RuntimeException(e); } List<Section> sections = handler.getEditorConfig().getSections(); List<Location> sectionLocations = handler.getSectionLocations(); ICodeLens[] lenses = new ICodeLens[sections.size()]; for (int i = 0; i < lenses.length; i++) { lenses[i] = new EditorConfigCodeLens(sections.get(i), sectionLocations.get(i), file); } return lenses; } @Override protected ICodeLens resolveSyncCodeLens(ICodeLensContext context, ICodeLens codeLens, IProgressMonitor monitor) { ITextEditor textEditor = ((IEditorCodeLensContext) context).getTextEditor(); IFile file = EditorConfigCodeLensControllerProvider.getFile(textEditor); if (file == null) { return null; } EditorConfigCodeLens cl = (EditorConfigCodeLens) codeLens; CountSectionPatternVisitor visitor = new CountSectionPatternVisitor(cl.getSection()); try { file.getParent().accept(visitor, IResource.NONE); cl.update(visitor.getNbFiles() + " files match"); } catch (CoreException e) { cl.update(e.getMessage()); } return cl; } }
package org.eclipse.mylar.tasks.ui.properties; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.mylar.core.MylarStatusHandler; import org.eclipse.mylar.internal.tasks.ui.actions.AddRepositoryAction; import org.eclipse.mylar.internal.tasks.ui.views.TaskRepositoriesSorter; import org.eclipse.mylar.internal.tasks.ui.views.TaskRepositoryLabelProvider; import org.eclipse.mylar.tasks.core.TaskRepository; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PropertyPage; import org.eclipse.ui.internal.dialogs.DialogUtil; /** * @author Rob Elves * @see Adapted from org.eclipse.ui.internal.ide.dialogs.ProjectReferencePage */ public class ProjectTaskRepositoryPage extends PropertyPage { private static final int REPOSITORY_LIST_MULTIPLIER = 30; private IProject project; private boolean modified = false; private CheckboxTableViewer listViewer; public ProjectTaskRepositoryPage() { // Do nothing on creation } @Override protected Control createContents(Composite parent) { Font font = parent.getFont(); Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); composite.setFont(font); initialize(); Label description = createDescriptionLabel(composite); description.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); listViewer = CheckboxTableViewer.newCheckList(composite, SWT.TOP | SWT.BORDER); listViewer.getTable().setFont(font); GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessHorizontalSpace = true; // Only set a height hint if it will not result in a cut off dialog if (DialogUtil.inRegularFontMode(parent)) { data.heightHint = getDefaultFontHeight(listViewer.getTable(), REPOSITORY_LIST_MULTIPLIER); } listViewer.getTable().setLayoutData(data); listViewer.getTable().setFont(font); listViewer.setLabelProvider(new DecoratingLabelProvider(new TaskRepositoryLabelProvider(), PlatformUI .getWorkbench().getDecoratorManager().getLabelDecorator())); listViewer.setContentProvider(new IStructuredContentProvider() { public void inputChanged(Viewer v, Object oldInput, Object newInput) { } public void dispose() { } public Object[] getElements(Object parent) { return TasksUiPlugin.getRepositoryManager().getAllRepositories().toArray(); } }); listViewer.setSorter(new TaskRepositoriesSorter()); listViewer.setInput(project.getWorkspace()); listViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event) { if (event.getChecked()) { // only allow single selection listViewer.setAllChecked(false); listViewer.setChecked(event.getElement(), event.getChecked()); } modified = true; } }); updateLinkedRepository(); final AddRepositoryAction action = new AddRepositoryAction(); Button button = new Button(composite, SWT.NONE); button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING)); button.setText(AddRepositoryAction.TITLE); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { action.run(); listViewer.setInput(project.getWorkspace()); updateLinkedRepository(); } }); return composite; } void updateLinkedRepository() { TaskRepository repository = TasksUiPlugin.getDefault().getRepositoryForResource(project, true); if (repository != null) { listViewer.setCheckedElements(new Object[] { repository }); } listViewer.getControl().setEnabled(TasksUiPlugin.getDefault().canSetRepositoryForResource(project)); } private static int getDefaultFontHeight(Control control, int lines) { FontData[] viewerFontData = control.getFont().getFontData(); int fontHeight = 10; // If we have no font data use our guess if (viewerFontData.length > 0) { fontHeight = viewerFontData[0].getHeight(); } return lines * fontHeight; } /** * Initializes a ProjectReferencePage. */ private void initialize() { project = (IProject) getElement().getAdapter(IResource.class); noDefaultAndApplyButton(); setDescription("Select a task repository to associate with this project below:"); } /** * @see PreferencePage#performOk */ @Override public boolean performOk() { if (!modified) { return true; } if (listViewer.getCheckedElements().length > 0) { TaskRepository selectedRepository = (TaskRepository) listViewer.getCheckedElements()[0]; try { TasksUiPlugin plugin = TasksUiPlugin.getDefault(); if(plugin.canSetRepositoryForResource(project)) { plugin.setRepositoryForResource(project, selectedRepository); } } catch (CoreException e) { MylarStatusHandler.fail(e, "Unable to associate project with task repository", true); } } return true; } }
package org.eclipse.titan.designer.AST.TTCN3.values; /** * Extracts TTCN-3 charstring * @author Arpad Lovassy */ public class CharstringExtractor { // Error messages private static final String INVALID_ESCAPE_SEQUENCE = "Invalid escape sequence: "; /** true, if TTCN-3 string contains error */ private boolean mErrorneous = false; /** the value string of the TTCN-3 string */ private String mExtractedString; /** the error message (if any) */ private String mErrorMessage; /** * Constructor * @param aTccnCharstring the TTCN-3 string with escapes to extract */ public CharstringExtractor( final String aTccnCharstring ) { mExtractedString = extractString( aTccnCharstring ); } /** @return the value string of the TTCN-3 string */ public String getExtractedString() { return mExtractedString; } /** * @return if TTCN-3 string contains error */ public boolean isErrorneous() { return mErrorneous; } /** * @return the error message (if any) */ public String getErrorMessage() { return mErrorMessage; } /** * Converts string with special characters to normal displayable string * Special characters: * "" -> " * \['"?\abfnrtv\u000a] * \x[0-9a-fA-F][0-9a-fA-F]? * \[0-3]?[0-7][0-7]? * @param aTccnCharstring TTCN-3 charstring representation, it can contain escape characters, NOT NULL * @return extracted string value */ private String extractString(final String aTccnCharstring) { final int slength = aTccnCharstring.length(); int pointer = 0; StringBuilder sb = new StringBuilder(); while (pointer < slength) { // Special characters: // Special characters by the TTCNv3 standard: // The 2 double-quotes: "" -> it is one double-quote if (pointer + 1 < slength && aTccnCharstring.substring(pointer, pointer + 2).equals("\"\"")) { sb.append('"'); pointer += 2; } // TITAN specific special characters: // backslash-escaped character sequences: else if (pointer + 1 < slength) { char c1 = aTccnCharstring.charAt(pointer); if (c1 == '\\') { pointer++; char c2 = aTccnCharstring.charAt(pointer); // backslash-escaped singlequote, // doublequote, question mark or // backslash: if (c2 == '\'' || c2 == '"' || c2 == '?' || c2 == '\\') { sb.append(aTccnCharstring.charAt(pointer)); pointer++; } else if (c2 == 'a') { // Audible bell sb.append((char) 0x07); pointer++; } else if (c2 == 'b') { // Backspace sb.append((char) 0x08); pointer++; } else if (c2 == 'f') { // Form feed sb.append((char) 0x0c); pointer++; } else if (c2 == 'n') { // New line sb.append((char) 0x0a); pointer++; } else if (c2 == 'r') { // Carriage return sb.append((char) 0x0d); pointer++; } else if (c2 == 't') { // Horizontal tab sb.append((char) 0x09); pointer++; } else if (c2 == 'v') { // Vertical tab sb.append((char) 0x0b); pointer++; } else if (c2 == 10) { // New line escaped sb.append((char) 0x0a); pointer++; } else if (c2 == 'x') { // hex-notation: \xHH? pointer++; if (pointer >= slength) { // end of string reached mErrorMessage = INVALID_ESCAPE_SEQUENCE + "'\\x'"; mErrorneous = true; return null; } final int hexStart = pointer; if (!isHexDigit(aTccnCharstring.charAt(pointer))) { // invalid char after \x mErrorMessage = INVALID_ESCAPE_SEQUENCE + "'\\x" + aTccnCharstring.charAt(hexStart) + "'"; mErrorneous = true; return null; } pointer++; if (pointer < slength && isHexDigit(aTccnCharstring.charAt(pointer))) { // 2nd hex digit is optional pointer++; } sb.append((char) Integer.parseInt(aTccnCharstring.substring(hexStart, pointer), 16)); } else if (isOctDigit(c2)) { // [0..7] // octal notation: \[0-3]?[0-7][0-7]? final int octStart = pointer; pointer++; while (pointer < slength && pointer - octStart < 3 && isOctDigit(aTccnCharstring.charAt(pointer))) { pointer++; } final int octInt = Integer.parseInt(aTccnCharstring.substring(octStart, pointer), 8); if (octInt > 255) { // oct 377 mErrorMessage = INVALID_ESCAPE_SEQUENCE + "'\\" + aTccnCharstring.substring(octStart, pointer) + "'"; mErrorneous = true; return null; } else { sb.append((char) octInt); } } else { mErrorMessage = INVALID_ESCAPE_SEQUENCE + "'\\" + c2 + "'"; mErrorneous = true; return null; } } else { // End of backslash-escape sb.append(aTccnCharstring.charAt(pointer)); pointer++; } } else { sb.append(aTccnCharstring.charAt(pointer)); pointer++; } } // End of While return sb.toString(); } /** * @param aChar character to check * @return true if aChar is hexadecimal digit */ private static boolean isHexDigit( final char aChar ) { return (aChar >= '0' && aChar <= '9') || (aChar >= 'a' && aChar <= 'f') || (aChar >= 'A' && aChar <= 'F'); } /** * @param aChar character to check * @return true if aChar is octal digit */ private static boolean isOctDigit( final char aChar ) { return aChar >= '0' && aChar <= '7'; } }
package ua.com.fielden.platform.entity.validation; import static java.lang.String.format; import static ua.com.fielden.platform.entity.AbstractEntity.KEY_NOT_ASSIGNED; import static ua.com.fielden.platform.entity.ActivatableAbstractEntity.ACTIVE; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchOnly; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import static ua.com.fielden.platform.error.Result.failure; import static ua.com.fielden.platform.error.Result.successful; import java.lang.annotation.Annotation; import java.util.Set; import ua.com.fielden.platform.dao.IEntityDao; import ua.com.fielden.platform.dao.QueryExecutionModel; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.ActivatableAbstractEntity; import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder; import ua.com.fielden.platform.entity.meta.MetaProperty; import ua.com.fielden.platform.entity.query.fluent.fetch; import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel; import ua.com.fielden.platform.entity_centre.review.criteria.EntityQueryCriteria; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.reflection.TitlesDescsGetter; /** * Validator that checks entity value for existence using an {@link IEntityDao} instance. * * IMPORTANT: value null is considered valid. * * @author TG Team * */ public class EntityExistsValidator<T extends AbstractEntity<?>> implements IBeforeChangeEventHandler<T> { public static final String WAS_NOT_FOUND_CONCRETE_ERR = "%s [%s] was not found."; private static final String WAS_NOT_FOUND_ERR = "%s was not found."; public static final String EXISTS_BUT_NOT_ACTIVE_ERR = "%s [%s] exists, but is not active."; private final Class<T> type; private final ICompanionObjectFinder coFinder; protected EntityExistsValidator() { type = null; coFinder = null; } public EntityExistsValidator(final Class<T> type, final ICompanionObjectFinder coFinder) { this.type = type; this.coFinder = coFinder; } @Override public Result handle(final MetaProperty<T> property, final T newValue, final Set<Annotation> mutatorAnnotations) { final IEntityDao<T> co = coFinder.find(type); if (co == null) { throw new IllegalStateException("EntityExistsValidator is not fully initialised: companion object is missing"); } final AbstractEntity<?> entity = property.getEntity(); try { if (newValue == null) { return successful(entity); } else if (newValue.isInstrumented() && newValue.isDirty()) { // if entity uninstrumented its dirty state is irrelevant and cannot be checked final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(newValue.getType()).getKey(); return failure(entity, format("EntityExists validator: dirty entity %s (%s) is not acceptable.", newValue, entityTitle)); } if (EntityQueryCriteria.class.isAssignableFrom(entity.getType())) { return successful(entity); } // the notion of existence is different for activatable and non-activatable entities, // where for activatable entities to exists mens also to be active final boolean exists; final boolean activeEnough; // Does not have to 100% active - see below if (!property.isActivatable()) { // is property value represents non-activatable? exists = co.entityExists(newValue); activeEnough = true; } else { // otherwise, property value is activatable final Class<T> entityType = co.getEntityType(); final EntityResultQueryModel<T> query = select(entityType).where().prop("id").eq().val(newValue.getId()).model(); final fetch<T> fm = fetchOnly(entityType).with(ACTIVE); final QueryExecutionModel<T, EntityResultQueryModel<T>> qem = from(query).with(fm).lightweight().model(); final T ent = co.getEntity(qem); exists = (ent != null); // two possible cases: // 1. if the property owning entity is itself an inactive activatable then the inactive property value is appropriate // 2. otherwise, the activatable value should also be active if ((entity instanceof ActivatableAbstractEntity) && !entity.<Boolean>get(ACTIVE)) { activeEnough = true; } else { activeEnough = ((ent != null) && ent.<Boolean> get(ACTIVE)); } } if (!exists || !activeEnough) { final String entityTitle = TitlesDescsGetter.getEntityTitleAndDesc(newValue.getType()).getKey(); final String newValueStr = newValue.toString(); if (!exists) { return failure(entity, KEY_NOT_ASSIGNED.equals(newValueStr) ? format(WAS_NOT_FOUND_ERR, entityTitle) : format(WAS_NOT_FOUND_CONCRETE_ERR, entityTitle, newValueStr)); } else { return failure(entity, format(EXISTS_BUT_NOT_ACTIVE_ERR, entityTitle, newValueStr)); } } else { return successful(entity); } } catch (final Exception e) { return failure(entity, e); } } }
package com.intellij.testFramework.fixtures.impl; import com.intellij.analysis.AnalysisScope; import com.intellij.codeHighlighting.RainbowHighlighter; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.TargetElementUtil; import com.intellij.codeInsight.completion.CodeCompletionHandlerBase; import com.intellij.codeInsight.completion.CompletionProgressIndicator; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.codeInsight.daemon.impl.*; import com.intellij.codeInsight.folding.CodeFoldingManager; import com.intellij.codeInsight.highlighting.actions.HighlightUsagesAction; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.impl.IntentionListStep; import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.InspectionToolProvider; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ex.InspectionManagerEx; import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.facet.Facet; import com.intellij.facet.FacetManager; import com.intellij.find.FindManager; import com.intellij.find.findUsages.FindUsagesHandler; import com.intellij.find.findUsages.FindUsagesOptions; import com.intellij.find.impl.FindManagerImpl; import com.intellij.ide.startup.StartupManagerEx; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.ide.structureView.StructureViewBuilder; import com.intellij.ide.structureView.newStructureView.StructureViewComponent; import com.intellij.ide.util.gotoByName.ChooseByNameBase; import com.intellij.ide.util.gotoByName.ChooseByNamePopup; import com.intellij.ide.util.gotoByName.GotoClassModel2; import com.intellij.injected.editor.DocumentWindow; import com.intellij.injected.editor.EditorWindow; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.internal.DumpLookupElementWeights; import com.intellij.lang.Language; import com.intellij.lang.LanguageStructureViewBuilder; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.mock.MockProgressIndicator; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.impl.DocumentMarkupModel; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.extensions.ExtensionPoint; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.ExtensionsArea; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.impl.EditorHistoryManager; import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.readOnlyHandler.ReadonlyStatusHandlerImpl; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.impl.VirtualFilePointerTracker; import com.intellij.psi.*; import com.intellij.psi.impl.DebugUtil; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.cache.CacheManager; import com.intellij.psi.impl.cache.impl.todo.TodoIndex; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.FileElement; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.UsageSearchContext; import com.intellij.psi.stubs.StubTextInconsistencyException; import com.intellij.psi.stubs.StubUpdatingIndex; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilBase; import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor; import com.intellij.refactoring.rename.*; import com.intellij.rt.execution.junit.FileComparisonFailure; import com.intellij.testFramework.*; import com.intellij.testFramework.fixtures.*; import com.intellij.testFramework.utils.inlays.CaretAndInlaysInfo; import com.intellij.testFramework.utils.inlays.InlayHintsChecker; import com.intellij.ui.breadcrumbs.BreadcrumbsProvider; import com.intellij.ui.breadcrumbs.BreadcrumbsUtil; import com.intellij.ui.components.breadcrumbs.Crumb; import com.intellij.usageView.UsageInfo; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.io.ReadOnlyAttributeUtil; import com.intellij.util.ui.UIUtil; import junit.framework.ComparisonFailure; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.*; /** * @author Dmitry Avdeev */ @TestOnly public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsightTestFixture { private static final Function<IntentionAction, String> INTENTION_NAME_FUN = intentionAction -> '"' + intentionAction.getText() + '"'; private static final String RAINBOW = "rainbow"; private static final String FOLD = "fold"; private final IdeaProjectTestFixture myProjectFixture; private final TempDirTestFixture myTempDirFixture; private PsiManagerImpl myPsiManager; private VirtualFile myFile; private Editor myEditor; private String myTestDataPath; private boolean myEmptyLookup; private VirtualFileFilter myVirtualFileFilter = new FileTreeAccessFilter(); private ChooseByNameBase myChooseByNamePopup; private boolean myAllowDirt; private boolean myCaresAboutInjection = true; private VirtualFilePointerTracker myVirtualFilePointerTracker; public CodeInsightTestFixtureImpl(@NotNull IdeaProjectTestFixture projectFixture, @NotNull TempDirTestFixture tempDirTestFixture) { myProjectFixture = projectFixture; myTempDirFixture = tempDirTestFixture; } private static void addGutterIconRenderer(GutterMark renderer, int offset, @NotNull SortedMap<Integer, List<GutterMark>> result) { if (renderer == null) return; List<GutterMark> renderers = result.computeIfAbsent(offset, k -> new SmartList<>()); renderers.add(renderer); } private static void removeDuplicatedRangesForInjected(@NotNull List<HighlightInfo> infos) { Collections.sort(infos, (o1, o2) -> { final int i = o2.startOffset - o1.startOffset; return i != 0 ? i : o1.getSeverity().myVal - o2.getSeverity().myVal; }); HighlightInfo prevInfo = null; for (Iterator<HighlightInfo> it = infos.iterator(); it.hasNext();) { final HighlightInfo info = it.next(); if (prevInfo != null && info.getSeverity() == HighlightInfoType.SYMBOL_TYPE_SEVERITY && info.getDescription() == null && info.startOffset == prevInfo.startOffset && info.endOffset == prevInfo.endOffset) { it.remove(); } prevInfo = info.type == HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT ? info : null; } } @NotNull @TestOnly public static List<HighlightInfo> instantiateAndRun(@NotNull PsiFile file, @NotNull Editor editor, @NotNull int[] toIgnore, boolean canChangeDocument) { Project project = file.getProject(); ensureIndexesUpToDate(project); DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project); TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor); DaemonCodeAnalyzerSettings settings = DaemonCodeAnalyzerSettings.getInstance(); ProcessCanceledException exception = null; int retries = 1000; for (int i = 0; i < retries; i++) { int oldDelay = settings.AUTOREPARSE_DELAY; try { settings.AUTOREPARSE_DELAY = 0; List<HighlightInfo> infos = new ArrayList<>(); EdtTestUtil.runInEdtAndWait(() -> infos.addAll( codeAnalyzer.runPasses(file, editor.getDocument(), Collections.singletonList(textEditor), toIgnore, canChangeDocument, null))); infos.addAll(DaemonCodeAnalyzerEx.getInstanceEx(project).getFileLevelHighlights(project, file)); return infos; } catch (ProcessCanceledException e) { Throwable cause = e.getCause(); if (cause != null && cause.getClass() != Throwable.class) { // canceled because of an exception, no need to repeat the same a lot times throw e; } PsiDocumentManager.getInstance(project).commitAllDocuments(); UIUtil.dispatchAllInvocationEvents(); exception = e; } finally { settings.AUTOREPARSE_DELAY = oldDelay; } } throw new AssertionError("Unable to highlight after " + retries + " retries", exception); } public static void ensureIndexesUpToDate(@NotNull Project project) { if (!DumbService.isDumb(project)) { ReadAction.run(() -> { FileBasedIndex.getInstance().ensureUpToDate(StubUpdatingIndex.INDEX_ID, project, null); FileBasedIndex.getInstance().ensureUpToDate(TodoIndex.NAME, project, null); }); } } @NotNull public static List<IntentionAction> getAvailableIntentions(@NotNull Editor editor, @NotNull PsiFile file) { return ReadAction.compute(() -> doGetAvailableIntentions(editor, file)); } @NotNull private static List<IntentionAction> doGetAvailableIntentions(@NotNull Editor editor, @NotNull PsiFile file) { ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo(); ShowIntentionsPass.getActionsToShow(editor, file, intentions, -1); List<IntentionAction> result = new ArrayList<>(); IntentionListStep intentionListStep = new IntentionListStep(null, intentions, editor, file, file.getProject()); for (Map.Entry<IntentionAction, List<IntentionAction>> entry : intentionListStep.getActionsWithSubActions().entrySet()) { result.add(entry.getKey()); result.addAll(entry.getValue()); } List<HighlightInfo> infos = DaemonCodeAnalyzerEx.getInstanceEx(file.getProject()).getFileLevelHighlights(file.getProject(), file); for (HighlightInfo info : infos) { for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) { HighlightInfo.IntentionActionDescriptor actionInGroup = pair.first; if (actionInGroup.getAction().isAvailable(file.getProject(), editor, file)) { result.add(actionInGroup.getAction()); List<IntentionAction> options = actionInGroup.getOptions(file, editor); if (options != null) { for (IntentionAction subAction : options) { if (subAction.isAvailable(file.getProject(), editor, file)) { result.add(subAction); } } } } } } return result; } @NotNull @Override public String getTempDirPath() { return myTempDirFixture.getTempDirPath(); } @NotNull @Override public TempDirTestFixture getTempDirFixture() { return myTempDirFixture; } @NotNull @Override public VirtualFile copyFileToProject(@NotNull String sourcePath) { return copyFileToProject(sourcePath, sourcePath); } @NotNull @Override public VirtualFile copyFileToProject(@NotNull String sourcePath, @NotNull String targetPath) { String testDataPath = getTestDataPath(); File sourceFile = FileUtil.findFirstThatExist(testDataPath + '/' + sourcePath, sourcePath); VirtualFile targetFile = myTempDirFixture.getFile(targetPath); if (sourceFile == null && targetFile != null && targetPath.equals(sourcePath)) { return targetFile; } assertFileEndsWithCaseSensitivePath(sourceFile); assertNotNull("Cannot find source file: " + sourcePath + "; test data path: " + testDataPath, sourceFile); assertTrue("Not a file: " + sourceFile, sourceFile.isFile()); if (targetFile == null) { targetFile = myTempDirFixture.createFile(targetPath); VfsTestUtil.assertFilePathEndsWithCaseSensitivePath(targetFile, sourcePath); targetFile.putUserData(VfsTestUtil.TEST_DATA_FILE_PATH, sourceFile.getAbsolutePath()); } copyContent(sourceFile, targetFile); return targetFile; } private static void assertFileEndsWithCaseSensitivePath(@Nullable File sourceFile) { if (sourceFile == null) return; try { String sourceName = sourceFile.getName(); File realFile = sourceFile.getCanonicalFile(); String realFileName = realFile.getName(); if (sourceName.equalsIgnoreCase(realFileName) && !sourceName.equals(realFileName)) { fail("Please correct case-sensitivity of path to prevent test failure on case-sensitive file systems:\n" + " path " + sourceFile.getPath() + "\n" + "real path " + realFile.getPath()); } } catch (IOException e) { throw new UncheckedIOException(e); } } private static void copyContent(File sourceFile, VirtualFile targetFile) { new WriteAction() { @Override protected void run(@NotNull Result result) throws IOException { targetFile.setBinaryContent(FileUtil.loadFileBytes(sourceFile)); // update the document now, otherwise MemoryDiskConflictResolver will do it later at unexpected moment of time FileDocumentManager.getInstance().reloadFiles(targetFile); } }.execute(); } @NotNull @Override public VirtualFile copyDirectoryToProject(@NotNull String sourcePath, @NotNull String targetPath) { final String testDataPath = getTestDataPath(); final File fromFile = new File(testDataPath + "/" + sourcePath); if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) { return myTempDirFixture.copyAll(fromFile.getPath(), targetPath); } final File targetFile = new File(getTempDirPath() + "/" + targetPath); try { FileUtil.copyDir(fromFile, targetFile); } catch (IOException e) { throw new RuntimeException(e); } final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(targetFile); assertNotNull(file); file.refresh(false, true); return file; } @Override public void enableInspections(@NotNull InspectionProfileEntry... inspections) { assertInitialized(); InspectionsKt.enableInspectionTools(getProject(), myProjectFixture.getTestRootDisposable(), inspections); } @SafeVarargs @Override public final void enableInspections(@NotNull Class<? extends LocalInspectionTool>... inspections) { enableInspections(Arrays.asList(inspections)); } @Override public void enableInspections(@NotNull Collection<Class<? extends LocalInspectionTool>> inspections) { List<InspectionProfileEntry> tools = InspectionTestUtil.instantiateTools(inspections); enableInspections(tools.toArray(new InspectionProfileEntry[0])); } @Override public void disableInspections(@NotNull InspectionProfileEntry... inspections) { InspectionsKt.disableInspections(getProject(), inspections); } @Override public void enableInspections(@NotNull InspectionToolProvider... providers) { List<Class<? extends LocalInspectionTool>> classes = Stream.of(providers) .flatMap(p -> Stream.of(p.getInspectionClasses())) .filter(LocalInspectionTool.class::isAssignableFrom) .map(c -> { @SuppressWarnings("unchecked") Class<? extends LocalInspectionTool> toolClass = c; return toolClass; }) .collect(Collectors.toList()); enableInspections(classes); } @Override public long testHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, @NotNull String... filePaths) { if (filePaths.length > 0) { configureByFilesInner(filePaths); } return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings); } @Override public long testHighlightingAllFiles(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, @NotNull String... paths) { return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings, Stream.of(paths).map(this::copyFileToProject)); } @Override public long testHighlightingAllFiles(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, @NotNull VirtualFile... files) { return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings, Stream.of(files)); } private long collectAndCheckHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, Stream<VirtualFile> files) { List<Trinity<PsiFile, Editor, ExpectedHighlightingData>> data = files.map(file -> { PsiFile psiFile = myPsiManager.findFile(file); assertNotNull(psiFile); Document document = PsiDocumentManager.getInstance(getProject()).getDocument(psiFile); assertNotNull(document); ExpectedHighlightingData datum = new ExpectedHighlightingData(document, checkWarnings, checkWeakWarnings, checkInfos, psiFile); datum.init(); return Trinity.create(psiFile, createEditor(file), datum); }).collect(Collectors.toList()); long elapsed = 0; for (Trinity<PsiFile, Editor, ExpectedHighlightingData> trinity : data) { myEditor = trinity.second; myFile = trinity.first.getVirtualFile(); elapsed += collectAndCheckHighlighting(trinity.third); } return elapsed; } @Override public long checkHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings) { return checkHighlighting(checkWarnings, checkInfos, checkWeakWarnings, false); } @Override public long checkHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, boolean ignoreExtraHighlighting) { return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings, ignoreExtraHighlighting); } @Override public long checkHighlighting() { return checkHighlighting(true, false, true); } @Override public long testHighlighting(@NotNull String... filePaths) { return testHighlighting(true, false, true, filePaths); } @Override public long testHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, @NotNull VirtualFile file) { openFileInEditor(file); return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings); } @NotNull @Override public HighlightTestInfo testFile(@NotNull String... filePath) { return new HighlightTestInfo(myProjectFixture.getTestRootDisposable(), filePath) { @Override public HighlightTestInfo doTest() { configureByFiles(filePaths); ExpectedHighlightingData data = new ExpectedHighlightingData(myEditor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, getFile()); if (checkSymbolNames) data.checkSymbolNames(); data.init(); collectAndCheckHighlighting(data); return this; } }; } @Override public void openFileInEditor(@NotNull final VirtualFile file) { myFile = file; myEditor = createEditor(file); } @Override public void testInspection(@NotNull String testDir, @NotNull InspectionToolWrapper toolWrapper) { VirtualFile sourceDir = copyDirectoryToProject(new File(testDir, "src").getPath(), ""); PsiDirectory psiDirectory = getPsiManager().findDirectory(sourceDir); assertNotNull(psiDirectory); AnalysisScope scope = new AnalysisScope(psiDirectory); scope.invalidate(); GlobalInspectionContextForTests globalContext = InspectionsKt.createGlobalContextForTool(scope, getProject(), Collections.<InspectionToolWrapper<?, ?>>singletonList(toolWrapper)); InspectionTestUtil.runTool(toolWrapper, scope, globalContext); InspectionTestUtil.compareToolResults(globalContext, toolWrapper, false, new File(getTestDataPath(), testDir).getPath()); } @Override @Nullable public PsiReference getReferenceAtCaretPosition(@NotNull final String... filePaths) { if (filePaths.length > 0) { configureByFilesInner(filePaths); } return getFile().findReferenceAt(myEditor.getCaretModel().getOffset()); } @Override @NotNull public PsiReference getReferenceAtCaretPositionWithAssertion(@NotNull final String... filePaths) { final PsiReference reference = getReferenceAtCaretPosition(filePaths); assertNotNull("no reference found at " + myEditor.getCaretModel().getLogicalPosition(), reference); return reference; } @Override @NotNull public List<IntentionAction> getAvailableIntentions(@NotNull final String... filePaths) { if (filePaths.length > 0) { configureByFilesInner(filePaths); } return getAvailableIntentions(); } @Override @NotNull public List<IntentionAction> getAllQuickFixes(@NotNull final String... filePaths) { if (filePaths.length != 0) { configureByFilesInner(filePaths); } List<HighlightInfo> infos = doHighlighting(); List<IntentionAction> actions = new ArrayList<>(); for (HighlightInfo info : infos) { if (info.quickFixActionRanges != null) { for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) { actions.add(pair.getFirst().getAction()); } } } return actions; } @Override @NotNull public List<IntentionAction> getAvailableIntentions() { doHighlighting(); return getAvailableIntentions(getHostEditor(), getHostFileAtCaret()); } @NotNull private Editor getHostEditor() { return InjectedLanguageUtil.getTopLevelEditor(getEditor()); } private PsiFile getHostFileAtCaret() { return Objects.requireNonNull(PsiUtilBase.getPsiFileInEditor(getHostEditor(), getProject())); } @NotNull @Override public List<IntentionAction> filterAvailableIntentions(@NotNull String hint) { return getAvailableIntentions().stream().filter(action -> action.getText().startsWith(hint)).collect(Collectors.toList()); } @NotNull @Override public IntentionAction findSingleIntention(@NotNull String hint) { final List<IntentionAction> list = filterAvailableIntentions(hint); if (list.isEmpty()) { fail("\"" + hint + "\" not in [" + StringUtil.join(getAvailableIntentions(), INTENTION_NAME_FUN, ", ") + "]"); } else if (list.size() > 1) { fail("Too many intentions found for \"" + hint + "\": [" + StringUtil.join(list, INTENTION_NAME_FUN, ", ") + "]"); } return UsefulTestCase.assertOneElement(list); } @Override public IntentionAction getAvailableIntention(@NotNull final String intentionName, @NotNull final String... filePaths) { List<IntentionAction> intentions = getAvailableIntentions(filePaths); IntentionAction action = CodeInsightTestUtil.findIntentionByText(intentions, intentionName); if (action == null) { //noinspection UseOfSystemOutOrSystemErr System.out.println(intentionName + " not found among " + StringUtil.join(intentions, IntentionAction::getText, ",")); } return action; } @Override public void launchAction(@NotNull final IntentionAction action) { invokeIntention(action, getHostFileAtCaret(), getHostEditor(), action.getText()); } @Override public void testCompletion(@NotNull String[] filesBefore, @NotNull @TestDataFile String fileAfter) { testCompletionTyping(filesBefore, "", fileAfter); } @Override public void testCompletionTyping(@NotNull final String[] filesBefore, @NotNull String toType, @NotNull final String fileAfter) { assertInitialized(); configureByFiles(filesBefore); complete(CompletionType.BASIC); type(toType); try { checkResultByFile(fileAfter); } catch (RuntimeException e) { //noinspection UseOfSystemOutOrSystemErr System.out.println("LookupElementStrings = " + getLookupElementStrings()); throw e; } } protected void assertInitialized() { assertNotNull("setUp() hasn't been called", myPsiManager); } @Override public void testCompletion(@NotNull String fileBefore, @NotNull String fileAfter, @TestDataFile @NotNull String... additionalFiles) { testCompletionTyping(fileBefore, "", fileAfter, additionalFiles); } @Override public void testCompletionTyping(@NotNull @TestDataFile String fileBefore, @NotNull String toType, @NotNull @TestDataFile String fileAfter, @TestDataFile @NotNull String... additionalFiles) { testCompletionTyping(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, fileBefore)), toType, fileAfter); } @Override public void testCompletionVariants(@NotNull final String fileBefore, @NotNull final String... expectedItems) { assertInitialized(); final List<String> result = getCompletionVariants(fileBefore); assertNotNull(result); UsefulTestCase.assertSameElements(result, expectedItems); } @Override public List<String> getCompletionVariants(@NotNull final String... filesBefore) { assertInitialized(); configureByFiles(filesBefore); final LookupElement[] items = complete(CompletionType.BASIC); assertNotNull("No lookup was shown, probably there was only one lookup element that was inserted automatically", items); return getLookupElementStrings(); } @Override @Nullable public List<String> getLookupElementStrings() { assertInitialized(); final LookupElement[] elements = getLookupElements(); if (elements == null) return null; return ContainerUtil.map(elements, LookupElement::getLookupString); } @Override public void finishLookup(final char completionChar) { Runnable command = () -> { LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(getEditor()); assertNotNull(lookup); lookup.finishLookup(completionChar); }; CommandProcessor.getInstance().executeCommand(getProject(), command, null, null); } @Override public void testRename(@NotNull final String fileBefore, @NotNull String fileAfter, @NotNull String newName, @TestDataFile @NotNull String... additionalFiles) { assertInitialized(); configureByFiles(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, fileBefore))); testRename(fileAfter, newName); } @Override public void testRename(@NotNull final String fileAfter, @NotNull final String newName) { renameElementAtCaret(newName); checkResultByFile(fileAfter); } @Override @NotNull public PsiElement getElementAtCaret() { assertInitialized(); Editor editor = getCompletionEditor(); int findTargetFlags = TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED | TargetElementUtil.ELEMENT_NAME_ACCEPTED; PsiElement element = TargetElementUtil.findTargetElement(editor, findTargetFlags); // if no references found in injected fragment, try outer document if (element == null && editor instanceof EditorWindow) { element = TargetElementUtil.findTargetElement(((EditorWindow)editor).getDelegate(), findTargetFlags); } if (element == null) { fail("element not found in file " + myFile.getName() + " at caret position offset " + myEditor.getCaretModel().getOffset() + "," + " psi structure:\n" + DebugUtil.psiToString(getFile(), true, true)); } return element; } @Override public void renameElementAtCaret(@NotNull final String newName) { renameElement(getElementAtCaret(), newName); } @Override public void renameElementAtCaretUsingHandler(@NotNull final String newName) { final DataContext editorContext = ((EditorEx)myEditor).getDataContext(); final DataContext context = dataId -> PsiElementRenameHandler.DEFAULT_NAME.getName().equals(dataId) ? newName : editorContext.getData(dataId); final RenameHandler renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(context); assertNotNull("No handler for this context", renameHandler); renameHandler.invoke(getProject(), myEditor, getFile(), context); } @Override public void renameElement(@NotNull final PsiElement element, @NotNull final String newName) { final boolean searchInComments = false; final boolean searchTextOccurrences = false; renameElement(element, newName, searchInComments, searchTextOccurrences); } @Override public void renameElement(@NotNull final PsiElement element, @NotNull final String newName, final boolean searchInComments, final boolean searchTextOccurrences) { final PsiElement substitution = RenamePsiElementProcessor.forElement(element).substituteElementToRename(element, myEditor); if (substitution == null) return; new RenameProcessor(getProject(), substitution, newName, searchInComments, searchTextOccurrences).run(); } @Override public <T extends PsiElement> T findElementByText(@NotNull String text, @NotNull Class<T> elementClass) { Document document = PsiDocumentManager.getInstance(getProject()).getDocument(getFile()); assertNotNull(document); int pos = document.getText().indexOf(text); assertTrue(text, pos >= 0); return PsiTreeUtil.getParentOfType(getFile().findElementAt(pos), elementClass); } @Override public void type(final char c) { assertInitialized(); ApplicationManager.getApplication().invokeAndWait(() -> { final EditorActionManager actionManager = EditorActionManager.getInstance(); if (c == '\b') { performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE); return; } if (c == '\n') { if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM)) { return; } if (_performEditorAction(IdeActions.ACTION_EDITOR_NEXT_TEMPLATE_VARIABLE)) { return; } performEditorAction(IdeActions.ACTION_EDITOR_ENTER); return; } if (c == '\t') { if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_REPLACE)) { return; } if (_performEditorAction(IdeActions.ACTION_EXPAND_LIVE_TEMPLATE_BY_TAB)) { return; } if (_performEditorAction(IdeActions.ACTION_EDITOR_NEXT_TEMPLATE_VARIABLE)) { return; } if (_performEditorAction(IdeActions.ACTION_EDITOR_TAB)) { return; } } if (c == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) { if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_COMPLETE_STATEMENT)) { return; } } ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, getEditorDataContext()); actionManager.getTypedAction().actionPerformed(getEditor(), c, getEditorDataContext()); }); } @NotNull private DataContext getEditorDataContext() { return ((EditorEx)myEditor).getDataContext(); } @Override public void type(@NotNull String s) { for (int i = 0; i < s.length(); i++) { type(s.charAt(i)); } } @Override public void performEditorAction(@NotNull final String actionId) { assertInitialized(); _performEditorAction(actionId); } private boolean _performEditorAction(@NotNull String actionId) { final DataContext dataContext = getEditorDataContext(); final ActionManagerEx managerEx = ActionManagerEx.getInstanceEx(); final AnAction action = managerEx.getAction(actionId); final AnActionEvent event = new AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, new Presentation(), managerEx, 0); action.beforeActionPerformedUpdate(event); if (!event.getPresentation().isEnabled()) { return false; } managerEx.fireBeforeActionPerformed(action, dataContext, event); ActionUtil.performActionDumbAware(action, event); managerEx.fireAfterActionPerformed(action, dataContext, event); return true; } @NotNull @Override public Presentation testAction(@NotNull AnAction action) { TestActionEvent e = new TestActionEvent(action); action.beforeActionPerformedUpdate(e); if (e.getPresentation().isEnabled() && e.getPresentation().isVisible()) { action.actionPerformed(e); } return e.getPresentation(); } @NotNull @Override public Collection<UsageInfo> testFindUsages(@NotNull final String... fileNames) { assertInitialized(); configureByFiles(fileNames); int flags = TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED; PsiElement targetElement = TargetElementUtil.findTargetElement(getEditor(), flags); assertNotNull("Cannot find referenced element", targetElement); return findUsages(targetElement); } @NotNull @Override public Collection<UsageInfo> findUsages(@NotNull final PsiElement targetElement) { return findUsages(targetElement, null); } @NotNull public Collection<UsageInfo> findUsages(@NotNull final PsiElement targetElement, @Nullable SearchScope scope) { final Project project = getProject(); final FindUsagesHandler handler = ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager().getFindUsagesHandler(targetElement, false); final CommonProcessors.CollectProcessor<UsageInfo> processor = new CommonProcessors.CollectProcessor<>(); assertNotNull("Cannot find handler for: " + targetElement, handler); final PsiElement[] psiElements = ArrayUtil.mergeArrays(handler.getPrimaryElements(), handler.getSecondaryElements()); final FindUsagesOptions options = handler.getFindUsagesOptions(null); if (scope != null) options.searchScope = scope; for (PsiElement psiElement : psiElements) { handler.processElementUsages(psiElement, processor, options); } return processor.getResults(); } @NotNull @Override public RangeHighlighter[] testHighlightUsages(@NotNull final String... files) { configureByFiles(files); testAction(new HighlightUsagesAction()); final Editor editor = getEditor(); //final Editor editor = com.intellij.openapi.actionSystem.CommonDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext()); //assert editor != null; //HighlightUsagesHandler.invoke(getProject(), editor, getFile()); return editor.getMarkupModel().getAllHighlighters(); } @Override public void moveFile(@NotNull final String filePath, @NotNull final String to, @TestDataFile @NotNull final String... additionalFiles) { assertInitialized(); final Project project = getProject(); configureByFiles(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, filePath))); final VirtualFile file = findFileInTempDir(to); assertNotNull("Directory " + to + " not found", file); assertTrue(to + " is not a directory", file.isDirectory()); final PsiDirectory directory = myPsiManager.findDirectory(file); new MoveFilesOrDirectoriesProcessor(project, new PsiElement[]{getFile()}, directory, false, false, null, null).run(); } @Override @Nullable public GutterMark findGutter(@NotNull final String filePath) { configureByFilesInner(filePath); CommonProcessors.FindFirstProcessor<GutterMark> processor = new CommonProcessors.FindFirstProcessor<>(); doHighlighting(); processGuttersAtCaret(myEditor, getProject(), processor); return processor.getFoundValue(); } @NotNull @Override public List<GutterMark> findGuttersAtCaret() { CommonProcessors.CollectProcessor<GutterMark> processor = new CommonProcessors.CollectProcessor<>(); doHighlighting(); processGuttersAtCaret(myEditor, getProject(), processor); return new ArrayList<>(processor.getResults()); } public static boolean processGuttersAtCaret(Editor editor, Project project, @NotNull Processor<GutterMark> processor) { int offset = editor.getCaretModel().getOffset(); RangeHighlighter[] highlighters = DocumentMarkupModel.forDocument(editor.getDocument(), project, true).getAllHighlighters(); for (RangeHighlighter highlighter : highlighters) { GutterMark renderer = highlighter.getGutterIconRenderer(); if (renderer != null && editor.getDocument().getLineNumber(offset) == editor.getDocument().getLineNumber(highlighter.getStartOffset()) && !processor.process(renderer)) { return false; } } return true; } @Override @NotNull public List<GutterMark> findAllGutters(@NotNull final String filePath) { configureByFilesInner(filePath); return findAllGutters(); } @Override @NotNull public List<GutterMark> findAllGutters() { final Project project = getProject(); final SortedMap<Integer, List<GutterMark>> result = new TreeMap<>(); List<HighlightInfo> infos = doHighlighting(); for (HighlightInfo info : infos) { addGutterIconRenderer(info.getGutterIconRenderer(), info.startOffset, result); } RangeHighlighter[] highlighters = DocumentMarkupModel.forDocument(myEditor.getDocument(), project, true).getAllHighlighters(); for (final RangeHighlighter highlighter : highlighters) { if (!highlighter.isValid()) continue; addGutterIconRenderer(highlighter.getGutterIconRenderer(), highlighter.getStartOffset(), result); } return ContainerUtil.concat(result.values()); } @Override public PsiFile addFileToProject(@NotNull final String relativePath, @NotNull final String fileText) { assertInitialized(); return addFileToProject(getTempDirPath(), relativePath, fileText); } protected PsiFile addFileToProject(@NotNull final String rootPath, @NotNull final String relativePath, @NotNull final String fileText) { VirtualFile file = new WriteCommandAction<VirtualFile>(getProject()) { @Override protected void run(@NotNull Result<VirtualFile> result) { try { if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) { result.setResult(myTempDirFixture.createFile(relativePath, fileText)); } else if (myProjectFixture instanceof HeavyIdeaTestFixture){ result.setResult(((HeavyIdeaTestFixture)myProjectFixture).addFileToProject(rootPath, relativePath, fileText).getViewProvider().getVirtualFile()); } else { result.setResult(myTempDirFixture.createFile(relativePath, fileText)); } } catch (IOException e) { throw new RuntimeException(e); } finally { PsiManager.getInstance(getProject()).dropPsiCaches(); } } }.execute().getResultObject(); return ReadAction.compute(() -> PsiManager.getInstance(getProject()).findFile(file)); } public <T> void registerExtension(final ExtensionsArea area, final ExtensionPointName<T> epName, final T extension) { assertInitialized(); final ExtensionPoint<T> extensionPoint = area.getExtensionPoint(epName); extensionPoint.registerExtension(extension); Disposer.register(myProjectFixture.getTestRootDisposable(), () -> extensionPoint.unregisterExtension(extension)); } @NotNull @Override public PsiManager getPsiManager() { return myPsiManager; } @Override public LookupElement[] complete(@NotNull CompletionType type) { return complete(type, 1); } @Override public LookupElement[] complete(@NotNull final CompletionType type, final int invocationCount) { assertInitialized(); myEmptyLookup = false; ApplicationManager.getApplication().invokeAndWait(() -> CommandProcessor.getInstance().executeCommand(getProject(), () -> { final CodeCompletionHandlerBase handler = new CodeCompletionHandlerBase(type) { @Override @SuppressWarnings("deprecation") protected void completionFinished(CompletionProgressIndicator indicator, boolean hasModifiers) { myEmptyLookup = indicator.getLookup().getItems().isEmpty(); super.completionFinished(indicator, hasModifiers); } }; Editor editor = getCompletionEditor(); assertNotNull(editor); handler.invokeCompletion(getProject(), editor, invocationCount); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); // to compare with file text }, null, null, getEditor().getDocument())); return getLookupElements(); } @Nullable protected Editor getCompletionEditor() { return InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myEditor, getFile()); } @Override @Nullable public LookupElement[] completeBasic() { return complete(CompletionType.BASIC); } @Override @NotNull public final List<LookupElement> completeBasicAllCarets(@Nullable final Character charToTypeAfterCompletion) { final CaretModel caretModel = myEditor.getCaretModel(); final List<Caret> carets = caretModel.getAllCarets(); final List<Integer> originalOffsets = new ArrayList<>(carets.size()); for (final Caret caret : carets) { originalOffsets.add(caret.getOffset()); } caretModel.removeSecondaryCarets(); // We do it in reverse order because completions would affect offsets // i.e.: when you complete "spa" to "spam", next caret offset increased by 1 Collections.reverse(originalOffsets); final List<LookupElement> result = new ArrayList<>(); for (final int originalOffset : originalOffsets) { caretModel.moveToOffset(originalOffset); final LookupElement[] lookupElements = completeBasic(); if (charToTypeAfterCompletion != null) { type(charToTypeAfterCompletion); } if (lookupElements != null) { result.addAll(Arrays.asList(lookupElements)); } } return result; } @Override public void saveText(@NotNull final VirtualFile file, @NotNull final String text) { new WriteAction() { @Override protected void run(@NotNull Result result) throws Throwable { VfsUtil.saveText(file, text); } }.execute().throwException(); } @Override @Nullable public LookupElement[] getLookupElements() { LookupImpl lookup = getLookup(); if (lookup == null) { return myEmptyLookup ? LookupElement.EMPTY_ARRAY : null; } else { final List<LookupElement> list = lookup.getItems(); return list.toArray(LookupElement.EMPTY_ARRAY); } } @Override public void checkResult(@NotNull String text) { checkResult(text, false); } @Override public void checkResult(@NotNull String text, boolean stripTrailingSpaces) { new WriteCommandAction(getProject()) { @Override protected void run(@NotNull Result result) { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); EditorUtil.fillVirtualSpaceUntilCaret(getHostEditor()); checkResult("TEXT", stripTrailingSpaces, SelectionAndCaretMarkupLoader.fromText(text), getHostFile().getText()); } }.execute(); } @Override public void checkResult(@NotNull String filePath, @NotNull String text, boolean stripTrailingSpaces) { new WriteCommandAction(getProject()) { @Override protected void run(@NotNull Result result) { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); PsiFile psiFile = getFileToCheck(filePath); checkResult("TEXT", stripTrailingSpaces, SelectionAndCaretMarkupLoader.fromText(text), psiFile.getText()); } }.execute(); } @Override public void checkResultByFile(@NotNull String expectedFile) { checkResultByFile(expectedFile, false); } @Override public void checkResultByFile(@NotNull String expectedFile, boolean ignoreTrailingWhitespaces) { assertInitialized(); ApplicationManager.getApplication().invokeAndWait(() -> checkResultByFile(expectedFile, getHostFile(), ignoreTrailingWhitespaces)); } @Override public void checkResultByFile(@NotNull String filePath, @NotNull String expectedFile, boolean ignoreTrailingWhitespaces) { assertInitialized(); ApplicationManager.getApplication().invokeAndWait(() -> checkResultByFile(expectedFile, getFileToCheck(filePath), ignoreTrailingWhitespaces)); } private PsiFile getFileToCheck(String filePath) { String path = filePath.replace(File.separatorChar, '/'); VirtualFile copy = findFileInTempDir(path); assertNotNull("could not find results file " + path, copy); PsiFile psiFile = myPsiManager.findFile(copy); assertNotNull(copy.getPath(), psiFile); return psiFile; } @Override public void setUp() throws Exception { super.setUp(); TestRunnerUtil.replaceIdeEventQueueSafely(); EdtTestUtil.runInEdtAndWait(() -> { myProjectFixture.setUp(); myTempDirFixture.setUp(); VirtualFile tempDir = myTempDirFixture.getFile(""); assertNotNull(tempDir); PlatformTestCase.synchronizeTempDirVfs(tempDir); myPsiManager = (PsiManagerImpl)PsiManager.getInstance(getProject()); InspectionsKt.configureInspections(LocalInspectionTool.EMPTY_ARRAY, getProject(), myProjectFixture.getTestRootDisposable()); DaemonCodeAnalyzerImpl daemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject()); daemonCodeAnalyzer.prepareForTest(); DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(false); ensureIndexesUpToDate(getProject()); ((StartupManagerImpl)StartupManagerEx.getInstanceEx(getProject())).runPostStartupActivities(); }); for (Module module : ModuleManager.getInstance(getProject()).getModules()) { ModuleRootManager.getInstance(module).orderEntries().getAllLibrariesAndSdkClassesRoots(); // instantiate all VFPs } if (shouldTrackVirtualFilePointers()) { myVirtualFilePointerTracker = new VirtualFilePointerTracker(); } } protected boolean shouldTrackVirtualFilePointers() { return true; } @Override public void tearDown() throws Exception { // don't use method references here to make stack trace reading easier //noinspection Convert2MethodRef new RunAll() .append(() -> EdtTestUtil.runInEdtAndWait(() -> { AutoPopupController.getInstance(getProject()).cancelAllRequests(); // clear "show param info" delayed requests leaking project DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(true); // return default value to avoid unnecessary save closeOpenFiles(); ((DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject())).cleanupAfterTest(); // clear order entry roots cache WriteAction.run(()->ProjectRootManagerEx.getInstanceEx(getProject()).makeRootsChange(EmptyRunnable.getInstance(), false, true)); })) .append(() -> { myEditor = null; myFile = null; myPsiManager = null; myChooseByNamePopup = null; }) .append(() -> disposeRootDisposable()) .append(() -> EdtTestUtil.runInEdtAndWait(() -> myProjectFixture.tearDown())) .append(() -> EdtTestUtil.runInEdtAndWait(() -> myTempDirFixture.tearDown())) .append(() -> super.tearDown()) .append(() -> { if (myVirtualFilePointerTracker != null) { myVirtualFilePointerTracker.assertPointersAreDisposed(); } }).run(); } private void closeOpenFiles() { LookupManager.getInstance(getProject()).hideActiveLookup(); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); FileEditorManagerEx.getInstanceEx(getProject()).closeAllFiles(); for (VirtualFile file : EditorHistoryManager.getInstance(getProject()).getFiles()) { EditorHistoryManager.getInstance(getProject()).removeFile(file); } } @NotNull private PsiFile[] configureByFilesInner(@NotNull String... filePaths) { assertInitialized(); myFile = null; myEditor = null; PsiFile[] psiFiles = new PsiFile[filePaths.length]; for (int i = filePaths.length - 1; i >= 0; i psiFiles[i] = configureByFileInner(filePaths[i]); } return psiFiles; } @Override public PsiFile configureByFile(@NotNull final String file) { configureByFilesInner(file); return getFile(); } @NotNull @Override public PsiFile[] configureByFiles(@NotNull final String... files) { return configureByFilesInner(files); } @Override public PsiFile configureByText(@NotNull final FileType fileType, @NotNull final String text) { assertInitialized(); final String extension = fileType.getDefaultExtension(); final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); if (fileTypeManager.getFileTypeByExtension(extension) != fileType) { new WriteCommandAction(getProject()) { @Override protected void run(@NotNull Result result) { fileTypeManager.associateExtension(fileType, extension); } }.execute(); } final String fileName = "aaa." + extension; return configureByText(fileName, text); } @Override public PsiFile configureByText(@NotNull final String fileName, @NotNull final String text) { assertInitialized(); VirtualFile vFile = new WriteCommandAction<VirtualFile>(getProject()) { @Override protected void run(@NotNull Result<VirtualFile> result) throws Throwable { final VirtualFile vFile; if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) { final VirtualFile root = LightPlatformTestCase.getSourceRoot(); root.refresh(false, false); vFile = root.findOrCreateChildData(this, fileName); assertNotNull(fileName + " not found in " + root.getPath(), vFile); } else if (myTempDirFixture instanceof TempDirTestFixtureImpl) { final File tempFile = ((TempDirTestFixtureImpl)myTempDirFixture).createTempFile(fileName); vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempFile); assertNotNull(tempFile + " not found", vFile); } else { vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(getTempDirPath(), fileName)); assertNotNull(fileName + " not found in " + getTempDirPath(), vFile); } prepareVirtualFile(vFile); final Document document = FileDocumentManager.getInstance().getCachedDocument(vFile); if (document != null) { PsiDocumentManager.getInstance(getProject()).doPostponedOperationsAndUnblockDocument(document); FileDocumentManager.getInstance().saveDocument(document); } VfsUtil.saveText(vFile, text); result.setResult(vFile); } }.execute().getResultObject(); configureInner(vFile, SelectionAndCaretMarkupLoader.fromFile(vFile)); return getFile(); } @Override public Document getDocument(@NotNull final PsiFile file) { assertInitialized(); return PsiDocumentManager.getInstance(getProject()).getDocument(file); } private PsiFile configureByFileInner(@NotNull String filePath) { assertInitialized(); final VirtualFile file = copyFileToProject(filePath); return configureByFileInner(file); } @Override public PsiFile configureFromTempProjectFile(@NotNull final String filePath) { final VirtualFile fileInTempDir = findFileInTempDir(filePath); if (fileInTempDir == null) { throw new IllegalArgumentException("Could not find file in temp dir: " + filePath); } return configureByFileInner(fileInTempDir); } @Override public void configureFromExistingVirtualFile(@NotNull VirtualFile virtualFile) { configureByFileInner(virtualFile); } private PsiFile configureByFileInner(@NotNull VirtualFile copy) { return configureInner(copy, SelectionAndCaretMarkupLoader.fromFile(copy)); } private PsiFile configureInner(@NotNull final VirtualFile copy, @NotNull final SelectionAndCaretMarkupLoader loader) { assertInitialized(); EdtTestUtil.runInEdtAndWait(() -> { if (!copy.getFileType().isBinary()) { try { WriteAction.run(() -> copy.setBinaryContent(loader.newFileText.getBytes(copy.getCharset()))); } catch (IOException e) { throw new RuntimeException(e); } } myFile = copy; myEditor = createEditor(copy); if (myEditor == null) { fail("editor couldn't be created for: " + copy.getPath() + ", use copyFileToProject() instead of configureByFile()"); } EditorTestUtil.setCaretsAndSelection(myEditor, loader.caretState); Module module = getModule(); if (module != null) { for (Facet facet : FacetManager.getInstance(module).getAllFacets()) { module.getMessageBus().syncPublisher(FacetManager.FACETS_TOPIC).facetConfigurationChanged(facet); } } PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); if (myCaresAboutInjection) { setupEditorForInjectedLanguage(); } }); return getFile(); } protected void prepareVirtualFile(@NotNull VirtualFile file) { } private void setupEditorForInjectedLanguage() { Editor editor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myEditor, getFile()); if (editor instanceof EditorWindow) { myFile = ((EditorWindow)editor).getInjectedFile().getViewProvider().getVirtualFile(); myEditor = editor; } } @Override public VirtualFile findFileInTempDir(@NotNull final String filePath) { if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) { return myTempDirFixture.getFile(filePath); } String fullPath = getTempDirPath() + "/" + filePath; final VirtualFile copy = LocalFileSystem.getInstance().refreshAndFindFileByPath(fullPath.replace(File.separatorChar, '/')); assertNotNull("file " + fullPath + " not found", copy); VfsTestUtil.assertFilePathEndsWithCaseSensitivePath(copy, filePath); return copy; } @Nullable protected Editor createEditor(@NotNull VirtualFile file) { final Project project = getProject(); final FileEditorManager instance = FileEditorManager.getInstance(project); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); Editor editor = instance.openTextEditor(new OpenFileDescriptor(project, file), false); EditorTestUtil.waitForLoading(editor); if (editor != null) { DaemonCodeAnalyzer.getInstance(getProject()).restart(); } return editor; } private long collectAndCheckHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings) { return collectAndCheckHighlighting(checkWarnings, checkInfos, checkWeakWarnings, false); } private long collectAndCheckHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, boolean ignoreExtraHighlighting) { ExpectedHighlightingData data = new ExpectedHighlightingData( myEditor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, ignoreExtraHighlighting, getHostFile()); data.init(); return collectAndCheckHighlighting(data); } private PsiFile getHostFile() { VirtualFile hostVFile = myFile instanceof VirtualFileWindow ? ((VirtualFileWindow)myFile).getDelegate() : myFile; return ReadAction.compute(() -> PsiManager.getInstance(getProject()).findFile(hostVFile)); } private long collectAndCheckHighlighting(@NotNull ExpectedHighlightingData data) { final Project project = getProject(); EdtTestUtil.runInEdtAndWait(() -> PsiDocumentManager.getInstance(project).commitAllDocuments()); PsiFileImpl file = (PsiFileImpl)getHostFile(); FileElement hardRefToFileElement = file.calcTreeElement();//to load text //to initialize caches if (!DumbService.isDumb(project)) { CacheManager.SERVICE.getInstance(project) .getFilesWithWord("XXX", UsageSearchContext.IN_COMMENTS, GlobalSearchScope.allScope(project), true); } final long start = System.currentTimeMillis(); final VirtualFileFilter fileTreeAccessFilter = myVirtualFileFilter; Disposable disposable = Disposer.newDisposable(); if (fileTreeAccessFilter != null) { PsiManagerEx.getInstanceEx(project).setAssertOnFileLoadingFilter(fileTreeAccessFilter, disposable); } // ProfilingUtil.startCPUProfiling(); List<HighlightInfo> infos; try { infos = doHighlighting(); removeDuplicatedRangesForInjected(infos); } finally { Disposer.dispose(disposable); } // ProfilingUtil.captureCPUSnapshot("testing"); final long elapsed = System.currentTimeMillis() - start; data.checkResult(infos, file.getText()); if (data.hasLineMarkers()) { Document document = getDocument(getFile()); data.checkLineMarkers(DaemonCodeAnalyzerImpl.getLineMarkers(document, getProject()), document.getText()); } //noinspection ResultOfMethodCallIgnored hardRefToFileElement.hashCode(); // use it so gc won't collect it return elapsed; } public void setVirtualFileFilter(@Nullable VirtualFileFilter filter) { myVirtualFileFilter = filter; } @Override @NotNull public List<HighlightInfo> doHighlighting() { final Project project = getProject(); EdtTestUtil.runInEdtAndWait(() -> PsiDocumentManager.getInstance(project).commitAllDocuments()); PsiFile file = getFile(); Editor editor = getEditor(); if (editor instanceof EditorWindow) { editor = ((EditorWindow)editor).getDelegate(); file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file); } assertNotNull(file); return instantiateAndRun(file, editor, ArrayUtil.EMPTY_INT_ARRAY, myAllowDirt); } @NotNull @Override public List<HighlightInfo> doHighlighting(@NotNull final HighlightSeverity minimalSeverity) { return ContainerUtil.filter(doHighlighting(), info -> info.getSeverity().compareTo(minimalSeverity) >= 0); } @NotNull @Override public String getTestDataPath() { return myTestDataPath; } @Override public void setTestDataPath(@NotNull String dataPath) { myTestDataPath = dataPath; } @Override public Project getProject() { return myProjectFixture.getProject(); } @Override public Module getModule() { return myProjectFixture.getModule(); } @Override public Editor getEditor() { return myEditor; } @Override public int getCaretOffset() { return myEditor.getCaretModel().getOffset(); } @Override public PsiFile getFile() { return myFile != null ? ReadAction.compute(() -> PsiManager.getInstance(getProject()).findFile(myFile)) : null; } @Override public void allowTreeAccessForFile(@NotNull final VirtualFile file) { assert myVirtualFileFilter instanceof FileTreeAccessFilter : "configured filter does not support this method"; ((FileTreeAccessFilter)myVirtualFileFilter).allowTreeAccessForFile(file); } @Override public void allowTreeAccessForAllFiles() { assert myVirtualFileFilter instanceof FileTreeAccessFilter : "configured filter does not support this method"; ((FileTreeAccessFilter)myVirtualFileFilter).allowTreeAccessForAllFiles(); } private void checkResultByFile(@NotNull String expectedFile, @NotNull PsiFile originalFile, boolean stripTrailingSpaces) { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); if (!stripTrailingSpaces) { EditorUtil.fillVirtualSpaceUntilCaret(getHostEditor()); } String fileText = originalFile.getText(); String path = getTestDataPath() + "/" + expectedFile; String charset = Optional.ofNullable(originalFile.getVirtualFile()).map(f -> f.getCharset().name()).orElse(null); checkResult(expectedFile, stripTrailingSpaces, SelectionAndCaretMarkupLoader.fromFile(path, charset), fileText); } private void checkResult(@NotNull String expectedFile, boolean stripTrailingSpaces, @NotNull SelectionAndCaretMarkupLoader loader, @NotNull String actualText) { assertInitialized(); Project project = getProject(); Editor editor = getEditor(); if (editor instanceof EditorWindow) { editor = ((EditorWindow)editor).getDelegate(); } UsefulTestCase.doPostponedFormatting(getProject()); if (stripTrailingSpaces) { actualText = stripTrailingSpaces(actualText); } PsiDocumentManager.getInstance(project).commitAllDocuments(); String expectedText = loader.newFileText; if (stripTrailingSpaces) { expectedText = stripTrailingSpaces(expectedText); } actualText = StringUtil.convertLineSeparators(actualText); if (!Comparing.equal(expectedText, actualText)) { if (loader.filePath != null) { throw new FileComparisonFailure(expectedFile, expectedText, actualText, loader.filePath); } else { throw new ComparisonFailure(expectedFile, expectedText, actualText); } } EditorTestUtil.verifyCaretAndSelectionState(editor, loader.caretState, expectedFile); } @NotNull private String stripTrailingSpaces(@NotNull String actualText) { final Document document = EditorFactory.getInstance().createDocument(actualText); ((DocumentImpl)document).stripTrailingSpaces(getProject()); actualText = document.getText(); return actualText; } public void canChangeDocumentDuringHighlighting(boolean canI) { myAllowDirt = canI; } @NotNull public String getFoldingDescription(boolean withCollapseStatus) { final Editor topEditor = getHostEditor(); CodeFoldingManager.getInstance(getProject()).buildInitialFoldings(topEditor); return getTagsFromSegments(topEditor.getDocument().getText(), Arrays.asList(topEditor.getFoldingModel().getAllFoldRegions()), FOLD, foldRegion -> "text=\'" + foldRegion.getPlaceholderText() + "\'" + (withCollapseStatus ? " expand=\'" + foldRegion.isExpanded() + "\'" : "")); } @NotNull public static <T extends Segment> String getTagsFromSegments(@NotNull String text, @NotNull Collection<T> segments, @NotNull String tagName, @Nullable Function<T, String> attrCalculator) { final List<Border> borders = new LinkedList<>(); for (T region : segments) { String attr = attrCalculator == null ? null : attrCalculator.fun(region); borders.add(new CodeInsightTestFixtureImpl.Border(true, region.getStartOffset(), attr)); borders.add(new CodeInsightTestFixtureImpl.Border(false, region.getEndOffset(), "")); } Collections.sort(borders); StringBuilder result = new StringBuilder(text); for (CodeInsightTestFixtureImpl.Border border : borders) { StringBuilder info = new StringBuilder(); info.append('<'); if (border.isLeftBorder) { info.append(tagName); if (border.text != null) { info.append(' ').append(border.text); } } else { info.append('/').append(tagName); } info.append('>'); result.insert(border.offset, info); } return result.toString(); } private void testFoldingRegions(@NotNull String verificationFileName, @Nullable String destinationFileName, boolean doCheckCollapseStatus) { String expectedContent; final File verificationFile; try { verificationFile = new File(verificationFileName); expectedContent = FileUtil.loadFile(verificationFile); } catch (IOException e) { throw new RuntimeException(e); } assertNotNull(expectedContent); expectedContent = StringUtil.replace(expectedContent, "\r", ""); final String cleanContent = expectedContent.replaceAll("<" + FOLD + "\\stext=\'[^\']*\'(\\sexpand=\'[^\']*\')*>", "") .replace("</" + FOLD + ">", ""); if (destinationFileName == null) { configureByText(FileTypeManager.getInstance().getFileTypeByFileName(verificationFileName), cleanContent); } else { try { FileUtil.writeToFile(new File(destinationFileName), cleanContent); VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(destinationFileName); assertNotNull(file); configureFromExistingVirtualFile(file); } catch (IOException e) { throw new RuntimeException(e); } } final String actual = getFoldingDescription(doCheckCollapseStatus); if (!expectedContent.equals(actual)) { throw new FileComparisonFailure(verificationFile.getName(), expectedContent, actual, verificationFile.getPath()); } } @Override public void testFoldingWithCollapseStatus(@NotNull final String verificationFileName) { testFoldingRegions(verificationFileName, null, true); } @Override public void testFoldingWithCollapseStatus(@NotNull final String verificationFileName, @Nullable String destinationFileName) { testFoldingRegions(verificationFileName, destinationFileName, true); } @Override public void testFolding(@NotNull final String verificationFileName) { testFoldingRegions(verificationFileName, null, false); } @Override public void testRainbow(@NotNull String fileName, @NotNull String text, boolean isRainbowOn, boolean withColor) { final EditorColorsScheme globalScheme = EditorColorsManager.getInstance().getGlobalScheme(); final boolean isRainbowOnInScheme = RainbowHighlighter.isRainbowEnabled(globalScheme, null); try { RainbowHighlighter.setRainbowEnabled(globalScheme, null, isRainbowOn); configureByText(fileName, text.replaceAll("<" + RAINBOW + "(\\scolor=\'[^\']*\')?>", "").replace("</" + RAINBOW + ">", "")); List<HighlightInfo> highlighting = ContainerUtil.filter(doHighlighting(), info -> info.type == RainbowHighlighter.RAINBOW_ELEMENT); assertEquals(text, getTagsFromSegments(myEditor.getDocument().getText(), highlighting, RAINBOW, highlightInfo -> { if (!withColor) { return null; } TextAttributes attributes = highlightInfo.getTextAttributes(null, null); String color = attributes == null ? "null" : attributes.getForegroundColor() == null ? "null" : Integer.toHexString(attributes.getForegroundColor().getRGB()); return "color=\'" + color + "\'"; })); } finally { RainbowHighlighter.setRainbowEnabled(globalScheme, null, isRainbowOnInScheme); } } @Override public void testInlays() { InlayHintsChecker checker = new InlayHintsChecker(this); try { checker.setUp(); checker.checkInlays(); } finally { checker.tearDown(); } } @Override public void checkResultWithInlays(String text) { Document checkDocument = new DocumentImpl(text); InlayHintsChecker checker = new InlayHintsChecker(this); CaretAndInlaysInfo inlaysAndCaretInfo = checker.extractInlaysAndCaretInfo(checkDocument); checkResult(checkDocument.getText()); checker.verifyInlaysAndCaretInfo(inlaysAndCaretInfo, text); } @Override public void assertPreferredCompletionItems(final int selected, @NotNull final String... expected) { final LookupImpl lookup = getLookup(); assertNotNull("No lookup is shown", lookup); final JList list = lookup.getList(); List<String> strings = getLookupElementStrings(); assertNotNull(strings); final List<String> actual = strings.subList(0, Math.min(expected.length, strings.size())); if (!actual.equals(Arrays.asList(expected))) { UsefulTestCase.assertOrderedEquals(DumpLookupElementWeights.getLookupElementWeights(lookup, false), expected); } if (selected != list.getSelectedIndex()) { //noinspection UseOfSystemOutOrSystemErr System.out.println(DumpLookupElementWeights.getLookupElementWeights(lookup, false)); } assertEquals(selected, list.getSelectedIndex()); } @Override public void testStructureView(@NotNull Consumer<StructureViewComponent> consumer) { assertNotNull("configure first", myFile); final FileEditor fileEditor = FileEditorManager.getInstance(getProject()).getSelectedEditor(myFile); assertNotNull("editor not opened for " + myFile, myFile); final StructureViewBuilder builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(getFile()); assertNotNull("no builder for " + myFile, builder); StructureViewComponent component = null; try { component = (StructureViewComponent)builder.createStructureView(fileEditor, getProject()); PlatformTestUtil.waitForPromise(component.rebuildAndUpdate()); consumer.consume(component); } finally { if (component != null) Disposer.dispose(component); } } @Override public void setCaresAboutInjection(boolean caresAboutInjection) { myCaresAboutInjection = caresAboutInjection; } @Override public LookupImpl getLookup() { return (LookupImpl)LookupManager.getActiveLookup(myEditor); } @NotNull @Override public List<Object> getGotoClassResults(@NotNull String pattern, boolean searchEverywhere, @Nullable PsiElement contextForSorting) { final ChooseByNameBase chooseByNamePopup = getMockChooseByNamePopup(contextForSorting); final ArrayList<Object> results = new ArrayList<>(); chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, chooseByNamePopup.transformPattern(pattern), searchEverywhere, new MockProgressIndicator(), new CommonProcessors.CollectProcessor<>(results)); return results; } @NotNull @Override public List<Crumb> getBreadcrumbsAtCaret() { PsiElement element = getFile().findElementAt(getCaretOffset()); if (element == null) { return Collections.emptyList(); } final Language language = element.getContainingFile().getLanguage(); final BreadcrumbsProvider provider = BreadcrumbsUtil.getInfoProvider(language); if (provider == null) { return Collections.emptyList(); } List<Crumb> result = new ArrayList<>(); while (element != null) { if (provider.acceptElement(element)) { result.add(new Crumb.Impl(provider.getElementIcon(element), provider.getElementInfo(element), provider.getElementTooltip(element))); } element = provider.getParent(element); } return ContainerUtil.reverse(result); } @NotNull private ChooseByNameBase getMockChooseByNamePopup(@Nullable PsiElement contextForSorting) { final Project project = getProject(); if (contextForSorting != null) { return ChooseByNamePopup.createPopup(project, new GotoClassModel2(project), contextForSorting); } if (myChooseByNamePopup == null) { myChooseByNamePopup = ChooseByNamePopup.createPopup(project, new GotoClassModel2(project), (PsiElement)null); } return myChooseByNamePopup; } protected void bringRealEditorBack() { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); if (myEditor instanceof EditorWindow) { Document document = ((DocumentWindow)myEditor.getDocument()).getDelegate(); myFile = FileDocumentManager.getInstance().getFile(document); myEditor = ((EditorWindow)myEditor).getDelegate(); } } public static boolean invokeIntention(@NotNull IntentionAction action, PsiFile file, Editor editor, String actionText) { // Test that action will automatically clear the read-only attribute if modification is necessary. // If your test fails due to this, make sure that your quick-fix/intention // overrides "getElementToMakeWritable" or has the following line: // if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; Project project = file.getProject(); ReadonlyStatusHandlerImpl handler = (ReadonlyStatusHandlerImpl)ReadonlyStatusHandler.getInstance(project); VirtualFile vFile = Objects.requireNonNull(InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file)).getVirtualFile(); setReadOnly(vFile, true); handler.setClearReadOnlyInTests(true); AtomicBoolean result = new AtomicBoolean(); try { ApplicationManager.getApplication().invokeLater(() -> { try { result.set(ShowIntentionActionsHandler.chooseActionAndInvoke(file, editor, action, actionText)); } catch (StubTextInconsistencyException e) { PsiTestUtil.compareStubTexts(e); } }); UIUtil.dispatchAllInvocationEvents(); checkPsiTextConsistency(project, vFile); } catch (AssertionError e) { ExceptionUtil.rethrowUnchecked(ExceptionUtil.getRootCause(e)); throw e; } finally { handler.setClearReadOnlyInTests(false); setReadOnly(vFile, false); } return result.get(); } private static void checkPsiTextConsistency(Project project, VirtualFile vFile) { PsiFile topLevelPsi = vFile.isValid() ? PsiManager.getInstance(project).findFile(vFile) : null; if (topLevelPsi != null) { PsiTestUtil.checkStubsMatchText(topLevelPsi); } } private static void setReadOnly(VirtualFile vFile, boolean readOnlyStatus) { try { WriteAction.run(() -> ReadOnlyAttributeUtil.setReadOnlyAttribute(vFile, readOnlyStatus)); } catch (IOException e) { throw new UncheckedIOException(e); } } private static class SelectionAndCaretMarkupLoader { private final String filePath; private final String newFileText; private final EditorTestUtil.CaretAndSelectionState caretState; private SelectionAndCaretMarkupLoader(@NotNull String fileText, String filePath) { this.filePath = filePath; final Document document = EditorFactory.getInstance().createDocument(fileText); caretState = EditorTestUtil.extractCaretAndSelectionMarkers(document); newFileText = document.getText(); } @NotNull private static SelectionAndCaretMarkupLoader fromFile(@NotNull String path, String charset) { return fromIoSource(() -> FileUtil.loadFile(new File(path), charset), path); } @NotNull private static SelectionAndCaretMarkupLoader fromFile(@NotNull VirtualFile file) { return fromIoSource(() -> VfsUtilCore.loadText(file), file.getPath()); } @NotNull private static SelectionAndCaretMarkupLoader fromIoSource(@NotNull ThrowableComputable<String, IOException> source, String path) { try { return new SelectionAndCaretMarkupLoader(StringUtil.convertLineSeparators(source.compute()), path); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull private static SelectionAndCaretMarkupLoader fromText(@NotNull String text) { return new SelectionAndCaretMarkupLoader(text, null); } } private static class Border implements Comparable<Border> { private final boolean isLeftBorder; private final int offset; private final String text; private Border(boolean isLeftBorder, int offset, String text) { this.isLeftBorder = isLeftBorder; this.offset = offset; this.text = text; } @Override public int compareTo(@NotNull Border o) { return offset < o.offset ? 1 : -1; } } @Override @NotNull public Disposable getProjectDisposable() { return myProjectFixture.getTestRootDisposable(); } //<editor-fold desc="Deprecated stuff."> @Deprecated public static GlobalInspectionContextForTests createGlobalContextForTool(@NotNull AnalysisScope scope, @NotNull final Project project, @NotNull InspectionManagerEx inspectionManager, @NotNull final InspectionToolWrapper... toolWrappers) { return InspectionsKt.createGlobalContextForTool(scope, project, Arrays.<InspectionToolWrapper<?, ?>>asList(toolWrappers)); } //</editor-fold> }
package br.com.redesocial.modelo.bo; import br.com.redesocial.modelo.dto.Postagem; import br.com.redesocial.modelo.dto.Album; import br.com.redesocial.modelo.dto.Cidade; import br.com.redesocial.modelo.dto.Estado; import br.com.redesocial.modelo.dto.Pais; import br.com.redesocial.modelo.dto.Usuario; import br.com.redesocial.modelo.dto.enumeracoes.Sexo; import br.com.redesocial.modelo.utilitarios.Utilitarios; import java.io.File; import java.util.Calendar; import java.util.Date; import java.util.List; import org.junit.Test; import static org.junit.Assert.*; import br.com.redesocial.modelo.dto.Comentario; /** * * @author Lara */ public class ComentarioBOTest { @Test public void testMetodoInserir() throws Exception{ Pais pais = new Pais(); pais.setNome("Brasil"); try{ PaisBO paisBO = new PaisBO(); paisBO.inserir(pais); Estado estado = new Estado(); estado.setNome("São Paulo"); estado.setPais(pais); EstadoBO estadoBO = new EstadoBO(); estadoBO.inserir(estado); Cidade cidade = new Cidade(); cidade.setNome("Riberão Preto"); cidade.setEstado(estado); CidadeBO cidadeBO = new CidadeBO(); cidadeBO.inserir(cidade); Usuario usuario = new Usuario(); usuario.setNome("Marcos A."); usuario.setDataCadastro(new Date()); usuario.setEmail("raul@gmail.com"); Calendar calendario = Calendar.getInstance(); calendario.set(1986, 2, 8, 0, 0, 0); usuario.setDataNascimento(calendario.getTime()); usuario.setSenha("123789"); usuario.setSexo(Sexo.MASCULINO); usuario.setStatus(true); usuario.setTelefone("(62) 91432-9867"); usuario.setCidade(cidade); UsuarioBO usuarioBO = new UsuarioBO(); usuarioBO.inserir(usuario); Postagem postagem = new Postagem(); postagem.setDescricao("Comentário"); postagem.setCurtidas(0); postagem.setUsuario(usuario); calendario.set(2017, 7, 16, 21, 58, 0); postagem.setData(calendario.getTime()); PostagemBO postagemBO = new PostagemBO(); postagemBO.inserir(postagem); ComentarioBO bo = new ComentarioBO(); //instancia comentario e insere Comentario comentario = new Comentario(); comentario.setDescricao("bommm"); comentario.setResposta(comentario); comentario.setCurtidas(0); calendario.set(1986, 4, 8, 0, 0, 0); comentario.setData(calendario.getTime()); comentario.setPostagem(postagem); bo.inserir(comentario); } catch(Exception ex){ //Mensagem de erro caso falhe fail("Falha ao inserir um comentário: " + ex.getMessage()); } } @Test public void testMetodoAlterar(){ } @Test public void testMetodoSelecionar(){ ComentarioBO bo = new ComentarioBO(); try{ List existentes = bo.listar(); int qtdeExistentes = existentes.size(); Calendar calendario = Calendar.getInstance(); calendario.set(2017, 7, 18, 10, 55, 13); Calendar calendarioPost = Calendar.getInstance(); calendarioPost.set(2017, 7, 18, 9, 30, 45); Calendar calendarioNascimento = Calendar.getInstance(); calendarioNascimento.set(2017, 7, 18, 9, 30, 45); Pais pais = new Pais(); pais.setNome("Brasil"); PaisBO paisBO = new PaisBO(); paisBO.inserir(pais); Estado estado = new Estado(); estado.setNome("Paraná"); estado.setPais(pais); EstadoBO estadoBO = new EstadoBO(); estadoBO.inserir(estado); Cidade cidade = new Cidade(); cidade.setNome("Ceres"); cidade.setEstado(estado); CidadeBO cidadeBO = new CidadeBO(); cidadeBO.inserir(cidade); Usuario usuario = new Usuario(); usuario.setNome("Jeferson Rossini"); usuario.setDataCadastro(new Date()); usuario.setEmail("contatinho@contato.com"); usuario.setDataNascimento(calendarioNascimento.getTime()); usuario.setSenha("202030"); usuario.setSexo(Sexo.MASCULINO); usuario.setStatus(true); usuario.setTelefone("(62) 8432-98632"); usuario.setCidade(cidade); UsuarioBO usuarioBO = new UsuarioBO(); usuarioBO.inserir(usuario); Postagem postagem = new Postagem(); postagem.setCurtidas(6); postagem.setDescricao("Texto do Post"); postagem.setData(calendarioPost.getTime()); postagem.setUsuario(usuario); //insere post PostagemBO postagemBO = new PostagemBO(); postagemBO.inserir(postagem); //instancia comentario e insere Comentario comentario = new Comentario(); comentario.setDescricao("Comentário escrito aqui!!!"); comentario.setCurtidas(2); comentario.setData(calendario.getTime()); comentario.setPostagem(postagem); try{ bo.inserir(comentario); }catch(Exception ex){ /** * Mensagem de erro caso falhe */ fail("Falha ao inserir um comentário: " + ex.getMessage()); } }catch (Exception ex){ /** * Erro caso a listagem falhe */ fail("Erro ao listar: " + ex.getMessage()); } } //@Test public void testMetodoListar() { ComentarioBO bo = new ComentarioBO(); try{ List existentes = bo.listar(); int qtdeExistentes = existentes.size(); Calendar calendario = Calendar.getInstance(); calendario.set(2017, 7, 18, 10, 55, 13); Calendar calendarioPost = Calendar.getInstance(); calendarioPost.set(2017, 7, 18, 9, 30, 45); Calendar calendarioNascimento = Calendar.getInstance(); calendarioNascimento.set(2017, 7, 18, 9, 30, 45); Pais pais = new Pais(); pais.setNome("Brasil"); PaisBO paisBO = new PaisBO(); paisBO.inserir(pais); Estado estado = new Estado(); estado.setNome("Goiás"); estado.setPais(pais); EstadoBO estadoBO = new EstadoBO(); estadoBO.inserir(estado); Cidade cidade = new Cidade(); cidade.setNome("Goiânia"); cidade.setEstado(estado); CidadeBO cidadeBO = new CidadeBO(); cidadeBO.inserir(cidade); Usuario usuario = new Usuario(); usuario.setNome("Joana"); usuario.setDataCadastro(new Date()); usuario.setEmail("joaninha@contato.com"); usuario.setDataNascimento(calendarioNascimento.getTime()); usuario.setSenha("192837"); usuario.setSexo(Sexo.FEMININO); usuario.setStatus(true); usuario.setTelefone("(62) 91234-4567"); usuario.setCidade(cidade); UsuarioBO usuarioBO = new UsuarioBO(); usuarioBO.inserir(usuario); Postagem postagem = new Postagem(); postagem.setCurtidas(6); postagem.setDescricao("Post de texto"); postagem.setData(calendarioPost.getTime()); postagem.setUsuario(usuario); PostagemBO postagemBO = new PostagemBO(); postagemBO.inserir(postagem); final int qtde = 3; for (int i = 0; i < 3; i++){ Comentario comentario = new Comentario(); comentario.setDescricao("Que legal!"); comentario.setCurtidas(2); comentario.setData(calendario.getTime()); comentario.setPostagem(postagem); try{ bo.inserir(comentario); }catch(Exception ex){ //Mensagem de erro caso falhe fail("Falha ao inserir um comentário: " + ex.getMessage()); } } List existentesFinal = bo.listar(); int qtdeExistentesFinal = existentesFinal.size(); int diferenca = qtdeExistentesFinal - qtdeExistentes; assertEquals(qtde, diferenca); }catch (Exception ex){ //Erro caso a listagem falhe fail("Erro ao listar: " + ex.getMessage()); } } //@Test public void testMetodoExcluir(){ Pais pais = new Pais(); pais.setNome("Brasil"); try{ PaisBO paisBO = new PaisBO(); paisBO.inserir(pais); Estado estado = new Estado(); estado.setNome("Acre"); estado.setPais(pais); EstadoBO estadoBO = new EstadoBO(); estadoBO.inserir(estado); Cidade cidade = new Cidade(); cidade.setNome("Los Angel"); cidade.setEstado(estado); CidadeBO cidadeBO = new CidadeBO(); cidadeBO.inserir(cidade); Usuario usuario = new Usuario(); usuario.setNome("Raul"); usuario.setDataCadastro(new Date()); usuario.setEmail("raul@gmail.com"); Calendar calendario = Calendar.getInstance(); calendario.set(1986, 2, 8, 0, 0, 0); usuario.setDataNascimento(calendario.getTime()); usuario.setSenha("123789"); usuario.setSexo(Sexo.MASCULINO); usuario.setStatus(true); usuario.setTelefone("(62) 91432-9867"); usuario.setCidade(cidade); UsuarioBO usuarioBO = new UsuarioBO(); usuarioBO.inserir(usuario); Postagem postagem = new Postagem(); postagem.setDescricao("Comentário"); postagem.setCurtidas(0); postagem.setUsuario(usuario); calendario.set(2017, 7, 16, 21, 58, 0); postagem.setData(calendario.getTime()); PostagemBO postagemBO = new PostagemBO(); postagemBO.inserir(postagem); ComentarioBO bo = new ComentarioBO(); Comentario comentario = new Comentario(); comentario.setDescricao("bommm"); comentario.setCurtidas(0); calendario.set(1986, 4, 8, 0, 0, 0); comentario.setData(calendario.getTime()); comentario.setPostagem(postagem); bo.inserir(comentario); int id = comentario.getId(); Comentario comentarioSelecionado = bo.selecionar(id); assertNotNull("Comentario não encontrado", comentarioSelecionado); bo.excluir(id); Comentario comentarioSelecionadoPosExclusao = bo.selecionar(id); assertNull("comentario encontrado, mesmo apos exclui-la", comentarioSelecionadoPosExclusao); }catch (Exception ex){ fail ("Falha ao inserir um comentario" + ex.getMessage()); } } }
package org.cometd.client; import java.io.IOException; import java.util.Random; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; import org.cometd.Bayeux; import org.cometd.Client; import org.cometd.Message; import org.cometd.MessageListener; import org.cometd.server.AbstractBayeux; import org.cometd.server.MessageImpl; import org.cometd.server.continuation.ContinuationCometdServlet; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.component.LifeCycle; import org.eclipse.jetty.util.resource.Resource; import org.omg.CORBA._PolicyStub; public class BayeuxClientTest extends TestCase { private boolean _stress=Boolean.getBoolean("STRESS"); Server _server; SelectChannelConnector _connector; ContinuationCometdServlet _cometd; Random _random = new Random(); HttpClient _httpClient; AbstractBayeux _bayeux; TestFilter _filter; int _port; protected void setUp() throws Exception { super.setUp(); // Manually contruct context to avoid hassles with webapp classloaders for now. _server = new Server(); _connector=new SelectChannelConnector(); // SocketConnector connector=new SocketConnector(); _connector.setPort(0); _connector.setMaxIdleTime(30000); _server.addConnector(_connector); ServletContextHandler context = new ServletContextHandler(_server,"/"); context.setBaseResource(Resource.newResource("./src/test")); // Test Filter _filter = new TestFilter(); /** * @see junit.framework.TestCase#tearDown() */ @Override protected void tearDown() throws Exception { super.tearDown(); if (_httpClient!=null) _httpClient.stop(); _httpClient=null; if (_server!=null) _server.stop(); _server=null; } public void testClient() throws Exception { AbstractBayeux _bayeux = _cometd.getBayeux(); final Exchanger<Object> exchanger = new Exchanger<Object>(); BayeuxClient client = new BayeuxClient(_httpClient,"http://localhost:"+_server.getConnectors()[0].getLocalPort()+"/cometd") { volatile boolean connected; protected void metaConnect(boolean success, Message message) { super.metaConnect(success,message); if (!connected) { connected=true; try { ((MessageImpl)message).incRef(); exchanger.exchange(message,1,TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } } } protected void metaHandshake(boolean success, boolean reestablish, Message message) { connected=false; super.metaHandshake(success,reestablish,message); try { ((MessageImpl)message).incRef(); exchanger.exchange(message,1,TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } } }; client.addListener(new MessageListener(){ public void deliver(Client fromClient, Client toClient, Message message) { if (message.getData()!=null || Bayeux.META_SUBSCRIBE.equals(message.getChannel()) || Bayeux.META_DISCONNECT.equals(message.getChannel())) { try { ((MessageImpl)message).incRef(); exchanger.exchange(message,1,TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } } } }); client.addLifeCycleListener(new LifeCycle.Listener(){ public void lifeCycleFailure(LifeCycle event, Throwable cause) { } public void lifeCycleStarted(LifeCycle event) { } public void lifeCycleStarting(LifeCycle event) { } public void lifeCycleStopped(LifeCycle event) { try { exchanger.exchange(event,1,TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } } public void lifeCycleStopping(LifeCycle event) { } } ); client.start(); MessageImpl message = (MessageImpl)exchanger.exchange(null,1,TimeUnit.SECONDS); assertEquals(Bayeux.META_HANDSHAKE,message.getChannel()); assertTrue(message.isSuccessful()); String id = client.getId(); assertTrue(id!=null); message.decRef(); message = (MessageImpl)exchanger.exchange(null,1,TimeUnit.SECONDS); assertEquals(Bayeux.META_CONNECT,message.getChannel()); assertTrue(message.isSuccessful()); message.decRef(); client.subscribe("/a/channel"); message = (MessageImpl)exchanger.exchange(null,1,TimeUnit.SECONDS); assertEquals(Bayeux.META_SUBSCRIBE,message.getChannel()); assertTrue(message.isSuccessful()); message.decRef(); client.publish("/a/channel","data","id"); message = (MessageImpl)exchanger.exchange(null,1,TimeUnit.SECONDS); assertEquals("data",message.getData()); message.decRef(); client.disconnect(); message = (MessageImpl)exchanger.exchange(null,1,TimeUnit.SECONDS); assertEquals(Bayeux.META_DISCONNECT,message.getChannel()); assertTrue(message.isSuccessful()); message.decRef(); Object o = exchanger.exchange(null,1,TimeUnit.SECONDS); assertTrue(client.isStopped()); } public void testRetry() throws Exception { AbstractBayeux _bayeux = _cometd.getBayeux(); final BlockingArrayQueue<Object> queue = new BlockingArrayQueue<Object>(100,100); BayeuxClient client = new BayeuxClient(_httpClient,"http://localhost:"+_server.getConnectors()[0].getLocalPort()+"/cometd") { volatile boolean connected; protected void metaConnect(boolean success, Message message) { super.metaConnect(success,message); connected|=success; try { ((MessageImpl)message).incRef(); queue.offer(message); } catch (Exception e) { e.printStackTrace(); } } protected void metaHandshake(boolean success, boolean reestablish, Message message) { _filter._code=0; connected=false; super.metaHandshake(success,reestablish,message); try { ((MessageImpl)message).incRef(); queue.offer(message); } catch (Exception e) { e.printStackTrace(); } } }; client.addListener(new MessageListener(){ public void deliver(Client fromClient, Client toClient, Message message) { if (message.getData()!=null || Bayeux.META_SUBSCRIBE.equals(message.getChannel()) || Bayeux.META_DISCONNECT.equals(message.getChannel())) { try { ((MessageImpl)message).incRef(); queue.offer(message); } catch (Exception e) { e.printStackTrace(); } } } }); _filter._code=503; client.start(); MessageImpl message = (MessageImpl)queue.poll(1,TimeUnit.SECONDS); assertFalse(message.isSuccessful()); message.decRef(); message = (MessageImpl)queue.poll(1,TimeUnit.SECONDS); assertTrue(message.isSuccessful()); String id = client.getId(); assertTrue(id!=null); message.decRef(); message = (MessageImpl)queue.poll(1,TimeUnit.SECONDS); assertEquals(Bayeux.META_CONNECT,message.getChannel()); assertTrue(message.isSuccessful()); message.decRef(); _server.stop(); Thread.sleep(500); message=(MessageImpl)queue.poll(); assertFalse(message.isSuccessful()); while ((message=(MessageImpl)queue.poll())!=null) { assertFalse(message.isSuccessful()); } _connector.setPort(_port); _server.start(); message=(MessageImpl)queue.poll(2,TimeUnit.SECONDS); System.err.println(message); assertFalse(message.isSuccessful()); assertEquals("402::Unknown client",message.get("error")); client.disconnect(); } public void testCookies() throws Exception { BayeuxClient client = new BayeuxClient(_httpClient,"http://localhost:"+_server.getConnectors()[0].getLocalPort()+"/cometd"); String cookieName = "foo"; Cookie cookie = new Cookie(cookieName, "bar"); cookie.setMaxAge(1); client.setCookie(cookie); assertNotNull(client.getCookie(cookieName)); // Allow cookie to expire Thread.sleep(1500); assertNull(client.getCookie(cookieName)); cookie.setMaxAge(-1); client.setCookie(cookie); assertNotNull(client.getCookie(cookieName)); } public void testPerf() throws Exception { Runtime.getRuntime().addShutdownHook(new DumpThread()); AbstractBayeux bayeux = _cometd.getBayeux(); final int rooms=_stress?100:50; final int publish=_stress?4000:2000; final int batch=_stress?10:10; final int pause=_stress?50:100; BayeuxClient[] clients= new BayeuxClient[_stress?500:2*rooms]; final AtomicInteger connected=new AtomicInteger(); final AtomicInteger received=new AtomicInteger(); for (int i=0;i<clients.length;i++) { clients[i] = new BayeuxClient(_httpClient,"http://localhost:"+_server.getConnectors()[0].getLocalPort()+"/cometd") { volatile boolean _connected; protected void metaConnect(boolean success, Message message) { super.metaConnect(success,message); if (!_connected) { _connected=true; connected.incrementAndGet(); } } protected void metaHandshake(boolean success, boolean reestablish, Message message) { if (_connected) connected.decrementAndGet(); _connected=false; super.metaHandshake(success,reestablish,message); } }; clients[i].addListener(new MessageListener(){ public void deliver(Client fromClient, Client toClient, Message message) { // System.err.println(message); if (message.getData()!=null) { received.incrementAndGet(); } } }); clients[i].start(); clients[i].subscribe("/channel/"+(i%rooms)); } long start=System.currentTimeMillis(); int d=0; while(connected.get()<clients.length && (System.currentTimeMillis()-start)<30000) { Thread.sleep(1000); System.err.println("connected "+connected.get()+"/"+clients.length); } assertEquals(clients.length,connected.get()); long start0=System.currentTimeMillis(); for (int i=0;i<publish;i++) { final int sender=_random.nextInt(clients.length); final String channel="/channel/"+_random.nextInt(rooms); String data="data from "+sender+" to "+channel; // System.err.println(data); clients[sender].publish(channel,data,""+i); if (i%batch==(batch-1)) { System.err.print('.'); Thread.sleep(pause); } if (i%1000==999) System.err.println(); } System.err.println(); int expected=clients.length*publish/rooms; start=System.currentTimeMillis(); while(received.get()<expected && (System.currentTimeMillis()-start)<10000) { Thread.sleep(1000); System.err.println("received "+received.get()+"/"+expected); } System.err.println((received.get()*1000)/(System.currentTimeMillis()-start0)+" m/s"); assertEquals(expected,received.get()); for (BayeuxClient client : clients) client.disconnect(); Thread.sleep(clients.length*20); for (BayeuxClient client : clients) client.stop(); } private class DumpThread extends Thread { public void run() { try { if (_server!=null) _server.dump(); if (_httpClient!=null) _httpClient.dump(); } catch (Exception x) { x.printStackTrace(); } } } private static class TestFilter implements Filter { volatile int _code=0; public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (_code!=0) ((HttpServletResponse)response).sendError(_code); else chain.doFilter(request,response); } public void init(FilterConfig filterConfig) throws ServletException { } } }
package tools.devnull.boteco.plugins.norris; import tools.devnull.boteco.message.Sendable; public class ChuckNorrisFact implements Sendable { private static final long serialVersionUID = -2791001971425417273L; private String value; public ChuckNorrisFact(String value) { this.value = value; } @Override public String message() { return this.value; } }
package common.sunshine.model.selling.order; import common.sunshine.model.Entity; import common.sunshine.model.selling.event.Event; import common.sunshine.model.selling.event.EventApplication; import common.sunshine.model.selling.goods.Goods4Customer; import common.sunshine.model.selling.order.support.OrderItemStatus; public class EventOrder extends Entity { private String orderId; private String doneeName; private String doneePhone; private String doneeAddress; private OrderItemStatus status; private int quantity; private EventApplication application; private Event event; private Goods4Customer goods; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getDoneeName() { return doneeName; } public void setDoneeName(String doneeName) { this.doneeName = doneeName; } public String getDoneePhone() { return doneePhone; } public void setDoneePhone(String doneePhone) { this.doneePhone = doneePhone; } public String getDoneeAddress() { return doneeAddress; } public void setDoneeAddress(String doneeAddress) { this.doneeAddress = doneeAddress; } public OrderItemStatus getStatus() { return status; } public void setStatus(OrderItemStatus status) { this.status = status; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public EventApplication getApplication() { return application; } public void setApplication(EventApplication application) { this.application = application; } public Event getEvent() { return event; } public void setEvent(Event event) { this.event = event; } public Goods4Customer getGoods() { return goods; } public void setGoods(Goods4Customer goods) { this.goods = goods; } }
package com.redhat.ceylon.eclipse.code.editor; import java.util.Collections; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.menus.CommandContributionItemParameter; public class DynamicMenuItem extends CommandContributionItem { private boolean enabled; public DynamicMenuItem(String id, String label, boolean enabled) { super(new CommandContributionItemParameter( PlatformUI.getWorkbench().getActiveWorkbenchWindow(), id + ".cci", id, Collections.emptyMap(), null, null, null, label, null, null, CommandContributionItem.STYLE_PUSH, null, false)); this.enabled = enabled; } public DynamicMenuItem(String id, String label, boolean enabled, ImageDescriptor image) { super(new CommandContributionItemParameter( PlatformUI.getWorkbench().getActiveWorkbenchWindow(), id + ".cci", id, Collections.emptyMap(), image, null, null, label, null, null, CommandContributionItem.STYLE_PUSH, null, false)); this.enabled = enabled; } @Override public boolean isEnabled() { return super.isEnabled() && enabled; } public static boolean collapseMenuItems(IContributionManager parent) { return isContextMenu(parent) && Display.getCurrent().getBounds().height < 2048; } static boolean isContextMenu(IContributionManager parent) { return parent instanceof IContributionItem && ((IContributionItem) parent).getId().equals("#TextEditorContext"); } }
package gov.nih.nci.cabig.caaers.web.ae; import gov.nih.nci.cabig.caaers.web.ControllerTools; import gov.nih.nci.cabig.caaers.domain.Grade; import gov.nih.nci.cabig.caaers.domain.Hospitalization; import gov.nih.nci.cabig.caaers.domain.Attribution; import gov.nih.nci.cabig.caaers.dao.ParticipantDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.CtcTermDao; import gov.nih.nci.cabig.caaers.dao.AdverseEventReportDao; import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao; import gov.nih.nci.cabig.caaers.dao.AgentDao; import gov.nih.nci.cabig.caaers.rules.runtime.RuleExecutionService; import gov.nih.nci.cabig.ctms.web.tabs.AbstractTabbedFlowFormController; import gov.nih.nci.cabig.ctms.web.tabs.Flow; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.validation.BindException; import org.springframework.ui.ModelMap; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.beans.factory.InitializingBean; import java.util.Date; import java.util.Map; /** * @author Rhett Sutphin */ public abstract class AbstractAdverseEventInputController<C extends AdverseEventInputCommand> extends AbstractTabbedFlowFormController<AdverseEventInputCommand> implements InitializingBean { public static final String AJAX_SUBVIEW_PARAMETER = "subview"; private TabAutowirer autowirer; protected ParticipantDao participantDao; protected StudyDao studyDao; protected StudyParticipantAssignmentDao assignmentDao; protected CtcTermDao ctcTermDao; protected AgentDao agentDao; protected AdverseEventReportDao reportDao; protected RuleExecutionService ruleExecutionService; protected AbstractAdverseEventInputController() { setFlow(new Flow<AdverseEventInputCommand>(getFlowName())); addTabs(getFlow()); } protected void addTabs(Flow<AdverseEventInputCommand> flow) { flow.addTab(new BasicsTab()); flow.addTab(new MedicalInfoTab); flow.addTab(new LabsTab()); flow.addTab(new EmptyAeTab("Treatment information", "Treatment", "ae/notimplemented")); flow.addTab(new EmptyAeTab("Outcome information", "Outcome", "ae/notimplemented")); flow.addTab(new EmptyAeTab("Prior therapies", "Prior therapies", "ae/notimplemented")); flow.addTab(new ConcomitantMedicationsTab()); flow.addTab(new AttributionTab()); flow.addTab(new ReporterTab()); flow.addTab(new EmptyAeTab("Confirm and save", "Save", "ae/save")); } protected abstract String getFlowName(); @Override protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { ControllerTools.registerDomainObjectEditor(binder, "participant", participantDao); ControllerTools.registerDomainObjectEditor(binder, "study", studyDao); ControllerTools.registerDomainObjectEditor(binder, "aeReport", reportDao); ControllerTools.registerDomainObjectEditor(binder, ctcTermDao); ControllerTools.registerDomainObjectEditor(binder, agentDao); binder.registerCustomEditor(Date.class, ControllerTools.getDateEditor(false)); binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); ControllerTools.registerEnumEditor(binder, Grade.class); ControllerTools.registerEnumEditor(binder, Hospitalization.class); ControllerTools.registerEnumEditor(binder, Attribution.class); } /** Adds ajax sub-page view capability. TODO: factor this into main tabbed flow controller. */ @Override protected String getViewName(HttpServletRequest request, Object command, int page) { String subviewName = request.getParameter(AJAX_SUBVIEW_PARAMETER); if (subviewName != null) { return "ae/ajax/" + subviewName; } else { return super.getViewName(request, command, page); } } @Override @SuppressWarnings("unchecked") protected ModelAndView processFinish( HttpServletRequest request, HttpServletResponse response, Object oCommand, BindException errors ) throws Exception { C command = (C) oCommand; doSave(command); Map<String, Object> model = new ModelMap("participant", command.getParticipant().getId()); model.put("study", command.getStudy().getId()); return new ModelAndView("redirectToAeList", model); } protected void doSave(C command) { } ////// CONFIGURATION public void afterPropertiesSet() throws Exception { autowirer.injectDependencies(getFlow()); } public void setAutowirer(TabAutowirer autowirer) { this.autowirer = autowirer; } public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } public void setAssignmentDao(StudyParticipantAssignmentDao assignmentDao) { this.assignmentDao = assignmentDao; } public void setCtcTermDao(CtcTermDao ctcTermDao) { this.ctcTermDao = ctcTermDao; } public void setAgentDao(AgentDao agentDao) { this.agentDao = agentDao; } public void setReportDao(AdverseEventReportDao reportDao) { this.reportDao = reportDao; } public void setRuleExecutionService(RuleExecutionService ruleExecutionService) { this.ruleExecutionService = ruleExecutionService; } }
package uk.ac.ebi.quickgo.solr.model.miscellaneous; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.solr.client.solrj.beans.Field; import uk.ac.ebi.quickgo.solr.model.SolrDocumentType; /** * Solr representation of miscellaneous data * * @author cbonill * */ public class SolrMiscellaneous { @Field String docType; // Taxonomies @Field public int taxonomyId; @Field public String taxonomyName; @Field("taxonomyClosure") public List<Integer> taxonomyClosures; // Co-Occurrence statistics @Field private String term; @Field private String comparedTerm; @Field private float together; @Field private float compared; @Field private float selected; @Field private float all; @Field private String statsType;//Non-IEA or All // Sequences @Field private String dbObjectID; @Field private String sequence; // Publications @Field private int publicationID; @Field private String publicationTitle; // Annotation guideline @Field private String guidelineTitle; @Field private String guidelineURL; // Annotation blacklist @Field private String backlistReason; @Field private String blacklistMethodID; @Field private String backlistCategory; @Field private String backlistEntryType; // Annotation Extension Relations @Field private String aerName; @Field private String aerUsage; @Field private String aerDomain; @Field private List<String> aerParents; @Field private String aerRange; @Field private List<String> aerSecondaries; @Field private List<String> aerSubsets; // Xrefs Databases @Field private String xrefAbbreviation; @Field private String xrefDatabase; @Field private String xrefGenericURL; @Field private String xrefUrlSyntax; // Subsets count @Field private String subset; @Field private int subsetCount; // Evidences @Field private String evidenceCode; @Field private String evidenceName; // Post processing rule @Field private String pprRuleId; @Field private String pprAncestorGoId; @Field private String pprAncestorTerm; @Field private String pprRelationship; @Field private String pprTaxonName; @Field private String pprOriginalGoId; @Field private String pprOriginalTerm; @Field private String pprCleanupAction; @Field private String pprAffectedTaxGroup; @Field private String pprSubstitutedGoId; @Field private String pprSubstitutedTerm; @Field private String pprCuratorNotes; //Pre-calculated stats (not co-ocurrence stats) @Field private String statisticTupleType; @Field private String statisticTupleKey; @Field private long statisticTupleHits; public String getDocType() { return docType; } public void setDocType(String docType) { this.docType = docType; } public int getTaxonomyId() { return taxonomyId; } public void setTaxonomyId(int taxonomyId) { this.taxonomyId = taxonomyId; } public String getTaxonomyName() { return taxonomyName; } public void setTaxonomyName(String taxonomyName) { this.taxonomyName = taxonomyName; } public List<Integer> getTaxonomyClosures() { return taxonomyClosures; } public void setTaxonomyClosures(List<Integer> taxonomyClosures) { this.taxonomyClosures = taxonomyClosures; } public String getTerm() { return term; } public void setTerm(String term) { this.term = term; } public String getComparedTerm() { return comparedTerm; } public void setComparedTerm(String comparedTerm) { this.comparedTerm = comparedTerm; } public float getTogether() { return together; } public void setTogether(float together) { this.together = together; } public float getCompared() { return compared; } public void setCompared(float compared) { this.compared = compared; } public float getSelected() { return selected; } public void setSelected(float selected) { this.selected = selected; } public float getAll() { return all; } public void setAll(float all) { this.all = all; } public String getStatsType() { return statsType; } public void setStatsType(String statsType) { this.statsType = statsType; } public String getDbObjectID() { return dbObjectID; } public void setDbObjectID(String dbObjectID) { this.dbObjectID = dbObjectID; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; } public int getPublicationID() { return publicationID; } public void setPublicationID(int publicationID) { this.publicationID = publicationID; } public String getPublicationTitle() { return publicationTitle; } public void setPublicationTitle(String publicationTitle) { this.publicationTitle = publicationTitle; } public String getGuidelineTitle() { return guidelineTitle; } public void setGuidelineTitle(String guidelineTitle) { this.guidelineTitle = guidelineTitle; } public String getGuidelineURL() { return guidelineURL; } public void setGuidelineURL(String guidelineURL) { this.guidelineURL = guidelineURL; } public String getBacklistReason() { return backlistReason; } public void setBacklistReason(String backlistReason) { this.backlistReason = backlistReason; } public String getBlacklistMethodID() { return blacklistMethodID; } public void setBlacklistMethodID(String blacklistMethodID) { this.blacklistMethodID = blacklistMethodID; } public String getBacklistCategory() { return backlistCategory; } public void setBacklistCategory(String backlistCategory) { this.backlistCategory = backlistCategory; } public String getBacklistEntryType() { return backlistEntryType; } public void setBacklistEntryType(String backlistEntryType) { this.backlistEntryType = backlistEntryType; } public String getAerName() { return aerName; } public void setAerName(String aerName) { this.aerName = aerName; } public String getAerUsage() { return aerUsage; } public void setAerUsage(String aerUsage) { this.aerUsage = aerUsage; } public String getAerDomain() { return aerDomain; } public void setAerDomain(String aerDomain) { this.aerDomain = aerDomain; } public List<String> getAerParents() { return aerParents; } public void setAerParents(List<String> aerParents) { this.aerParents = aerParents; } public List<String> getAerSecondaries() { return aerSecondaries; } public void setAerSecondaries(List<String> aerSecondaries) { this.aerSecondaries = aerSecondaries; } public List<String> getAerSubsets() { return aerSubsets; } public void setAerSubsets(List<String> aerSubsets) { this.aerSubsets = aerSubsets; } public String getAerRange() { return aerRange; } public void setAerRange(String aerRange) { this.aerRange = aerRange; } public String getXrefAbbreviation() { return xrefAbbreviation; } public void setXrefAbbreviation(String xrefAbbreviation) { this.xrefAbbreviation = xrefAbbreviation; } public String getXrefDatabase() { return xrefDatabase; } public void setXrefDatabase(String xrefDatabase) { this.xrefDatabase = xrefDatabase; } public String getXrefGenericURL() { return xrefGenericURL; } public void setXrefGenericURL(String xrefGenericURL) { this.xrefGenericURL = xrefGenericURL; } public String getXrefUrlSyntax() { return xrefUrlSyntax; } public void setXrefUrlSyntax(String xrefUrlSyntax) { this.xrefUrlSyntax = xrefUrlSyntax; } public String getSubset() { return subset; } public void setSubset(String subset) { this.subset = subset; } public int getSubsetCount() { return subsetCount; } public void setSubsetCount(int subsetCount) { this.subsetCount = subsetCount; } public String getEvidenceCode() { return evidenceCode; } public void setEvidenceCode(String evidenceCode) { this.evidenceCode = evidenceCode; } public String getEvidenceName() { return evidenceName; } public void setEvidenceName(String evidenceName) { this.evidenceName = evidenceName; } public String getPprRuleId() { return pprRuleId; } public void setPprRuleId(String pprRuleId) { this.pprRuleId = pprRuleId; } public String getPprAncestorGoId() { return pprAncestorGoId; } public void setPprAncestorGoId(String pprAncestorGoId) { this.pprAncestorGoId = pprAncestorGoId; } public String getPprAncestorTerm() { return pprAncestorTerm; } public void setPprAncestorTerm(String pprAncestorTerm) { this.pprAncestorTerm = pprAncestorTerm; } public String getPprRelationship() { return pprRelationship; } public void setPprRelationship(String pprRelationship) { this.pprRelationship = pprRelationship; } public String getPprTaxonName() { return pprTaxonName; } public void setPprTaxonName(String pprTaxonName) { this.pprTaxonName = pprTaxonName; } public String getPprOriginalGoId() { return pprOriginalGoId; } public void setPprOriginalGoId(String pprOriginalGoId) { this.pprOriginalGoId = pprOriginalGoId; } public String getPprOriginalTerm() { return pprOriginalTerm; } public void setPprOriginalTerm(String pprOriginalTerm) { this.pprOriginalTerm = pprOriginalTerm; } public String getPprCleanupAction() { return pprCleanupAction; } public void setPprCleanupAction(String pprCleanupAction) { this.pprCleanupAction = pprCleanupAction; } public String getPprAffectedTaxGroup() { return pprAffectedTaxGroup; } public void setPprAffectedTaxGroup(String pprAffectedTaxGroup) { this.pprAffectedTaxGroup = pprAffectedTaxGroup; } public String getPprSubstitutedGoId() { return pprSubstitutedGoId; } public void setPprSubstitutedGoId(String pprSubstitutedGoId) { this.pprSubstitutedGoId = pprSubstitutedGoId; } public String getPprSubstitutedTerm() { return pprSubstitutedTerm; } public void setPprSubstitutedTerm(String pprSubstitutedTerm) { this.pprSubstitutedTerm = pprSubstitutedTerm; } public String getPprCuratorNotes() { return pprCuratorNotes; } public void setPprCuratorNotes(String pprCuratorNotes) { this.pprCuratorNotes = pprCuratorNotes; } public String getStatisticTupleType() { return statisticTupleType; } public void setStatisticTupleType(String statisticTupleType) { this.statisticTupleType = statisticTupleType; } public String getStatisticTupleKey() { return statisticTupleKey; } public void setStatisticTupleKey(String statisticTupleKey) { this.statisticTupleKey = statisticTupleKey; } public long getStatisticTupleHits() { return statisticTupleHits; } public void setStatisticTupleHits(long statisticTupleHits) { this.statisticTupleHits = statisticTupleHits; } /** * Gene products documents types * * @author cbonill * */ public enum SolrMiscellaneousDocumentType implements SolrDocumentType { TAXONOMY("taxonomy"), STATS("stats"), SEQUENCE("sequence"), PUBLICATION("publication"), GUIDELINE("guideline"), BLACKLIST("blacklist"), EXTENSION("extension"), XREFDB("xrefdb"), SUBSETCOUNT("subsetcount"), EVIDENCE("evidence"), POSTPROCESSINGRULE("postprocessingrule"), PRECALCULATED_STATS("precalculated-stats"); String value; SolrMiscellaneousDocumentType(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } /** * Get values as SolrDocumentType objects * * @return Enum values as SolrDocumentType objects */ public static List<SolrDocumentType> getAsInterfaces() { List<SolrDocumentType> documentTypes = new ArrayList<>(); documentTypes.addAll(Arrays.asList(values())); return documentTypes; } } }
package net.runelite.client.plugins.cluescrolls.clues; import com.google.common.collect.ImmutableSet; import java.awt.Color; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.Item; import net.runelite.api.ItemID; import net.runelite.api.NPC; import net.runelite.api.Point; import net.runelite.api.TileObject; import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR; import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_BORDER_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_FILL_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_HOVER_BORDER_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET; import net.runelite.client.plugins.cluescrolls.clues.item.AnyRequirementCollection; import net.runelite.client.plugins.cluescrolls.clues.item.ItemRequirement; import static net.runelite.client.plugins.cluescrolls.clues.item.ItemRequirements.*; import net.runelite.client.plugins.cluescrolls.clues.item.SingleItemRequirement; import net.runelite.client.ui.FontManager; import net.runelite.client.ui.overlay.OverlayUtil; import net.runelite.client.ui.overlay.components.LineComponent; import net.runelite.client.ui.overlay.components.PanelComponent; import net.runelite.client.ui.overlay.components.TitleComponent; @Getter public class SkillChallengeClue extends ClueScroll implements NpcClueScroll, NamedObjectClueScroll { @AllArgsConstructor @Getter enum ChallengeType { CHARLIE("Charlie the Tramp", "Southern Entrance to Varrock"), SHERLOCK("Sherlock", "East of the Sorcerer's Tower in Seers' Village"); private String name; private String location; } private static final AnyRequirementCollection ANY_PICKAXE = any("Any Pickaxe", item(ItemID.BRONZE_PICKAXE), item(ItemID.IRON_PICKAXE), item(ItemID.STEEL_PICKAXE), item(ItemID.BLACK_PICKAXE), item(ItemID.MITHRIL_PICKAXE), item(ItemID.ADAMANT_PICKAXE), item(ItemID.RUNE_PICKAXE), item(ItemID.DRAGON_PICKAXE), item(ItemID.DRAGON_PICKAXE_12797), item(ItemID.DRAGON_PICKAXE_OR), item(ItemID.DRAGON_PICKAXE_OR_25376), item(ItemID.INFERNAL_PICKAXE), item(ItemID.INFERNAL_PICKAXE_OR), item(ItemID.INFERNAL_PICKAXE_UNCHARGED), item(ItemID.INFERNAL_PICKAXE_UNCHARGED_25369), item(ItemID.GILDED_PICKAXE), item(ItemID._3RD_AGE_PICKAXE), item(ItemID.CRYSTAL_PICKAXE), item(ItemID.CRYSTAL_PICKAXE_INACTIVE) ); private static final AnyRequirementCollection ANY_AXE = any("Any Axe", item(ItemID.BRONZE_AXE), item(ItemID.IRON_AXE), item(ItemID.STEEL_AXE), item(ItemID.BLACK_AXE), item(ItemID.MITHRIL_AXE), item(ItemID.ADAMANT_AXE), item(ItemID.RUNE_AXE), item(ItemID.DRAGON_AXE), item(ItemID.DRAGON_AXE_OR), item(ItemID.INFERNAL_AXE), item(ItemID.INFERNAL_AXE_OR), item(ItemID.INFERNAL_AXE_UNCHARGED), item(ItemID.INFERNAL_AXE_UNCHARGED_25371), item(ItemID.GILDED_AXE), item(ItemID._3RD_AGE_AXE), item(ItemID.CRYSTAL_AXE), item(ItemID.CRYSTAL_AXE_INACTIVE) ); private static final AnyRequirementCollection ANY_HARPOON = any("Harpoon", item(ItemID.HARPOON), item(ItemID.BARBTAIL_HARPOON), item(ItemID.DRAGON_HARPOON), item(ItemID.DRAGON_HARPOON_OR), item(ItemID.INFERNAL_HARPOON), item(ItemID.INFERNAL_HARPOON_OR), item(ItemID.INFERNAL_HARPOON_UNCHARGED), item(ItemID.INFERNAL_HARPOON_UNCHARGED_25367), item(ItemID.CRYSTAL_HARPOON), item(ItemID.CRYSTAL_HARPOON_INACTIVE) ); private static final Set<SkillChallengeClue> CLUES = ImmutableSet.of( // Charlie Tasks new SkillChallengeClue("Cook a Pike", "i need to cook charlie a pike.", "i need to take the cooked pike to charlie.", item(ItemID.PIKE), item(ItemID.RAW_PIKE)), new SkillChallengeClue("Cook a Trout", "i need to cook charlie a trout.", "i need to take the cooked trout to charlie.", item(ItemID.TROUT), item(ItemID.RAW_TROUT)), new SkillChallengeClue("Craft a Leather Body", "i need to craft charlie a leather body.", "i need to take the leather body i crafted to charlie.", item(ItemID.LEATHER_BODY), item(ItemID.LEATHER), item(ItemID.NEEDLE), item(ItemID.THREAD)), new SkillChallengeClue("Craft some Leather Chaps", "i need to craft charlie some leather chaps.", "i need to take the leather chaps i crafted to charlie.", item(ItemID.LEATHER_CHAPS), item(ItemID.LEATHER), item(ItemID.NEEDLE), item(ItemID.THREAD)), new SkillChallengeClue("Fish a Herring", "i need to fish charlie a herring.", "i need to take a raw herring to charlie.", item(ItemID.RAW_HERRING), any("Fishing rod", item(ItemID.FISHING_ROD), item(ItemID.PEARL_FISHING_ROD)), item(ItemID.FISHING_BAIT)), new SkillChallengeClue("Fish a Trout", "i need to fish charlie a trout.", "i need to take a raw trout to charlie.", item(ItemID.RAW_TROUT), any("Fly fishing rod", item(ItemID.FLY_FISHING_ROD), item(ItemID.PEARL_FLY_FISHING_ROD)), item(ItemID.FEATHER)), new SkillChallengeClue("Mine a piece of Iron Ore", "i need to mine charlie a piece of iron ore from an iron vein.", "i need to take the iron ore to charlie.", item(ItemID.IRON_ORE), ANY_PICKAXE), new SkillChallengeClue("Smith an Iron Dagger", "i need to smith charlie one iron dagger.", "i need to take the iron dagger i smithed to charlie.", item(ItemID.IRON_DAGGER), item(ItemID.IRON_BAR), item(ItemID.HAMMER)), // Elite Sherlock Tasks new SkillChallengeClue("Equip a Dragon Scimitar.", true, any("Any Dragon Scimitar", item(ItemID.DRAGON_SCIMITAR), item(ItemID.DRAGON_SCIMITAR_OR))), new SkillChallengeClue("Enchant some Dragonstone Jewellery.", "enchant a piece of dragonstone jewellery.", xOfItem(ItemID.COSMIC_RUNE, 1), any("Water Rune x15", xOfItem(ItemID.WATER_RUNE, 15), xOfItem(ItemID.MIST_RUNE, 15), xOfItem(ItemID.MUD_RUNE, 15), xOfItem(ItemID.STEAM_RUNE, 15), item(ItemID.STAFF_OF_WATER), item(ItemID.WATER_BATTLESTAFF), item(ItemID.MYSTIC_WATER_STAFF), item(ItemID.MUD_BATTLESTAFF), item(ItemID.MYSTIC_MUD_STAFF), item(ItemID.MIST_BATTLESTAFF), item(ItemID.MYSTIC_MIST_STAFF), item(ItemID.STEAM_BATTLESTAFF), item(ItemID.MYSTIC_STEAM_STAFF), item(ItemID.STEAM_BATTLESTAFF_12795), item(ItemID.MYSTIC_STEAM_STAFF_12796), item(ItemID.KODAI_WAND)), any("Earth Rune x15", xOfItem(ItemID.EARTH_RUNE, 15), xOfItem(ItemID.DUST_RUNE, 15), xOfItem(ItemID.MUD_RUNE, 15), xOfItem(ItemID.LAVA_RUNE, 15), item(ItemID.STAFF_OF_EARTH), item(ItemID.EARTH_BATTLESTAFF), item(ItemID.MYSTIC_EARTH_STAFF), item(ItemID.MUD_BATTLESTAFF), item(ItemID.MYSTIC_MUD_STAFF), item(ItemID.DUST_BATTLESTAFF), item(ItemID.MYSTIC_DUST_STAFF), item(ItemID.LAVA_BATTLESTAFF), item(ItemID.MYSTIC_LAVA_STAFF), item(ItemID.LAVA_BATTLESTAFF_21198), item(ItemID.MYSTIC_LAVA_STAFF_21200)), any("Unenchanted Dragonstone Jewellery", item(ItemID.DRAGONSTONE_RING), item(ItemID.DRAGON_NECKLACE), item(ItemID.DRAGONSTONE_BRACELET), item(ItemID.DRAGONSTONE_AMULET))), new SkillChallengeClue("Craft a nature rune.", item(ItemID.PURE_ESSENCE)), new SkillChallengeClue("Catch a mottled eel with aerial fishing in Lake Molch.", any("Fish chunks or King worms", item(ItemID.FISH_CHUNKS), item(ItemID.KING_WORM)), emptySlot("No Gloves", EquipmentInventorySlot.GLOVES), emptySlot("No Weapon", EquipmentInventorySlot.WEAPON), emptySlot("No Shield", EquipmentInventorySlot.SHIELD)), new SkillChallengeClue("Score a goal in skullball.", true, any("Ring of Charos", item(ItemID.RING_OF_CHAROS), item(ItemID.RING_OF_CHAROSA))), new SkillChallengeClue("Complete a lap of Ape atoll agility course.", true, any("Ninja Monkey Greegree", item(ItemID.NINJA_MONKEY_GREEGREE), item(ItemID.NINJA_MONKEY_GREEGREE_4025), item(ItemID.KRUK_MONKEY_GREEGREE))), new SkillChallengeClue("Create a super defence potion.", item(ItemID.CADANTINE_POTION_UNF), item(ItemID.WHITE_BERRIES)), new SkillChallengeClue("Steal from a chest in Ardougne Castle."), new SkillChallengeClue("Craft a green dragonhide body.", xOfItem(ItemID.GREEN_DRAGON_LEATHER, 3), item(ItemID.NEEDLE), item(ItemID.THREAD)), new SkillChallengeClue("String a yew longbow.", item(ItemID.YEW_LONGBOW_U), item(ItemID.BOW_STRING)), new SkillChallengeClue("Kill a Dust Devil.", "slay a dust devil.", true, any("Facemask or Slayer Helmet", item(ItemID.FACEMASK), item(ItemID.SLAYER_HELMET), item(ItemID. SLAYER_HELMET_I), item(ItemID. BLACK_SLAYER_HELMET), item(ItemID. BLACK_SLAYER_HELMET_I), item(ItemID. PURPLE_SLAYER_HELMET), item(ItemID. PURPLE_SLAYER_HELMET_I), item(ItemID. RED_SLAYER_HELMET), item(ItemID. RED_SLAYER_HELMET_I), item(ItemID.GREEN_SLAYER_HELMET), item(ItemID. GREEN_SLAYER_HELMET_I), item(ItemID. TURQUOISE_SLAYER_HELMET), item(ItemID. TURQUOISE_SLAYER_HELMET_I), item(ItemID. HYDRA_SLAYER_HELMET), item(ItemID. HYDRA_SLAYER_HELMET_I), item(ItemID.TWISTED_SLAYER_HELMET), item(ItemID.TWISTED_SLAYER_HELMET_I), item(ItemID.SLAYER_HELMET_I_25177), item(ItemID.BLACK_SLAYER_HELMET_I_25179), item(ItemID.GREEN_SLAYER_HELMET_I_25181), item(ItemID.RED_SLAYER_HELMET_I_25183), item(ItemID.PURPLE_SLAYER_HELMET_I_25185), item(ItemID.TURQUOISE_SLAYER_HELMET_I_25187), item(ItemID.HYDRA_SLAYER_HELMET_I_25189), item(ItemID.TWISTED_SLAYER_HELMET_I_25191))), new SkillChallengeClue("Catch a black warlock.", item(ItemID.BUTTERFLY_JAR), any("Butterfly Net", item(ItemID.BUTTERFLY_NET), item(ItemID.MAGIC_BUTTERFLY_NET))), new SkillChallengeClue("Catch a red chinchompa.", item(ItemID.BOX_TRAP)), new SkillChallengeClue("Mine a mithril ore.", ANY_PICKAXE), new SkillChallengeClue("Smith a mithril 2h sword.", item(ItemID.HAMMER), xOfItem(ItemID.MITHRIL_BAR, 3)), new SkillChallengeClue("Catch a raw shark.", ANY_HARPOON), new SkillChallengeClue("Cut a yew log.", ANY_AXE), new SkillChallengeClue("Fix a magical lamp in Dorgesh-Kaan.", new String[] { "Broken lamp" }, new int[] { 10834, 10835 }, item(ItemID.LIGHT_ORB)), new SkillChallengeClue("Burn a yew log.", item(ItemID.YEW_LOGS), item(ItemID.TINDERBOX)), new SkillChallengeClue("Cook a swordfish", "cook a swordfish", item(ItemID.RAW_SWORDFISH)), new SkillChallengeClue("Craft multiple cosmic runes from a single essence.", item(ItemID.PURE_ESSENCE)), new SkillChallengeClue("Plant a watermelon seed.", item(ItemID.RAKE), item(ItemID.SEED_DIBBER), xOfItem(ItemID.WATERMELON_SEED, 3)), new SkillChallengeClue("Activate the Chivalry prayer."), new SkillChallengeClue("Hand in a Tier 2 or higher set of Shayzien supply armour. (Requires 11 lovakite bars)", "take the lovakengj armourers a boxed set of shayzien supply armour at tier 2 or above.", any("Shayzien Supply Set (Tier 2 or higher)", item(ItemID.SHAYZIEN_SUPPLY_SET_2), item(ItemID.SHAYZIEN_SUPPLY_SET_3), item(ItemID.SHAYZIEN_SUPPLY_SET_4), item(ItemID.SHAYZIEN_SUPPLY_SET_5))), // Master Sherlock Tasks new SkillChallengeClue("Equip an abyssal whip in front of the abyssal demons of the Slayer Tower.", true, any("Abyssal Whip", item(ItemID.ABYSSAL_WHIP), item(ItemID.FROZEN_ABYSSAL_WHIP), item(ItemID.VOLCANIC_ABYSSAL_WHIP))), new SkillChallengeClue("Smith a runite med helm.", item(ItemID.HAMMER), item(ItemID.RUNITE_BAR)), new SkillChallengeClue("Teleport to a spirit tree you planted yourself."), new SkillChallengeClue("Create a Barrows teleport tablet.", item(ItemID.DARK_ESSENCE_BLOCK), xOfItem(ItemID.BLOOD_RUNE, 1), xOfItem(ItemID.LAW_RUNE, 2), xOfItem(ItemID.SOUL_RUNE, 2)), new SkillChallengeClue("Kill a Nechryael in the Slayer Tower.", "slay a nechryael in the slayer tower."), new SkillChallengeClue("Kill a Spiritual Mage while wearing something from their god.", "kill the spiritual, magic and godly whilst representing their own god."), new SkillChallengeClue("Create an unstrung dragonstone amulet at a furnace.", item(ItemID.GOLD_BAR), item(ItemID.DRAGONSTONE), item(ItemID.AMULET_MOULD)), new SkillChallengeClue("Burn a magic log.", item(ItemID.MAGIC_LOGS), item(ItemID.TINDERBOX)), new SkillChallengeClue("Burn a redwood log.", item(ItemID.REDWOOD_LOGS), item(ItemID.TINDERBOX)), new SkillChallengeClue("Complete a lap of Rellekka's Rooftop Agility Course", "complete a lap of the rellekka rooftop agility course whilst sporting the finest amount of grace.", true, all("A full Graceful set", any("", item(ItemID.GRACEFUL_HOOD), item(ItemID.GRACEFUL_HOOD_11851), item(ItemID.GRACEFUL_HOOD_13579), item(ItemID.GRACEFUL_HOOD_13580), item(ItemID.GRACEFUL_HOOD_13591), item(ItemID.GRACEFUL_HOOD_13592), item(ItemID.GRACEFUL_HOOD_13603), item(ItemID.GRACEFUL_HOOD_13604), item(ItemID.GRACEFUL_HOOD_13615), item(ItemID.GRACEFUL_HOOD_13616), item(ItemID.GRACEFUL_HOOD_13627), item(ItemID.GRACEFUL_HOOD_13628), item(ItemID.GRACEFUL_HOOD_13667), item(ItemID.GRACEFUL_HOOD_13668), item(ItemID.GRACEFUL_HOOD_21061), item(ItemID.GRACEFUL_HOOD_21063), item(ItemID.GRACEFUL_HOOD_24743), item(ItemID.GRACEFUL_HOOD_24745), item(ItemID.GRACEFUL_HOOD_25069), item(ItemID.GRACEFUL_HOOD_25071)), any("", item(ItemID.GRACEFUL_CAPE), item(ItemID.GRACEFUL_CAPE_11853), item(ItemID.GRACEFUL_CAPE_13581), item(ItemID.GRACEFUL_CAPE_13582), item(ItemID.GRACEFUL_CAPE_13593), item(ItemID.GRACEFUL_CAPE_13594), item(ItemID.GRACEFUL_CAPE_13605), item(ItemID.GRACEFUL_CAPE_13606), item(ItemID.GRACEFUL_CAPE_13617), item(ItemID.GRACEFUL_CAPE_13618), item(ItemID.GRACEFUL_CAPE_13629), item(ItemID.GRACEFUL_CAPE_13630), item(ItemID.GRACEFUL_CAPE_13669), item(ItemID.GRACEFUL_CAPE_13670), item(ItemID.GRACEFUL_CAPE_21064), item(ItemID.GRACEFUL_CAPE_21066), item(ItemID.GRACEFUL_CAPE_24746), item(ItemID.GRACEFUL_CAPE_24748), item(ItemID.GRACEFUL_CAPE_25072), item(ItemID.GRACEFUL_CAPE_25074), item(ItemID.AGILITY_CAPE), item(ItemID.AGILITY_CAPE_13340), item(ItemID.AGILITY_CAPET), item(ItemID.AGILITY_CAPET_13341), item(ItemID.MAX_CAPE), item(ItemID.MAX_CAPE_13342)), any("", item(ItemID.GRACEFUL_TOP), item(ItemID.GRACEFUL_TOP_11855), item(ItemID.GRACEFUL_TOP_13583), item(ItemID.GRACEFUL_TOP_13584), item(ItemID.GRACEFUL_TOP_13595), item(ItemID.GRACEFUL_TOP_13596), item(ItemID.GRACEFUL_TOP_13607), item(ItemID.GRACEFUL_TOP_13608), item(ItemID.GRACEFUL_TOP_13619), item(ItemID.GRACEFUL_TOP_13620), item(ItemID.GRACEFUL_TOP_13631), item(ItemID.GRACEFUL_TOP_13632), item(ItemID.GRACEFUL_TOP_13671), item(ItemID.GRACEFUL_TOP_13672), item(ItemID.GRACEFUL_TOP_21067), item(ItemID.GRACEFUL_TOP_21069), item(ItemID.GRACEFUL_TOP_24749), item(ItemID.GRACEFUL_TOP_24751), item(ItemID.GRACEFUL_TOP_25075), item(ItemID.GRACEFUL_TOP_25077)), any("", item(ItemID.GRACEFUL_LEGS), item(ItemID.GRACEFUL_LEGS_11857), item(ItemID.GRACEFUL_LEGS_13585), item(ItemID.GRACEFUL_LEGS_13586), item(ItemID.GRACEFUL_LEGS_13597), item(ItemID.GRACEFUL_LEGS_13598), item(ItemID.GRACEFUL_LEGS_13609), item(ItemID.GRACEFUL_LEGS_13610), item(ItemID.GRACEFUL_LEGS_13621), item(ItemID.GRACEFUL_LEGS_13622), item(ItemID.GRACEFUL_LEGS_13633), item(ItemID.GRACEFUL_LEGS_13634), item(ItemID.GRACEFUL_LEGS_13673), item(ItemID.GRACEFUL_LEGS_13674), item(ItemID.GRACEFUL_LEGS_21070), item(ItemID.GRACEFUL_LEGS_21072), item(ItemID.GRACEFUL_LEGS_24752), item(ItemID.GRACEFUL_LEGS_24754), item(ItemID.GRACEFUL_LEGS_25078), item(ItemID.GRACEFUL_LEGS_25080)), any("", item(ItemID.GRACEFUL_GLOVES), item(ItemID.GRACEFUL_GLOVES_11859), item(ItemID.GRACEFUL_GLOVES_13587), item(ItemID.GRACEFUL_GLOVES_13588), item(ItemID.GRACEFUL_GLOVES_13599), item(ItemID.GRACEFUL_GLOVES_13600), item(ItemID.GRACEFUL_GLOVES_13611), item(ItemID.GRACEFUL_GLOVES_13612), item(ItemID.GRACEFUL_GLOVES_13623), item(ItemID.GRACEFUL_GLOVES_13624), item(ItemID.GRACEFUL_GLOVES_13635), item(ItemID.GRACEFUL_GLOVES_13636), item(ItemID.GRACEFUL_GLOVES_13675), item(ItemID.GRACEFUL_GLOVES_13676), item(ItemID.GRACEFUL_GLOVES_21073), item(ItemID.GRACEFUL_GLOVES_21075), item(ItemID.GRACEFUL_GLOVES_24755), item(ItemID.GRACEFUL_GLOVES_24757), item(ItemID.GRACEFUL_GLOVES_25081), item(ItemID.GRACEFUL_GLOVES_25083)), any("", item(ItemID.GRACEFUL_BOOTS), item(ItemID.GRACEFUL_BOOTS_11861), item(ItemID.GRACEFUL_BOOTS_13589), item(ItemID.GRACEFUL_BOOTS_13590), item(ItemID.GRACEFUL_BOOTS_13601), item(ItemID.GRACEFUL_BOOTS_13602), item(ItemID.GRACEFUL_BOOTS_13613), item(ItemID.GRACEFUL_BOOTS_13614), item(ItemID.GRACEFUL_BOOTS_13625), item(ItemID.GRACEFUL_BOOTS_13626), item(ItemID.GRACEFUL_BOOTS_13637), item(ItemID.GRACEFUL_BOOTS_13638), item(ItemID.GRACEFUL_BOOTS_13677), item(ItemID.GRACEFUL_BOOTS_13678), item(ItemID.GRACEFUL_BOOTS_21076), item(ItemID.GRACEFUL_BOOTS_21078), item(ItemID.GRACEFUL_BOOTS_24758), item(ItemID.GRACEFUL_BOOTS_24760), item(ItemID.GRACEFUL_BOOTS_25084), item(ItemID.GRACEFUL_BOOTS_25086)))), new SkillChallengeClue("Mix an anti-venom potion.", item(ItemID.ANTIDOTE4_5952), xOfItem(ItemID.ZULRAHS_SCALES, 20)), new SkillChallengeClue("Mine a piece of Runite ore", "mine a piece of runite ore whilst sporting the finest mining gear.", true, ANY_PICKAXE, all("Prospector kit", any("", item(ItemID.PROSPECTOR_HELMET), item(ItemID.GOLDEN_PROSPECTOR_HELMET)), any("", item(ItemID.PROSPECTOR_JACKET), item(ItemID.VARROCK_ARMOUR_4), item(ItemID.GOLDEN_PROSPECTOR_JACKET)), any("", item(ItemID.PROSPECTOR_LEGS), item(ItemID.GOLDEN_PROSPECTOR_LEGS)), any("", item(ItemID.PROSPECTOR_BOOTS), item(ItemID.GOLDEN_PROSPECTOR_BOOTS)))), new SkillChallengeClue("Steal a gem from the Ardougne market."), new SkillChallengeClue("Pickpocket an elf."), new SkillChallengeClue("Bind a blood rune at the blood altar.", item(ItemID.DARK_ESSENCE_FRAGMENTS)), new SkillChallengeClue("Create a ranging mix potion.", "mix a ranging mix potion.", item(ItemID.RANGING_POTION2), item(ItemID.CAVIAR)), new SkillChallengeClue("Fletch a rune dart.", item(ItemID.RUNE_DART_TIP), item(ItemID.FEATHER)), new SkillChallengeClue("Cremate a set of fiyr remains.", any("Magic or Redwood Pyre Logs", item(ItemID.MAGIC_PYRE_LOGS), item(ItemID.REDWOOD_PYRE_LOGS)), item(ItemID.TINDERBOX), item(ItemID.FIYR_REMAINS)), new SkillChallengeClue("Dissect a sacred eel.", item(ItemID.KNIFE), any("Fishing rod", item(ItemID.FISHING_ROD), item(ItemID.PEARL_FISHING_ROD)), item(ItemID.FISHING_BAIT)), new SkillChallengeClue("Kill a lizardman shaman."), new SkillChallengeClue("Catch an Anglerfish.", "angle for an anglerfish whilst sporting the finest fishing gear.", true, any("Fishing rod", item(ItemID.FISHING_ROD), item(ItemID.PEARL_FISHING_ROD)), item(ItemID.SANDWORMS), all("Angler's outfit", any("", item(ItemID.ANGLER_HAT), item(ItemID.SPIRIT_ANGLER_HEADBAND)), any("", item(ItemID.ANGLER_TOP), item(ItemID.SPIRIT_ANGLER_TOP)), any("", item(ItemID.ANGLER_WADERS), item(ItemID.SPIRIT_ANGLER_WADERS)), any("", item(ItemID.ANGLER_BOOTS), item(ItemID.SPIRIT_ANGLER_BOOTS)))), new SkillChallengeClue("Chop a redwood log.", "chop a redwood log whilst sporting the finest lumberjack gear.", true, ANY_AXE, all("Lumberjack outfit", item(ItemID.LUMBERJACK_HAT), item(ItemID.LUMBERJACK_TOP), item(ItemID.LUMBERJACK_LEGS), item(ItemID.LUMBERJACK_BOOTS))), new SkillChallengeClue("Craft a light orb in the Dorgesh-Kaan bank.", item(ItemID.CAVE_GOBLIN_WIRE), item(ItemID.EMPTY_LIGHT_ORB)), new SkillChallengeClue("Kill a reanimated Abyssal Demon.", "kill a reanimated abyssal.", xOfItem(ItemID.SOUL_RUNE, 4), xOfItem(ItemID.BLOOD_RUNE, 2), any("Nature Rune x4", xOfItem(ItemID.NATURE_RUNE, 4), item(ItemID.BRYOPHYTAS_STAFF)), range("Ensouled abyssal head", ItemID.ENSOULED_ABYSSAL_HEAD, ItemID.ENSOULED_ABYSSAL_HEAD_13508)), new SkillChallengeClue("Kill a Fiyr shade inside Mort'tons shade catacombs.", any("Any Silver Shade Key", item(ItemID.SILVER_KEY_RED), item(ItemID.SILVER_KEY_BROWN), item(ItemID.SILVER_KEY_CRIMSON), item(ItemID.SILVER_KEY_BLACK), item(ItemID.SILVER_KEY_PURPLE))) ); private final ChallengeType type; private final String challenge; private final String rawChallenge; private final String returnText; private final ItemRequirement[] itemRequirements; private final SingleItemRequirement returnItem; private final boolean requireEquip; private final String[] objectNames; private final int[] objectRegions; @Setter private boolean challengeCompleted; // Charlie Tasks private SkillChallengeClue(String challenge, String rawChallenge, String returnText, SingleItemRequirement returnItem, ItemRequirement ... itemRequirements) { this.type = ChallengeType.CHARLIE; this.challenge = challenge; this.rawChallenge = rawChallenge; this.returnText = returnText; this.itemRequirements = itemRequirements; this.returnItem = returnItem; this.challengeCompleted = false; this.requireEquip = false; this.objectNames = new String[0]; this.objectRegions = null; } // Non-cryptic Sherlock Tasks private SkillChallengeClue(String challenge, ItemRequirement ... itemRequirements) { this(challenge, challenge.toLowerCase(), itemRequirements); } // Non-cryptic Sherlock Tasks private SkillChallengeClue(String challenge, String[] objectNames, int[] objectRegions, ItemRequirement ... itemRequirements) { this(challenge, challenge.toLowerCase(), false, objectNames, objectRegions, itemRequirements); } // Non-cryptic Sherlock Tasks private SkillChallengeClue(String challenge, boolean requireEquip, ItemRequirement ... itemRequirements) { this(challenge, challenge.toLowerCase(), requireEquip, new String[0], null, itemRequirements); } // Sherlock Tasks private SkillChallengeClue(String challenge, String rawChallenge, ItemRequirement ... itemRequirements) { this(challenge, rawChallenge, false, new String[0], null, itemRequirements); } // Sherlock Tasks private SkillChallengeClue(String challenge, String rawChallenge, boolean requireEquip, ItemRequirement ... itemRequirements) { this(challenge, rawChallenge, requireEquip, new String[0], null, itemRequirements); } // Sherlock Tasks private SkillChallengeClue(String challenge, String rawChallenge, boolean requireEquip, String[] objectNames, int[] objectRegions, ItemRequirement ... itemRequirements) { this.type = ChallengeType.SHERLOCK; this.challenge = challenge; this.rawChallenge = rawChallenge; this.itemRequirements = itemRequirements; this.challengeCompleted = false; this.requireEquip = requireEquip; this.objectNames = objectNames; this.objectRegions = objectRegions; this.returnText = "<str>" + rawChallenge + "</str>"; this.returnItem = null; } @Override public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin) { panelComponent.getChildren().add(TitleComponent.builder().text("Skill Challenge Clue").build()); if (!challengeCompleted) { panelComponent.getChildren().add(LineComponent.builder().left("Challenge:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(challenge) .leftColor(TITLED_CONTENT_COLOR) .build()); if (itemRequirements.length > 0) { panelComponent.getChildren().add(LineComponent.builder().left(requireEquip ? "Equipment:" : "Items Required:").build()); for (LineComponent line : getRequirements(plugin, requireEquip, itemRequirements)) { panelComponent.getChildren().add(line); } } } else { panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(type.getName()) .leftColor(TITLED_CONTENT_COLOR) .build()); panelComponent.getChildren().add(LineComponent.builder().left("Location:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(type.getLocation()) .leftColor(TITLED_CONTENT_COLOR) .build()); if (returnItem != null) { panelComponent.getChildren().add(LineComponent.builder().left("Item:").build()); for (LineComponent line : getRequirements(plugin, false, returnItem)) { panelComponent.getChildren().add(line); } } } } @Override public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin) { // Mark NPC if (plugin.getNpcsToMark() != null) { for (NPC npc : plugin.getNpcsToMark()) { OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET); } } // Mark objects if (!challengeCompleted && objectNames.length > 0 && plugin.getNamedObjectsToMark() != null) { final Point mousePosition = plugin.getClient().getMouseCanvasPosition(); for (final TileObject object : plugin.getNamedObjectsToMark()) { if (plugin.getClient().getPlane() != object.getPlane()) { continue; } OverlayUtil.renderHoverableArea(graphics, object.getClickbox(), mousePosition, CLICKBOX_FILL_COLOR, CLICKBOX_BORDER_COLOR, CLICKBOX_HOVER_BORDER_COLOR); OverlayUtil.renderImageLocation(plugin.getClient(), graphics, object.getLocalLocation(), plugin.getClueScrollImage(), IMAGE_Z_OFFSET); } } } private static List<LineComponent> getRequirements(ClueScrollPlugin plugin, boolean requireEquipped, ItemRequirement ... requirements) { List<LineComponent> components = new ArrayList<>(); Item[] equipment = plugin.getEquippedItems(); Item[] inventory = plugin.getInventoryItems(); // If equipment is null, the player is wearing nothing if (equipment == null) { equipment = new Item[0]; } // If inventory is null, the player has nothing in their inventory if (inventory == null) { inventory = new Item[0]; } Item[] combined = new Item[equipment.length + inventory.length]; System.arraycopy(equipment, 0, combined, 0, equipment.length); System.arraycopy(inventory, 0, combined, equipment.length, inventory.length); for (ItemRequirement requirement : requirements) { boolean equipmentFulfilled = requirement.fulfilledBy(equipment); boolean combinedFulfilled = requirement.fulfilledBy(combined); components.add(LineComponent.builder() .left(requirement.getCollectiveName(plugin.getClient())) .leftColor(TITLED_CONTENT_COLOR) .right(combinedFulfilled ? "\u2713" : "\u2717") .rightFont(FontManager.getDefaultFont()) .rightColor(equipmentFulfilled || (combinedFulfilled && !requireEquipped) ? Color.GREEN : (combinedFulfilled ? Color.ORANGE : Color.RED)) .build()); } return components; } public static SkillChallengeClue forText(String text, String rawText) { for (SkillChallengeClue clue : CLUES) { if (rawText.equalsIgnoreCase(clue.returnText)) { clue.setChallengeCompleted(true); return clue; } else if (text.equals(clue.rawChallenge)) { clue.setChallengeCompleted(false); return clue; } } return null; } @Override public String[] getNpcs() { return new String[] {type.getName()}; } }
package net.runelite.client.plugins.worldmap; import lombok.AllArgsConstructor; import lombok.Getter; import net.runelite.api.coords.WorldPoint; import javax.annotation.Nullable; @Getter @AllArgsConstructor enum TransportationPointLocation { //Ships ARDOUGNE_TO_BRIMHAVEN("Ship to Brimhaven", new WorldPoint(2675, 3275, 0), new WorldPoint(2772, 3234, 0)), ARDOUGNE_TO_FISHINGPLAT("Ship to Fishing Platform", new WorldPoint(2722, 3304, 0), new WorldPoint(2779, 3271, 0)), BRIMHAVEN_TO_ARDOUGNE("Ship to Ardougne", new WorldPoint(2772, 3234, 0), new WorldPoint(2675, 3275, 0)), CATHERBY_TO_KEEP_LE_FAYE("Ship to Keep Le Faye", new WorldPoint(2804, 3421, 0), new WorldPoint(2769, 3402, 0)), CORSAIR_TO_RIMMINGTON("Ship to Rimmington", new WorldPoint(2577, 2839, 0), new WorldPoint(2909, 3227, 0 )), DRAGONTOOTH_TO_PHASMATYS("Ship to Port Phasmatys", new WorldPoint(3791, 3561, 0), new WorldPoint(3703, 3487, 0)), DIGSITE_TO_FOSSIL("Ship to Fossil Island", new WorldPoint(3361, 3448, 0), new WorldPoint(3723, 3807, 0)), ENTRANA_TO_PORTSARIM("Ship to Port Sarim", new WorldPoint(2833, 3334, 0), new WorldPoint(3046, 3233, 0)), FISHINGPLAT_TO_ARDOUGNE("Ship to Ardougne", new WorldPoint(2779, 3271, 0), new WorldPoint(2722, 3304, 0)), HARMLESS_TO_PORT_PHASMATYS("Ship to Port Phasmatys", new WorldPoint(3682, 2951, 0), new WorldPoint(3709, 3497, 0)), ICEBERG_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2657, 3988, 0), new WorldPoint(2707, 3735, 0)), ISLAND_OF_STONE_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2470, 3994, 0), new WorldPoint(2621, 3692, 0)), ISLAND_TO_APE_ATOLL("Ship to Ape Atoll", new WorldPoint(2891, 2726, 0), new WorldPoint(2802, 2706, 0)), JATIZSO_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2420, 3780, 0), new WorldPoint(2639, 3710, 0)), KARAMJA_TO_PORT_SARIM("Ship to Port Sarim", new WorldPoint(2955, 3144, 0), new WorldPoint(3029, 3218, 0)), KARAMJA_TO_PORT_KHAZARD("Ship to Port Khazard", new WorldPoint(2763, 2957, 0), new WorldPoint(2653, 3166, 0)), LANDSEND_TO_PORTSARIM_PORTPISCARILIUS("Ship to Port Sarim/Port Piscarilius", new WorldPoint(1503, 3398, 0)), LUNAR_ISLE_TO_PIRATES_COVE("Ship to Pirates' Cove", new WorldPoint(2137, 3899, 0), new WorldPoint(2223, 3796, 0)), MISCELLANIA_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2579, 3846, 0), new WorldPoint(2627, 3692, 0)), NEITIZNOT_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2310, 3779, 0), new WorldPoint(2639, 3710, 0)), PESTCONTROL_TO_PORTSARIM("Ship to Port Sarim", new WorldPoint(2659, 2675, 0), new WorldPoint(3039, 3201, 0)), PIRATES_COVE_TO_LUNAR_ISLE("Ship to Lunar Isle", new WorldPoint(2223, 3796, 0), new WorldPoint(2137, 3899, 0)), PIRATES_COVE_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2212, 3794, 0), new WorldPoint(2620, 3695, 0)), PORT_PHASMATYS_TO_DRAGONTOOTH("Ship to Dragontooth Island", new WorldPoint(3703, 3487, 0), new WorldPoint(3791, 3561, 0)), PORT_PHASMATYS_TO_HARMLESS("Ship to Mos Le'Harmless", new WorldPoint(3709, 3497, 0), new WorldPoint(3682, 2951, 0)), PORT_PISCARILIUS_TO_PORTSARIM_LANDSEND("Ship to Port Sarim/Land's End", new WorldPoint(1823, 3692, 0)), PORTSARIM_TO_GREAT_KOUREND("Ship to Great Kourend", new WorldPoint(3054, 3244, 0), new WorldPoint(1823, 3692, 0)), PORTSARIM_TO_ENTRANA("Ship to Entrana", new WorldPoint(3046, 3233, 0), new WorldPoint(2833, 3334, 0)), PORTSARIM_TO_KARAMJA("Ship to Karamja", new WorldPoint(3029, 3218, 0), new WorldPoint(2955, 3144, 0)), PORTSARIM_TO_CRANDOR("Ship to Crandor", new WorldPoint(3045, 3205, 0), new WorldPoint(2839, 3261, 0)), PORTSARIM_TO_PEST_CONTROL("Ship to Pest Control", new WorldPoint(3039, 3201, 0), new WorldPoint(2659, 2675, 0)), RELLEKKA_TO_JATIZSO_NEITIZNOT("Ship to Jatizso/Neitiznot", new WorldPoint(2639, 3710, 0)), RELLEKKA_TO_MISCELLANIA("Ship to Miscellania", new WorldPoint(2627, 3692, 0), new WorldPoint(2579, 3846, 0)), RELLEKKA_TO_PIRATES_COVE("Ship to Pirates' Cove", new WorldPoint(2620, 3695, 0), new WorldPoint(2212, 3794, 0)), RELLEKKA_TO_WATERBIRTH("Ship to Waterbirth", new WorldPoint(2618, 3685, 0), new WorldPoint(2549, 3758, 0)), RELLEKKA_TO_WEISS_ICEBERG("Ship to Weiss/Iceberg", new WorldPoint(2707, 3735, 0)), RELLEKKA_TO_UNGAEL("Ship to Ungael", new WorldPoint(2638, 3698, 0), new WorldPoint(2276, 4034, 0)), RIMMINGTON_TO_CORSAIR_COVE("Ship to Corsair Cove", new WorldPoint(2909, 3227, 0 ), new WorldPoint(2577, 2839, 0)), WATERBIRTH_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2549, 3758, 0), new WorldPoint(2618, 3685, 0)), WEISS_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2847, 3967, 0), new WorldPoint(2707, 3735, 0)), UNGAEL_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2276, 4034, 0), new WorldPoint(2638, 3698, 0)), //Row Boats ROW_BOAT_BATTLEFRONT("Rowboat to Molch/Molch Island/Shayzien", new WorldPoint(1383, 3663, 0)), ROW_BOAT_BRAIN_DEATH("Rowboat to Port Phasmatys", new WorldPoint(2161, 5117, 0), new WorldPoint(3680, 3538, 0)), ROW_BOAT_BURGH_DE_ROTT("Rowboat to Meiyerditch", new WorldPoint(3522, 3168, 0), new WorldPoint(3589, 3172, 0)), ROW_BOAT_CRABCLAW("Rowboat to Hosidius", new WorldPoint(1780, 3417, 0), new WorldPoint(1779, 3457, 0)), ROW_BOAT_DIVING_ISLAND("Rowboat to Barge/Camp/North of Island", new WorldPoint(3764, 3901, 0)), ROW_BOAT_FISHING_GUILD("Rowboat to Hemenster", new WorldPoint(2598, 3426, 0), new WorldPoint(2613, 3439, 0)), ROW_BOAT_GNOME_STRONGHOLD("Rowboat to Fishing Colony", new WorldPoint(2368, 3487, 0), new WorldPoint(2356, 3641, 0)), ROW_BOAT_FISHING_COLONY("Rowboat to Gnome Stronghold", new WorldPoint(2356, 3641, 0), new WorldPoint(2368, 3487, 0)), ROW_BOAT_HEMENSTER("Rowboat to Fishing Guild", new WorldPoint(2613, 3439, 0), new WorldPoint(2598, 3426, 0)), ROW_BOAT_HOSIDIUS("Rowboat to Crabclaw Isle", new WorldPoint(1779, 3457, 0), new WorldPoint(1780, 3417, 0)), ROW_BOAT_LITHKREN("Rowboat to Mushroom Forest", new WorldPoint(3582, 3973, 0), new WorldPoint(3659, 3849, 0)), ROW_BOAT_LUMBRIDGE("Rowboat to Misthalin Mystery", new WorldPoint(3238, 3141, 0)), ROW_BOAT_MOLCH("Rowboat to Molch Island/Shayzien/Battlefront", new WorldPoint(1343, 3646, 0)), ROW_BOAT_MOLCH_ISLAND("Rowboat to Molch/Shayzien/Battlefront", new WorldPoint(1368, 3641, 0)), ROW_BOAT_MORT("Rowboat to Mort Myre", new WorldPoint(3518, 3284, 0), new WorldPoint(3498, 3380, 0)), ROW_BOAT_MORT_SWAMP("Rowboat to Mort'ton", new WorldPoint(3498, 3380, 0), new WorldPoint(3518, 3284, 0)), ROW_BOAT_MUSEUM_CAMP("Rowboat to Barge/Digsite/North of Island", new WorldPoint(3723, 3807, 0)), ROW_BOAT_MUSHROOM_FOREST_WEST("Rowboat to Lithkren", new WorldPoint(3659, 3849, 0), new WorldPoint(3582, 3973, 0)), ROW_BOAT_MUSHROOM_FOREST_NE("Rowboat to Barge/Camp/Sea", new WorldPoint(3733, 3894, 0)), ROW_BOAT_PORT_PHASMATYS_NORTH("Rowboat to Slepe", new WorldPoint(3670, 3545, 0), new WorldPoint(3661, 3279, 0)), ROW_BOAT_PORT_PHASMATYS_EAST("Rowboat to Braindeath Island", new WorldPoint(3680, 3538, 0), new WorldPoint(2161, 5117, 0)), ROW_BOAT_SHAYZIEN("Rowboat to Molch/Molch Island/Battlefront", new WorldPoint(1405, 3612, 0)), ROW_BOAT_SLEPE("Rowboat to Port Phasmatys", new WorldPoint(3661, 3279, 0), new WorldPoint(3670, 3545, 0)), OGRE_BOAT_FELDIP("Ogre Boat to Karamja", new WorldPoint(2653, 2964, 0), new WorldPoint(2757, 3085, 0)), OGRE_BOAT_KARAMJA("Ogre Boat to Feldip", new WorldPoint(2757, 3085, 0), new WorldPoint(2653, 2964, 0)), //Charter ships CHARTER_BRIMHAVEN("Charter Ship", new WorldPoint(2760, 3238, 0)), CHARTER_CATHERBY("Charter Ship", new WorldPoint(2791, 3415, 0)), CHARTER_CORSAIR_("Charter Ship", new WorldPoint(2589, 2851, 0)), CHARTER_KARAMJA_NORTH("Charter Ship", new WorldPoint(2954, 3159, 0)), CHARTER_KARAMJA_EAST("Charter Ship", new WorldPoint(2999, 3032, 0)), CHARTER_KHAZARD("Charter Ship", new WorldPoint(2673, 3143, 0)), CHARTER_MOSLE_HARMLESS("Charter Ship", new WorldPoint(3669, 2931, 0)), CHARTER_PORT_PHASMATYS("Charter Ship", new WorldPoint(3702, 3503, 0)), CHARTER_PORTSARIM("Charter Ship", new WorldPoint(3037, 3191, 0)), CHARTER_TYRAS("Charter Ship", new WorldPoint(2141, 3123, 0)), CHARTER_PRIFDDINAS("Charter Ship", new WorldPoint(2156, 3331, 0)), CHARTER_PRIFDDINAS_INSTANCE("Charter Ship", new WorldPoint(3180, 6083, 0)), //Minecarts/Carts MINE_CART_ARCEUUS("Minecart", new WorldPoint(1673, 3832, 0)), MINE_CART_GRANDEXCHANGE("Minecart to Keldagrim", new WorldPoint(3139, 3504, 0)), MINE_CART_HOSIDIUS("Minecart", new WorldPoint(1656, 3542, 0)), MINE_CART_KELDAGRIM("Minecart", new WorldPoint(2908, 10170, 0)), MINE_CART_LOVAKENGJ("Minecart", new WorldPoint(1524, 3721, 0)), MINE_CART_PORT_PISCARILIUS("Minecart", new WorldPoint(1760, 3708, 0)), MINE_CART_QUIDAMORTEM("Minecart", new WorldPoint(1253, 3550, 0)), MINE_CART_SHAYZIEN("Minecart", new WorldPoint(1586, 3622, 0)), MINE_CART_TAVERLEY_UNDERGROUND("Minecart", new WorldPoint(2874, 9870, 0)), CART_TO_BRIMHAVEN("Cart to Brimhaven", new WorldPoint(2833, 2958, 0), new WorldPoint(2780, 3214, 0)), CART_TO_SHILO("Cart to Shilo", new WorldPoint(2780, 3214, 0), new WorldPoint(2833, 2958, 0)), //Canoes CANOE_BARBVILLAGE("Canoe", new WorldPoint(3111, 3409, 0)), CANOE_CHAMPIONSGUILD("Canoe", new WorldPoint(3202, 3344, 0)), CANOE_EDGEVILLE("Canoe", new WorldPoint(3130, 3509, 0)), CANOE_LUMBRIDGE("Canoe", new WorldPoint(3241, 3238, 0)), //Gnome Gliders GNOME_GLIDER_KHARID("Gnome Glider", new WorldPoint(3278, 3213, 0)), GNOME_GLIDER_APE_ATOLL("Gnome Glider", new WorldPoint(2712, 2804, 0)), GNOME_GLIDER_KARAMJA("Gnome Glider", new WorldPoint(2971, 2974, 0)), GNOME_GLIDER_FELDIP("Gnome Glider", new WorldPoint(2540, 2969, 0)), GNOME_GLIDER_GNOMESTRONGHOLD("Gnome Glider", new WorldPoint(2460, 3502, 0)), GNOME_GLIDER_WHITEWOLF("Gnome Glider", new WorldPoint(2845, 3501, 0)), //Balloons BALLOON_VARROCK("Hot Air Balloon", new WorldPoint(3298, 3480, 0)), BALLOON_YANILLE("Hot Air Balloon", new WorldPoint(2458, 3108, 0)), BALLOON_GNOMESTRONGHOLD("Hot Air Balloon", new WorldPoint(2478, 3459, 0)), BALLOON_TAVERLEY("Hot Air Balloon", new WorldPoint(2936, 3422, 0)), BALLOON_FALADOR("Hot Air Balloon", new WorldPoint(2921, 3301, 0)), //Spirit Tree SPIRITTREE_ARDOUGNE("Spirit Tree", new WorldPoint(2554, 3259, 0)), SPIRITTREE_CORSAIR("Spirit Tree", new WorldPoint(2485, 2850, 0)), SPIRITTREE_GNOMESTRONGHOLD("Spirit Tree", new WorldPoint(2459, 3446, 0)), SPIRITTREE_GNOMEVILLAGE("Spirit Tree", new WorldPoint(2538, 3166, 0)), SPIRITTREE_GRANDEXCHANGE("Spirit Tree", new WorldPoint(3184, 3510, 0)), SPIRITTREE_PRIFDDINAS("Spirit Tree", new WorldPoint(3274, 6124, 0)), //Carpets CARPET_KHARID("Carpet to Bedabin/Pollnivneach/Uzer", new WorldPoint(3311, 3107, 0)), CARPET_BEDABIN("Carpet to Shantay Pass", new WorldPoint(3183, 3042, 0), new WorldPoint(3311, 3107, 0)), CARPET_POLLNIVNEACH_NORTH("Carpet to Shantay Pass", new WorldPoint(3351, 3001, 0), new WorldPoint(3311, 3107, 0)), CARPET_POLLNIVNEACH_SOUTH("Carpet to Nardah/Sophanem/Menaphos", new WorldPoint(3345, 2943, 0)), CARPET_NARDAH("Carpet to Pollnivneach", new WorldPoint(3399, 2916, 0), new WorldPoint(3345, 2943, 0)), CARPET_SOPHANEM("Carpet to Pollnivneach", new WorldPoint(3288, 2814, 0), new WorldPoint(3345, 2943, 0)), CARPET_MENAPHOS("Carpet to Pollnivneach", new WorldPoint(3244, 2812, 0), new WorldPoint(3345, 2943, 0)), CARPET_UZER("Carpet to Shantay Pass", new WorldPoint(3468, 3111, 0), new WorldPoint(3311, 3107, 0)), //Teleports TELEPORT_ARCHIVE_FROM_ARCEUUS("Teleport to Library Archive", new WorldPoint(1623, 3808, 0)), TELEPORT_HARMLESS_FROM_HARMONY("Teleport to Mos Le'Harmless", new WorldPoint(3784, 2828, 0)), TELEPORT_RUNE_ARDOUGNE("Teleport to Rune Essence", new WorldPoint(2681, 3325, 0)), TELEPORT_RUNE_YANILLE("Teleport to Rune Essence", new WorldPoint(2592, 3089, 0)), TELEPORT_SORCERESS_GARDEN("Teleport to Sorceress's Garden", new WorldPoint(3320, 3141, 0)), TELEPORT_PRIFDDINAS_LIBRARY("Teleport to Prifddinas Library", new WorldPoint(3254, 6082, 2)), //Other ALTER_KOUREND_UNDERGROUND("Altar to Skotizo", new WorldPoint(1662, 10047, 0)), FAIRY_RING_ZANARIS_TO_KHARID("Fairy Ring to Al Kharid", new WorldPoint(2483, 4471, 0)), FAIRY_RING_ZANARIS_TO_SHACK("Fairy Ring to Shack", new WorldPoint(2451, 4471, 0)), MOUNTAIN_GUIDE_QUIDAMORTEM("Mountain Guide", new WorldPoint(1275, 3559, 0)), MOUNTAIN_GUIDE_WALL("Mountain Guide", new WorldPoint(1400, 3538, 0)), MUSHTREE_MUSHROOM_FOREST("Mushtree", new WorldPoint(3674, 3871, 0)), MUSHTREE_TAR_SWAMP("Mushtree", new WorldPoint(3676, 3755, 0)), MUSHTREE_VERDANT_VALLEY("Mushtree", new WorldPoint(3757, 3756, 0)), MYTHS_GUILD_PORTAL("Portal to Guilds", new WorldPoint(2456, 2856, 0)), TRAIN_KELDAGRIM("Railway Station", new WorldPoint(2941, 10179, 0)), WILDERNESS_LEVER_ARDOUGNE("Wilderness Lever", new WorldPoint(2559, 3309, 0)), WILDERNESS_LEVER_EDGEVILLE("Wilderness Lever", new WorldPoint(3088, 3474, 0)), WILDERNESS_LEVER_WILDERNESS("Wilderness Lever", new WorldPoint(3154, 3924, 0)); private final String tooltip; private final WorldPoint location; @Nullable private final WorldPoint target; TransportationPointLocation(String tooltip, WorldPoint worldPoint) { this(tooltip, worldPoint, null); } }
package org.openas2.cert; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openas2.OpenAS2Exception; import org.openas2.Session; import org.openas2.WrappedException; import org.openas2.message.Message; import org.openas2.message.MessageMDN; import org.openas2.params.InvalidParameterException; import org.openas2.partner.Partnership; import org.openas2.partner.SecurePartnership; import org.openas2.util.AS2Util; import org.openas2.util.FileMonitor; import org.openas2.util.FileMonitorListener; public class PKCS12CertificateFactory extends BaseCertificateFactory implements AliasedCertificateFactory, KeyStoreCertificateFactory, StorableCertificateFactory, FileMonitorListener { public static final String PARAM_FILENAME = "filename"; public static final String PARAM_PASSWORD = "password"; public static final String PARAM_INTERVAL = "interval"; private FileMonitor fileMonitor; private KeyStore keyStore; private Log logger = LogFactory.getLog(PKCS12CertificateFactory.class.getSimpleName()); public String getAlias(Partnership partnership, String partnershipType) throws OpenAS2Exception { String alias = null; if (partnershipType == Partnership.PTYPE_RECEIVER) { alias = partnership.getReceiverID(SecurePartnership.PID_X509_ALIAS); } else if (partnershipType == Partnership.PTYPE_SENDER) { alias = partnership.getSenderID(SecurePartnership.PID_X509_ALIAS); } if (alias == null) { throw new CertificateNotFoundException(partnershipType, null); } return alias; } public X509Certificate getCertificate(String alias) throws OpenAS2Exception { try { KeyStore ks = getKeyStore(); X509Certificate cert = (X509Certificate) ks.getCertificate(alias); if (cert == null) { throw new CertificateNotFoundException(null, alias); } return cert; } catch (KeyStoreException kse) { throw new WrappedException(kse); } } public X509Certificate getCertificate(Message msg, String partnershipType) throws OpenAS2Exception { try { return getCertificate(getAlias(msg.getPartnership(), partnershipType)); } catch (CertificateNotFoundException cnfe) { cnfe.setPartnershipType(partnershipType); throw cnfe; } } public X509Certificate getCertificate(MessageMDN mdn, String partnershipType) throws OpenAS2Exception { try { return getCertificate(getAlias(mdn.getPartnership(), partnershipType)); } catch (CertificateNotFoundException cnfe) { cnfe.setPartnershipType(partnershipType); throw cnfe; } } public Map<String,X509Certificate> getCertificates() throws OpenAS2Exception { KeyStore ks = getKeyStore(); try { Map<String,X509Certificate> certs = new HashMap<String,X509Certificate>(); String certAlias; Enumeration<String> e = ks.aliases(); while (e.hasMoreElements()) { certAlias = (String) e.nextElement(); certs.put(certAlias, (X509Certificate) ks.getCertificate(certAlias)); } return certs; } catch (GeneralSecurityException gse) { throw new WrappedException(gse); } } public void setFileMonitor(FileMonitor fileMonitor) { this.fileMonitor = fileMonitor; } public FileMonitor getFileMonitor() throws InvalidParameterException { boolean createMonitor = ((fileMonitor == null) && (getParameter(PARAM_INTERVAL, false) != null)); if (!createMonitor && fileMonitor != null) { String filename = fileMonitor.getFilename(); createMonitor = ((filename != null) && !filename.equals(getFilename())); } if (createMonitor) { if (fileMonitor != null) { fileMonitor.stop(); } int interval = getParameterInt(PARAM_INTERVAL, true); File file = new File(getFilename()); fileMonitor = new FileMonitor(file, interval); fileMonitor.addListener(this); } return fileMonitor; } public void setFilename(String filename) { getParameters().put(PARAM_FILENAME, filename); } public String getFilename() throws InvalidParameterException { return getParameter(PARAM_FILENAME, true); } public void setKeyStore(KeyStore keyStore) { this.keyStore = keyStore; } public KeyStore getKeyStore() { return keyStore; } public void setPassword(char[] password) { getParameters().put(PARAM_PASSWORD, new String(password)); } public char[] getPassword() throws InvalidParameterException { return getParameter(PARAM_PASSWORD, true).toCharArray(); } public PrivateKey getPrivateKey(X509Certificate cert) throws OpenAS2Exception { KeyStore ks = getKeyStore(); String alias = null; try { alias = ks.getCertificateAlias(cert); if (alias == null) { throw new KeyNotFoundException(cert, null); } PrivateKey key = (PrivateKey) ks.getKey(alias, getPassword()); if (key == null) { throw new KeyNotFoundException(cert, null); } return key; } catch (GeneralSecurityException e) { throw new KeyNotFoundException(cert, alias, e); } } public PrivateKey getPrivateKey(Message msg, X509Certificate cert) throws OpenAS2Exception { return getPrivateKey(cert); } public PrivateKey getPrivateKey(MessageMDN mdn, X509Certificate cert) throws OpenAS2Exception { return getPrivateKey(cert); } public void addCertificate(String alias, X509Certificate cert, boolean overwrite) throws OpenAS2Exception { KeyStore ks = getKeyStore(); try { if (ks.containsAlias(alias) && !overwrite) { throw new CertificateExistsException(alias); } ks.setCertificateEntry(alias, cert); save(getFilename(), getPassword()); } catch (GeneralSecurityException gse) { throw new WrappedException(gse); } } public void addPrivateKey(String alias, Key key, String password) throws OpenAS2Exception { KeyStore ks = getKeyStore(); try { if (!ks.containsAlias(alias)) { throw new CertificateNotFoundException(null, alias); } Certificate[] certChain = ks.getCertificateChain(alias); ks.setKeyEntry(alias, key, password.toCharArray(), certChain); save(getFilename(), getPassword()); } catch (GeneralSecurityException gse) { throw new WrappedException(gse); } } public void clearCertificates() throws OpenAS2Exception { KeyStore ks = getKeyStore(); try { Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { ks.deleteEntry((String) aliases.nextElement()); } save(getFilename(), getPassword()); } catch (GeneralSecurityException gse) { throw new WrappedException(gse); } } public void handle(FileMonitor monitor, File file, int eventID) { switch (eventID) { case FileMonitorListener.EVENT_MODIFIED: try { load(); logger.info("- Certificates Reloaded -"); } catch (OpenAS2Exception oae) { oae.terminate(); } break; } } public void init(Session session, Map<String, String> options) throws OpenAS2Exception { super.init(session, options); // Override the password if it was passed as a system property String pwd = System.getProperty("org.openas2.cert.Password"); if (pwd != null) { setPassword(pwd.toCharArray()); } try { this.keyStore = AS2Util.getCryptoHelper().getKeyStore(); } catch (Exception e) { throw new WrappedException(e); } load(getFilename(), getPassword()); } public void load(String filename, char[] password) throws OpenAS2Exception { try { FileInputStream fIn = new FileInputStream(filename); load(fIn, password); fIn.close(); } catch (IOException ioe) { throw new WrappedException(ioe); } } public void load(InputStream in, char[] password) throws OpenAS2Exception { try { KeyStore ks = getKeyStore(); synchronized (ks) { ks.load(in, password); } getFileMonitor(); } catch (IOException ioe) { throw new WrappedException(ioe); } catch (GeneralSecurityException gse) { throw new WrappedException(gse); } } public void load() throws OpenAS2Exception { load(getFilename(), getPassword()); } public void removeCertificate(X509Certificate cert) throws OpenAS2Exception { KeyStore ks = getKeyStore(); try { String alias = ks.getCertificateAlias(cert); if (alias == null) { throw new CertificateNotFoundException(cert); } removeCertificate(alias); } catch (GeneralSecurityException gse) { throw new WrappedException(gse); } } public void removeCertificate(String alias) throws OpenAS2Exception { KeyStore ks = getKeyStore(); try { if (ks.getCertificate(alias) == null) { throw new CertificateNotFoundException(null, alias); } ks.deleteEntry(alias); save(getFilename(), getPassword()); } catch (GeneralSecurityException gse) { throw new WrappedException(gse); } } public void save() throws OpenAS2Exception { save(getFilename(), getPassword()); } public void save(String filename, char[] password) throws OpenAS2Exception { try { FileOutputStream fOut = new FileOutputStream(filename, false); save(fOut, password); fOut.close(); } catch (IOException ioe) { throw new WrappedException(ioe); } } public void save(OutputStream out, char[] password) throws OpenAS2Exception { try { getKeyStore().store(out, password); } catch (IOException ioe) { throw new WrappedException(ioe); } catch (GeneralSecurityException gse) { throw new WrappedException(gse); } } }
package com.example; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.stubrunner.junit.StubRunnerRule; import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.util.StringUtils; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * @author Marcin Grzejszczak */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureJsonTesters public class BeerControllerRouterFunctionTest extends AbstractTest { @Autowired MockMvc mockMvc; @Autowired BeerController beerController; //remove::start[] @Rule public StubRunnerRule rule = new StubRunnerRule() .downloadStub("com.example","beer-api-producer-routerfunction-webtestclient", "0.0.1.BUILD-SNAPSHOT") .stubsMode(StubRunnerProperties.StubsMode.LOCAL); //remove::end[] @BeforeClass public static void beforeClass() { Assume.assumeTrue("Spring Cloud Contract must be in version at least 2.2.0", atLeast220()); Assume.assumeTrue("Env var OLD_PRODUCER_TRAIN must not be set", StringUtils.isEmpty(System.getenv("OLD_PRODUCER_TRAIN"))); } private static boolean atLeast220() { try { Class.forName("org.springframework.cloud.contract.spec.internal.DslPropertyConverter"); } catch (Exception ex) { return false; } return true; } @Before public void setupPort() { //remove::start[] this.beerController.port = this.rule.findStubUrl("beer-api-producer-routerfunction-webtestclient").getPort(); //remove::end[] } //remove::end[] @Test public void should_give_me_a_beer_when_im_old_enough() throws Exception { //remove::start[] this.mockMvc.perform(MockMvcRequestBuilders.post("/beer") .contentType(MediaType.APPLICATION_JSON) .content(this.json.write(new Person("marcin", 22)).getJson())) .andExpect(status().isOk()) .andExpect(content().string("THERE YOU GO")); //remove::end[] } @Test public void should_reject_a_beer_when_im_too_young() throws Exception { //remove::start[] this.mockMvc.perform(MockMvcRequestBuilders.post("/beer") .contentType(MediaType.APPLICATION_JSON) .content(this.json.write(new Person("marcin", 17)).getJson())) .andExpect(status().isOk()) .andExpect(content().string("GET LOST")); //remove::end[] } }
package commons; public class ErrorCodes { public static final int INVALID_USERNAME_CODE=800; public static final int INVALID_POSITION_CODE=801; public static final String INVALID_USERNAME_DESCRIPTION="Invalid username"; }
package com.streamsets.pipeline.runner; import com.google.common.base.Preconditions; import com.streamsets.pipeline.api.Batch; import com.streamsets.pipeline.api.BatchMaker; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.OnRecordError; import com.streamsets.pipeline.api.Processor; import com.streamsets.pipeline.api.Source; import com.streamsets.pipeline.api.Stage; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.api.Target; import com.streamsets.pipeline.config.ConfigConfiguration; import com.streamsets.pipeline.config.ConfigDefinition; import com.streamsets.pipeline.config.ModelType; import com.streamsets.pipeline.config.PipelineConfiguration; import com.streamsets.pipeline.api.impl.Utils; import com.streamsets.pipeline.stagelibrary.StageLibraryTask; import com.streamsets.pipeline.util.ContainerError; import com.streamsets.pipeline.validation.PipelineConfigurationValidator; import com.streamsets.pipeline.config.StageConfiguration; import com.streamsets.pipeline.config.StageDefinition; import com.streamsets.pipeline.validation.StageIssue; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class StageRuntime { private final StageDefinition def; private final StageConfiguration conf; private final Stage stage; private final Stage.Info info; private final List<String> requiredFields; private final OnRecordError onRecordError; private StageContext context; private StageRuntime(final StageDefinition def, final StageConfiguration conf, List<String> requiredFields, OnRecordError onRecordError, Stage stage) { this.def = def; this.conf = conf; this.requiredFields = requiredFields; this.onRecordError = onRecordError; this.stage = stage; info = new Stage.Info() { @Override public String getName() { return def.getName(); } @Override public String getVersion() { return def.getVersion(); } @Override public String getInstanceName() { return conf.getInstanceName(); } @Override public String toString() { return Utils.format("Info[instance='{}' name='{}' version='{}']", getInstanceName(), getName(), getVersion()); } }; } public StageDefinition getDefinition() { return def; } public StageConfiguration getConfiguration() { return conf; } public List<String> getRequiredFields() { return requiredFields; } public OnRecordError getOnRecordError() { return onRecordError; } public Stage getStage() { return stage; } public void setContext(StageContext context) { this.context = context; } public void setErrorSink(ErrorSink errorSink) { context.setErrorSink(errorSink); } @SuppressWarnings("unchecked") public <T extends Stage.Context> T getContext() { return (T) context; } @SuppressWarnings("unchecked") public List<StageIssue> validateConfigs() throws StageException { Preconditions.checkState(context != null, "context has not been set"); ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getDefinition().getStageClassLoader()); List<StageIssue> issues = stage.validateConfigs(info, context); if (issues == null) { issues = Collections.emptyList(); } return issues; } finally { Thread.currentThread().setContextClassLoader(cl); } } @SuppressWarnings("unchecked") public void init() throws StageException { Preconditions.checkState(context != null, "context has not been set"); ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getDefinition().getStageClassLoader()); stage.init(info, context); } finally { Thread.currentThread().setContextClassLoader(cl); } } public String execute(String previousOffset, int batchSize, Batch batch, BatchMaker batchMaker, ErrorSink errorSink) throws StageException { String newOffset = null; ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { setErrorSink(errorSink); Thread.currentThread().setContextClassLoader(getDefinition().getStageClassLoader()); switch (getDefinition().getType()) { case SOURCE: { newOffset = ((Source) getStage()).produce(previousOffset, batchSize, batchMaker); break; } case PROCESSOR: { ((Processor) getStage()).process(batch, batchMaker); break; } case TARGET: { ((Target) getStage()).write(batch); break; } } } finally { setErrorSink(null); Thread.currentThread().setContextClassLoader(cl); } return newOffset; } public void destroy() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getDefinition().getStageClassLoader()); stage.destroy(); } finally { Thread.currentThread().setContextClassLoader(cl); } } public Stage.Info getInfo() { return info; } public static class Builder { private final StageLibraryTask stageLib; private final String name; private final PipelineConfiguration pipelineConf; private List<String> requiredFields; private OnRecordError onRecordError; public Builder(StageLibraryTask stageLib, String name, PipelineConfiguration pipelineConf) { this.stageLib = stageLib; this.name = name; this.pipelineConf = pipelineConf; onRecordError = OnRecordError.STOP_PIPELINE; } public StageRuntime[] build() throws PipelineRuntimeException { PipelineConfigurationValidator validator = new PipelineConfigurationValidator(stageLib, name, pipelineConf); if (!validator.validate()) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0150, validator.getIssues()); } try { StageRuntime[] runtimes = new StageRuntime[pipelineConf.getStages().size()]; for (int i = 0; i < pipelineConf.getStages().size(); i++) { runtimes[i] = buildStage(pipelineConf.getStages().get(i)); } return runtimes; } catch (PipelineRuntimeException ex) { throw ex; } catch (Exception ex) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0151, ex.getMessage(), ex); } } public StageRuntime buildErrorStage() throws PipelineRuntimeException { return buildStage(pipelineConf.getErrorStage()); } private StageRuntime buildStage(StageConfiguration conf) throws PipelineRuntimeException { try { StageDefinition def = stageLib.getStage(conf.getLibrary(), conf.getStageName(), conf.getStageVersion()); Class klass = def.getStageClassLoader().loadClass(def.getClassName()); Stage stage = (Stage) klass.newInstance(); configureStage(def, conf, klass, stage); return new StageRuntime(def, conf, requiredFields, onRecordError, stage); } catch (Exception ex) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0151, ex.getMessage(), ex); } } @SuppressWarnings("unchecked") private void configureStage(StageDefinition stageDef, StageConfiguration stageConf, Class klass, Stage stage) throws PipelineRuntimeException { for (ConfigDefinition confDef : stageDef.getConfigDefinitions()) { ConfigConfiguration confConf = stageConf.getConfig(confDef.getName()); if (confConf == null) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0153, stageDef.getClassName(), stageConf.getInstanceName(), confDef.getName()); } Object value = confConf.getValue(); String instanceVar = confDef.getFieldName(); switch (confDef.getName()) { case ConfigDefinition.REQUIRED_FIELDS: requiredFields = (List<String>) value; break; case ConfigDefinition.ON_RECORD_ERROR: onRecordError = OnRecordError.valueOf(value.toString()); break; default: try { Field var = klass.getField(instanceVar); //check if the field is an enum and convert the value to enum if so if (confDef.getModel() != null && confDef.getModel().getModelType() == ModelType.COMPLEX_FIELD) { setComplexField(var, stageDef, stageConf, stage, confDef, value); } else { setField(var, stageDef, stageConf, stage, confDef, value); } } catch (PipelineRuntimeException ex) { throw ex; } catch (Exception ex) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0152, stageDef.getClassName(), stageConf.getInstanceName(), instanceVar, value, ex.getMessage(), ex); } } } } private void setComplexField(Field var, StageDefinition stageDef, StageConfiguration stageConf, Stage stage, ConfigDefinition confDef, Object value) throws IllegalAccessException, InstantiationException, NoSuchFieldException, PipelineRuntimeException { Type genericType = var.getGenericType(); Class klass; if(genericType instanceof ParameterizedType) { Type[] typeArguments = ((ParameterizedType) genericType).getActualTypeArguments(); klass = (Class) typeArguments[0]; } else { klass = (Class) genericType; } //value is a list of map where each map has keys which represent the field names in custom config object and the // value is the value of the field if(value instanceof List) { List<Object> customConfigObjects = new ArrayList<>(); for(Object object : (List) value) { if(object instanceof Map) { Map<String, ?> map = (Map) object; Object customConfigObj = klass.newInstance(); customConfigObjects.add(customConfigObj); for (ConfigDefinition configDefinition : confDef.getModel().getConfigDefinitions()) { Field f = klass.getField(configDefinition.getFieldName()); setField(f, stageDef, stageConf, customConfigObj, configDefinition, map.get(configDefinition.getFieldName())); } } } var.set(stage, customConfigObjects); } } private void setField(Field var, StageDefinition stageDef, StageConfiguration stageConf, Object stage, ConfigDefinition confDef, Object value) throws IllegalAccessException, PipelineRuntimeException { if(var.getType().isEnum()) { var.set(stage, Enum.valueOf((Class<Enum>) var.getType(), (String) value)); } else { if (value != null) { if (value instanceof List) { if (confDef.getType() == ConfigDef.Type.LIST) { validateList((List) value, stageDef.getClassName(), stageConf.getInstanceName(), confDef.getName()); } else if (confDef.getType() == ConfigDef.Type.MAP) { // special type of Map config where is a List of Maps with 'key' & 'value' entries. validateMapAsList((List) value, stageDef.getClassName(), stageConf.getInstanceName(), confDef.getName()); value = convertToMap((List<Map>) value); } } else if (value instanceof Map) { validateMap((Map) value, stageDef.getClassName(), stageConf.getInstanceName(), confDef.getName()); } else if (confDef.getType() == ConfigDef.Type.CHARACTER) { value = ((String)value).charAt(0); } } if (value != null) { var.set(stage, value); } else { // if the value is NULL we set the default value var.set(stage, confDef.getDefaultValue()); } } } } private static void validateMapAsList(List list, String stageName, String instanceName, String configName) throws PipelineRuntimeException { for (Map map : (List<Map>) list) { String key = (String) map.get("key"); String value = (String) map.get("value"); if (!(key instanceof String) || !(value instanceof String)) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0164, stageName, instanceName, configName); } } } private static Map convertToMap(List<Map> list) { Map<String, String> map = new HashMap<>(); for (Map element : list) { String key = (String) element.get("key"); String value = (String) element.get("value"); map.put(key, value); } return map; } private static void validateList(List list, String stageName, String instanceName, String configName) throws PipelineRuntimeException { for (Object e : list) { if (e != null && !(e instanceof String)) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0161, stageName, instanceName, configName); } } } private static void validateMap(Map map, String stageName, String instanceName, String configName) throws PipelineRuntimeException { for (Map.Entry e : ((Map<?, ?>) map).entrySet()) { if (!(e.getKey() instanceof String)) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0162, stageName, instanceName, configName); } if (e.getValue() != null && !(e.getValue() instanceof String)) { throw new PipelineRuntimeException(ContainerError.CONTAINER_0163, stageName, instanceName, configName); } } } @Override public String toString() { return Utils.format("StageRuntime[{}]", getInfo()); } }
package com.dtolabs.rundeck.core.plugins; import java.util.List; import java.util.Map; /** * Matches plugin file or providers against a block list */ public interface PluginBlocklist { /** * @return true if file name is present */ public Boolean isPluginFilePresent(String fileName); /** * @return true if provider name and service are present in the list */ public Boolean isPluginProviderPresent(String service, String providerName); public Boolean isBlocklistSet(); }
package org.hisp.dhis.android.core.utils.services; import com.google.auto.value.AutoValue; @AutoValue public abstract class Paging { public abstract int page(); public abstract int pageSize(); public abstract int previousItemsToSkipCount(); public abstract int posteriorItemsToSkipCount(); public abstract boolean isLastPage(); public static Paging create(int page, int pageSize, int previousItemsToSkipCount, int posteriorItemsToSkipCount, boolean isLastPage) { return new AutoValue_Paging(page, pageSize, previousItemsToSkipCount, posteriorItemsToSkipCount, isLastPage); } }
package org.mskcc.cbio.portal.scripts; import org.mskcc.cbio.portal.dao.*; import org.mskcc.cbio.portal.model.*; import org.mskcc.cbio.portal.util.*; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; /** * Code to Import Copy Number Alteration or MRNA Expression Data. * * @author Ethan Cerami */ public class ImportTabDelimData { private HashSet<Long> importedGeneSet = new HashSet<Long>(); private static Logger logger = Logger.getLogger(ImportTabDelimData.class); /** * Barry Target Line: A constant currently used to indicate the RAE method. */ public static final String BARRY_TARGET = "Barry"; /** * Consensus Target Line: A constant currently used to indicate consensus of multiple * CNA calling algorithms. */ public static final String CONSENSUS_TARGET = "consensus"; private ProgressMonitor pMonitor; private File mutationFile; private String targetLine; private int geneticProfileId; private GeneticProfile geneticProfile; private HashSet<String> microRnaIdSet; /** * Constructor. * * @param dataFile Data File containing CNA data. * @param targetLine The line we want to import. * If null, all lines are imported. * @param geneticProfileId GeneticProfile ID. * @param pMonitor Progress Monitor Object. */ public ImportTabDelimData(File dataFile, String targetLine, int geneticProfileId, ProgressMonitor pMonitor) { this.mutationFile = dataFile; this.targetLine = targetLine; this.geneticProfileId = geneticProfileId; this.pMonitor = pMonitor; } /** * Constructor. * * @param dataFile Data File containing CNA data. * @param geneticProfileId GeneticProfile ID. * @param pMonitor Progress Monitor Object. */ public ImportTabDelimData(File dataFile, int geneticProfileId, ProgressMonitor pMonitor) { this.mutationFile = dataFile; this.geneticProfileId = geneticProfileId; this.pMonitor = pMonitor; } /** * Import the CNA Data. * * @throws IOException IO Error. * @throws DaoException Database Error. */ public void importData() throws IOException, DaoException { DaoMicroRna daoMicroRna = new DaoMicroRna(); microRnaIdSet = daoMicroRna.getEntireSet(); geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); FileReader reader = new FileReader(mutationFile); BufferedReader buf = new BufferedReader(reader); String headerLine = buf.readLine(); String parts[] = headerLine.split("\t"); int sampleStartIndex = getStartIndex(parts); int hugoSymbolIndex = getHugoSymbolIndex(parts); int entrezGeneIdIndex = getEntrezGeneIdIndex(parts); String sampleIds[]; // Branch, depending on targetLine setting if (targetLine == null) { sampleIds = new String[parts.length - sampleStartIndex]; System.arraycopy(parts, sampleStartIndex, sampleIds, 0, parts.length - sampleStartIndex); } else { sampleIds = new String[parts.length - sampleStartIndex]; System.arraycopy(parts, sampleStartIndex, sampleIds, 0, parts.length - sampleStartIndex); } ImportDataUtil.addPatients(sampleIds, geneticProfileId); ImportDataUtil.addSamples(sampleIds, geneticProfileId); pMonitor.setCurrentMessage("Import tab delimited data for " + sampleIds.length + " samples."); // Add Samples to the Database ArrayList <Integer> orderedSampleList = new ArrayList<Integer>(); ArrayList <Integer> filteredSampleIndices = new ArrayList<Integer>(); for (int i = 0; i < sampleIds.length; i++) { Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(), StableIdUtil.getSampleId(sampleIds[i])); if (sample == null) { assert StableIdUtil.isNormal(sampleIds[i]); filteredSampleIndices.add(i); continue; } if (!DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId)) { DaoSampleProfile.addSampleProfile(sample.getInternalId(), geneticProfileId); } orderedSampleList.add(sample.getInternalId()); } DaoGeneticProfileSamples.addGeneticProfileSamples(geneticProfileId, orderedSampleList); String line = buf.readLine(); int numRecordsStored = 0; DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); DaoGeneticAlteration daoGeneticAlteration = DaoGeneticAlteration.getInstance(); boolean discritizedCnaProfile = geneticProfile!=null && geneticProfile.getGeneticAlterationType() == GeneticAlterationType.COPY_NUMBER_ALTERATION && geneticProfile.showProfileInAnalysisTab(); Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents = null; long cnaEventId = 0; if (discritizedCnaProfile) { existingCnaEvents = new HashMap<CnaEvent.Event, CnaEvent.Event>(); for (CnaEvent.Event event : DaoCnaEvent.getAllCnaEvents()) { existingCnaEvents.put(event, event); } cnaEventId = DaoCnaEvent.getLargestCnaEventId(); MySQLbulkLoader.bulkLoadOn(); } int lenParts = parts.length; while (line != null) { if (pMonitor != null) { pMonitor.incrementCurValue(); ConsoleUtil.showProgress(pMonitor); } // Ignore lines starting with if (!line.startsWith("#") && line.trim().length() > 0) { parts = line.split("\t",-1); if (parts.length>lenParts) { if (line.split("\t").length>lenParts) { System.err.println("The following line has more fields (" + parts.length + ") than the headers(" + lenParts + "): \n"+parts[0]); } } String values[] = (String[]) ArrayUtils.subarray(parts, sampleStartIndex, parts.length>lenParts?lenParts:parts.length); values = filterOutNormalValues(filteredSampleIndices, values); String hugo = parts[hugoSymbolIndex]; if (hugo!=null && hugo.isEmpty()) { hugo = null; } String entrez = null; if (entrezGeneIdIndex!=-1) { entrez = parts[entrezGeneIdIndex]; } if (entrez!=null && !entrez.matches("-?[0-9]+")) { entrez = null; } if (hugo != null || entrez != null) { if (hugo != null && (hugo.contains(" // Ignore gene IDs separated by ///. This indicates that // the line contains information regarding multiple genes, and // we cannot currently handle this. // the line contains information regarding an unknown gene, and // we cannot currently handle this. logger.debug("Ignoring gene ID: " + hugo); } else { List<CanonicalGene> genes = null; if (entrez!=null) { CanonicalGene gene = daoGene.getGene(Long.parseLong(entrez)); if (gene!=null) { genes = Arrays.asList(gene); } } if (genes==null && hugo != null) { // deal with multiple symbols separate by |, use the first one int ix = hugo.indexOf("|"); if (ix>0) { hugo = hugo.substring(0, ix); } genes = daoGene.guessGene(hugo); } if (genes == null) { genes = Collections.emptyList(); } // If no target line is specified or we match the target, process. if (targetLine == null || parts[0].equals(targetLine)) { if (genes.isEmpty()) { // if gene is null, we might be dealing with a micro RNA ID if (hugo != null && hugo.toLowerCase().contains("-mir-")) { // if (microRnaIdSet.contains(geneId)) { // storeMicroRnaAlterations(values, daoMicroRnaAlteration, geneId); // numRecordsStored++; // } else { pMonitor.logWarning("microRNA is not known to me: [" + hugo + "]. Ignoring it " + "and all tab-delimited data associated with it!"); } else { String gene = (hugo != null) ? hugo : entrez; pMonitor.logWarning("Gene not found: [" + gene + "]. Ignoring it " + "and all tab-delimited data associated with it!"); } } else if (genes.size()==1) { if (discritizedCnaProfile) { long entrezGeneId = genes.get(0).getEntrezGeneId(); int n = values.length; if (n==0) System.out.println(); int i = values[0].equals(""+entrezGeneId) ? 1:0; for (; i<n; i++) { // temporary solution -- change partial deletion back to full deletion. if (values[i].equals(GeneticAlterationType.PARTIAL_DELETION)) { values[i] = GeneticAlterationType.HOMOZYGOUS_DELETION; } if (values[i].equals(GeneticAlterationType.AMPLIFICATION) // || values[i].equals(GeneticAlterationType.GAIN) // || values[i].equals(GeneticAlterationType.ZERO) // || values[i].equals(GeneticAlterationType.HEMIZYGOUS_DELETION) || values[i].equals(GeneticAlterationType.HOMOZYGOUS_DELETION)) { CnaEvent cnaEvent = new CnaEvent(orderedSampleList.get(i), geneticProfileId, entrezGeneId, Short.parseShort(values[i])); if (existingCnaEvents.containsKey(cnaEvent.getEvent())) { cnaEvent.setEventId(existingCnaEvents.get(cnaEvent.getEvent()).getEventId()); DaoCnaEvent.addCaseCnaEvent(cnaEvent, false); } else { cnaEvent.setEventId(++cnaEventId); DaoCnaEvent.addCaseCnaEvent(cnaEvent, true); existingCnaEvents.put(cnaEvent.getEvent(), cnaEvent.getEvent()); } } } } storeGeneticAlterations(values, daoGeneticAlteration, genes.get(0)); numRecordsStored++; } else { for (CanonicalGene gene : genes) { if (gene.isMicroRNA()) { // for micro rna, duplicate the data storeGeneticAlterations(values, daoGeneticAlteration, gene); } } } } } } } line = buf.readLine(); } if (MySQLbulkLoader.isBulkLoad()) { MySQLbulkLoader.flushAll(); } if (numRecordsStored == 0) { throw new DaoException ("Something has gone wrong! I did not save any records" + " to the database!"); } } private void storeGeneticAlterations(String[] values, DaoGeneticAlteration daoGeneticAlteration, CanonicalGene gene) throws DaoException { // Check that we have not already imported information regarding this gene. // This is an important check, because a GISTIC or RAE file may contain // multiple rows for the same gene, and we only want to import the first row. if (!importedGeneSet.contains(gene.getEntrezGeneId())) { daoGeneticAlteration.addGeneticAlterations(geneticProfileId, gene.getEntrezGeneId(), values); importedGeneSet.add(gene.getEntrezGeneId()); } } private List<CanonicalGene> parseRPPAGenes(String antibodyWithGene) throws DaoException { DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); String[] parts = antibodyWithGene.split("\\|"); String[] symbols = parts[0].split(" "); String arrayId = parts[1]; List<CanonicalGene> genes = new ArrayList<CanonicalGene>(); for (String symbol : symbols) { CanonicalGene gene = daoGene.getNonAmbiguousGene(symbol); if (gene!=null) { genes.add(gene); } } Pattern p = Pattern.compile("(p[STY][0-9]+)"); Matcher m = p.matcher(arrayId); String type, residue; if (!m.find()) { type = "protein_level"; return genes; } else { type = "phosphorylation"; residue = m.group(1); return importPhosphoGene(genes, residue); } } private List<CanonicalGene> importPhosphoGene(List<CanonicalGene> genes, String residue) throws DaoException { DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); List<CanonicalGene> phosphoGenes = new ArrayList<CanonicalGene>(); for (CanonicalGene gene : genes) { Set<String> aliases = new HashSet<String>(); aliases.add("rppa-phospho"); aliases.add("phosphoprotein"); aliases.add("phospho"+gene.getStandardSymbol()); String phosphoSymbol = gene.getStandardSymbol()+"_"+residue; CanonicalGene phosphoGene = new CanonicalGene(phosphoSymbol, aliases); phosphoGene.setType(CanonicalGene.PHOSPHOPROTEIN_TYPE); daoGene.addGene(phosphoGene); phosphoGenes.add(phosphoGene); } return phosphoGenes; } private int getHugoSymbolIndex(String[] headers) { return targetLine==null ? 0 : 1; } private int getEntrezGeneIdIndex(String[] headers) { for (int i = 0; i<headers.length; i++) { if (headers[i].equalsIgnoreCase("Entrez_Gene_Id")) { return i; } } return -1; } private int getStartIndex(String[] headers) { int startIndex = targetLine==null ? 1 : 2; for (int i=startIndex; i<headers.length; i++) { String h = headers[i]; if (!h.equalsIgnoreCase("Gene Symbol") && !h.equalsIgnoreCase("Hugo_Symbol") && !h.equalsIgnoreCase("Entrez_Gene_Id") && !h.equalsIgnoreCase("Locus ID") && !h.equalsIgnoreCase("Cytoband") && !h.equalsIgnoreCase("Composite.Element.Ref")) { return i; } } return startIndex; } private String[] filterOutNormalValues(ArrayList <Integer> filteredSampleIndices, String[] values) { ArrayList<String> filteredValues = new ArrayList<String>(); for (int lc = 0; lc < values.length; lc++) { if (!filteredSampleIndices.contains(lc)) { filteredValues.add(values[lc]); } } return filteredValues.toArray(new String[filteredValues.size()]); } }
package org.bouncycastle.crypto.tls.test; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.security.SecureRandom; import junit.framework.TestCase; import org.bouncycastle.crypto.tls.TlsClientProtocol; import org.bouncycastle.crypto.tls.TlsServerProtocol; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.io.Streams; public class TlsProtocolTest extends TestCase { public void testClientServer() throws Exception { SecureRandom secureRandom = new SecureRandom(); PipedInputStream clientRead = new PipedInputStream(); PipedInputStream serverRead = new PipedInputStream(); PipedOutputStream clientWrite = new PipedOutputStream(serverRead); PipedOutputStream serverWrite = new PipedOutputStream(clientRead); TlsClientProtocol clientProtocol = new TlsClientProtocol(clientRead, clientWrite, secureRandom); TlsServerProtocol serverProtocol = new TlsServerProtocol(serverRead, serverWrite, secureRandom); ServerThread serverThread = new ServerThread(serverProtocol); serverThread.start(); MockTlsClient client = new MockTlsClient(null); clientProtocol.connect(client); // NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity int length = 1000; byte[] data = new byte[length]; secureRandom.nextBytes(data); OutputStream output = clientProtocol.getOutputStream(); output.write(data); byte[] echo = new byte[data.length]; int count = Streams.readFully(clientProtocol.getInputStream(), echo); assertEquals(count, data.length); assertTrue(Arrays.areEqual(data, echo)); output.close(); serverThread.join(); } static class ServerThread extends Thread { private final TlsServerProtocol serverProtocol; ServerThread(TlsServerProtocol serverProtocol) { this.serverProtocol = serverProtocol; } public void run() { try { MockTlsServer server = new MockTlsServer(); serverProtocol.accept(server); Streams.pipeAll(serverProtocol.getInputStream(), serverProtocol.getOutputStream()); serverProtocol.close(); } catch (Exception e) { // throw new RuntimeException(e); } } } }
package gov.nih.nci.cananolab.restful.view.edit; import gov.nih.nci.cananolab.dto.common.AccessibilityBean; import gov.nih.nci.cananolab.dto.common.ProtocolBean; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; public class SimpleSubmitProtocolBean { String type = ""; String name = ""; String abbreviation = ""; String version = ""; Long fileId; Long id = 0L; String fileTitle = ""; String fileName = ""; String fileDescription = ""; List<AccessibilityBean> groupAccesses = new ArrayList<AccessibilityBean>(); List<AccessibilityBean> userAccesses = new ArrayList<AccessibilityBean>(); String protectedData = ""; Boolean isPublic = false; Boolean isOwner = false; String ownerName = ""; String createdBy = ""; Date createdDate; AccessibilityBean theAccess; Boolean userDeletable = false; List<String> errors; Boolean userUpdatable = false; String uri = ""; Boolean uriExternal = false; String externalUrl = ""; Boolean review =false; public Boolean getReview() { return review; } public void setReview(Boolean review) { this.review = review; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Boolean getUriExternal() { return uriExternal; } public void setUriExternal(Boolean uriExternal) { this.uriExternal = uriExternal; } public String getExternalUrl() { return externalUrl; } public void setExternalUrl(String externalUrl) { this.externalUrl = externalUrl; } public Boolean getUserUpdatable() { return userUpdatable; } public void setUserUpdatable(Boolean userUpdatable) { this.userUpdatable = userUpdatable; } public List<String> getErrors() { return errors; } public void setErrors(List<String> errors) { this.errors = errors; } public Boolean getUserDeletable() { return userDeletable; } public void setUserDeletable(Boolean userDeletable) { this.userDeletable = userDeletable; } public AccessibilityBean getTheAccess() { return theAccess; } public void setTheAccess(AccessibilityBean theAccess) { this.theAccess = theAccess; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAbbreviation() { return abbreviation; } public void setAbbreviation(String abbreviation) { this.abbreviation = abbreviation; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Long getFileId() { return fileId; } public void setFileId(Long fileId) { this.fileId = fileId; } public String getFileTitle() { return fileTitle; } public void setFileTitle(String fileTitle) { this.fileTitle = fileTitle; } public String getFileDescription() { return fileDescription; } public void setFileDescription(String fileDescription) { this.fileDescription = fileDescription; } public List<AccessibilityBean> getGroupAccesses() { return groupAccesses; } public void setGroupAccesses(List<AccessibilityBean> groupAccesses) { this.groupAccesses = groupAccesses; } public List<AccessibilityBean> getUserAccesses() { return userAccesses; } public void setUserAccesses(List<AccessibilityBean> userAccesses) { this.userAccesses = userAccesses; } public String getProtectedData() { return protectedData; } public void setProtectedData(String protectedData) { this.protectedData = protectedData; } public Boolean getIsPublic() { return isPublic; } public void setIsPublic(Boolean isPublic) { this.isPublic = isPublic; } public Boolean getIsOwner() { return isOwner; } public void setIsOwner(Boolean isOwner) { this.isOwner = isOwner; } public String getOwnerName() { return ownerName; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public void transferProtocolBeanForEdit(ProtocolBean bean, HttpServletRequest request) { setAbbreviation(bean.getDomain().getAbbreviation()); setCreatedBy(bean.getDomain().getCreatedBy()); setCreatedDate(bean.getDomain().getCreatedDate()); if(bean.getDomain().getFile()!= null){ // setFileDescription(bean.getDomain().getFile().getDescription()); setFileId(bean.getDomain().getFile().getId()); // setFileTitle(bean.getDomain().getFile().getTitle()); setUri(bean.getDomain().getFile().getUri()); setUriExternal(bean.getDomain().getFile().getUriExternal()); setFileName(bean.getDomain().getFile().getName()); setFileDescription(bean.getDomain().getFile().getDescription()); setFileTitle(bean.getDomain().getFile().getTitle()); } setGroupAccesses(bean.getGroupAccesses()); setUserAccesses(bean.getUserAccesses()); setTheAccess(bean.getTheAccess()); setId(bean.getDomain().getId()); setIsOwner(bean.getUserIsOwner()); setIsPublic(bean.getPublicStatus()); setName(bean.getDomain().getName()); setType(bean.getDomain().getType()); setUserDeletable(bean.getUserDeletable()); setVersion(bean.getDomain().getVersion()); setUserUpdatable(bean.getUserUpdatable()); setReview((Boolean) request.getAttribute("review")); } }
package org.hisp.dhis.android.core.program; import com.fasterxml.jackson.databind.ObjectMapper; import org.hisp.dhis.android.core.Inject; import org.hisp.dhis.android.core.common.BaseIdentifiableObject; import org.junit.Test; import java.io.IOException; import java.text.ParseException; import static org.assertj.core.api.Java6Assertions.assertThat; public class ProgramShould { @Test public void map_from_json_string() throws IOException, ParseException { ObjectMapper objectMapper = Inject.objectMapper(); Program program = objectMapper.readValue("{\n" + "\n" + " \"lastUpdated\": \"2015-10-15T11:32:27.242\",\n" + " \"id\": \"WSGAb5XwJ3Y\",\n" + " \"created\": \"2014-06-06T20:44:21.375\",\n" + " \"name\": \"WHO RMNCH Tracker\",\n" + " \"shortName\": \"WHO RMNCH Tracker\",\n" + " \"publicAccess\": \"rw " \"ignoreOverdueEvents\": false,\n" + " \"skipOffline\": false,\n" + " \"dataEntryMethod\": false,\n" + " \"captureCoordinates\": false,\n" + " \"enrollmentDateLabel\": \"Date of first visit\",\n" + " \"onlyEnrollOnce\": false,\n" + " \"version\": 11,\n" + " \"selectIncidentDatesInFuture\": true,\n" + " \"incidentDateLabel\": \"Date of incident\",\n" + " \"selectEnrollmentDatesInFuture\": false,\n" + " \"registration\": true,\n" + " \"useFirstStageDuringRegistration\": false,\n" + " \"displayName\": \"WHO RMNCH Tracker\",\n" + " \"completeEventsExpiryDays\": 0,\n" + " \"displayShortName\": \"WHO RMNCH Tracker\",\n" + " \"externalAccess\": false,\n" + " \"withoutRegistration\": false,\n" + " \"displayFrontPageList\": false,\n" + " \"programType\": \"WITH_REGISTRATION\",\n" + " \"relationshipFromA\": true,\n" + " \"relationshipText\": \"Add child\",\n" + " \"displayIncidentDate\": false,\n" + " \"expiryDays\": 0,\n" + " \"minAttributesRequiredToSearch\": 3,\n" + " \"categoryCombo\": {\n" + " \"id\": \"p0KPaWEg3cf\"\n" + " },\n" + " \"trackedEntityType\": {\n" + " \"id\": \"nEenWmSyUEp\"\n" + " },\n" + " \"relatedProgram\": {\n" + " \"id\": \"IpHINAT79UW\"\n" + " },\n" + " \"relationshipType\": {\n" + " \"id\": \"V2kkHafqs8G\"\n" + " },\n" + " \"user\": {\n" + " \"id\": \"xE7jOejl9FI\"\n" + " },\n" + " \"programIndicators\": [ ],\n" + " \"translations\": [ ],\n" + " \"userGroupAccesses\": [ ],\n" + " \"attributeValues\": [ ],\n" + " \"validationCriterias\": [ ],\n" + " \"userRoles\": [\n" + " {\n" + " \"id\": \"Ufph3mGRmMo\"\n" + " },\n" + " {\n" + " \"id\": \"LGWLyWNro4x\"\n" + " }\n" + " ],\n" + " \"programRuleVariables\": [\n" + " {\n" + " \"id\": \"varonrw1032\"\n" + " },\n" + " {\n" + " \"id\": \"idLCptBEOF9\"\n" + " },\n" + " {\n" + " \"id\": \"iGBDXK1Gbcb\"\n" + " },\n" + " {\n" + " \"id\": \"varonrw1026\"\n" + " },\n" + " {\n" + " \"id\": \"pJ79JBmuFT4\"\n" + " },\n" + " {\n" + " \"id\": \"YnREl4QOKFB\"\n" + " },\n" + " {\n" + " \"id\": \"varonrw1030\"\n" + " },\n" + " {\n" + " \"id\": \"yrhN4QM8gqg\"\n" + " },\n" + " {\n" + " \"id\": \"WS8wNA4Jvev\"\n" + " },\n" + " {\n" + " \"id\": \"varonrw1027\"\n" + " },\n" + " {\n" + " \"id\": \"OnXTZg6lPA6\"\n" + " },\n" + " {\n" + " \"id\": \"Jx93QwiIP1B\"\n" + " },\n" + " {\n" + " \"id\": \"varonrw1029\"\n" + " },\n" + " {\n" + " \"id\": \"AU9n351Zwno\"\n" + " },\n" + " {\n" + " \"id\": \"k8QP8SWkQtA\"\n" + " },\n" + " {\n" + " \"id\": \"VY8KZyr8d2d\"\n" + " },\n" + " {\n" + " \"id\": \"varonrw1028\"\n" + " },\n" + " {\n" + " \"id\": \"varonrw1033\"\n" + " },\n" + " {\n" + " \"id\": \"varonrw1031\"\n" + " },\n" + " {\n" + " \"id\": \"WuSvlMvjeu9\"\n" + " },\n" + " {\n" + " \"id\": \"d1XWbV9mlle\"\n" + " },\n" + " {\n" + " \"id\": \"XJ3gR8WFYP1\"\n" + " }\n" + " ],\n" + " \"programTrackedEntityAttributes\": [\n" + " {\n" + " \"id\": \"YGMlKXYa5xF\"\n" + " },\n" + " {\n" + " \"id\": \"WZWEBrkJSAm\"\n" + " },\n" + " {\n" + " \"id\": \"v4GVdtLY8KV\"\n" + " },\n" + " {\n" + " \"id\": \"pasqxL7MU6h\"\n" + " },\n" + " {\n" + " \"id\": \"B5ggND5eXU5\"\n" + " },\n" + " {\n" + " \"id\": \"pCliTGHh5WS\"\n" + " },\n" + " {\n" + " \"id\": \"ypiK0ehyoCv\"\n" + " },\n" + " {\n" + " \"id\": \"Z5eRPdPIL49\"\n" + " },\n" + " {\n" + " \"id\": \"dHThsTGLdC3\"\n" + " },\n" + " {\n" + " \"id\": \"eNdG4pvswEX\"\n" + " }\n" + " ],\n" + " \"notificationTemplates\": [ ],\n" + " \"programStages\": [\n" + " {\n" + " \"id\": \"WZbXY0S00lP\"\n" + " },\n" + " {\n" + " \"id\": \"PUZaKR0Jh2k\"\n" + " },\n" + " {\n" + " \"id\": \"edqlbukwRfQ\"\n" + " },\n" + " {\n" + " \"id\": \"PFDfvmGpsR3\"\n" + " },\n" + " {\n" + " \"id\": \"bbKtnxRZKEP\"\n" + " }\n" + " ],\n" + " \"programRules\": [\n" + " {\n" + " \"id\": \"tO1D62oB0tq\"\n" + " },\n" + " {\n" + " \"id\": \"ruleonr1065\"\n" + " },\n" + " {\n" + " \"id\": \"jZ6TKNCRhdt\"\n" + " },\n" + " {\n" + " \"id\": \"HTKIQDVMu0K\"\n" + " },\n" + " {\n" + " \"id\": \"ruleonr1066\"\n" + " },\n" + " {\n" + " \"id\": \"ruleonr1055\"\n" + " },\n" + " {\n" + " \"id\": \"ruleonr1061\"\n" + " },\n" + " {\n" + " \"id\": \"RtCIjfyRB9L\"\n" + " },\n" + " {\n" + " \"id\": \"hpO8g3CRAeC\"\n" + " },\n" + " {\n" + " \"id\": \"IdrDtQmRGrv\"\n" + " },\n" + " {\n" + " \"id\": \"NkpU28ZlfVh\"\n" + " },\n" + " {\n" + " \"id\": \"GTtHkDt4doY\"\n" + " },\n" + " {\n" + " \"id\": \"ruleonr1062\"\n" + " }\n" + " ]\n" + "\n" + "}", Program.class); assertThat(program.lastUpdated()).isEqualTo( BaseIdentifiableObject.DATE_FORMAT.parse("2015-10-15T11:32:27.242")); assertThat(program.created()).isEqualTo( BaseIdentifiableObject.DATE_FORMAT.parse("2014-06-06T20:44:21.375")); assertThat(program.uid()).isEqualTo("WSGAb5XwJ3Y"); assertThat(program.name()).isEqualTo("WHO RMNCH Tracker"); assertThat(program.displayName()).isEqualTo("WHO RMNCH Tracker"); assertThat(program.shortName()).isEqualTo("WHO RMNCH Tracker"); assertThat(program.displayShortName()).isEqualTo("WHO RMNCH Tracker"); assertThat(program.ignoreOverdueEvents()).isFalse(); assertThat(program.dataEntryMethod()).isFalse(); assertThat(program.captureCoordinates()).isFalse(); assertThat(program.enrollmentDateLabel()).isEqualTo("Date of first visit"); assertThat(program.onlyEnrollOnce()).isFalse(); assertThat(program.version()).isEqualTo(11); assertThat(program.selectIncidentDatesInFuture()).isTrue(); assertThat(program.incidentDateLabel()).isEqualTo("Date of incident"); assertThat(program.selectEnrollmentDatesInFuture()).isFalse(); assertThat(program.registration()).isTrue(); assertThat(program.useFirstStageDuringRegistration()).isFalse(); assertThat(program.minAttributesRequiredToSearch()).isEqualTo(3); assertThat(program.displayFrontPageList()).isFalse(); assertThat(program.programType()).isEqualTo(ProgramType.WITH_REGISTRATION); assertThat(program.relationshipFromA()).isTrue(); assertThat(program.relationshipText()).isEqualTo("Add child"); assertThat(program.displayIncidentDate()).isFalse(); assertThat(program.categoryCombo().uid()).isEqualTo("p0KPaWEg3cf"); assertThat(program.trackedEntityType().uid()).isEqualTo("nEenWmSyUEp"); assertThat(program.relatedProgram().uid()).isEqualTo("IpHINAT79UW"); assertThat(program.relationshipType().uid()).isEqualTo("V2kkHafqs8G"); assertThat(program.programIndicators()).isEmpty(); assertThat(program.programStages().get(0).uid()).isEqualTo("WZbXY0S00lP"); assertThat(program.programStages().get(1).uid()).isEqualTo("PUZaKR0Jh2k"); assertThat(program.programStages().get(2).uid()).isEqualTo("edqlbukwRfQ"); assertThat(program.programStages().get(3).uid()).isEqualTo("PFDfvmGpsR3"); assertThat(program.programStages().get(4).uid()).isEqualTo("bbKtnxRZKEP"); assertThat(program.programRules().get(0).uid()).isEqualTo("tO1D62oB0tq"); assertThat(program.programRules().get(1).uid()).isEqualTo("ruleonr1065"); assertThat(program.programRules().get(2).uid()).isEqualTo("jZ6TKNCRhdt"); assertThat(program.programRules().get(3).uid()).isEqualTo("HTKIQDVMu0K"); assertThat(program.programRules().get(4).uid()).isEqualTo("ruleonr1066"); assertThat(program.programRules().get(5).uid()).isEqualTo("ruleonr1055"); assertThat(program.programRules().get(6).uid()).isEqualTo("ruleonr1061"); assertThat(program.programRules().get(7).uid()).isEqualTo("RtCIjfyRB9L"); assertThat(program.programRules().get(8).uid()).isEqualTo("hpO8g3CRAeC"); assertThat(program.programRules().get(9).uid()).isEqualTo("IdrDtQmRGrv"); assertThat(program.programRules().get(10).uid()).isEqualTo("NkpU28ZlfVh"); assertThat(program.programRules().get(11).uid()).isEqualTo("GTtHkDt4doY"); assertThat(program.programRules().get(12).uid()).isEqualTo("ruleonr1062"); assertThat(program.programRuleVariables().get(0).uid()).isEqualTo("varonrw1032"); assertThat(program.programRuleVariables().get(1).uid()).isEqualTo("idLCptBEOF9"); assertThat(program.programRuleVariables().get(2).uid()).isEqualTo("iGBDXK1Gbcb"); assertThat(program.programRuleVariables().get(3).uid()).isEqualTo("varonrw1026"); assertThat(program.programRuleVariables().get(4).uid()).isEqualTo("pJ79JBmuFT4"); assertThat(program.programRuleVariables().get(5).uid()).isEqualTo("YnREl4QOKFB"); assertThat(program.programRuleVariables().get(6).uid()).isEqualTo("varonrw1030"); assertThat(program.programRuleVariables().get(7).uid()).isEqualTo("yrhN4QM8gqg"); assertThat(program.programRuleVariables().get(8).uid()).isEqualTo("WS8wNA4Jvev"); assertThat(program.programRuleVariables().get(9).uid()).isEqualTo("varonrw1027"); assertThat(program.programRuleVariables().get(10).uid()).isEqualTo("OnXTZg6lPA6"); assertThat(program.programRuleVariables().get(11).uid()).isEqualTo("Jx93QwiIP1B"); assertThat(program.programRuleVariables().get(12).uid()).isEqualTo("varonrw1029"); assertThat(program.programRuleVariables().get(13).uid()).isEqualTo("AU9n351Zwno"); assertThat(program.programRuleVariables().get(14).uid()).isEqualTo("k8QP8SWkQtA"); assertThat(program.programRuleVariables().get(15).uid()).isEqualTo("VY8KZyr8d2d"); assertThat(program.programRuleVariables().get(16).uid()).isEqualTo("varonrw1028"); assertThat(program.programRuleVariables().get(17).uid()).isEqualTo("varonrw1033"); assertThat(program.programRuleVariables().get(18).uid()).isEqualTo("varonrw1031"); assertThat(program.programRuleVariables().get(19).uid()).isEqualTo("WuSvlMvjeu9"); assertThat(program.programRuleVariables().get(20).uid()).isEqualTo("d1XWbV9mlle"); assertThat(program.programRuleVariables().get(21).uid()).isEqualTo("XJ3gR8WFYP1"); assertThat(program.programTrackedEntityAttributes().get(0).uid()).isEqualTo("YGMlKXYa5xF"); assertThat(program.programTrackedEntityAttributes().get(1).uid()).isEqualTo("WZWEBrkJSAm"); assertThat(program.programTrackedEntityAttributes().get(2).uid()).isEqualTo("v4GVdtLY8KV"); assertThat(program.programTrackedEntityAttributes().get(3).uid()).isEqualTo("pasqxL7MU6h"); assertThat(program.programTrackedEntityAttributes().get(4).uid()).isEqualTo("B5ggND5eXU5"); assertThat(program.programTrackedEntityAttributes().get(5).uid()).isEqualTo("pCliTGHh5WS"); assertThat(program.programTrackedEntityAttributes().get(6).uid()).isEqualTo("ypiK0ehyoCv"); assertThat(program.programTrackedEntityAttributes().get(7).uid()).isEqualTo("Z5eRPdPIL49"); assertThat(program.programTrackedEntityAttributes().get(8).uid()).isEqualTo("dHThsTGLdC3"); assertThat(program.programTrackedEntityAttributes().get(9).uid()).isEqualTo("eNdG4pvswEX"); } }
package imagej.updater.core; import imagej.updater.core.FileObject.Action; import imagej.updater.core.FileObject.Status; import imagej.updater.util.DependencyAnalyzer; import imagej.updater.util.Progress; import imagej.updater.util.Util; import imagej.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.GZIPOutputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import org.xml.sax.SAXException; /** * TODO * * @author Johannes Schindelin */ @SuppressWarnings("serial") public class FilesCollection extends LinkedHashMap<String, FileObject> implements Iterable<FileObject> { public final static String DEFAULT_UPDATE_SITE = "ImageJ"; protected File imagejRoot; protected Set<FileObject> ignoredConflicts = new HashSet<FileObject>(); public static class UpdateSite implements Cloneable, Comparable<UpdateSite> { public String url, sshHost, uploadDirectory; public long timestamp; public int rank; public UpdateSite(String url, final String sshHost, String uploadDirectory, final long timestamp) { if (!url.endsWith("/")) url += "/"; if (uploadDirectory != null && !uploadDirectory.equals("") && !uploadDirectory.endsWith("/")) uploadDirectory += "/"; this.url = url; this.sshHost = sshHost; this.uploadDirectory = uploadDirectory; this.timestamp = timestamp; } @Override public Object clone() { return new UpdateSite(url, sshHost, uploadDirectory, timestamp); } public boolean isLastModified(final long lastModified) { return timestamp == Long.parseLong(Util.timestamp(lastModified)); } public void setLastModified(final long lastModified) { timestamp = Long.parseLong(Util.timestamp(lastModified)); } public boolean isUploadable() { return uploadDirectory != null && !uploadDirectory.equals(""); } @Override public String toString() { return url + (sshHost != null ? ", " + sshHost : "") + (uploadDirectory != null ? ", " + uploadDirectory : ""); } @Override public int compareTo(UpdateSite other) { return rank - other.rank; } @Override public boolean equals(Object other) { if (other instanceof UpdateSite) return rank == ((UpdateSite)other).rank; return false; } @Override public int hashCode() { return rank; } } private Map<String, UpdateSite> updateSites; /** * This constructor takes the imagejRoot primarily for testing purposes. * * @param imagejRoot the ImageJ directory */ public FilesCollection(final File imagejRoot) { this.imagejRoot = imagejRoot; updateSites = new LinkedHashMap<String, UpdateSite>(); addUpdateSite(DEFAULT_UPDATE_SITE, Util.MAIN_URL, null, null, imagejRoot == null ? 0 : Util.getTimestamp(prefix(Util.XML_COMPRESSED))); } public void addUpdateSite(final String name, final String url, final String sshHost, final String uploadDirectory, final long timestamp) { addUpdateSite(name, new UpdateSite(url, sshHost, uploadDirectory, timestamp)); } protected void addUpdateSite(final String name, final UpdateSite updateSite) { updateSite.rank = updateSites.size(); updateSites.put(name, updateSite); } public void renameUpdateSite(final String oldName, final String newName) { if (getUpdateSite(newName) != null) throw new RuntimeException( "Update site " + newName + " exists already!"); if (getUpdateSite(oldName) == null) throw new RuntimeException( "Update site " + oldName + " does not exist!"); // handle all files for (final FileObject file : this) if (file.updateSite.equals(oldName)) file.updateSite = newName; // preserve order final Map<String, UpdateSite> oldMap = updateSites; updateSites = new LinkedHashMap<String, UpdateSite>(); for (final String name : oldMap.keySet()) { addUpdateSite(name.equals(oldName) ? newName : name, oldMap.get(name)); } } public void removeUpdateSite(final String name) throws IOException { // TODO: remove NOT_INSTALLED files, mark others LOCAL_ONLY Set<String> toReRead = new HashSet<String>(); for (final FileObject file : forUpdateSite(name)) { toReRead.addAll(file.overriddenUpdateSites); if (file.getStatus() == Status.NOT_INSTALLED) { remove(file); } else { file.setStatus(Status.LOCAL_ONLY); file.updateSite = null; } } updateSites.remove(name); // re-read the overridden sites // no need to sort, the XMLFileReader will only override data from higher-ranked sites new XMLFileDownloader(this, toReRead).start(); // update rank int counter = 1; for (final Map.Entry<String, UpdateSite> entry : updateSites.entrySet()) { entry.getValue().rank = counter++; } } public UpdateSite getUpdateSite(final String name) { if (name == null) return null; return updateSites.get(name); } public Collection<String> getUpdateSiteNames() { return updateSites.keySet(); } public Collection<String> getSiteNamesToUpload() { final Collection<String> set = new HashSet<String>(); for (final FileObject file : toUpload(true)) set.add(file.updateSite); for (final FileObject file : toRemove()) set.add(file.updateSite); // keep the update sites' order final List<String> result = new ArrayList<String>(); for (final String name : getUpdateSiteNames()) if (set.contains(name)) result.add(name); if (result.size() != set.size()) throw new RuntimeException( "Unknown update site in " + set.toString() + " (known: " + result.toString() + ")"); return result; } public boolean hasUploadableSites() { for (final String name : updateSites.keySet()) if (getUpdateSite(name).isUploadable()) return true; return false; } public void reReadUpdateSite(final String name, final Progress progress) throws ParserConfigurationException, IOException, SAXException { new XMLFileReader(this).read(name); final List<String> filesFromSite = new ArrayList<String>(); for (final FileObject file : forUpdateSite(name)) filesFromSite.add(file.localFilename != null ? file.localFilename : file.filename); final Checksummer checksummer = new Checksummer(this, progress); checksummer.updateFromLocal(filesFromSite); } public Action[] getActions(final FileObject file) { return file.isUploadable(this) ? file.getStatus().getDeveloperActions() : file.getStatus().getActions(); } public Action[] getActions(final Iterable<FileObject> files) { List<Action> result = null; for (final FileObject file : files) { final Action[] actions = getActions(file); if (result == null) { result = new ArrayList<Action>(); for (final Action action : actions) result.add(action); } else { final Set<Action> set = new TreeSet<Action>(); for (final Action action : actions) set.add(action); final Iterator<Action> iter = result.iterator(); while (iter.hasNext()) if (!set.contains(iter.next())) iter.remove(); } } return result.toArray(new Action[result.size()]); } public void read() throws IOException, ParserConfigurationException, SAXException { read(prefix(Util.XML_COMPRESSED)); } public void read(final File file) throws IOException, ParserConfigurationException, SAXException { read(new FileInputStream(file)); } public void read(final FileInputStream in) throws IOException, ParserConfigurationException, SAXException { new XMLFileReader(this).read(in); } public void write() throws IOException, SAXException, TransformerConfigurationException, ParserConfigurationException { new XMLFileWriter(this).write(new GZIPOutputStream(new FileOutputStream( prefix(Util.XML_COMPRESSED))), true); } protected static DependencyAnalyzer dependencyAnalyzer; public interface Filter { boolean matches(FileObject file); } public FilesCollection clone(final Iterable<FileObject> iterable) { final FilesCollection result = new FilesCollection(imagejRoot); for (final FileObject file : iterable) result.add(file); for (final String name : updateSites.keySet()) result.updateSites.put(name, (UpdateSite) updateSites.get(name).clone()); return result; } public Iterable<FileObject> toUploadOrRemove() { return filter(or(is(Action.UPLOAD), is(Action.REMOVE))); } public Iterable<FileObject> toUpload() { return toUpload(false); } public Iterable<FileObject> toUpload(final boolean includeMetadataChanges) { if (!includeMetadataChanges) return filter(is(Action.UPLOAD)); return filter(or(is(Action.UPLOAD), new Filter() { @Override public boolean matches(final FileObject file) { return file.metadataChanged; } })); } public Iterable<FileObject> toUpload(final String updateSite) { return filter(and(is(Action.UPLOAD), isUpdateSite(updateSite))); } public Iterable<FileObject> toUninstall() { return filter(is(Action.UNINSTALL)); } public Iterable<FileObject> toRemove() { return filter(is(Action.REMOVE)); } public Iterable<FileObject> toUpdate() { return filter(is(Action.UPDATE)); } public Iterable<FileObject> upToDate() { return filter(is(Action.INSTALLED)); } public Iterable<FileObject> toInstall() { return filter(is(Action.INSTALL)); } public Iterable<FileObject> toInstallOrUpdate() { return filter(oneOf(new Action[] { Action.INSTALL, Action.UPDATE })); } public Iterable<FileObject> notHidden() { return filter(and(not(is(Status.OBSOLETE_UNINSTALLED)), doesPlatformMatch())); } public Iterable<FileObject> uninstalled() { return filter(is(Status.NOT_INSTALLED)); } public Iterable<FileObject> installed() { return filter(not(oneOf(new Status[] { Status.LOCAL_ONLY, Status.NOT_INSTALLED }))); } public Iterable<FileObject> locallyModified() { return filter(oneOf(new Status[] { Status.MODIFIED, Status.OBSOLETE_MODIFIED })); } public Iterable<FileObject> forUpdateSite(final String name) { return filter(isUpdateSite(name)); } public Iterable<FileObject> managedFiles() { return filter(not(is(Status.LOCAL_ONLY))); } public Iterable<FileObject> localOnly() { return filter(is(Status.LOCAL_ONLY)); } public Iterable<FileObject> shownByDefault() { /* * Let's not show the NOT_INSTALLED ones, as the user chose not * to have them. */ final Status[] oneOf = { Status.UPDATEABLE, Status.NEW, Status.OBSOLETE, Status.OBSOLETE_MODIFIED }; return filter(or(oneOf(oneOf), is(Action.INSTALL))); } public Iterable<FileObject> uploadable() { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.isUploadable(FilesCollection.this); } }); } public Iterable<FileObject> changes() { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() != file.getStatus().getActions()[0]; } }); } public static class FilteredIterator implements Iterator<FileObject> { Filter filter; boolean opposite; Iterator<FileObject> iterator; FileObject next; FilteredIterator(final Filter filter, final Iterable<FileObject> files) { this.filter = filter; iterator = files.iterator(); findNext(); } @Override public boolean hasNext() { return next != null; } @Override public FileObject next() { final FileObject file = next; findNext(); return file; } @Override public void remove() { throw new UnsupportedOperationException(); } protected void findNext() { while (iterator.hasNext()) { next = iterator.next(); if (filter.matches(next)) return; } next = null; } } public static Iterable<FileObject> filter(final Filter filter, final Iterable<FileObject> files) { return new Iterable<FileObject>() { @Override public Iterator<FileObject> iterator() { return new FilteredIterator(filter, files); } }; } public static Iterable<FileObject> filter(final String search, final Iterable<FileObject> files) { final String keyword = search.trim().toLowerCase(); return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.getFilename().trim().toLowerCase().indexOf(keyword) >= 0; } }, files); } public Filter yes() { return new Filter() { @Override public boolean matches(final FileObject file) { return true; } }; } public Filter doesPlatformMatch() { // If we're a developer or no platform was specified, return yes if (hasUploadableSites()) return yes(); return new Filter() { @Override public boolean matches(final FileObject file) { return file.isUpdateablePlatform(); } }; } public Filter is(final Action action) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() == action; } }; } public Filter isNoAction() { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() == file.getStatus().getNoAction(); } }; } public Filter oneOf(final Action[] actions) { final Set<Action> oneOf = new HashSet<Action>(); for (final Action action : actions) oneOf.add(action); return new Filter() { @Override public boolean matches(final FileObject file) { return oneOf.contains(file.getAction()); } }; } public Filter is(final Status status) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getStatus() == status; } }; } public Filter isUpdateSite(final String updateSite) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.updateSite != null && // is null for local-only files file.updateSite.equals(updateSite); } }; } public Filter oneOf(final Status[] states) { final Set<Status> oneOf = new HashSet<Status>(); for (final Status status : states) oneOf.add(status); return new Filter() { @Override public boolean matches(final FileObject file) { return oneOf.contains(file.getStatus()); } }; } public Filter startsWith(final String prefix) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.filename.startsWith(prefix); } }; } public Filter startsWith(final String[] prefixes) { return new Filter() { @Override public boolean matches(final FileObject file) { for (final String prefix : prefixes) if (file.filename.startsWith(prefix)) return true; return false; } }; } public Filter endsWith(final String suffix) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.filename.endsWith(suffix); } }; } public Filter not(final Filter filter) { return new Filter() { @Override public boolean matches(final FileObject file) { return !filter.matches(file); } }; } public Filter or(final Filter a, final Filter b) { return new Filter() { @Override public boolean matches(final FileObject file) { return a.matches(file) || b.matches(file); } }; } public Filter and(final Filter a, final Filter b) { return new Filter() { @Override public boolean matches(final FileObject file) { return a.matches(file) && b.matches(file); } }; } public Iterable<FileObject> filter(final Filter filter) { return filter(filter, this); } public FileObject getFileFromDigest(final String filename, final String digest) { for (final FileObject file : this) if (file.getFilename().equals(filename) && file.getChecksum().equals(digest)) return file; return null; } public Iterable<String> analyzeDependencies(final FileObject file) { try { if (dependencyAnalyzer == null) dependencyAnalyzer = new DependencyAnalyzer(imagejRoot); return dependencyAnalyzer.getDependencies(imagejRoot, file.getFilename()); } catch (final IOException e) { Log.error(e); return null; } } public void updateDependencies(final FileObject file) { final Iterable<String> dependencies = analyzeDependencies(file); if (dependencies == null) return; for (final String dependency : dependencies) file.addDependency(dependency, prefix(dependency)); } public boolean has(final Filter filter) { for (final FileObject file : this) if (filter.matches(file)) return true; return false; } public boolean hasChanges() { return has(not(isNoAction())); } public boolean hasUploadOrRemove() { return has(oneOf(new Action[] { Action.UPLOAD, Action.REMOVE })); } public boolean hasForcableUpdates() { for (final FileObject file : updateable(true)) if (!file.isUpdateable(false)) return true; return false; } public Iterable<FileObject> updateable(final boolean evenForcedOnes) { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.isUpdateable(evenForcedOnes) && file.isUpdateablePlatform(); } }); } public void markForUpdate(final boolean evenForcedUpdates) { for (final FileObject file : updateable(evenForcedUpdates)) { file.setFirstValidAction(this, new Action[] { Action.UPDATE, Action.UNINSTALL, Action.INSTALL }); } } public String getURL(final FileObject file) { final String siteName = file.updateSite; assert (siteName != null && !siteName.equals("")); final UpdateSite site = getUpdateSite(siteName); return site.url + file.filename.replace(" ", "%20") + "-" + file.getTimestamp(); } public static class DependencyMap extends HashMap<FileObject, FilesCollection> { // returns true when the map did not have the dependency before public boolean add(final FileObject dependency, final FileObject dependencee) { if (containsKey(dependency)) { get(dependency).add(dependencee); return false; } final FilesCollection list = new FilesCollection(null); list.add(dependencee); put(dependency, list); return true; } } // TODO: for developers, there should be a consistency check: // no dependencies on local-only files, no circular dependencies, // and no overring circular dependencies. void addDependencies(final FileObject file, final DependencyMap map, final boolean overriding) { for (final Dependency dependency : file.getDependencies()) { final FileObject other = get(dependency.filename); if (other == null || overriding != dependency.overrides || !other.isUpdateablePlatform()) continue; if (dependency.overrides) { if (other.willNotBeInstalled()) continue; } else if (other.willBeUpToDate()) continue; if (!map.add(other, file)) continue; // overriding dependencies are not recursive if (!overriding) addDependencies(other, map, overriding); } } public DependencyMap getDependencies(final boolean overridingOnes) { final DependencyMap result = new DependencyMap(); for (final FileObject file : toInstallOrUpdate()) addDependencies(file, result, overridingOnes); return result; } public void sort() { // first letters in this order: 'C', 'I', 'f', 'p', 'j', 's', 'i', 'm', 'l, final ArrayList<FileObject> files = new ArrayList<FileObject>(); for (final FileObject file : this) { files.add(file); } Collections.sort(files, new Comparator<FileObject>() { @Override public int compare(final FileObject a, final FileObject b) { final int result = firstChar(a) - firstChar(b); return result != 0 ? result : a.filename.compareTo(b.filename); } int firstChar(final FileObject file) { final char c = file.filename.charAt(0); final int index = "CIfpjsim".indexOf(c); return index < 0 ? 0x200 + c : index; } }); this.clear(); for (final FileObject file : files) { super.put(file.filename, file); } } String checkForCircularDependency(final FileObject file, final Set<FileObject> seen) { if (seen.contains(file)) return ""; final String result = checkForCircularDependency(file, seen, new HashSet<FileObject>()); if (result == null) return ""; // Display only the circular dependency final int last = result.lastIndexOf(' '); final int off = result.lastIndexOf(result.substring(last), last - 1); return "Circular dependency detected: " + result.substring(off + 1) + "\n"; } String checkForCircularDependency(final FileObject file, final Set<FileObject> seen, final Set<FileObject> chain) { if (seen.contains(file)) return null; for (final String dependency : file.dependencies.keySet()) { final FileObject dep = get(dependency); if (dep == null) continue; if (chain.contains(dep)) return " " + dependency; chain.add(dep); final String result = checkForCircularDependency(dep, seen, chain); seen.add(dep); if (result != null) return " " + dependency + " ->" + result; chain.remove(dep); } return null; } /* returns null if consistent, error string when not */ public String checkConsistency() { final StringBuilder result = new StringBuilder(); final Set<FileObject> circularChecked = new HashSet<FileObject>(); for (final FileObject file : this) { result.append(checkForCircularDependency(file, circularChecked)); // only non-obsolete components can have dependencies final Set<String> deps = file.dependencies.keySet(); if (deps.size() > 0 && file.isObsolete()) result.append("Obsolete file " + file + "has dependencies: " + Util.join(", ", deps) + "!\n"); for (final String dependency : deps) { final FileObject dep = get(dependency); if (dep == null || dep.current == null) result.append("The file " + file + " has the obsolete/local-only " + "dependency " + dependency + "!\n"); } } return result.length() > 0 ? result.toString() : null; } public File prefix(final FileObject file) { return prefix(file.getFilename()); } public File prefix(final String path) { final File file = new File(path); if (file.isAbsolute()) return file; assert (imagejRoot != null); return new File(imagejRoot, path); } public File prefixUpdate(final String path) { return prefix("update/" + path); } public boolean fileExists(final String filename) { return prefix(filename).exists(); } @Override public String toString() { return Util.join(", ", this); } public FileObject get(final int index) { throw new UnsupportedOperationException(); } public void add(final FileObject file) { super.put(file.getFilename(true), file); } @Override public FileObject get(final Object filename) { return super.get(FileObject.getFilename((String)filename, true)); } @Override public FileObject put(final String key, final FileObject file) { throw new UnsupportedOperationException(); } @Override public Iterator<FileObject> iterator() { final Iterator<Map.Entry<String, FileObject>> iterator = entrySet().iterator(); return new Iterator<FileObject>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public FileObject next() { return iterator.next().getValue(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }
package imagej.updater.core; import imagej.log.LogService; import imagej.updater.core.FileObject.Action; import imagej.updater.core.FileObject.Status; import imagej.updater.util.Canceled; import imagej.updater.util.DependencyAnalyzer; import imagej.updater.util.Progress; import imagej.updater.util.StderrLogService; import imagej.updater.util.Util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.GZIPOutputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import org.xml.sax.SAXException; /** * TODO * * @author Johannes Schindelin */ @SuppressWarnings("serial") public class FilesCollection extends LinkedHashMap<String, FileObject> implements Iterable<FileObject> { public final static String DEFAULT_UPDATE_SITE = "ImageJ"; protected File imagejRoot; public LogService log; protected Set<FileObject> ignoredConflicts = new HashSet<FileObject>(); public static class UpdateSite implements Cloneable, Comparable<UpdateSite> { public String url, sshHost, uploadDirectory; public long timestamp; public int rank; public UpdateSite(String url, final String sshHost, String uploadDirectory, final long timestamp) { if (!url.endsWith("/")) url += "/"; if (uploadDirectory != null && !uploadDirectory.equals("") && !uploadDirectory.endsWith("/")) uploadDirectory += "/"; this.url = url; this.sshHost = sshHost; this.uploadDirectory = uploadDirectory; this.timestamp = timestamp; } @Override public Object clone() { return new UpdateSite(url, sshHost, uploadDirectory, timestamp); } public boolean isLastModified(final long lastModified) { return timestamp == Long.parseLong(Util.timestamp(lastModified)); } public void setLastModified(final long lastModified) { timestamp = Long.parseLong(Util.timestamp(lastModified)); } public boolean isUploadable() { return uploadDirectory != null && !uploadDirectory.equals(""); } @Override public String toString() { return url + (sshHost != null ? ", " + sshHost : "") + (uploadDirectory != null ? ", " + uploadDirectory : ""); } @Override public int compareTo(UpdateSite other) { return rank - other.rank; } @Override public boolean equals(Object other) { if (other instanceof UpdateSite) return rank == ((UpdateSite)other).rank; return false; } @Override public int hashCode() { return rank; } } private Map<String, UpdateSite> updateSites; /** * This constructor takes the imagejRoot primarily for testing purposes. * * @param imagejRoot the ImageJ directory */ public FilesCollection(final File imagejRoot) { this(new StderrLogService(), imagejRoot); } /** * This constructor takes the imagejRoot primarily for testing purposes. * * @param imagejRoot the ImageJ directory */ public FilesCollection(final LogService log, final File imagejRoot) { this.log = log; this.imagejRoot = imagejRoot; updateSites = new LinkedHashMap<String, UpdateSite>(); addUpdateSite(DEFAULT_UPDATE_SITE, Util.MAIN_URL, null, null, imagejRoot == null ? 0 : Util.getTimestamp(prefix(Util.XML_COMPRESSED))); } public void addUpdateSite(final String name, final String url, final String sshHost, final String uploadDirectory, final long timestamp) { addUpdateSite(name, new UpdateSite(url, sshHost, uploadDirectory, timestamp)); } protected void addUpdateSite(final String name, final UpdateSite updateSite) { UpdateSite already = updateSites.get(name); updateSite.rank = already != null ? already.rank : updateSites.size(); updateSites.put(name, updateSite); } public void renameUpdateSite(final String oldName, final String newName) { if (getUpdateSite(newName) != null) throw new RuntimeException( "Update site " + newName + " exists already!"); if (getUpdateSite(oldName) == null) throw new RuntimeException( "Update site " + oldName + " does not exist!"); // handle all files for (final FileObject file : this) if (file.updateSite.equals(oldName)) file.updateSite = newName; // preserve order final Map<String, UpdateSite> oldMap = updateSites; updateSites = new LinkedHashMap<String, UpdateSite>(); for (final String name : oldMap.keySet()) { addUpdateSite(name.equals(oldName) ? newName : name, oldMap.get(name)); } } public void removeUpdateSite(final String name) throws IOException { // TODO: remove NOT_INSTALLED files, mark others LOCAL_ONLY Set<String> toReRead = new HashSet<String>(); for (final FileObject file : forUpdateSite(name)) { toReRead.addAll(file.overriddenUpdateSites); if (file.getStatus() == Status.NOT_INSTALLED) { remove(file); } else { file.setStatus(Status.LOCAL_ONLY); file.updateSite = null; } } updateSites.remove(name); // re-read the overridden sites // no need to sort, the XMLFileReader will only override data from higher-ranked sites new XMLFileDownloader(this, toReRead).start(); // update rank int counter = 1; for (final Map.Entry<String, UpdateSite> entry : updateSites.entrySet()) { entry.getValue().rank = counter++; } } public UpdateSite getUpdateSite(final String name) { if (name == null) return null; return updateSites.get(name); } public Collection<String> getUpdateSiteNames() { return updateSites.keySet(); } public Collection<String> getSiteNamesToUpload() { final Collection<String> set = new HashSet<String>(); for (final FileObject file : toUpload(true)) set.add(file.updateSite); for (final FileObject file : toRemove()) set.add(file.updateSite); // keep the update sites' order final List<String> result = new ArrayList<String>(); for (final String name : getUpdateSiteNames()) if (set.contains(name)) result.add(name); if (result.size() != set.size()) throw new RuntimeException( "Unknown update site in " + set.toString() + " (known: " + result.toString() + ")"); return result; } public boolean hasUploadableSites() { for (final String name : updateSites.keySet()) if (getUpdateSite(name).isUploadable()) return true; return false; } public void reReadUpdateSite(final String name, final Progress progress) throws ParserConfigurationException, IOException, SAXException { new XMLFileReader(this).read(name); final List<String> filesFromSite = new ArrayList<String>(); for (final FileObject file : forUpdateSite(name)) filesFromSite.add(file.localFilename != null ? file.localFilename : file.filename); final Checksummer checksummer = new Checksummer(this, progress); checksummer.updateFromLocal(filesFromSite); } public Action[] getActions(final FileObject file) { return file.isUploadable(this) ? file.getStatus().getDeveloperActions() : file.getStatus().getActions(); } public Action[] getActions(final Iterable<FileObject> files) { List<Action> result = null; for (final FileObject file : files) { final Action[] actions = getActions(file); if (result == null) { result = new ArrayList<Action>(); for (final Action action : actions) result.add(action); } else { final Set<Action> set = new TreeSet<Action>(); for (final Action action : actions) set.add(action); final Iterator<Action> iter = result.iterator(); while (iter.hasNext()) if (!set.contains(iter.next())) iter.remove(); } } return result.toArray(new Action[result.size()]); } public void read() throws IOException, ParserConfigurationException, SAXException { read(prefix(Util.XML_COMPRESSED)); } public void read(final File file) throws IOException, ParserConfigurationException, SAXException { read(new FileInputStream(file)); } public void read(final FileInputStream in) throws IOException, ParserConfigurationException, SAXException { new XMLFileReader(this).read(in); } public void write() throws IOException, SAXException, TransformerConfigurationException, ParserConfigurationException { new XMLFileWriter(this).write(new GZIPOutputStream(new FileOutputStream( prefix(Util.XML_COMPRESSED))), true); } protected static DependencyAnalyzer dependencyAnalyzer; public interface Filter { boolean matches(FileObject file); } public FilesCollection clone(final Iterable<FileObject> iterable) { final FilesCollection result = new FilesCollection(imagejRoot); for (final FileObject file : iterable) result.add(file); for (final String name : updateSites.keySet()) result.updateSites.put(name, (UpdateSite) updateSites.get(name).clone()); return result; } public Iterable<FileObject> toUploadOrRemove() { return filter(or(is(Action.UPLOAD), is(Action.REMOVE))); } public Iterable<FileObject> toUpload() { return toUpload(false); } public Iterable<FileObject> toUpload(final boolean includeMetadataChanges) { if (!includeMetadataChanges) return filter(is(Action.UPLOAD)); return filter(or(is(Action.UPLOAD), new Filter() { @Override public boolean matches(final FileObject file) { return file.metadataChanged; } })); } public Iterable<FileObject> toUpload(final String updateSite) { return filter(and(is(Action.UPLOAD), isUpdateSite(updateSite))); } public Iterable<FileObject> toUninstall() { return filter(is(Action.UNINSTALL)); } public Iterable<FileObject> toRemove() { return filter(is(Action.REMOVE)); } public Iterable<FileObject> toUpdate() { return filter(is(Action.UPDATE)); } public Iterable<FileObject> upToDate() { return filter(is(Action.INSTALLED)); } public Iterable<FileObject> toInstall() { return filter(is(Action.INSTALL)); } public Iterable<FileObject> toInstallOrUpdate() { return filter(oneOf(Action.INSTALL, Action.UPDATE)); } public Iterable<FileObject> notHidden() { return filter(and(not(is(Status.OBSOLETE_UNINSTALLED)), doesPlatformMatch())); } public Iterable<FileObject> uninstalled() { return filter(is(Status.NOT_INSTALLED)); } public Iterable<FileObject> installed() { return filter(not(oneOf(Status.LOCAL_ONLY, Status.NOT_INSTALLED))); } public Iterable<FileObject> locallyModified() { return filter(oneOf(Status.MODIFIED, Status.OBSOLETE_MODIFIED)); } public Iterable<FileObject> forUpdateSite(final String name) { return filter(and(not(is(Status.OBSOLETE_UNINSTALLED)), and(doesPlatformMatch(), isUpdateSite(name)))); } public Iterable<FileObject> managedFiles() { return filter(not(is(Status.LOCAL_ONLY))); } public Iterable<FileObject> localOnly() { return filter(is(Status.LOCAL_ONLY)); } public Iterable<FileObject> shownByDefault() { /* * Let's not show the NOT_INSTALLED ones, as the user chose not * to have them. */ final Status[] oneOf = { Status.UPDATEABLE, Status.NEW, Status.OBSOLETE, Status.OBSOLETE_MODIFIED }; return filter(or(oneOf(oneOf), is(Action.INSTALL))); } public Iterable<FileObject> uploadable() { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.isUploadable(FilesCollection.this); } }); } public Iterable<FileObject> changes() { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() != file.getStatus().getActions()[0]; } }); } public static class FilteredIterator implements Iterator<FileObject> { Filter filter; boolean opposite; Iterator<FileObject> iterator; FileObject next; FilteredIterator(final Filter filter, final Iterable<FileObject> files) { this.filter = filter; iterator = files.iterator(); findNext(); } @Override public boolean hasNext() { return next != null; } @Override public FileObject next() { final FileObject file = next; findNext(); return file; } @Override public void remove() { throw new UnsupportedOperationException(); } protected void findNext() { while (iterator.hasNext()) { next = iterator.next(); if (filter.matches(next)) return; } next = null; } } public static Iterable<FileObject> filter(final Filter filter, final Iterable<FileObject> files) { return new Iterable<FileObject>() { @Override public Iterator<FileObject> iterator() { return new FilteredIterator(filter, files); } }; } public static Iterable<FileObject> filter(final String search, final Iterable<FileObject> files) { final String keyword = search.trim().toLowerCase(); return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.getFilename().trim().toLowerCase().indexOf(keyword) >= 0; } }, files); } public Filter yes() { return new Filter() { @Override public boolean matches(final FileObject file) { return true; } }; } public Filter doesPlatformMatch() { // If we're a developer or no platform was specified, return yes if (hasUploadableSites()) return yes(); return new Filter() { @Override public boolean matches(final FileObject file) { return file.isUpdateablePlatform(); } }; } public Filter is(final Action action) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() == action; } }; } public Filter isNoAction() { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getAction() == file.getStatus().getNoAction(); } }; } public Filter oneOf(final Action... actions) { final Set<Action> oneOf = new HashSet<Action>(); for (final Action action : actions) oneOf.add(action); return new Filter() { @Override public boolean matches(final FileObject file) { return oneOf.contains(file.getAction()); } }; } public Filter is(final Status status) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.getStatus() == status; } }; } public Filter isUpdateSite(final String updateSite) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.updateSite != null && // is null for local-only files file.updateSite.equals(updateSite); } }; } public Filter oneOf(final Status... states) { final Set<Status> oneOf = new HashSet<Status>(); for (final Status status : states) oneOf.add(status); return new Filter() { @Override public boolean matches(final FileObject file) { return oneOf.contains(file.getStatus()); } }; } public Filter startsWith(final String prefix) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.filename.startsWith(prefix); } }; } public Filter startsWith(final String... prefixes) { return new Filter() { @Override public boolean matches(final FileObject file) { for (final String prefix : prefixes) if (file.filename.startsWith(prefix)) return true; return false; } }; } public Filter endsWith(final String suffix) { return new Filter() { @Override public boolean matches(final FileObject file) { return file.filename.endsWith(suffix); } }; } public Filter not(final Filter filter) { return new Filter() { @Override public boolean matches(final FileObject file) { return !filter.matches(file); } }; } public Filter or(final Filter a, final Filter b) { return new Filter() { @Override public boolean matches(final FileObject file) { return a.matches(file) || b.matches(file); } }; } public Filter and(final Filter a, final Filter b) { return new Filter() { @Override public boolean matches(final FileObject file) { return a.matches(file) && b.matches(file); } }; } public Iterable<FileObject> filter(final Filter filter) { return filter(filter, this); } public FileObject getFileFromDigest(final String filename, final String digest) { for (final FileObject file : this) if (file.getFilename().equals(filename) && file.getChecksum().equals(digest)) return file; return null; } public Iterable<String> analyzeDependencies(final FileObject file) { try { if (dependencyAnalyzer == null) dependencyAnalyzer = new DependencyAnalyzer(imagejRoot); return dependencyAnalyzer.getDependencies(imagejRoot, file.getFilename()); } catch (final IOException e) { log.error(e); return null; } } public void updateDependencies(final FileObject file) { final Iterable<String> dependencies = analyzeDependencies(file); if (dependencies == null) return; for (final String dependency : dependencies) file.addDependency(dependency, prefix(dependency)); } public boolean has(final Filter filter) { for (final FileObject file : this) if (filter.matches(file)) return true; return false; } public boolean hasChanges() { return has(not(isNoAction())); } public boolean hasUploadOrRemove() { return has(oneOf(Action.UPLOAD, Action.REMOVE)); } public boolean hasForcableUpdates() { for (final FileObject file : updateable(true)) if (!file.isUpdateable(false)) return true; return false; } public Iterable<FileObject> updateable(final boolean evenForcedOnes) { return filter(new Filter() { @Override public boolean matches(final FileObject file) { return file.isUpdateable(evenForcedOnes) && file.isUpdateablePlatform(); } }); } public void markForUpdate(final boolean evenForcedUpdates) { for (final FileObject file : updateable(evenForcedUpdates)) { file.setFirstValidAction(this, Action.UPDATE, Action.UNINSTALL, Action.INSTALL); } } public String getURL(final FileObject file) { final String siteName = file.updateSite; assert (siteName != null && !siteName.equals("")); final UpdateSite site = getUpdateSite(siteName); return site.url + file.filename.replace(" ", "%20") + "-" + file.getTimestamp(); } public static class DependencyMap extends HashMap<FileObject, FilesCollection> { // returns true when the map did not have the dependency before public boolean add(final FileObject dependency, final FileObject dependencee) { if (containsKey(dependency)) { get(dependency).add(dependencee); return false; } final FilesCollection list = new FilesCollection(null); list.add(dependencee); put(dependency, list); return true; } } // TODO: for developers, there should be a consistency check: // no dependencies on local-only files, no circular dependencies, // and no overring circular dependencies. void addDependencies(final FileObject file, final DependencyMap map, final boolean overriding) { for (final Dependency dependency : file.getDependencies()) { final FileObject other = get(dependency.filename); if (other == null || overriding != dependency.overrides || !other.isUpdateablePlatform()) continue; if (dependency.overrides) { if (other.willNotBeInstalled()) continue; } else if (other.willBeUpToDate()) continue; if (!map.add(other, file)) continue; // overriding dependencies are not recursive if (!overriding) addDependencies(other, map, overriding); } } public DependencyMap getDependencies(final boolean overridingOnes) { final DependencyMap result = new DependencyMap(); for (final FileObject file : toInstallOrUpdate()) addDependencies(file, result, overridingOnes); return result; } public void sort() { // first letters in this order: 'C', 'I', 'f', 'p', 'j', 's', 'i', 'm', 'l, final ArrayList<FileObject> files = new ArrayList<FileObject>(); for (final FileObject file : this) { files.add(file); } Collections.sort(files, new Comparator<FileObject>() { @Override public int compare(final FileObject a, final FileObject b) { final int result = firstChar(a) - firstChar(b); return result != 0 ? result : a.filename.compareTo(b.filename); } int firstChar(final FileObject file) { final char c = file.filename.charAt(0); final int index = "CIfpjsim".indexOf(c); return index < 0 ? 0x200 + c : index; } }); this.clear(); for (final FileObject file : files) { super.put(file.filename, file); } } String checkForCircularDependency(final FileObject file, final Set<FileObject> seen) { if (seen.contains(file)) return ""; final String result = checkForCircularDependency(file, seen, new HashSet<FileObject>()); if (result == null) return ""; // Display only the circular dependency final int last = result.lastIndexOf(' '); final int off = result.lastIndexOf(result.substring(last), last - 1); return "Circular dependency detected: " + result.substring(off + 1) + "\n"; } String checkForCircularDependency(final FileObject file, final Set<FileObject> seen, final Set<FileObject> chain) { if (seen.contains(file)) return null; for (final String dependency : file.dependencies.keySet()) { final FileObject dep = get(dependency); if (dep == null) continue; if (chain.contains(dep)) return " " + dependency; chain.add(dep); final String result = checkForCircularDependency(dep, seen, chain); seen.add(dep); if (result != null) return " " + dependency + " ->" + result; chain.remove(dep); } return null; } /* returns null if consistent, error string when not */ public String checkConsistency() { final StringBuilder result = new StringBuilder(); final Set<FileObject> circularChecked = new HashSet<FileObject>(); for (final FileObject file : this) { result.append(checkForCircularDependency(file, circularChecked)); // only non-obsolete components can have dependencies final Set<String> deps = file.dependencies.keySet(); if (deps.size() > 0 && file.isObsolete()) result.append("Obsolete file " + file + "has dependencies: " + Util.join(", ", deps) + "!\n"); for (final String dependency : deps) { final FileObject dep = get(dependency); if (dep == null || dep.current == null) result.append("The file " + file + " has the obsolete/local-only " + "dependency " + dependency + "!\n"); } } return result.length() > 0 ? result.toString() : null; } public File prefix(final FileObject file) { return prefix(file.getFilename()); } public File prefix(final String path) { final File file = new File(path); if (file.isAbsolute()) return file; assert (imagejRoot != null); return new File(imagejRoot, path); } public File prefixUpdate(final String path) { return prefix("update/" + path); } public boolean fileExists(final String filename) { return prefix(filename).exists(); } @Override public String toString() { return Util.join(", ", this); } public FileObject get(final int index) { throw new UnsupportedOperationException(); } public void add(final FileObject file) { super.put(file.getFilename(true), file); } @Override public FileObject get(final Object filename) { return super.get(FileObject.getFilename((String)filename, true)); } @Override public FileObject put(final String key, final FileObject file) { throw new UnsupportedOperationException(); } @Override public Iterator<FileObject> iterator() { final Iterator<Map.Entry<String, FileObject>> iterator = entrySet().iterator(); return new Iterator<FileObject>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public FileObject next() { return iterator.next().getValue(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } public String downloadIndexAndChecksum(final Progress progress) throws IOException, ParserConfigurationException, SAXException { try { read(); } catch (final FileNotFoundException e) { /* ignore */} final XMLFileDownloader downloader = new XMLFileDownloader(this); downloader.addProgress(progress); try { downloader.start(false); } catch (final Canceled e) { downloader.done(); throw e; } new Checksummer(this, progress).updateFromLocal(); return downloader.getWarnings(); } }
package com.almende.dialog.adapter; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import com.almende.dialog.Settings; import com.almende.dialog.accounts.AdapterConfig; import com.almende.dialog.adapter.tools.CM; import com.almende.dialog.adapter.tools.CMStatus; import com.almende.dialog.agent.tools.TextMessage; import com.almende.dialog.example.agent.TestServlet; import com.almende.dialog.exception.NotFoundException; import com.almende.dialog.model.Session; import com.almende.dialog.model.ddr.DDRRecord; import com.almende.dialog.model.ddr.DDRRecord.CommunicationStatus; import com.almende.dialog.util.DDRUtils; import com.almende.dialog.util.ServerUtils; import com.almende.util.ParallelInit; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.thetransactioncompany.cors.HTTPMethod; public class CMSmsServlet extends TextServlet { private static final long serialVersionUID = 408503132941968804L; protected static final com.almende.dialog.Logger dialogLog = new com.almende.dialog.Logger(); private static final String servletPath = "/_ah/sms/"; private static final String adapterType = "CM"; private static final String deliveryStatusPath = "/dialoghandler/sms/cm/deliveryStatus"; @Override protected int sendMessage(String message, String subject, String from, String fromName, String to, String toName, Map<String, Object> extras, AdapterConfig config) throws Exception { String[] tokens = config.getAccessToken().split("\\|"); CM cm = new CM(tokens[0], tokens[1], config.getAccessTokenSecret()); return cm.sendMessage(message, subject, from, fromName, to, toName, extras, config); } @Override protected int broadcastMessage( String message, String subject, String from, String senderName, Map<String, String> addressNameMap, Map<String, Object> extras, AdapterConfig config ) throws Exception { String[] tokens = config.getAccessToken().split( "\\|" ); CM cm = new CM( tokens[0], tokens[1], config.getAccessTokenSecret() ); return cm.broadcastMessage( message, subject, from, senderName, addressNameMap, extras, config ); } @Override public void service( HttpServletRequest req, HttpServletResponse res ) throws IOException { if ( req.getRequestURI().startsWith( deliveryStatusPath ) ) { if ( req.getMethod().equals( "POST" ) ) { StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = req.getReader(); while ( ( line = reader.readLine() ) != null ) { jb.append( line ); } String response = handleDeliveryStatusReport( jb.toString() ); res.getWriter().println( response ); } catch ( Exception e ) { log.severe( "POST payload retrieval failed. Message: " + e.getLocalizedMessage() ); return; } } else if ( req.getMethod().equals( "GET" ) ) { try { String responseText = "No result fetched"; String reference = req.getParameter("reference"); //check the host in the CMStatus if (reference != null) { String hostFromReference = CMStatus.getHostFromReference(reference); log.info(String.format("Host from reference: %s and actual host: %s", hostFromReference + "?" + req.getQueryString(), Settings.HOST)); if (hostFromReference != null && !hostFromReference.contains((Settings.HOST))) { hostFromReference += deliveryStatusPath; log.info("CM delivery status is being redirect to: " + hostFromReference); hostFromReference += ("?" + (req.getQueryString() != null ? req.getQueryString() : "")); responseText = forwardToHost(hostFromReference, HTTPMethod.GET, null); } else { CMStatus cmStatus = handleDeliveryStatusReport(req.getParameter("reference"), req.getParameter("sent"), req.getParameter("received"), req.getParameter("to"), req.getParameter("statuscode"), req.getParameter("errorcode"), req.getParameter("errordescription")); responseText = ServerUtils.serializeWithoutException( cmStatus ); } } res.getWriter().println(responseText); } catch ( Exception e ) { log.severe( "GET query processing failed. Message: " + e.getLocalizedMessage() ); return; } } res.setStatus(HttpServletResponse.SC_OK); } else { super.service( req, res ); } } @Override protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { super.doPost( req, resp ); } @Override protected TextMessage receiveMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception { // TODO: Needs implementation, but service not available at CM return null; } @Override protected String getServletPath() { return servletPath; } @Override protected String getAdapterType() { return adapterType; } @Override protected void doErrorPost(HttpServletRequest req, HttpServletResponse res) throws IOException {} @Override protected DDRRecord createDDRForIncoming(AdapterConfig adapterConfig, String fromAddress, String message) throws Exception { // Needs implementation, but service not available at CM return null; } @Override protected DDRRecord createDDRForOutgoing(AdapterConfig adapterConfig, String senderName, Map<String, String> toAddress, String message) throws Exception { //add costs with no.of messages * recipients return DDRUtils.createDDRRecordOnOutgoingCommunication(adapterConfig, senderName, toAddress, CM.countMessageParts(message) * toAddress.size(), message); } private String handleDeliveryStatusReport(String payload) { try { log.info("payload seen: " + payload); DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance(); DocumentBuilder newDocumentBuilder = newInstance.newDocumentBuilder(); Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(payload.getBytes("UTF-8"))); Node sentNode = parse.getElementsByTagName("MESSAGES").item(0).getAttributes().getNamedItem("SENT"); Node receivedNode = parse.getElementsByTagName("MSG").item(0).getAttributes().getNamedItem("RECEIVED"); Node toNode = parse.getElementsByTagName("TO").item(0); Node referenceNode = parse.getElementsByTagName("REFERENCE").item(0); Node codeNode = parse.getElementsByTagName("CODE").item(0); Node errorCodeNode = parse.getElementsByTagName("ERRORCODE").item(0); Node errorDescNode = parse.getElementsByTagName("ERRORDESCRIPTION").item(0); String reference = referenceNode != null ? referenceNode.getTextContent() : null; String sent = sentNode != null ? sentNode.getTextContent() : null; String received = receivedNode != null ? receivedNode.getTextContent() : null; String to = toNode != null ? toNode.getTextContent() : null; String code = codeNode != null ? codeNode.getTextContent() : null; String errorCode = errorCodeNode != null ? errorCodeNode.getTextContent() : null; String errorDescription = errorDescNode != null ? errorDescNode.getTextContent() : null; //check the host in the CMStatus if (reference != null) { String hostFromReference = CMStatus.getHostFromReference(reference); log.info(String.format("Host from reference: %s and actual host: ", hostFromReference, Settings.HOST)); if (hostFromReference != null && !hostFromReference.contains((Settings.HOST))) { log.info("CM delivery status is being redirect to: " + hostFromReference); hostFromReference += deliveryStatusPath; return forwardToHost(hostFromReference, HTTPMethod.POST, payload); } else { CMStatus cmStatus = handleDeliveryStatusReport(reference, sent, received, to, code, errorCode, errorDescription); return ServerUtils.serializeWithoutException(cmStatus); } } } catch (Exception e) { log.severe("Document parse failed. \nMessage: " + e.getLocalizedMessage()); } return null; } private CMStatus handleDeliveryStatusReport(String reference, String sent, String received, String to, String code, String errorCode, String errorDescription) throws Exception { log.info(String.format("CM SR: reference: %s, sent: %s, received: %s, to: %s, statusCode: %s errorCode: %s, errorDesc: %s", reference, sent, received, to, code, errorCode, errorDescription)); if (reference != null && !reference.isEmpty()) { CMStatus cmStatus = CMStatus.fetch(reference); if (cmStatus != null) { if (sent != null) { cmStatus.setSentTimeStamp(sent); } if (received != null) { cmStatus.setDeliveredTimeStamp(received); } if (to != null) { if (!to.equals(cmStatus.getRemoteAddress())) { log.warning("To address dont match between entity and status callback from CM !!"); } cmStatus.setRemoteAddress(to); } if (code != null) { cmStatus.setCode(code); } if (errorCode != null) { cmStatus.setErrorCode(errorCode); } if (errorDescription != null) { cmStatus.setErrorDescription(errorDescription); } else if (errorCode != null && !errorCode.isEmpty()) { cmStatus.setErrorDescription(erroCodeMapping(Integer.parseInt(errorCode))); } if (cmStatus.getCallback() != null && cmStatus.getCallback().startsWith("http")) { Client client = ParallelInit.getClient(); WebResource webResource = client.resource(cmStatus.getCallback()); try { String callbackPayload = ServerUtils.serialize(cmStatus); if (ServerUtils.isInUnitTestingEnvironment()) { TestServlet.logForTest(cmStatus); } webResource.type("text/plain").post(String.class, callbackPayload); dialogLog.info(cmStatus.getAdapterID(), String .format("POST request with payload %s sent to: %s", callbackPayload, cmStatus.getCallback())); } catch (Exception ex) { log.severe("Callback failed. Message: " + ex.getLocalizedMessage()); } } else { log.info("Reference: " + reference + ". No delivered callback found."); dialogLog.info(cmStatus.getAdapterID(), "No delivered callback found for reference: " + reference); } //fetch ddr corresponding to this if (cmStatus.getSessionKey() != null) { Session session = Session.getSession(cmStatus.getSessionKey()); if (session != null) { DDRRecord ddrRecord = DDRRecord.getDDRRecord(session.getDdrRecordId(), cmStatus.getAccountId()); if (ddrRecord != null) { if (errorCode == null || errorCode.isEmpty()) { ddrRecord.addStatusForAddress(cmStatus.getRemoteAddress(), CommunicationStatus.DELIVERED); } else { ddrRecord.addStatusForAddress(cmStatus.getRemoteAddress(), CommunicationStatus.ERROR); ddrRecord.addAdditionalInfo("ERROR", cmStatus.getErrorDescription()); } ddrRecord.createOrUpdate(); } else { log.warning(String.format("No ddr record found for id: %s", session.getDdrRecordId())); } //check if session is killed. if so drop it :) if(session.isKilled() && isSMSsDelivered(ddrRecord)) { session.drop(); } } else { log.warning(String.format("No session found for id: %s", cmStatus.getSessionKey())); } } else { log.warning(String.format("No session attached for cm status: %s", cmStatus.getReference())); } cmStatus.store(); } return cmStatus; } else { log.severe("Reference code cannot be null"); return null; } } /** * check if all of the SMSs to toAddresses in the ddrRecord is {@link CommunicationStatus#DELIVERED} * @param ddrRecord * @return true if ddrRecord is null or all SMS are delivered */ private boolean isSMSsDelivered(DDRRecord ddrRecord) { if(ddrRecord == null) { return true; } else if(ddrRecord.getStatusPerAddress() != null) { int smsDeliveryCount = 0; for (String toAddress : ddrRecord.getStatusPerAddress().keySet()) { if(ddrRecord.getStatusForAddress(toAddress).equals(CommunicationStatus.DELIVERED)) { smsDeliveryCount++; } } if(smsDeliveryCount == ddrRecord.getStatusPerAddress().size()){ return true; } } return false; } /** * forward the CM delivery status to a different host with a POST request based on the * host attached in the reference * @param host * @param post * @param payload * @return */ private String forwardToHost(String host, HTTPMethod method, String payload) { Client client = ParallelInit.getClient(); WebResource webResource = client.resource(host); try { switch (method) { case GET: return webResource.type("text/plain").get(String.class); case POST: return webResource.type("text/plain").post(String.class, payload); default: throw new NotFoundException(String.format("METHOD %s not implemented", method)); } } catch (Exception e) { log.severe(String.format("Failed to send CM DLR status to host: %s. Message: %s", host, e.getLocalizedMessage())); } return null; } private String erroCodeMapping( int errorCode ) { String result = null; switch ( errorCode ) { case 5: result = "The message has been confirmed as undelivered but no detailed information related to the failure is known."; break; case 7: result = "Used to indicate to the client that the message has not yet been delivered due to insufficient subscriber credit but is being retried within the network."; break; case 8: result = "Temporary Used when a message expired (could not be delivered within the life time of the message) within the operator SMSC but is not associated with a reason for failure. "; break; case 20: result = "Used when a message in its current form is undeliverable."; break; case 21: result = "Temporary Only occurs where the operator accepts the message before performing the subscriber credit check. If there is insufficient credit then the operator will retry the message until the subscriber tops up or the message expires. If the message expires and the last failure reason is related to credit then this error code will be used."; break; case 22: result = "Temporary Only occurs where the operator performs the subscriber credit check before accepting the message and rejects messages if there are insufficient funds available."; break; case 23: result = "Used when the message is undeliverable due to an incorrect / invalid / blacklisted / permanently barred MSISDN for this operator. This MSISDN should not be used again for message submissions to this operator."; break; case 24: result = "Used when a message is undeliverable because the subscriber is temporarily absent, e.g. his/her phone is switch off, he/she cannot be located on the network. "; break; case 25: result = "Used when the message has failed due to a temporary condition in the operator network. This could be related to the SS7 layer, SMSC or gateway. "; break; case 26: result = "Used when a message has failed due to a temporary phone related error, e.g. SIM card full, SME busy, memory exceeded etc. This does not mean the phone is unable to receive this type of message/content (refer to error code 27)."; break; case 27: result = "Permanent Used when a handset is permanently incompatible or unable to receive this type of message. "; break; case 28: result = "Used if a message fails or is rejected due to suspicion of SPAM on the operator network. This could indicate in some geographies that the operator has no record of the mandatory MO required for an MT. "; break; case 29: result = "Used when this specific content is not permitted on the network / shortcode. "; break; case 30: result = "Used when message fails or is rejected because the subscriber has reached the predetermined spend limit for the current billing period."; break; case 31: result = "Used when the MSISDN is for a valid subscriber on the operator but the message fails or is rejected because the subscriber is unable to be billed, e.g. the subscriber account is suspended (either voluntarily or involuntarily), the subscriber is not enabled for bill-to-phone services, the subscriber is not eligible for bill-to-phone services, etc."; break; case 33: result = "Used when the subscriber cannot receive adult content because of a parental lock. "; break; case 34: result = "Permanent Used when the subscriber cannot receive adult content because they have previously failed the age verification process. "; break; case 35: result = "Temporary Used when the subscriber cannot receive adult content because they have not previously completed age verification. "; break; case 36: result = "Temporary Used when the subscriber cannot receive adult content because a temporary communication error prevents their status being verified on the age verification platform."; break; case 37: result = "The MSISDN is on the national blacklist (currently only for NL: SMS dienstenfilter)"; break; default: break; } return result; } }
package org.rstudio.studio.client.workbench.views.console.shell.assist; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayBoolean; import com.google.gwt.core.client.JsArrayInteger; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import org.rstudio.core.client.SafeHtmlUtil; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.js.JsUtil; import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations; import org.rstudio.studio.client.common.codetools.Completions; import org.rstudio.studio.client.common.codetools.RCompletionType; import org.rstudio.studio.client.common.icons.StandardIcons; import org.rstudio.studio.client.common.r.RToken; import org.rstudio.studio.client.common.r.RTokenizer; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.NavigableSourceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.RFunction; import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeFunction; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.CodeModel; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.DplyrJoinContext; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.RScopeObject; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.TokenCursor; import org.rstudio.studio.client.workbench.views.source.model.RnwChunkOptions; import org.rstudio.studio.client.workbench.views.source.model.RnwChunkOptions.RnwOptionCompletionResult; import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class CompletionRequester { private final CodeToolsServerOperations server_ ; private final NavigableSourceEditor editor_ ; private String cachedLinePrefix_ ; private CompletionResult cachedResult_ ; private RnwCompletionContext rnwContext_ ; public CompletionRequester(CodeToolsServerOperations server, RnwCompletionContext rnwContext, NavigableSourceEditor editor) { server_ = server ; rnwContext_ = rnwContext; editor_ = editor; } private boolean usingCache( final String token, final ServerRequestCallback<CompletionResult> callback) { if (!StringUtil.isNullOrEmpty(token) && cachedResult_ != null) { if (token.toLowerCase().startsWith(cachedLinePrefix_.toLowerCase())) { String diff = token.substring(cachedLinePrefix_.length(), token.length()); if (diff.length() > 0) { ArrayList<RToken> tokens = RTokenizer.asTokens("a" + diff) ; // when we cross a :: the list may actually grow, not shrink if (!diff.endsWith("::")) { while (tokens.size() > 0 && tokens.get(tokens.size()-1).getContent().equals(":")) { tokens.remove(tokens.size()-1) ; } if (tokens.size() == 1 && tokens.get(0).getTokenType() == RToken.ID) { callback.onResponseReceived(narrow(diff)) ; return true; } } } } } return false; } public void getDplyrJoinCompletionsString( final String token, final String string, final String cursorPos, final boolean implicit, final ServerRequestCallback<CompletionResult> callback) { if (usingCache(token, callback)) return; server_.getDplyrJoinCompletionsString( token, string, cursorPos, new ServerRequestCallback<Completions>() { @Override public void onResponseReceived(Completions response) { cachedLinePrefix_ = token; fillCompletionResult(response, implicit, callback); } @Override public void onError(ServerError error) { callback.onError(error); } }); } public void getDplyrJoinCompletions( final DplyrJoinContext joinContext, final boolean implicit, final ServerRequestCallback<CompletionResult> callback) { final String token = joinContext.getToken(); if (usingCache(token, callback)) return; server_.getDplyrJoinCompletions( joinContext.getToken(), joinContext.getLeftData(), joinContext.getRightData(), joinContext.getVerb(), joinContext.getCursorPos(), new ServerRequestCallback<Completions>() { @Override public void onError(ServerError error) { callback.onError(error); } @Override public void onResponseReceived(Completions response) { cachedLinePrefix_ = token; fillCompletionResult(response, implicit, callback); } }); } private void fillCompletionResult( Completions response, boolean implicit, ServerRequestCallback<CompletionResult> callback) { JsArrayString comp = response.getCompletions(); JsArrayString pkgs = response.getPackages(); JsArrayBoolean quote = response.getQuote(); JsArrayInteger type = response.getType(); ArrayList<QualifiedName> newComp = new ArrayList<QualifiedName>(); for (int i = 0; i < comp.length(); i++) { newComp.add(new QualifiedName(comp.get(i), pkgs.get(i), quote.get(i), type.get(i))); } CompletionResult result = new CompletionResult( response.getToken(), newComp, response.getGuessedFunctionName(), response.getSuggestOnAccept(), response.getOverrideInsertParens()); cachedResult_ = response.isCacheable() ? result : null; if (!implicit || result.completions.size() != 0) callback.onResponseReceived(result); } public void getCompletions( final String token, final List<String> assocData, final List<Integer> dataType, final List<Integer> numCommas, final String functionCallString, final String chainDataName, final JsArrayString chainAdditionalArgs, final JsArrayString chainExcludeArgs, final boolean chainExcludeArgsFromObject, final boolean implicit, final ServerRequestCallback<CompletionResult> callback) { if (usingCache(token, callback)) return; doGetCompletions( token, assocData, dataType, numCommas, functionCallString, chainDataName, chainAdditionalArgs, chainExcludeArgs, chainExcludeArgsFromObject, new ServerRequestCallback<Completions>() { @Override public void onError(ServerError error) { callback.onError(error); } @Override public void onResponseReceived(Completions response) { cachedLinePrefix_ = token; String token = response.getToken(); JsArrayString comp = response.getCompletions(); JsArrayString pkgs = response.getPackages(); JsArrayBoolean quote = response.getQuote(); JsArrayInteger type = response.getType(); ArrayList<QualifiedName> newComp = new ArrayList<QualifiedName>(); // Try getting our own function argument completions if (!response.getExcludeOtherCompletions()) { addFunctionArgumentCompletions(token, newComp); addScopedArgumentCompletions(token, newComp); } // Get server completions for (int i = 0; i < comp.length(); i++) newComp.add(new QualifiedName(comp.get(i), pkgs.get(i), quote.get(i), type.get(i))); // Get variable completions from the current scope if (!response.getExcludeOtherCompletions()) { addScopedCompletions(token, newComp, "variable"); addScopedCompletions(token, newComp, "function"); } CompletionResult result = new CompletionResult( response.getToken(), newComp, response.getGuessedFunctionName(), response.getSuggestOnAccept(), response.getOverrideInsertParens()); cachedResult_ = response.isCacheable() ? result : null; if (!implicit || result.completions.size() != 0) callback.onResponseReceived(result); } }) ; } @SuppressWarnings("unused") private ArrayList<QualifiedName> withoutDupes(ArrayList<QualifiedName> completions) { Set<String> names = new HashSet<String>(); ArrayList<QualifiedName> noDupes = new ArrayList<QualifiedName>(); for (int i = 0; i < completions.size(); i++) { if (!names.contains(completions.get(i).name)) { noDupes.add(completions.get(i)); names.add(completions.get(i).name); } } return noDupes; } private void addScopedArgumentCompletions( String token, ArrayList<QualifiedName> completions) { AceEditor editor = (AceEditor) editor_; // NOTE: this will be null in the console, so protect against that if (editor != null) { Position cursorPosition = editor.getSession().getSelection().getCursor(); CodeModel codeModel = editor.getSession().getMode().getCodeModel(); JsArray<RFunction> scopedFunctions = codeModel.getFunctionsInScope(cursorPosition); for (int i = 0; i < scopedFunctions.length(); i++) { RFunction scopedFunction = scopedFunctions.get(i); String functionName = scopedFunction.getFunctionName(); JsArrayString argNames = scopedFunction.getFunctionArgs(); for (int j = 0; j < argNames.length(); j++) { String argName = argNames.get(j); if (argName.startsWith(token)) { if (functionName == null || functionName == "") { completions.add(new QualifiedName( argName, "<anonymous function>" )); } else { completions.add(new QualifiedName( argName, "[" + functionName + "]" )); } } } } } } private void addScopedCompletions( String token, ArrayList<QualifiedName> completions, String type) { AceEditor editor = (AceEditor) editor_; // NOTE: this will be null in the console, so protect against that if (editor != null) { Position cursorPosition = editor.getSession().getSelection().getCursor(); CodeModel codeModel = editor.getSession().getMode().getCodeModel(); JsArray<RScopeObject> scopeVariables = codeModel.getVariablesInScope(cursorPosition); for (int i = 0; i < scopeVariables.length(); i++) { RScopeObject variable = scopeVariables.get(i); if (variable.getToken().startsWith(token) && variable.getType() == type) completions.add(new QualifiedName( variable.getToken(), "<" + variable.getType() + ">" )); } } } private void addFunctionArgumentCompletions( String token, ArrayList<QualifiedName> completions) { AceEditor editor = (AceEditor) editor_; if (editor != null) { Position cursorPosition = editor.getSession().getSelection().getCursor(); CodeModel codeModel = editor.getSession().getMode().getCodeModel(); // Try to see if we can find a function name TokenCursor cursor = codeModel.getTokenCursor(); // NOTE: This can fail if the document is empty if (!cursor.moveToPosition(cursorPosition)) return; if (cursor.currentValue() == "(" || cursor.findOpeningBracket("(", false)) { if (cursor.moveToPreviousToken()) { // Check to see if this really is the name of a function JsArray<ScopeFunction> functionsInScope = codeModel.getAllFunctionScopes(); String tokenName = cursor.currentValue(); for (int i = 0; i < functionsInScope.length(); i++) { ScopeFunction rFunction = functionsInScope.get(i); String fnName = rFunction.getFunctionName(); if (tokenName == fnName) { JsArrayString args = rFunction.getFunctionArgs(); for (int j = 0; j < args.length(); j++) { completions.add(new QualifiedName( args.get(j) + " = ", "[" + fnName + "]" )); } } } } } } } private void doGetCompletions( final String token, final List<String> assocData, final List<Integer> dataType, final List<Integer> numCommas, final String functionCallString, final String chainObjectName, final JsArrayString chainAdditionalArgs, final JsArrayString chainExcludeArgs, final boolean chainExcludeArgsFromObject, final ServerRequestCallback<Completions> requestCallback) { int optionsStartOffset; if (rnwContext_ != null && (optionsStartOffset = rnwContext_.getRnwOptionsStart(token, token.length())) >= 0) { doGetSweaveCompletions(token, optionsStartOffset, token.length(), requestCallback); } else { server_.getCompletions( token, assocData, dataType, numCommas, functionCallString, chainObjectName, chainAdditionalArgs, chainExcludeArgs, chainExcludeArgsFromObject, requestCallback); } } private void doGetSweaveCompletions( final String line, final int optionsStartOffset, final int cursorPos, final ServerRequestCallback<Completions> requestCallback) { rnwContext_.getChunkOptions(new ServerRequestCallback<RnwChunkOptions>() { @Override public void onResponseReceived(RnwChunkOptions options) { RnwOptionCompletionResult result = options.getCompletions( line, optionsStartOffset, cursorPos, rnwContext_ == null ? null : rnwContext_.getActiveRnwWeave()); String[] pkgNames = new String[result.completions.length()]; Arrays.fill(pkgNames, "`chunk-option`"); Completions response = Completions.createCompletions( result.token, result.completions, JsUtil.toJsArrayString(pkgNames), JsUtil.toJsArrayBoolean(new ArrayList<Boolean>(result.completions.length())), JsUtil.toJsArrayInteger(new ArrayList<Integer>(result.completions.length())), "", false, false); // Unlike other completion types, Sweave completions are not // guaranteed to narrow the candidate list (in particular // true/false). response.setCacheable(false); if (result.completions.length() > 0 && result.completions.get(0).endsWith("=")) { response.setSuggestOnAccept(true); } requestCallback.onResponseReceived(response); } @Override public void onError(ServerError error) { requestCallback.onError(error); } }); } public void flushCache() { cachedLinePrefix_ = null ; cachedResult_ = null ; } private CompletionResult narrow(String diff) { String token = cachedResult_.token.toLowerCase() + diff ; ArrayList<QualifiedName> newCompletions = new ArrayList<QualifiedName>() ; for (QualifiedName qname : cachedResult_.completions) if (qname.name.toLowerCase().startsWith(token.toLowerCase())) newCompletions.add(qname) ; return new CompletionResult( token, newCompletions, cachedResult_.guessedFunctionName, cachedResult_.suggestOnAccept, cachedResult_.dontInsertParens) ; } public static class CompletionResult { public CompletionResult(String token, ArrayList<QualifiedName> completions, String guessedFunctionName, boolean suggestOnAccept, boolean dontInsertParens) { this.token = token ; this.completions = completions ; this.guessedFunctionName = guessedFunctionName ; this.suggestOnAccept = suggestOnAccept ; this.dontInsertParens = dontInsertParens ; } public final String token ; public final ArrayList<QualifiedName> completions ; public final String guessedFunctionName ; public final boolean suggestOnAccept ; public final boolean dontInsertParens ; } public static class QualifiedName implements Comparable<QualifiedName> { public QualifiedName( String name, String pkgName, boolean shouldQuote, int type) { this.name = name; this.pkgName = pkgName; this.shouldQuote = shouldQuote; this.type = type; } public QualifiedName(String name, String pkgName) { this.name = name; this.pkgName = pkgName; this.shouldQuote = false; this.type = RCompletionType.UNKNOWN; } @Override public String toString() { SafeHtmlBuilder sb = new SafeHtmlBuilder(); // Get an icon for the completion SafeHtmlUtil.appendImage( sb, RES.styles().completionIcon(), getIcon()); // Get the name for the completion SafeHtmlUtil.appendSpan( sb, RES.styles().completion(), name); // Get the associated package for functions if (type == RCompletionType.FUNCTION) { SafeHtmlUtil.appendSpan( sb, RES.styles().packageName(), "{" + pkgName.replaceAll("package:", "") + "}"); } return sb.toSafeHtml().asString(); } private ImageResource getIcon() { // TODO: fill in for other types return ICONS.function(); } public static QualifiedName parseFromText(String val) { String name, pkgName = ""; int idx = val.indexOf('{') ; if (idx < 0) { name = val ; } else { name = val.substring(0, idx).trim() ; pkgName = val.substring(idx + 1, val.length() - 1) ; } return new QualifiedName(name, pkgName) ; } public int compareTo(QualifiedName o) { if (name.endsWith("=") ^ o.name.endsWith("=")) return name.endsWith("=") ? -1 : 1 ; int result = String.CASE_INSENSITIVE_ORDER.compare(name, o.name) ; if (result != 0) return result ; String pkg = pkgName == null ? "" : pkgName ; String opkg = o.pkgName == null ? "" : o.pkgName ; return pkg.compareTo(opkg) ; } public final String name ; public final String pkgName ; public final boolean shouldQuote ; public final int type ; } private static final CompletionRequesterResources RES = CompletionRequesterResources.INSTANCE; private static final StandardIcons ICONS = StandardIcons.INSTANCE; static { RES.styles().ensureInjected(); } }
package data_objects.drivers; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.Map; import java.util.Properties; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.jruby.Ruby; import org.jruby.RubyBigDecimal; import org.jruby.RubyBignum; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyFloat; import org.jruby.RubyHash; import org.jruby.RubyNumeric; import org.jruby.RubyObjectAdapter; import org.jruby.RubyProc; import org.jruby.RubyRegexp; import org.jruby.RubyString; import org.jruby.RubyTime; import org.jruby.exceptions.RaiseException; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.marshal.UnmarshalStream; import org.jruby.util.ByteList; import data_objects.RubyType; import java.lang.UnsupportedOperationException; import java.math.BigInteger; /** * * @author alexbcoles * @author mkristian */ public abstract class AbstractDriverDefinition implements DriverDefinition { // assuming that API is thread safe protected static final RubyObjectAdapter API = JavaEmbedUtils .newObjectAdapter(); protected final static DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); private final String scheme; private final String jdbcScheme; private final String moduleName; protected AbstractDriverDefinition(String scheme, String moduleName) { this(scheme, scheme, moduleName); } protected AbstractDriverDefinition(String scheme, String jdbcScheme, String moduleName) { this.scheme = scheme; this.jdbcScheme = jdbcScheme; this.moduleName = moduleName; } public String getModuleName() { return this.moduleName; } public String getErrorName() { return this.moduleName + "Error"; } @SuppressWarnings("unchecked") public URI parseConnectionURI(IRubyObject connection_uri) throws URISyntaxException, UnsupportedEncodingException { URI uri; if ("DataObjects::URI".equals(connection_uri.getType().getName())) { String query; StringBuffer userInfo = new StringBuffer(); verifyScheme(stringOrNull(API.callMethod(connection_uri, "scheme"))); String user = stringOrNull(API.callMethod(connection_uri, "user")); String password = stringOrNull(API.callMethod(connection_uri, "password")); String host = stringOrNull(API.callMethod(connection_uri, "host")); int port = intOrMinusOne(API.callMethod(connection_uri, "port")); String path = stringOrNull(API.callMethod(connection_uri, "path")); IRubyObject query_values = API.callMethod(connection_uri, "query"); String fragment = stringOrNull(API.callMethod(connection_uri, "fragment")); if (user != null && !"".equals(user)) { userInfo.append(user); if (password != null && !"".equals(password)) { userInfo.append(":").append(password); } } if (query_values.isNil()) { query = null; } else if (query_values instanceof RubyHash) { query = mapToQueryString(query_values.convertToHash()); } else { query = API.callMethod(query_values, "to_s").asJavaString(); } if (host != null && !"".equals(host)) { // a client/server database (e.g. MySQL, PostgreSQL, MS // SQLServer) String normalizedPath; if (path != null && path.length() > 0 && path.charAt(0) != '/') { normalizedPath = '/' + path; } else { normalizedPath = path; } uri = new URI(this.jdbcScheme, (userInfo.length() > 0 ? userInfo.toString() : null), host, port, normalizedPath, query, fragment); } else { // an embedded / file-based database (e.g. SQLite3, Derby // (embedded mode), HSQLDB - use opaque uri uri = new URI(this.jdbcScheme, path, fragment); } } else { // If connection_uri comes in as a string, we just pass it // through uri = new URI(connection_uri.asJavaString()); } return uri; } protected void verifyScheme(String scheme) { if (!this.scheme.equals(scheme)) { throw new RuntimeException("scheme mismatch, expected: " + this.scheme + " but got: " + scheme); } } /** * Convert a map of key/values to a URI query string * * @param map * @return * @throws java.io.UnsupportedEncodingException */ private String mapToQueryString(Map<Object, Object> map) throws UnsupportedEncodingException { StringBuffer querySb = new StringBuffer(); for (Map.Entry<Object, Object> pairs: map.entrySet()){ String key = (pairs.getKey() != null) ? pairs.getKey().toString() : ""; String value = (pairs.getValue() != null) ? pairs.getValue() .toString() : ""; querySb.append(java.net.URLEncoder.encode(key, "UTF-8")) .append("="); querySb.append(java.net.URLEncoder.encode(value, "UTF-8")); } return querySb.toString(); } public RaiseException newDriverError(Ruby runtime, String message) { RubyClass driverError = runtime.getClass(getErrorName()); return new RaiseException(runtime, driverError, message, true); } public RaiseException newDriverError(Ruby runtime, SQLException exception) { return newDriverError(runtime, exception, null); } public RaiseException newDriverError(Ruby runtime, SQLException exception, java.sql.Statement statement) { RubyClass driverError = runtime.getClass(getErrorName()); int code = exception.getErrorCode(); StringBuffer sb = new StringBuffer("("); // Append the Vendor Code, if there is one // TODO: parse vendor exception codes // TODO: replace 'vendor' with vendor name if (code > 0) sb.append("vendor_errno=").append(code).append(", "); sb.append("sql_state=").append(exception.getSQLState()).append(") "); sb.append(exception.getLocalizedMessage()); if (statement != null) sb.append("\nQuery: ").append(statementToString(statement)); return new RaiseException(runtime, driverError, sb.toString(), true); } public RubyObjectAdapter getObjectAdapter() { return API; } public RubyType jdbcTypeToRubyType(int type, int precision, int scale) { return RubyType.jdbcTypeToRubyType(type, scale); } public final IRubyObject getTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { // TODO assert to needs to be turned on with the java call // better throw something assert (type != null); // this method does not expect a null Ruby Type if (rs == null) {// || rs.wasNull()) { return runtime.getNil(); } return doGetTypecastResultSetValue(runtime, rs, col, type); } protected IRubyObject doGetTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { //System.out.println(rs.getMetaData().getColumnTypeName(col) + " = " + type.toString()); switch (type) { case FIXNUM: case INTEGER: case BIGNUM: try { // in most cases integers will fit into long type // and therefore should be faster to use getLong long lng = rs.getLong(col); if (rs.wasNull()) { return runtime.getNil(); } return RubyNumeric.int2fix(runtime, lng); } catch (SQLException sqle) { // if getLong failed then use getBigDecimal BigDecimal bdi = rs.getBigDecimal(col); if (bdi == null) { return runtime.getNil(); } // will return either Fixnum or Bignum return RubyBignum.bignorm(runtime, bdi.toBigInteger()); } case FLOAT: // TODO: why getDouble is not used here? BigDecimal bdf = rs.getBigDecimal(col); if (bdf == null) { return runtime.getNil(); } return new RubyFloat(runtime, bdf.doubleValue()); case BIG_DECIMAL: BigDecimal bd = rs.getBigDecimal(col); if (bd == null) { return runtime.getNil(); } return new RubyBigDecimal(runtime, bd); case DATE: java.sql.Date date = rs.getDate(col); if (date == null) { return runtime.getNil(); } return prepareRubyDateFromSqlDate(runtime, sqlDateToDateTime(date)); case DATE_TIME: java.sql.Timestamp dt = null; // DateTimes with all-zero components throw a SQLException with // SQLState S1009 in MySQL Connector/J 3.1+ // See try { dt = rs.getTimestamp(col); } catch (SQLException ignored) { } if (dt == null) { return runtime.getNil(); } return prepareRubyDateTimeFromSqlTimestamp(runtime, sqlTimestampToDateTime(dt)); case TIME: switch (rs.getMetaData().getColumnType(col)) { case Types.TIME: java.sql.Time tm = rs.getTime(col); if (tm == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm)); case Types.TIMESTAMP: java.sql.Timestamp ts = rs.getTimestamp(col); if (ts == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, sqlTimestampToDateTime(ts)); case Types.DATE: java.sql.Date da = rs.getDate(col); if (da == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlDate(runtime, da); default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } case TRUE_CLASS: // getBoolean delivers False in case the underlying data is null if (rs.getString(col) == null){ return runtime.getNil(); } return runtime.newBoolean(rs.getBoolean(col)); case BYTE_ARRAY: InputStream binaryStream = rs.getBinaryStream(col); ByteList bytes = new ByteList(2048); try { byte[] buf = new byte[2048]; for (int n = binaryStream.read(buf); n != -1; n = binaryStream .read(buf)) { bytes.append(buf, 0, n); } } finally { binaryStream.close(); } return API.callMethod(runtime.fastGetModule("Extlib").fastGetClass( "ByteArray"), "new", runtime.newString(bytes)); case CLASS: String classNameStr = rs.getString(col); if (classNameStr == null) { return runtime.getNil(); } RubyString class_name_str = RubyString.newUnicodeString(runtime, rs .getString(col)); class_name_str.setTaint(true); return API.callMethod(runtime.getObject(), "full_const_get", class_name_str); case OBJECT: InputStream asciiStream = rs.getAsciiStream(col); IRubyObject obj = runtime.getNil(); try { UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream, RubyProc.NEVER); obj = ums.unmarshalObject(); } catch (IOException ioe) { // TODO: log this } return obj; case NIL: return runtime.getNil(); case STRING: default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } } public void setPreparedStatementParam(PreparedStatement ps, IRubyObject arg, int idx) throws SQLException { switch (RubyType.getRubyType(arg.getType().getName())) { case FIXNUM: ps.setInt(idx, Integer.parseInt(arg.toString())); break; case BIGNUM: BigInteger big = ((RubyBignum) arg).getValue(); int BIT_SIZE = 64; long MAX = (1L << (BIT_SIZE - 1)) - 1; BigInteger LONG_MAX = BigInteger.valueOf(MAX); BigInteger LONG_MIN = BigInteger.valueOf(-MAX - 1); if (big.compareTo(LONG_MIN) < 0 || big.compareTo(LONG_MAX) > 0) { // set as big decimal System.out.println(arg.toString() + "cannot be treated as a long"); ps.setString(idx, arg.toString()); //ps.setBigDecimal(idx, new BigDecimal(((RubyBignum) arg).getValue())); } else { // set as long ps.setLong(idx, ((RubyBignum) arg).getLongValue()); } break; case FLOAT: ps.setDouble(idx, RubyNumeric.num2dbl(arg)); break; case BIG_DECIMAL: ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue()); break; case NIL: ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx)); break; case TRUE_CLASS: case FALSE_CLASS: ps.setBoolean(idx, arg.toString().equals("true")); break; case STRING: ps.setString(idx, arg.toString()); break; case CLASS: ps.setString(idx, arg.toString()); break; case BYTE_ARRAY: ps.setBytes(idx, ((RubyString) arg).getBytes()); break; // TODO: add support for ps.setBlob(); case DATE: ps.setDate(idx, java.sql.Date.valueOf(arg.toString())); break; case TIME: DateTime dateTime = ((RubyTime) arg).getDateTime(); Timestamp ts = new Timestamp(dateTime.getMillis()); ps.setTimestamp(idx, ts, dateTime.toGregorianCalendar()); break; case DATE_TIME: String datetime = arg.toString().replace('T', ' '); ps.setTimestamp(idx, Timestamp.valueOf(datetime .replaceFirst("[-+]..:..$", ""))); break; case REGEXP: ps.setString(idx, ((RubyRegexp) arg).source().toString()); break; // default case handling is simplified // TODO: if something is not working because of that then should be added to specs default: int jdbcType = ps.getParameterMetaData().getParameterType(idx); ps.setObject(idx, arg.toString(), jdbcType); } } public boolean registerPreparedStatementReturnParam(String sqlText, PreparedStatement ps, int idx) throws SQLException { return false; } public long getPreparedStatementReturnParam(PreparedStatement ps) throws SQLException { return 0; } public String prepareSqlTextForPs(String sqlText, IRubyObject[] args) { return sqlText; } public abstract boolean supportsJdbcGeneratedKeys(); public abstract boolean supportsJdbcScrollableResultSets(); public boolean supportsConnectionEncodings() { return false; } public boolean supportsConnectionPrepareStatementMethodWithGKFlag() { return true; } public ResultSet getGeneratedKeys(Connection connection) { return null; } public Properties getDefaultConnectionProperties() { return new Properties(); } public void afterConnectionCallback(IRubyObject doConn, Connection conn, Map<String, String> query) throws SQLException { // do nothing } public void setEncodingProperty(Properties props, String encodingName) { // do nothing } public Connection getConnectionWithEncoding(Ruby runtime, IRubyObject connection, String url, Properties props) throws SQLException { throw new UnsupportedOperationException("This method only returns a method" + " for drivers that support specifiying an encoding."); } public String quoteString(String str) { StringBuffer quotedValue = new StringBuffer(str.length() + 2); quotedValue.append("\'"); quotedValue.append(str.replaceAll("'", "''")); quotedValue.append("\'"); return quotedValue.toString(); } public String quoteByteArray(IRubyObject connection, IRubyObject value) { return quoteString(value.asJavaString()); } public String statementToString(Statement s) { return s.toString(); } protected static DateTime sqlDateToDateTime(Date date) { date.getYear(); if (date == null) return null; else return new DateTime(date.getYear()+1900, date.getMonth()+1, date.getDate(), 0, 0, 0, 0); } protected static DateTime sqlTimestampToDateTime(Timestamp ts) { if (ts == null) return null; return new DateTime(ts.getYear()+1900, ts.getMonth()+1, ts.getDate(), ts.getHours(), ts.getMinutes(), ts.getSeconds(), ts.getNanos()/1000000); } protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp( Ruby runtime, DateTime stamp) { if (stamp.getMillis() == 0) { return runtime.getNil(); } int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod( runtime.getCurrentContext(), "new", new IRubyObject[] { runtime.newFixnum(zoneOffset), runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(stamp.getYear()), runtime.newFixnum(stamp.getMonthOfYear()), runtime.newFixnum(stamp.getDayOfMonth()), runtime.newFixnum(stamp.getHourOfDay()), runtime.newFixnum(stamp.getMinuteOfHour()), runtime.newFixnum(stamp.getSecondOfMinute()), rbOffset }); } protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime, DateTime time) { // TODO: why in this case nil is returned? if (time.getMillis() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, time); return rbTime; } protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime, Date date) { if (date.getTime() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, date.getTime()); return rbTime; } public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime, DateTime date) { if (date.getMillis() == 0) { return runtime.getNil(); } RubyClass klazz = runtime.fastGetClass("Date"); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(date.getYear()), runtime.newFixnum(date.getMonthOfYear()), runtime.newFixnum(date.getDayOfMonth()) }); } private static String stringOrNull(IRubyObject obj) { return (!obj.isNil()) ? obj.asJavaString() : null; } private static int intOrMinusOne(IRubyObject obj) { return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1; } // private static Integer integerOrNull(IRubyObject obj) { // return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null; }
package org.openlmis.referencedata.repository.custom.impl; import static org.springframework.util.CollectionUtils.isEmpty; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.tuple.Pair; import org.hibernate.SQLQuery; import org.hibernate.type.IntegerType; import org.hibernate.type.LongType; import org.hibernate.type.PostgresUUIDType; import org.hibernate.type.StringType; import org.openlmis.referencedata.domain.CommodityType; import org.openlmis.referencedata.domain.Facility; import org.openlmis.referencedata.domain.IdealStockAmount; import org.openlmis.referencedata.domain.ProcessingPeriod; import org.openlmis.referencedata.domain.ProcessingSchedule; import org.openlmis.referencedata.repository.custom.IdealStockAmountRepositoryCustom; import org.openlmis.referencedata.util.Pagination; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; public class IdealStockAmountRepositoryImpl implements IdealStockAmountRepositoryCustom { private static final String SEARCH_SQL = "SELECT" + " isa.id AS isa_id, isa.amount as isa_amount," + " f.id AS facility_id, f.code AS facility_code," + " c.id AS commodity_id, c.classificationid AS classification_id," + " c.classificationsystem AS classification_system, p.id AS period_id," + " p.name AS period_name, s.code AS schedule_code" + " FROM referencedata.ideal_stock_amounts isa" + " INNER JOIN referencedata.facilities f ON isa.facilityid = f.id" + " INNER JOIN referencedata.commodity_types c ON isa.commoditytypeid = c.id" + " INNER JOIN referencedata.processing_periods p ON isa.processingperiodid = p.id" + " INNER JOIN referencedata.processing_schedules s ON p.processingscheduleid = s.id"; private static final String MINIMAL_SEARCH_SQL = "SELECT" + " id AS isa_id," + " amount as isa_amount," + " facilityid AS facility_id," + " commoditytypeid AS commodity_id," + " processingperiodid AS period_id" + " FROM referencedata.ideal_stock_amounts"; private static final String COUNT_SEARCH_SQL = "SELECT" + " count(*) AS count" + " FROM referencedata.ideal_stock_amounts"; private static final String WHERE = "WHERE"; private static final String OR = " OR "; private static final String WITH_FACILITY_ID = "facilityid = :facilityId"; private static final String WITH_COMMODITYTYPE_ID = "commoditytypeid = :commodityTypeId"; private static final String WITH_PROCESSING_PERIOD_ID = "processingperiodid = :processingPeriodId"; private static final int ISA_ID = 0; private static final int ISA_AMOUNT = 1; private static final int FACILITY_ID = 2; private static final int COMMODITY_ID = 3; private static final int PERIOD_ID = 4; @PersistenceContext private EntityManager entityManager; /** * This method is supposed to retrieve all IdealStockAmounts that are present in given list. * List does not have to contain whole objects, just properties that will be used: * facility.code, processingPeriod.name, processingPeriod.processingSchedule.code, * commodityType.classificationId, commodityType.classificationSystem * * @param idealStockAmounts list of ideal stock amounts with required fields * @return List of found Ideal Stock Amounts. */ public List<IdealStockAmount> search(List<IdealStockAmount> idealStockAmounts) { Query query = createQuery(idealStockAmounts); prepareQuery(query); // hibernate always returns a list of array of objects @SuppressWarnings("unchecked") List<Object[]> list = Collections.checkedList(query.getResultList(), Object[].class); return list.stream().map(this::toIsa).collect(Collectors.toList()); } /** * This method is supposed to retrieve all IdealStockAmounts that are present in given params. * List does not contain whole objects, just id f nested objects * * @return List of found Ideal Stock Amounts. */ @Override public Page<IdealStockAmount> search(UUID facilityId, UUID commodityTypeId, UUID processingPeriodId, Pageable pageable) { Query query = createQuery(MINIMAL_SEARCH_SQL, facilityId, commodityTypeId, processingPeriodId); Query countQuery = createQuery(COUNT_SEARCH_SQL, facilityId, commodityTypeId, processingPeriodId); prepareMinimalQuery(query); prepareCountQuery(countQuery); // appropriate scalar is added to native query @SuppressWarnings("unchecked") List<Long> count = countQuery.getResultList(); if (count.get(0) == 0) { return Pagination.getPage(Collections.emptyList(), pageable, 0); } Pair<Integer, Integer> maxAndFirst = PageableUtil.querysMaxAndFirstResult(pageable); // hibernate returns a list of array of objects @SuppressWarnings("unchecked") List<Object[]> resultList = query .setMaxResults(maxAndFirst.getLeft()) .setFirstResult(maxAndFirst.getRight()) .getResultList(); List<IdealStockAmount> result = resultList.stream() .map(this::toMinimalIsa) .collect(Collectors.toList()); return Pagination.getPage(result, pageable, count.get(0)); } private IdealStockAmount toIsa(Object[] values) { Facility facility = new Facility((String) values[5]); facility.setId((UUID) values[FACILITY_ID]); ProcessingSchedule schedule = new ProcessingSchedule(); schedule.setCode((String) values[9]); ProcessingPeriod period = new ProcessingPeriod(); period.setId((UUID) values[PERIOD_ID]); period.setName((String) values[8]); period.setProcessingSchedule(schedule); CommodityType commodityType = new CommodityType(); commodityType.setId((UUID) values[COMMODITY_ID]); commodityType.setClassificationId((String) values[6]); commodityType.setClassificationSystem((String) values[7]); IdealStockAmount result = new IdealStockAmount(facility, commodityType, period, (Integer) values[ISA_AMOUNT]); result.setId((UUID) values[ISA_ID]); return result; } private IdealStockAmount toMinimalIsa(Object[] values) { Facility facility = new Facility((UUID) values[FACILITY_ID]); ProcessingPeriod period = new ProcessingPeriod(); period.setId((UUID) values[PERIOD_ID]); CommodityType commodityType = new CommodityType(); commodityType.setId((UUID) values[COMMODITY_ID]); IdealStockAmount result = new IdealStockAmount(facility, commodityType, period, (Integer) values[ISA_AMOUNT]); result.setId((UUID) values[ISA_ID]); return result; } private void prepareQuery(Query query) { SQLQuery sql = prepareMinimalQuery(query); sql.addScalar("facility_code", StringType.INSTANCE); sql.addScalar("classification_id", StringType.INSTANCE); sql.addScalar("classification_system", StringType.INSTANCE); sql.addScalar("period_name", StringType.INSTANCE); sql.addScalar("schedule_code", StringType.INSTANCE); } private SQLQuery prepareMinimalQuery(Query query) { SQLQuery sql = query.unwrap(SQLQuery.class); sql.addScalar("isa_id", PostgresUUIDType.INSTANCE); sql.addScalar("isa_amount", IntegerType.INSTANCE); sql.addScalar("facility_id", PostgresUUIDType.INSTANCE); sql.addScalar("commodity_id", PostgresUUIDType.INSTANCE); sql.addScalar("period_id", PostgresUUIDType.INSTANCE); return sql; } private void prepareCountQuery(Query query) { SQLQuery sql = query.unwrap(SQLQuery.class); sql.addScalar("count", LongType.INSTANCE); } private Query createQuery(List<IdealStockAmount> idealStockAmounts) { StringBuilder builder = new StringBuilder(SEARCH_SQL); if (!isEmpty(idealStockAmounts)) { builder.append(" WHERE"); for (int i = 0, size = idealStockAmounts.size(); i < size; ++i) { IdealStockAmount isa = idealStockAmounts.get(i); builder .append(" (f.code = '") .append(isa.getFacility().getCode()) .append("' AND c.classificationid = '") .append(isa.getCommodityType().getClassificationId()) .append("' AND c.classificationsystem = '") .append(isa.getCommodityType().getClassificationSystem()) .append("' AND p.name = '") .append(isa.getProcessingPeriod().getName()) .append("' AND s.code = '") .append(isa.getProcessingPeriod().getProcessingSchedule().getCode()) .append("')"); if (i + 1 < size) { builder.append(" OR"); } } } return entityManager.createNativeQuery(builder.toString()); } private Query createQuery(String searchSql, UUID facilityId, UUID commodityTypeId, UUID processingPeriodId) { List<String> sql = Lists.newArrayList(searchSql); List<String> where = Lists.newArrayList(); Map<String, Object> params = Maps.newHashMap(); if (facilityId != null) { where.add(WITH_FACILITY_ID); params.put("facilityId", facilityId); } if (commodityTypeId != null) { where.add(WITH_COMMODITYTYPE_ID); params.put("commodityTypeId", commodityTypeId); } if (processingPeriodId != null) { where.add(WITH_PROCESSING_PERIOD_ID); params.put("processingPeriodId", processingPeriodId); } if (!where.isEmpty()) { sql.add(WHERE); sql.add(Joiner.on(OR).join(where)); } String query = Joiner.on(' ').join(sql); Query nativeQuery = entityManager.createNativeQuery(query); params.forEach(nativeQuery::setParameter); return nativeQuery; } }
package org.openlmis.referencedata.repository.custom.impl; import org.openlmis.referencedata.domain.Program; import org.openlmis.referencedata.domain.RequisitionGroup; import org.openlmis.referencedata.domain.RequisitionGroupProgramSchedule; import org.openlmis.referencedata.domain.SupervisoryNode; import org.openlmis.referencedata.repository.custom.RequisitionGroupRepositoryCustom; import org.openlmis.referencedata.util.Pagination; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.List; public class RequisitionGroupRepositoryImpl implements RequisitionGroupRepositoryCustom { private static final String CODE = "code"; private static final String NAME = "name"; private static final String PROGRAM = "program"; private static final String PROGRAM_SCHEDULES = "requisitionGroupProgramSchedules"; private static final String SUPERVISORY_NODE = "supervisoryNode"; @PersistenceContext private EntityManager entityManager; /** * This method is supposed to retrieve all facilities with matched parameters. * Method is ignoring case for facility code and name. * To find all wanted Facilities by conde and name we use criteria query and like operator. * * @param code Part of wanted code. * @param name Part of wanted name. * @param program Geographic zone of facility location. * @param supervisoryNodes Wanted facility type. * @return List of Facilities matching the parameters. */ public Page<RequisitionGroup> search(String code, String name, Program program, List<SupervisoryNode> supervisoryNodes, Pageable pageable) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<RequisitionGroup> query = builder.createQuery(RequisitionGroup.class); CriteriaQuery<Long> countQuery = builder.createQuery(Long.class); query = prepareQuery(query, code, name, program, supervisoryNodes, false); countQuery = prepareQuery(countQuery, code, name, program, supervisoryNodes, true); Long count = entityManager.createQuery(countQuery).getSingleResult(); List<RequisitionGroup> result = entityManager.createQuery(query) .setMaxResults(pageable.getPageSize()) .setFirstResult(pageable.getPageNumber() * pageable.getPageSize()) .getResultList(); return Pagination.getPage(result, pageable, count); } private <T> CriteriaQuery<T> prepareQuery(CriteriaQuery<T> query, String code, String name, Program program, List<SupervisoryNode> supervisoryNodes, boolean count) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); Root<RequisitionGroup> root = query.from(RequisitionGroup.class); if (count) { CriteriaQuery<Long> countQuery = (CriteriaQuery<Long>) query; query = (CriteriaQuery<T>) countQuery.select(builder.count(root)); } Predicate predicate = builder.conjunction(); if (code != null) { predicate = builder.and(predicate, builder.like(builder.upper(root.get(CODE)), "%" + code.toUpperCase() + "%")); } if (name != null) { predicate = builder.and(predicate, builder.like(builder.upper(root.get(NAME)), "%" + name.toUpperCase() + "%")); } if (program != null) { Join<RequisitionGroup, RequisitionGroupProgramSchedule> programSchedulesJoin = root.join(PROGRAM_SCHEDULES, JoinType.LEFT); predicate = builder.and(predicate, builder.equal(programSchedulesJoin.get(PROGRAM), program)); } if (supervisoryNodes != null && !supervisoryNodes.isEmpty()) { if (supervisoryNodes.size() == 1) { predicate = builder.and(predicate, builder.equal(root.get(SUPERVISORY_NODE), supervisoryNodes.get(0))); } else { Predicate supervisoryNodePredicate = builder.disjunction(); for (SupervisoryNode node : supervisoryNodes) { supervisoryNodePredicate = builder.or(supervisoryNodePredicate, builder.equal(root.get(SUPERVISORY_NODE), node)); } predicate = builder.and(supervisoryNodePredicate); } } return query.where(predicate); } }
package org.spongepowered.common.mixin.core.entity.projectile; import net.minecraft.entity.item.ExperienceOrbEntity; import net.minecraft.entity.item.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.projectile.FishingBobberEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.stats.Stats; import net.minecraft.tags.ItemTags; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.server.ServerWorld; import net.minecraft.world.storage.loot.LootContext; import net.minecraft.world.storage.loot.LootParameterSets; import net.minecraft.world.storage.loot.LootParameters; import net.minecraft.world.storage.loot.LootTable; import net.minecraft.world.storage.loot.LootTables; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.projectile.FishingBobber; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.projectile.source.ProjectileSource; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.entity.projectile.ProjectileSourceSerializer; import org.spongepowered.common.item.util.ItemStackUtil; import org.spongepowered.common.mixin.core.entity.EntityMixin; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nullable; @Mixin(FishingBobberEntity.class) public abstract class FishingBobberEntityMixin extends EntityMixin { @Shadow @Nullable private PlayerEntity angler; @Shadow @Nullable public net.minecraft.entity.Entity caughtEntity; @Shadow private int ticksCatchable; @Shadow private int luck; @Shadow private boolean inGround; @Shadow protected abstract void bringInHookedEntity(); @Nullable private ProjectileSource impl$projectileSource; @Inject(method = "setHookedEntity", at = @At("HEAD"), cancellable = true) private void onSetHookedEntity(CallbackInfo ci) { if (SpongeImpl.postEvent(SpongeEventFactory.createFishingEventHookEntity(Sponge.getCauseStackManager().getCurrentCause(), (Entity) this.caughtEntity, (FishingBobber) this))) { this.caughtEntity = null; ci.cancel(); } } /** * @author Aaron1011 - February 6th, 2015 * @author Minecrell - December 24th, 2016 (Updated to Minecraft 1.11.2) * @author Minecrell - June 14th, 2017 (Rewritten to handle cases where no items are dropped) * @reason This needs to handle for both cases where a fish and/or an entity is being caught. */ @Overwrite public int handleHookRetraction(ItemStack stack) { if (!this.world.isRemote && this.angler != null) { int i = 0; // Sponge start final List<Transaction<ItemStackSnapshot>> transactions; if (this.ticksCatchable > 0) { // Moved from below final LootContext.Builder lootcontext$builder = new LootContext.Builder((ServerWorld)this.world) .withParameter(LootParameters.POSITION, new BlockPos((FishingBobberEntity) (Object) this)) .withParameter(LootParameters.TOOL, stack) .withRandom(this.rand) .withLuck((float)this.luck + this.angler.getLuck()); final LootTable lootTable = this.world.getServer().getLootTableManager().getLootTableFromLocation(LootTables.GAMEPLAY_FISHING); final List<ItemStack> list = lootTable.generate(lootcontext$builder.build(LootParameterSets.FISHING)); transactions = list.stream().map(ItemStackUtil::snapshotOf) .map(snapshot -> new Transaction<>(snapshot, snapshot)) .collect(Collectors.toList()); } else { transactions = new ArrayList<>(); } Sponge.getCauseStackManager().pushCause(this.angler); if (SpongeImpl.postEvent(SpongeEventFactory.createFishingEventStop(Sponge.getCauseStackManager().getCurrentCause(), ((FishingBobber) this), transactions))) { // Event is cancelled return -1; } if (this.caughtEntity != null) { this.bringInHookedEntity(); this.world.setEntityState((net.minecraft.entity.Entity) (Object) this, (byte) 31); i = this.caughtEntity instanceof ItemEntity ? 3 : 5; } // Sponge: Remove else // Sponge start - Moved up to event call if (!transactions.isEmpty()) { // Sponge: Check if we have any transactions instead //LootContext.Builder lootcontext$builder = new LootContext.Builder((WorldServer) this.world); //lootcontext$builder.withLuck((float) this.field_191518_aw + this.angler.getLuck()); // Use transactions for (Transaction<ItemStackSnapshot> transaction : transactions) { if (!transaction.isValid()) { continue; } ItemStack itemstack = (ItemStack) (Object) transaction.getFinal().createStack(); // Sponge end ItemEntity entityitem = new ItemEntity(this.world, this.posX, this.posY, this.posZ, itemstack); double d0 = this.angler.posX - this.posX; double d1 = this.angler.posY - this.posY; double d2 = this.angler.posZ - this.posZ; double d3 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); //double d4 = 0.1D; entityitem.setMotion(d0 * 0.1D, d1 * 0.1D + MathHelper.sqrt(d3) * 0.08D, d2 * 0.1D); this.world.addEntity(entityitem); this.angler.world.addEntity(new ExperienceOrbEntity(this.angler.world, this.angler.posX, this.angler.posY + 0.5D, this.angler.posZ + 0.5D, this.rand.nextInt(6) + 1)); Item item = itemstack.getItem(); if (item.isIn(ItemTags.FISHES)) { this.angler.addStat(Stats.FISH_CAUGHT, 1); } } Sponge.getCauseStackManager().popCause(); i = Math.max(i, 1); // Sponge: Don't lower damage if we've also caught an entity } if (this.inGround) { i = 2; } this.shadow$remove(); return i; } else { return 0; } } @Override public void impl$readFromSpongeCompound(CompoundNBT compound) { super.impl$readFromSpongeCompound(compound); ProjectileSourceSerializer.readSourceFromNbt(compound, ((FishingBobber) this)); } @Override public void impl$writeToSpongeCompound(CompoundNBT compound) { super.impl$writeToSpongeCompound(compound); ProjectileSourceSerializer.writeSourceToNbt(compound, ((FishingBobber) this).shooter().get(), this.angler); } }
package ca.corefacility.bioinformatics.irida.ria.unit.web.services; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.springframework.context.MessageSource; import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectMetadataTemplateJoin; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplate; import ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField; import ca.corefacility.bioinformatics.irida.ria.web.services.UIMetadataService; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.sample.MetadataTemplateService; import com.google.common.collect.ImmutableList; import static org.mockito.Mockito.*; public class UIMetadataServiceTest { private final Long PROJECT_ID = 1L; private final String TEMPLATE_NAME = "TEST TEMPLATE 01"; private final Long NEW_TEMPLATE_ID = 2L; private final Project project = new Project(); private final MetadataTemplate template = new MetadataTemplate(); private ProjectService projectService; private MetadataTemplateService templateService; private MessageSource messageSource; private UIMetadataService service; @Before public void setup() { this.projectService = Mockito.mock(ProjectService.class); this.templateService = Mockito.mock(MetadataTemplateService.class); this.messageSource = Mockito.mock(MessageSource.class); this.service = new UIMetadataService(projectService, templateService, messageSource); project.setId(PROJECT_ID); when(projectService.read(PROJECT_ID)).thenReturn(project); template.setName(TEMPLATE_NAME); template.setFields(ImmutableList.of(new MetadataTemplateField("FIELD 1", "text"))); ProjectMetadataTemplateJoin projectMetadataTemplateJoin = new ProjectMetadataTemplateJoin(project, template); when(templateService.getMetadataTemplatesForProject(project)).thenReturn( ImmutableList.of(projectMetadataTemplateJoin)); MetadataTemplate newTemplate = new MetadataTemplate(template.getName(), template.getFields()); newTemplate.setId(NEW_TEMPLATE_ID); when(templateService.createMetadataTemplateInProject(template, project)).thenReturn(new ProjectMetadataTemplateJoin(project, newTemplate)); } @Test public void testGetProjectMetadataTemplates() { List<MetadataTemplate> join = service.getProjectMetadataTemplates(PROJECT_ID); verify(projectService, times(1)).read(PROJECT_ID); verify(templateService, times(1)).getMetadataTemplatesForProject(project); Assert.assertEquals("Should have 1 template", 1, join.size()); Assert.assertEquals("Should have the correct template name", TEMPLATE_NAME, join.get(0).getName()); } @Test public void testCreateMetadataTemplate() { MetadataTemplate newTemplate = service.createMetadataTemplate(template, PROJECT_ID); verify(projectService, times(1)).read(PROJECT_ID); verify(templateService, times(1)).createMetadataTemplateInProject(template, project); Assert.assertEquals("Should have the same template name", template.getLabel(), newTemplate.getName()); Assert.assertEquals("Should have a new identifier", NEW_TEMPLATE_ID, newTemplate.getId()); } }
package com.codekidlabs.storagechooser.fragments; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.Animatable; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.support.v4.app.DialogFragment; import android.support.v4.content.ContextCompat; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.codekidlabs.storagechooser.R; import com.codekidlabs.storagechooser.StorageChooser; import com.codekidlabs.storagechooser.Content; import com.codekidlabs.storagechooser.adapters.SecondaryChooserAdapter; import com.codekidlabs.storagechooser.models.Config; import com.codekidlabs.storagechooser.utils.DiskUtil; import com.codekidlabs.storagechooser.utils.FileUtil; import com.codekidlabs.storagechooser.utils.ResourceUtil; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SecondaryChooserFragment extends android.app.DialogFragment { private View mLayout; private View mInactiveGradient; private ViewGroup mContainer; private TextView mPathChosen; private ImageButton mBackButton; private Button mSelectButton; private Button mCreateButton; private ImageView mNewFolderImageView; private EditText mFolderNameEditText; private RelativeLayout mNewFolderView; private String mBundlePath; private ListView listView; private static final String INTERNAL_STORAGE_TITLE = "Internal Storage"; private static final String EXTERNAL_STORAGE_TITLE = "ExtSD"; private static final int FLAG_DISSMISS_NORMAL = 0; private static final int FLAG_DISSMISS_INIT_DIALOG = 1; private boolean isOpen; private static String theSelectedPath = ""; private static String mAddressClippedPath = ""; private List<String> customStoragesList; private SecondaryChooserAdapter secondaryChooserAdapter; private FileUtil fileUtil; private Config mConfig; private Content mContent; private Context mContext; private Handler mHandler; private ResourceUtil mResourceUtil; private View.OnClickListener mSelectButtonClickListener = new View.OnClickListener() { @Override public void onClick(View view) { if(mConfig.isActionSave()) { DiskUtil.saveChooserPathPreference(mConfig.getPreference(), theSelectedPath); } else { Log.d("StorageChooser", "Chosen path: " + theSelectedPath); } StorageChooser.onSelectListener.onSelect(theSelectedPath); dissmissDialog(FLAG_DISSMISS_NORMAL); } }; private View.OnClickListener mBackButtonClickListener = new View.OnClickListener() { @Override public void onClick(View view) { performBackAction(); } }; private View.OnClickListener mNewFolderButtonClickListener = new View.OnClickListener() { @Override public void onClick(View view) { showAddFolderView(); } }; private View.OnClickListener mNewFolderButtonCloseListener = new View.OnClickListener() { @Override public void onClick(View view) { hideAddFolderView(); hideKeyboard(); } }; private View.OnClickListener mCreateButtonClickListener = new View.OnClickListener() { @Override public void onClick(View view) { if(validateFolderName()) { boolean success = FileUtil.createDirectory(mFolderNameEditText.getText().toString().trim(), theSelectedPath); if(success) { Toast.makeText(mContext, mContent.getFolderCreatedToastText(), Toast.LENGTH_SHORT).show(); trimPopulate(theSelectedPath); hideKeyboard(); hideAddFolderView(); } else { Toast.makeText(mContext, mContent.getFolderErrorToastText(), Toast.LENGTH_SHORT).show(); } } } }; private boolean keyboardToggle; private String TAG = "StorageChooser"; private boolean isFilePicker; private void showAddFolderView() { mNewFolderView.setVisibility(View.VISIBLE); Animation anim = AnimationUtils.loadAnimation(mContext, R.anim.anim_new_folder_view); mNewFolderView.startAnimation(anim); mInactiveGradient.startAnimation(anim); if (DiskUtil.isLollipopAndAbove()) { mNewFolderImageView.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.drawable_plus_to_close)); // image button animation Animatable animatable = (Animatable) mNewFolderImageView.getDrawable(); animatable.start(); } mNewFolderImageView.setOnClickListener(mNewFolderButtonCloseListener); // mNewFolderButton.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.window_close)); //listview should not be clickable SecondaryChooserAdapter.shouldEnable = false; } private void hideAddFolderView() { Animation anim = AnimationUtils.loadAnimation(mContext, R.anim.anim_close_folder_view); mNewFolderView.startAnimation(anim); mNewFolderView.setVisibility(View.INVISIBLE); if (DiskUtil.isLollipopAndAbove()) { mNewFolderImageView.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.drawable_close_to_plus)); // image button animation Animatable animatable = (Animatable) mNewFolderImageView.getDrawable(); animatable.start(); } mNewFolderImageView.setOnClickListener(mNewFolderButtonClickListener); //listview should be clickable SecondaryChooserAdapter.shouldEnable = true; mInactiveGradient.startAnimation(anim); mInactiveGradient.setVisibility(View.INVISIBLE); // mNewFolderButton.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.plus)); } private boolean isFolderViewVisible() { return mNewFolderView.getVisibility() == View.VISIBLE; } public void hideKeyboard() { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mFolderNameEditText.getWindowToken(), 0); } private void performBackAction() { int slashIndex = theSelectedPath.lastIndexOf("/"); if(!mConfig.isSkipOverview()) { if(theSelectedPath.equals(mBundlePath)) { SecondaryChooserFragment.this.dismiss(); //delay until close animation ends mHandler.postDelayed(new Runnable() { @Override public void run() { dissmissDialog(FLAG_DISSMISS_INIT_DIALOG); } }, 200); } else { theSelectedPath = theSelectedPath.substring(0, slashIndex); Log.e("SCLib", "Performing back action: " + theSelectedPath); StorageChooser.LAST_SESSION_PATH = theSelectedPath; populateList(""); } } else { dissmissDialog(FLAG_DISSMISS_NORMAL); } } private void dissmissDialog(int flag) { switch (flag) { case FLAG_DISSMISS_INIT_DIALOG: ChooserDialogFragment c = new ChooserDialogFragment(); c.show(mConfig.getFragmentManager(), "storagechooser_dialog"); break; case FLAG_DISSMISS_NORMAL: StorageChooser.LAST_SESSION_PATH = theSelectedPath; this.dismiss(); break; } } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContainer = container; if (getShowsDialog()) { // one could return null here, or be nice and call super() return super.onCreateView(inflater, container, savedInstanceState); } return getLayout(inflater, container); } private View getLayout(LayoutInflater inflater, ViewGroup container) { mConfig = StorageChooser.sConfig; mHandler = new Handler(); // init storage-chooser content [localization] if(mConfig.getContent() == null) { mContent = new Content(); } else { mContent = mConfig.getContent(); } mContext = getActivity().getApplicationContext(); mResourceUtil = new ResourceUtil(mContext); mLayout = inflater.inflate(R.layout.custom_storage_list, container, false); initListView(mContext, mLayout, mConfig.isShowMemoryBar()); initUI(); initNewFolderView(); updateUI(); return mLayout; } private void initUI() { mBackButton = (ImageButton) mLayout.findViewById(R.id.back_button); mSelectButton = (Button) mLayout.findViewById(R.id.select_button); mCreateButton = (Button) mLayout.findViewById(R.id.create_folder_button); mNewFolderView = (RelativeLayout) mLayout.findViewById(R.id.new_folder_view); mFolderNameEditText = (EditText) mLayout.findViewById(R.id.et_folder_name); mInactiveGradient = mLayout.findViewById(R.id.inactive_gradient); } private void updateUI() { //at start dont show the new folder view unless user clicks on the add/plus button mNewFolderView.setVisibility(View.INVISIBLE); mInactiveGradient.setVisibility(View.INVISIBLE); mFolderNameEditText.setHint(mContent.getTextfieldHintText()); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mFolderNameEditText.setHintTextColor(mResourceUtil.getColor(mContent.getTextfieldHintColor())); } // set label of buttons [localization] mSelectButton.setText(mContent.getSelectLabel()); mCreateButton.setText(mContent.getCreateLabel()); mSelectButton.setTextColor(mResourceUtil.getColor(R.color.select_color)); mBackButton.setOnClickListener(mBackButtonClickListener); mSelectButton.setOnClickListener(mSelectButtonClickListener); mCreateButton.setOnClickListener(mCreateButtonClickListener); if(mConfig.getSecondaryAction() == StorageChooser.FILE_PICKER) { mSelectButton.setVisibility(View.GONE); setBottomNewFolderView(); } } private void setBottomNewFolderView() { int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics()); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height); lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); mNewFolderView.setLayoutParams(lp); } private void initNewFolderView() { RelativeLayout mNewFolderButtonHolder = (RelativeLayout) mLayout.findViewById(R.id.new_folder_button_holder); mNewFolderImageView = (ImageView) mLayout.findViewById(R.id.new_folder_iv); mNewFolderImageView.setOnClickListener(mNewFolderButtonClickListener); if(!mConfig.isAllowAddFolder()) { mNewFolderButtonHolder.setVisibility(View.GONE); } } /** * storage listView related code in this block */ private void initListView(Context context, View view, boolean shouldShowMemoryBar) { listView = (ListView) view.findViewById(R.id.storage_list_view); mPathChosen = (TextView) view.findViewById(R.id.path_chosen); mBundlePath = this.getArguments().getString(DiskUtil.SC_PREFERENCE_KEY); isFilePicker = this.getArguments().getBoolean(DiskUtil.SC_CHOOSER_FLAG, false); populateList(mBundlePath); secondaryChooserAdapter =new SecondaryChooserAdapter(customStoragesList, context, mContent.getListTextColor()); secondaryChooserAdapter.setPrefixPath(theSelectedPath); listView.setAdapter(secondaryChooserAdapter); //listview should be clickable at first SecondaryChooserAdapter.shouldEnable = true; listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) { mHandler.postDelayed(new Runnable() { @Override public void run() { String jointPath = theSelectedPath + "/" + customStoragesList.get(i); if(FileUtil.isDir(jointPath)) { populateList("/" + customStoragesList.get(i)); } else { StorageChooser.onSelectListener.onSelect(jointPath); dissmissDialog(FLAG_DISSMISS_NORMAL); } } }, 300); } }); } /** * evaluates path with respect to the list click position * @param i position in list */ private void evaluateAction(int i) { String preDefPath = mConfig.getPredefinedPath(); boolean isCustom = mConfig.isAllowCustomPath(); if(preDefPath == null) { Log.w(TAG, "No predefined path set"); } else if(isCustom) { populateList("/" + customStoragesList.get(i)); } } private boolean doesPassMemoryThreshold(long threshold, String memorySuffix, long availableSpace) { return true; } /** * populate storageList with necessary storages with filter applied * @param path defines the path for which list of folder is requested */ private void populateList(String path) { if(customStoragesList == null) { customStoragesList = new ArrayList<>(); } else { customStoragesList.clear(); } fileUtil = new FileUtil(); theSelectedPath = theSelectedPath + path; if(secondaryChooserAdapter !=null && secondaryChooserAdapter.getPrefixPath() !=null) { secondaryChooserAdapter.setPrefixPath(theSelectedPath); } //if the path length is greater than that of the addressbar length // we need to clip the starting part so that it fits the length and makes some room int pathLength = theSelectedPath.length(); if(pathLength >= 25) { // how many directories did user choose int slashCount = getSlashCount(theSelectedPath); if(slashCount > 2) { mAddressClippedPath = theSelectedPath.substring(theSelectedPath.indexOf("/", theSelectedPath.indexOf("/") + 2), pathLength); } else if(slashCount <= 2) { mAddressClippedPath = theSelectedPath.substring(theSelectedPath.indexOf("/", theSelectedPath.indexOf("/") + 2), pathLength); } } else { mAddressClippedPath = theSelectedPath; } File[] volumeList; if(isFilePicker) { volumeList = fileUtil.listFilesInDir(theSelectedPath); } else { volumeList = fileUtil.listFilesAsDir(theSelectedPath); } Log.e("SCLib", theSelectedPath); if(volumeList != null) { for (File f : volumeList) { if(mConfig.isShowHidden()) { customStoragesList.add(f.getName()); } else { if (!f.getName().startsWith(".")) { customStoragesList.add(f.getName()); } } } Collections.sort(customStoragesList, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); }else { customStoragesList.clear(); } if(secondaryChooserAdapter !=null) { secondaryChooserAdapter.notifyDataSetChanged(); } playTheAddressBarAnimation(); if(mConfig.isResumeSession() && StorageChooser.LAST_SESSION_PATH !=null) { if(StorageChooser.LAST_SESSION_PATH.startsWith(Environment.getExternalStorageDirectory().getAbsolutePath())) { mBundlePath = Environment.getExternalStorageDirectory().getAbsolutePath(); } else { Log.e("Bundle_Path_Length", StorageChooser.LAST_SESSION_PATH); mBundlePath = StorageChooser.LAST_SESSION_PATH.substring(StorageChooser.LAST_SESSION_PATH.indexOf("/", 16), StorageChooser.LAST_SESSION_PATH.length()); } } } /** * Unlike populate list trim populate only updates the list not the addressbar. * This is used when creating new folder and update to list is required * @param s is the path to be refreshed * */ private void trimPopulate(String s) { if(customStoragesList == null) { customStoragesList = new ArrayList<>(); } else { customStoragesList.clear(); } File[] volumeList; if(isFilePicker) { volumeList = fileUtil.listFilesInDir(theSelectedPath); } else { volumeList = fileUtil.listFilesAsDir(theSelectedPath); } Log.e("SCLib", theSelectedPath); if(volumeList != null) { for (File f : volumeList) { if(!f.getName().startsWith(".")) { customStoragesList.add(f.getName()); } } Collections.sort(customStoragesList, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); }else { customStoragesList.clear(); } if(secondaryChooserAdapter !=null) { secondaryChooserAdapter.setPrefixPath(s); secondaryChooserAdapter.notifyDataSetChanged(); } } private void playTheAddressBarAnimation() { mPathChosen.setText(mAddressClippedPath); Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.anim_address_bar); mPathChosen.startAnimation(animation); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog d = StorageChooser.dialog; d.setContentView(getLayout(LayoutInflater.from(getActivity().getApplicationContext()), mContainer)); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(d.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; d.getWindow().setAttributes(lp); return d; } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); theSelectedPath = ""; mAddressClippedPath = ""; } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); StorageChooser.LAST_SESSION_PATH = theSelectedPath; theSelectedPath = ""; mAddressClippedPath = ""; StorageChooser.onCancelListener.onCancel(); } private int getSlashCount(String path) { int count = 0; for(char s: path.toCharArray()) { if(s == '/') { count++; } } return count; } /** * Checks if edit text field is empty or not. Since there is only one edit text here no * param is required for now. */ private boolean validateFolderName() { if (mFolderNameEditText.getText().toString().trim().isEmpty()) { mFolderNameEditText.setError(mContent.getTextfieldErrorText()); return false; } return true; } }
package org.drools.core.common; import org.kie.internal.utils.ClassLoaderUtil; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.drools.core.rule.JavaDialectRuntimeData.convertClassToResourcePath; public class ProjectClassLoader extends ClassLoader { private static final boolean CACHE_NON_EXISTING_CLASSES = true; private static final ClassNotFoundException dummyCFNE = CACHE_NON_EXISTING_CLASSES ? new ClassNotFoundException("This is just a cached Exception. Disable non existing classes cache to see the actual one.") : null; private Map<String, byte[]> store; private final Set<String> nonExistingClasses = new HashSet<String>(); private ClassLoader droolsClassLoader; private ProjectClassLoader(ClassLoader parent) { super(parent); } public static ClassLoader getClassLoader(final ClassLoader[] classLoaders, final Class< ? > cls, final boolean enableCache) { if (classLoaders == null || classLoaders.length == 0) { return cls == null ? createProjectClassLoader() : createProjectClassLoader(cls.getClassLoader()); } else if (classLoaders.length == 1) { ProjectClassLoader classLoader = createProjectClassLoader(classLoaders[0]); if (cls != null) { classLoader.setDroolsClassLoader(cls.getClassLoader()); } return classLoader; } else { return ClassLoaderUtil.getClassLoader(classLoaders, cls, enableCache); } } public static ProjectClassLoader createProjectClassLoader() { ClassLoader parent = Thread.currentThread().getContextClassLoader(); if (parent == null) { parent = ClassLoader.getSystemClassLoader(); } if (parent == null) { parent = ProjectClassLoader.class.getClassLoader(); } return new ProjectClassLoader(parent); } public static ProjectClassLoader createProjectClassLoader(ClassLoader parent) { if (parent == null) { return createProjectClassLoader(); } return parent instanceof ProjectClassLoader ? (ProjectClassLoader)parent : new ProjectClassLoader(parent); } public static ProjectClassLoader createProjectClassLoader(ClassLoader parent, Map<String, byte[]> store) { ProjectClassLoader projectClassLoader = createProjectClassLoader(parent); projectClassLoader.store = store; return projectClassLoader; } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (CACHE_NON_EXISTING_CLASSES && nonExistingClasses.contains(name)) { throw dummyCFNE; } if (droolsClassLoader != null) { try { return Class.forName(name, resolve, droolsClassLoader); } catch (ClassNotFoundException e) { } } try { return super.loadClass(name, resolve); } catch (ClassNotFoundException e1) { try { return Class.forName(name, resolve, getParent()); } catch (ClassNotFoundException e2) { byte[] bytecode = getBytecode(convertClassToResourcePath(name)); if (bytecode == null) { if (CACHE_NON_EXISTING_CLASSES) { nonExistingClasses.add(name); } throw e2; } return defineClass(name, bytecode, 0, bytecode.length); } } } public Class<?> defineClass(String name, byte[] bytecode) { return defineClass(name, convertClassToResourcePath(name), bytecode); } public Class<?> defineClass(String name, String resourceName, byte[] bytecode) { storeClass(name, resourceName, bytecode); return defineClass(name, bytecode, 0, bytecode.length); } public void storeClass(String name, String resourceName, byte[] bytecode) { int lastDot = name.lastIndexOf( '.' ); if (lastDot > 0) { String pkgName = name.substring( 0, lastDot ); if (getPackage( pkgName ) == null) { definePackage( pkgName, "", "", "", "", "", "", null ); } } if (store == null) { store = new HashMap<String, byte[]>(); } store.put(resourceName, bytecode); if (CACHE_NON_EXISTING_CLASSES) { nonExistingClasses.remove(name); } } @Override protected Enumeration<URL> findResources(String name) throws IOException { return getParent().getResources(name); } @Override public InputStream getResourceAsStream(String name) { byte[] bytecode = getBytecode(name); return bytecode != null ? new ByteArrayInputStream( bytecode ) : super.getResourceAsStream(name); } @Override public URL getResource(String name) { if (droolsClassLoader != null) { URL resource = droolsClassLoader.getResource(name); if (resource != null) { return resource; } } return super.getResource(name); } public byte[] getBytecode(String resourceName) { return store == null ? null : store.get(resourceName); } public Map<String, byte[]> getStore() { return store; } public void setDroolsClassLoader(ClassLoader droolsClassLoader) { if (getParent() != droolsClassLoader) { this.droolsClassLoader = droolsClassLoader; if (CACHE_NON_EXISTING_CLASSES) { nonExistingClasses.clear(); } } } public void initFrom(ProjectClassLoader other) { if (other.store != null) { if (store == null) { store = new HashMap<String, byte[]>(); } store.putAll(other.store); } nonExistingClasses.addAll(other.nonExistingClasses); } }
package org.torquebox.ruby.enterprise.web.rack; import org.torquebox.pool.DefaultPool; import org.torquebox.ruby.enterprise.web.rack.spi.RackApplication; import org.torquebox.ruby.enterprise.web.rack.spi.RackApplicationFactory; import org.torquebox.ruby.enterprise.web.rack.spi.RackApplicationPool; public class DefaultRackApplicationPool extends DefaultPool<RackApplication> implements RackApplicationPool { public DefaultRackApplicationPool(RackApplicationFactory factory) { super( factory ); } @Override public RackApplication borrowApplication() throws Exception { return borrowInstance(); } @Override public void releaseApplication(RackApplication app) { releaseInstance( app ); } }
package net.jueb.util4j.hotSwap.annationScriptFactory; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.jueb.util4j.hotSwap.annationScriptFactory.annations.AnnationScript; import net.jueb.util4j.hotSwap.classProvider.IClassProvider; import net.jueb.util4j.hotSwap.classProvider.IClassProvider.State; /** * jar, T T, * ,,. * ,,GC * */ public abstract class AnnationScriptClassProvider<S extends IAnnotationScript> implements IAnnationScriptFactory<S>{ protected final Logger _log = LoggerFactory.getLogger(this.getClass()); protected final IClassProvider classProvider; protected volatile boolean autoReload; private final Map<String, Class<? extends S>> nameMap = new ConcurrentHashMap<String, Class<? extends S>>(); private final Map<Integer, Class<? extends S>> idMap = new ConcurrentHashMap<Integer, Class<? extends S>>(); private final ReentrantReadWriteLock rwLock=new ReentrantReadWriteLock(); protected AnnationScriptClassProvider(IClassProvider classProvider) { Objects.requireNonNull(classProvider); this.classProvider=classProvider; init(); } private void init() { reload(); classProvider.addListener(this::classProviderListener); } private void classProviderListener() { try { load(); } catch (Exception e) { _log.error(e.getMessage(),e); } } /** * * @throws Exception */ protected final void load()throws Exception { rwLock.writeLock().lock(); try { Set<Class<?>> classes=classProvider.getLoadedClasses(); initScriptClasses(classes); onScriptLoaded(classes); } finally { rwLock.writeLock().unlock(); } } /** * * @param classes * @throws Exception */ private void initScriptClasses(Set<Class<?>> classes)throws Exception { Set<Class<? extends S>> scriptClass=findScriptClass(classes); Set<Class<? extends S>> instanceAbleScript = findInstanceAbleScript(scriptClass); this.idMap.clear(); this.nameMap.clear(); for(Class<? extends S> clazz:instanceAbleScript) { AnnationScript[] key=clazz.getDeclaredAnnotationsByType(AnnationScript.class); if(key!=null) { AnnationScript mapper=key[0]; int id=mapper.id(); String name=mapper.name(); if(id!=0) { Class<? extends S> old=idMap.getOrDefault(id,null); if(old!=null) { _log.error("find Repeat Id ScriptClass,id="+id+",addingScript:" + clazz + ",existScript:"+ old); }else { idMap.put(id, clazz); _log.info("regist id mapping ScriptClass:id="+id+",class=" + clazz); } } if(name!=null && name.trim().length()>0) { Class<? extends S> old=nameMap.getOrDefault(name,null); if(old!=null) { _log.error("find Repeat name ScriptClass,name="+name+",addingScript:" + clazz + ",existScript:"+ old); }else { nameMap.put(name, clazz); _log.info("regist name mapping ScriptClass:name="+name+",class=" + clazz); } } }else { _log.error("find no mapping ScriptClass:"+clazz); } } _log.info("loadScriptClass complete,id mapping size:"+idMap.size()+",name mapping size:"+nameMap.size()); } @SuppressWarnings("unchecked") private Set<Class<? extends S>> findScriptClass(Set<Class<?>> clazzs) throws InstantiationException, IllegalAccessException { Set<Class<? extends S>> scriptClazzs = new HashSet<Class<? extends S>>(); for (Class<?> clazz : clazzs) { if (IAnnotationScript.class.isAssignableFrom(clazz)) { Class<S> scriptClazz = (Class<S>) clazz; scriptClazzs.add(scriptClazz); } } return scriptClazzs; } private Set<Class<? extends S>> findInstanceAbleScript(Set<Class<? extends S>> scriptClazzs) throws InstantiationException, IllegalAccessException { Set<Class<? extends S>> result=new HashSet<>(); for (Class<? extends S> scriptClazz : scriptClazzs) { S script = getInstacne(scriptClazz); if(script==null) { continue; } if(skipRegistScript(script)) { _log.warn("skil regist script,class=" + script.getClass()); continue; } result.add(scriptClazz); } return result; } protected final boolean isAbstractOrInterface(Class<?> clazz) { return Modifier.isAbstract(clazz.getModifiers())|| Modifier.isInterface(clazz.getModifiers()); } protected final <C> C getInstacne(Class<C> clazz) { C instacne=null; if (!isAbstractOrInterface(clazz)) { try { instacne=clazz.newInstance(); } catch (Exception e) { _log.error("can't newInstance Class:" + clazz); } } return instacne; } /** * * @param script * @return */ protected boolean skipRegistScript(S script) { return false; } /** * , * @param classes */ protected void onScriptLoaded(Set<Class<?>> loadedClasses)throws Exception { } public final State getState() { return classProvider.getState(); } protected final Class<? extends S> getScriptClass(int id) { rwLock.readLock().lock(); try { return idMap.get(id); } finally { rwLock.readLock().unlock(); } } protected final Class<? extends S> getScriptClass(String name) { rwLock.readLock().lock(); try { return nameMap.get(name); } finally { rwLock.readLock().unlock(); } } protected final S newInstance(Class<? extends S> c,Object... args) { S result = null; try { Class<?>[] cs=new Class<?>[args.length]; for(int i=0;i<args.length;i++) { cs[i]=args[i].getClass(); } result = c.getConstructor(cs).newInstance(args); } catch (Exception e) { _log.error(e.getMessage(), e); } return result; } protected final S newInstance(Class<? extends S> c) { S result = null; try { result = c.newInstance(); } catch (Exception e) { _log.error(e.getMessage(), e); } return result; } public S buildInstance(int id) { S result=null; Class<? extends S> c = getScriptClass(id); if (c == null) { _log.error("not found script,id=" + id); }else { result=newInstance(c); } return result; } @Override public S buildInstance(int id, Object... args) { S result=null; Class<? extends S> c = getScriptClass(id); if (c == null) { _log.error("not found script,id=" + id); }else { result=newInstance(c,args); } return result; } public S buildInstance(String name) { S result=null; Class<? extends S> c = getScriptClass(name); if (c == null) { _log.error("not found script,name=" + name); }else { result=newInstance(c); } return result; } @Override public S buildInstance(String name, Object... args) { S result=null; Class<? extends S> c = getScriptClass(name); if (c == null) { _log.error("not found script,name=" + name); }else { result=newInstance(c,args); } return result; } public final void reload() { try { load(); } catch (Throwable e) { _log.error(e.getMessage(), e); } } public boolean isAutoReload() { return autoReload; } public void setAutoReload(boolean autoReload) { this.autoReload = autoReload; } }
/** Snorlax is an advanced sorting algorithm with extremely high efficiency. * Note that this high efficiency comes with certain accuracy drawbacks outlined in the readme. * * @author github.com/CMMCD/ * @version 1.3 */ public class snorlax { // Your Snorlax's name. private String name; /** Class constructor. * * @param name What you choose to name your Snorlax. */ public snorlax(String name){ this.name = name; } /** Snorlax's sorting algorithm. * * @param snorlax Integer Array passed to Snorlax for sorting. * @return The usualy* sorted input. *See readme for more information* */ public int[] sort(int[] snorlax) { return snorlax; } /** Snorlax's sorting algorithm, with output instead of return. * Note that the output is usualy* the sorted input. *See readme for more information* * * @param snorlax Integer Array passed to Snorlax for sorting. */ public void snorlaxSort(int[] snorlax) { int[] snorlaxSorted = sort(snorlax); System.out.println("Greetings, I am " + name + "! Here is your sorted array, enjoy!"); String snorlaxSpeak = ""; for (int zzz : snorlaxSorted) snorlaxSpeak += zzz + " "; System.out.println(snorlaxSpeak); } }
package sfBugs; public class Bug3358161 { public void setAvailableItems(String s, boolean b) { } public void resetAvailableList(String s, boolean b) { String t = "foo"; setAvailableItems(s, !b); } }
package com.rgi.geopackage.tiles; import java.io.ByteArrayInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import com.rgi.common.util.jdbc.ResultSetStream; import com.rgi.geopackage.DatabaseUtility; import com.rgi.geopackage.verification.Assert; import com.rgi.geopackage.verification.AssertionError; import com.rgi.geopackage.verification.ColumnDefinition; import com.rgi.geopackage.verification.ForeignKeyDefinition; import com.rgi.geopackage.verification.Requirement; import com.rgi.geopackage.verification.Severity; import com.rgi.geopackage.verification.TableDefinition; import com.rgi.geopackage.verification.Verifier; public class TilesVerifier extends Verifier { public static final double EPSILON = 0.0001; private Set<String> allPyramidUserDataTables; private Set<String> pyramidTablesInContents; private Set<String> pyramidTablesInTileMatrix; private boolean hasTileMatrixTable; private boolean hasTileMatrixSetTable; public TilesVerifier(final Connection sqliteConnection) throws SQLException { super(sqliteConnection); final String queryTables = "SELECT tbl_name FROM sqlite_master " + "WHERE tbl_name NOT LIKE 'gpkg_%' " + "AND (type = 'table' OR type = 'view');"; try(Statement createStmt = this.getSqliteConnection().createStatement(); ResultSet possiblePyramidTables = createStmt.executeQuery(queryTables);) { this.allPyramidUserDataTables = ResultSetStream.getStream(possiblePyramidTables) .map(resultSet -> { try { final TableDefinition possiblePyramidTable = new TilePyramidUserDataTableDefinition(resultSet.getString("tbl_name")); this.verifyTable(possiblePyramidTable); return possiblePyramidTable.getName(); } catch(final SQLException | AssertionError ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch(final SQLException ex) { this.allPyramidUserDataTables = Collections.emptySet(); } final String query2 = "SELECT table_name FROM gpkg_contents WHERE data_type = 'tiles';"; try(Statement createStmt2 = this.getSqliteConnection().createStatement(); ResultSet contentsPyramidTables = createStmt2.executeQuery(query2)) { this.pyramidTablesInContents = ResultSetStream.getStream(contentsPyramidTables) .map(resultSet -> { try { return resultSet.getString("table_name"); } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch(final SQLException ex) { this.pyramidTablesInContents = Collections.emptySet(); } String query3 = "SELECT DISTINCT table_name FROM gpkg_tile_matrix;"; try(Statement createStmt3 = this.getSqliteConnection().createStatement(); ResultSet tileMatrixPyramidTables = createStmt3.executeQuery(query3)) { this.pyramidTablesInTileMatrix = ResultSetStream.getStream(tileMatrixPyramidTables) .map(resultSet -> { try { String pyramidName = resultSet.getString("table_name"); if(DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), pyramidName)) { return pyramidName; } else { return null; } } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch(final SQLException ex) { this.pyramidTablesInTileMatrix = Collections.emptySet(); } this.hasTileMatrixSetTable = this.tileMatrixSetTableExists(); this.hasTileMatrixTable = this.tileMatrixTableExists(); } /**Requirement 33 * <blockquote> * The <code>gpkg_contents</code> table SHALL contain a row with * a <code>data_type</code> column value of 'tiles' for each * tile pyramid user data table or view. * </blockquote> * @throws AssertionError */ @Requirement(number = 33, text = "The gpkg_contents table SHALL contain a row with a " + "data_type column value of \"tiles\" for each " + "tile pyramid user data table or view.", severity = Severity.Warning) public void Requirement33() throws AssertionError { for(final String tableName: this.allPyramidUserDataTables) { Assert.assertTrue(String.format("The Tile Pyramid User Data table that is not refrenced in gpkg_contents table is: %s. " + "This table needs to be referenced in the gpkg_contents table.", tableName), this.pyramidTablesInContents.contains(tableName)); } } /**<div class="title">Requirement 34</div> *<blockquote> *In a GeoPackage that contains a tile pyramid user data table *that contains tile data, by default, zoom level pixel sizes *for that table SHALL vary by a factor of 2 between adjacent *zoom levels in the tile matrix metadata table. *</blockquote> *</div> * @throws AssertionError */ @Requirement(number = 34, text = "In a GeoPackage that contains a tile pyramid user data table" + "that contains tile data, by default, zoom level pixel sizes for that " + "table SHALL vary by a factor of 2 between zoom levels in tile matrix metadata table.", severity = Severity.Warning) public void Requirement34() throws AssertionError { if(this.hasTileMatrixTable) { for (final String tableName : this.allPyramidUserDataTables) { final String query1 = String.format("SELECT table_name, " + "zoom_level, " + "pixel_x_size, " + "pixel_y_size " + "FROM gpkg_tile_matrix " + "WHERE table_name = '%s' " + "ORDER BY zoom_level ASC;", tableName); try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet pixelInfo = stmt.executeQuery(query1)) { Double pixelXCurrent = null; Double pixelYCurrent = null; int zoomLevelCurrent = -1000;// arbitrary number to // initialize the variable while (pixelInfo.next()) { final Double pixelXNext = pixelInfo.getDouble("pixel_x_size"); final Double pixelYNext = pixelInfo.getDouble("pixel_y_size"); final int zoomLevelNext = pixelInfo.getInt("zoom_level"); if (pixelXCurrent != null && pixelYCurrent != null && zoomLevelNext == zoomLevelCurrent + 1) { Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not vary by factors of 2" + " between adjacent zoom levels in the tile matrix metadata table: %s, %s", pixelXNext.toString(), pixelYNext.toString()), TilesVerifier.isEqual((pixelXCurrent / 2), pixelXNext) && TilesVerifier.isEqual((pixelYCurrent / 2), pixelYNext)); pixelXCurrent = pixelXNext; pixelYCurrent = pixelYNext; } //this should only execute for the first time through the loop to get the first two records else if (pixelInfo.next()) { pixelXCurrent = pixelInfo.getDouble("pixel_x_size"); pixelYCurrent = pixelInfo.getDouble("pixel_y_size"); zoomLevelCurrent = pixelInfo.getInt("zoom_level"); if (zoomLevelNext + 1 == zoomLevelCurrent) { Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not vary by factors of 2 " + "between adjacent zoom levels in the tile matrix metadata table:(pixel_x_size, pixel_y_size) %s, %s. " + " between zoom levels %d and %d", pixelXCurrent.toString(), pixelYCurrent.toString(), zoomLevelNext, zoomLevelCurrent), TilesVerifier.isEqual((pixelXNext / 2), pixelXCurrent) && TilesVerifier.isEqual((pixelYNext / 2), pixelYCurrent)); } } } } catch (final SQLException e) { Assert.fail(e.getMessage()); } } } } @Requirement(number = 35, text = "In a GeoPackage that contains a tile pyramid user data table that " + "contains tile data that is not MIME type image/{jpeg or png}, " + "by default SHALL store that tile data in MIME type image/{png or jpeg}", severity = Severity.Warning) public void Requirement35() throws AssertionError { final Collection<ImageReader> jpegImageReaders = TilesVerifier.iteratorToCollection(ImageIO.getImageReadersByMIMEType("image/jpeg")); final Collection<ImageReader> pngImageReaders = TilesVerifier.iteratorToCollection(ImageIO.getImageReadersByMIMEType("image/png")); for (final String tableName : this.allPyramidUserDataTables) { final String selectTileDataQuery = String.format("SELECT tile_data, id FROM %s;", tableName); try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet tileDataResultSet = stmt.executeQuery(selectTileDataQuery)) { final Map<Integer, byte[]> allTileData = ResultSetStream.getStream(tileDataResultSet) .map(resultSet -> { try { final int tileId = resultSet.getInt("id"); final byte[] tileData = resultSet.getBytes("tile_data"); return new AbstractMap.SimpleImmutableEntry<>(tileId, tileData); } catch (final Exception ex1) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); for(final Integer imageID : allTileData.keySet()) { try(ByteArrayInputStream byteArray = new ByteArrayInputStream(allTileData.get(imageID)); MemoryCacheImageInputStream cacheImage = new MemoryCacheImageInputStream(byteArray)) { Assert.assertTrue(String.format("The tile id: %d in the table: %s is not in the correct format. The image must be of MIME type image/jpeg or image/png.", imageID, tableName), TilesVerifier.canReadImage(pngImageReaders, cacheImage) || TilesVerifier.canReadImage(jpegImageReaders, cacheImage)); } catch(final IOException ex) { Assert.fail(ex.getMessage()); } } } catch (final SQLException ex) { Assert.fail(ex.getMessage()); } } } @Requirement(number = 36, text = "In a GeoPackage that contains a tile pyramid user data table that " + "contains tile data that is not MIME type image png, " + "by default SHALL store that tile data in MIME type image jpeg", severity = Severity.Warning) public void Requirement36() { // This requirement is tested through Requirement 35 test in TilesVerifier. } @Requirement(number = 37, text = "A GeoPackage that contains a tile pyramid user data table SHALL " + "contain gpkg_tile_matrix_set table or view per Table Definition, " + "Tile Matrix Set Table or View Definition and gpkg_tile_matrix_set Table Creation SQL. ", severity = Severity.Error) public void Requirement37() throws AssertionError, SQLException { if(!this.allPyramidUserDataTables.isEmpty()) { Assert.assertTrue("The GeoPackage does not contain a gpkg_tile_matrix_set table. Every GeoPackage with a Pyramid User " + "Data Table must also have a gpkg_tile_matrix_set table.", this.hasTileMatrixSetTable); this.verifyTable(TilesVerifier.TileMatrixSetTableDefinition); } } /** * <div class="title">Requirement 38</div> * <blockquote> * Values of the <code>gpkg_tile_matrix_set</code> <code>table_name</code> * column SHALL reference values in the gpkg_contents table_name column * for rows with a data type of "tiles". * </blockquote> * </div> * @throws AssertionError */ @Requirement(number = 38, text = "Values of the gpkg_tile_matrix_set table_name column " + "SHALL reference values in the gpkg_contents table_name " + "column for rows with a data type of \"tiles\".", severity = Severity.Warning) public void Requirement38() throws AssertionError { if(this.hasTileMatrixSetTable) { final String queryMatrixSetPyramid = "SELECT table_name FROM gpkg_tile_matrix_set;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet tileTablesInTileMatrixSet = stmt.executeQuery(queryMatrixSetPyramid)) { final Set<String> tileMatrixSetTables = ResultSetStream.getStream(tileTablesInTileMatrixSet) .map(resultSet -> { try { return resultSet.getString("table_name"); } catch (final SQLException ex1) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); for(final String table: this.pyramidTablesInContents) { Assert.assertTrue(String.format("The table_name %s in the gpkg_tile_matrix_set is not referenced in the gpkg_contents table. Either delete the table %s " + "or create a record for that table in the gpkg_contents table", table, table), tileMatrixSetTables.contains(table)); } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 39</div> * <blockquote> * The gpkg_tile_matrix_set table or view SHALL contain one row record for each tile pyramid user data table. * </blockquote> * @throws AssertionError * */ @Requirement(number = 39, text = "The gpkg_tile_matrix_set table or view SHALL " + "contain one row record for each tile " + "pyramid user data table. ", severity = Severity.Error) public void Requirement39() throws AssertionError { if (this.hasTileMatrixSetTable) { final String queryMatrixSet = "SELECT table_name FROM gpkg_tile_matrix_set;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet tileTablesInTileMatrixSet = stmt.executeQuery(queryMatrixSet)) { final Set<String> tileMatrixSetTables = ResultSetStream.getStream(tileTablesInTileMatrixSet) .map(resultSet -> { try { return resultSet.getString("table_name"); } catch (final SQLException ex1) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); for(final String table: this.allPyramidUserDataTables) { Assert.assertTrue(String.format("The Pyramid User Data Table %s is not referenced in the gpkg_tile_matrix_set.", table), tileMatrixSetTables.contains(table)); } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 40</div> * <blockquote> * Values of the <code>gpkg_tile_matrix_set </code> <code> srs_id</code> column * SHALL reference values in the <code>gpkg_spatial_ref_sys </code> <code> srs_id</code> column. * </blockquote> * </div> * @throws AssertionError * @throws */ @Requirement (number = 40, text = "Values of the gpkg_tile_matrix_set srs_id column " + "SHALL reference values in the gpkg_spatial_ref_sys srs_id column. ", severity = Severity.Error) public void Requirement40() throws AssertionError { if(this.hasTileMatrixSetTable) { final String query1 = "SELECT srs_id from gpkg_tile_matrix_set AS tms " + "WHERE srs_id NOT IN" + "(SELECT srs_id " + "FROM gpkg_spatial_ref_sys);"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet unreferencedSRS = stmt.executeQuery(query1)) { if (unreferencedSRS.next()) { Assert.fail(String.format("The gpkg_tile_matrix_set table contains a reference to an srs_id that is not defined in the gpkg_spatial_ref_sys Table. " + "Unreferenced srs_id: %s", unreferencedSRS.getInt("srs_id"))); } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } @Requirement (number = 41, text = "A GeoPackage that contains a tile pyramid user data table " + "SHALL contain a gpkg_tile_matrix table or view per clause " + "2.2.7.1.1 Table Definition, Table Tile Matrix Metadata Table " + "or View Definition and Table gpkg_tile_matrix Table Creation SQL. ", severity = Severity.Error) public void Requirement41() throws AssertionError, SQLException { if(!this.allPyramidUserDataTables.isEmpty()) { Assert.assertTrue("The GeoPackage does not contain a gpkg_tile_matrix table. Every GeoPackage with a Pyramid User " + "Data Table must also have a gpkg_tile_matrix table.", this.hasTileMatrixTable); this.verifyTable(TilesVerifier.TileMatrixTableDefinition); } } /** * <div class="title">Requirement 42</div> * <blockquote> * Values of the <code>gpkg_tile_matrix</code> * <code>table_name</code> column SHALL reference * values in the <code>gpkg_contents</code> <code> * table_name</code> column for rows with a <code> * data_type</code> of 'tiles'. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 42, text = "Values of the gpkg_tile_matrix table_name column " + "SHALL reference values in the gpkg_contents table_name " + "column for rows with a data_type of 'tiles'. ", severity = Severity.Warning) public void Requirement42() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT table_name FROM gpkg_tile_matrix AS tm " + "WHERE table_name NOT IN" + "(SELECT table_name " + "FROM gpkg_contents AS gc " + "WHERE tm.table_name = gc.table_name AND gc.data_type = 'tiles');"); try(Statement stmt = this.getSqliteConnection().createStatement(); ResultSet unreferencedTables = stmt.executeQuery(query)) { if (unreferencedTables.next()) { Assert.fail(String.format("There are Pyramid user data tables in gpkg_tile_matrix table_name field such that the table_name does not" + " reference values in the gpkg_contents table_name column for rows with a data type of 'tiles'." + " Unreferenced table: %s", unreferencedTables.getString("table_name"))); } } catch (final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 43</div> * <blockquote> * The <code>gpkg_tile_matrix</code> table or view SHALL contain one row record for * each zoom level that contains one or more tiles in each tile pyramid user data table or view. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 43, text = "The gpkg_tile_matrix table or view SHALL contain " + "one row record for each zoom level that contains " + "one or more tiles in each tile pyramid user data table or view. ", severity = Severity.Error) public void Requirement43() throws AssertionError { if(this.hasTileMatrixTable) { for (final String tableName : this.allPyramidUserDataTables) { final String query1 = String.format("SELECT DISTINCT zoom_level FROM gpkg_tile_matrix WHERE table_name ='%s' ORDER BY zoom_level;", tableName); final String query2 = String.format("SELECT DISTINCT zoom_level FROM %s ORDER BY zoom_level;", tableName); try (Statement stmt1 = this.getSqliteConnection().createStatement(); ResultSet gm_zoomLevels = stmt1.executeQuery(query1); Statement stmt2 = this.getSqliteConnection().createStatement(); ResultSet py_zoomLevels = stmt2.executeQuery(query2)) { final Set<Integer> tileMatrixZooms = ResultSetStream.getStream(gm_zoomLevels) .map(resultSet -> { try { return resultSet.getInt("zoom_level"); } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); final Set<Integer> tilePyramidZooms = ResultSetStream.getStream(py_zoomLevels) .map(resultSet -> { try { return resultSet.getInt("zoom_level"); } catch(final SQLException ex) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); for(final Integer zoom: tilePyramidZooms) { Assert.assertTrue(String.format("The gpkg_tile_matrix does not contain a row record for zoom level %d in the Pyramid User Data Table %s.", zoom, tableName), tileMatrixZooms.contains(zoom)); } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } } /** * <div class="title">Requirement 44</div> * <blockquote> * The <code>zoom_level</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL not be negative. * </blockquote> * </div> * @throws * @throws AssertionError */ @Requirement (number = 44, text = "The zoom_level column value in a gpkg_tile_matrix table row SHALL not be negative." , severity = Severity.Error) public void Requirement44() throws AssertionError { if(this.hasTileMatrixTable) { final String query = String.format("SELECT min(zoom_level) FROM gpkg_tile_matrix;"); try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet minZoom = stmt.executeQuery(query)) { final int minZoomLevel = minZoom.getInt("min(zoom_level)"); if(!minZoom.wasNull()) { Assert.assertTrue(String.format("The zoom_level in gpkg_tile_matrix must be greater than 0. Invalid zoom_level: %d", minZoomLevel), minZoomLevel >= 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 45</div> * <blockquote> * <code>matrix_width</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 45, text = "The matrix_width column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement45() throws AssertionError { if(this.hasTileMatrixTable) { final String query = "SELECT min(matrix_width) FROM gpkg_tile_matrix;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet minMatrixWidthRS = stmt.executeQuery(query);) { final int minMatrixWidth = minMatrixWidthRS.getInt("min(matrix_width)"); if(!minMatrixWidthRS.wasNull()) { Assert.assertTrue(String.format("The matrix_width in gpkg_tile_matrix must be greater than 0. Invalid matrix_width: %d", minMatrixWidth), minMatrixWidth > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 46</div> * <blockquote> * <code>matrix_height</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 46, text = "The matrix_height column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement46() throws AssertionError { if(this.hasTileMatrixTable) { final String query = "SELECT min(matrix_height) FROM gpkg_tile_matrix;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet minMatrixHeightRS = stmt.executeQuery(query);) { final int minMatrixHeight = minMatrixHeightRS.getInt("min(matrix_height)"); if(!minMatrixHeightRS.wasNull()) { Assert.assertTrue(String.format("The matrix_height in gpkg_tile_matrix must be greater than 0. Invalid matrix_height: %d", minMatrixHeight), minMatrixHeight > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 47</div> * <blockquote> * <code>tile_width</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 47, text = "The tile_width column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement47() throws AssertionError { if(this.hasTileMatrixTable) { final String query = "SELECT min(tile_width) FROM gpkg_tile_matrix;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet minTileWidthRS = stmt.executeQuery(query);) { final int minTileWidth = minTileWidthRS.getInt("min(tile_width)"); if (!minTileWidthRS.wasNull()) { Assert.assertTrue(String.format("The tile_width in gpkg_tile_matrix must be greater than 0. Invalid tile_width: %d", minTileWidth), minTileWidth > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 47</div> * <blockquote> * <code>tile_height</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * </div> * @throws AssertionError */ @Requirement(number = 48, text = "The tile_height column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement48() throws AssertionError { if(this.hasTileMatrixTable) { final String query = "SELECT min(tile_height) FROM gpkg_tile_matrix;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet minTileHeightRS = stmt.executeQuery(query);) { final int testMinTileHeight = minTileHeightRS.getInt("min(tile_height)"); if (!minTileHeightRS.wasNull()) { Assert.assertTrue(String.format("The tile_height in gpkg_tile_matrix must be greater than 0. Invalid tile_height: %d", testMinTileHeight), testMinTileHeight > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 49</div> * <blockquote> * <code>pixel_x_size</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 49, text = "The pixel_x_size column value in a gpkg_tile_matrix table row SHALL be greater than 0." , severity = Severity.Error) public void Requirement49() throws AssertionError { if(this.hasTileMatrixTable) { final String query = "SELECT min(pixel_x_size) FROM gpkg_tile_matrix;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet minPixelXSizeRS = stmt.executeQuery(query);) { final double minPixelXSize = minPixelXSizeRS.getDouble("min(pixel_x_size)"); if (!minPixelXSizeRS.wasNull()) { Assert.assertTrue(String.format("The pixel_x_size in gpkg_tile_matrix must be greater than 0. Invalid pixel_x_size: %f", minPixelXSize), minPixelXSize > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 50</div> * <blockquote> * <code>pixel_y_size</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 50, text = "The pixel_y_size column value in a gpkg_tile_matrix table row SHALL be greater than 0.", severity = Severity.Error) public void Requirement50() throws AssertionError { if(this.hasTileMatrixTable) { final String query = "SELECT min(pixel_y_size) FROM gpkg_tile_matrix;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet minPixelYSizeRS = stmt.executeQuery(query);) { final double minPixelYSize = minPixelYSizeRS.getDouble("min(pixel_y_size)"); if (!minPixelYSizeRS.wasNull()) { Assert.assertTrue(String.format("The pixel_y_size in gpkg_tile_matrix must be greater than 0. Invalid pixel_y_size: %f", minPixelYSize), minPixelYSize > 0); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 51</div> * <blockquote> * The <code>pixel_x_size</code> and <code>pixel_y_size</code> * column values for <code>zoom_level</code> column values in a * <code>gpkg_tile_matrix</code> table sorted in ascending order * SHALL be sorted in descending order. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 51, text = "The pixel_x_size and pixel_y_size column values for zoom_level " + "column values in a gpkg_tile_matrix table sorted in ascending " + "order SHALL be sorted in descending order.", severity = Severity.Error) public void Requirement51() throws AssertionError { if(this.hasTileMatrixTable) { for (final String pyramidTable : this.allPyramidUserDataTables) { final String query2 = String.format("SELECT pixel_x_size, pixel_y_size " + "FROM gpkg_tile_matrix WHERE table_name = '%s' ORDER BY zoom_level ASC;", pyramidTable); Double pixelX2 = null; Double pixelY2 = null; try (Statement stmt2 = this.getSqliteConnection().createStatement(); ResultSet zoomPixxPixy = stmt2.executeQuery(query2)) { while (zoomPixxPixy.next()) { final Double pixelX = zoomPixxPixy.getDouble("pixel_x_size"); final Double pixelY = zoomPixxPixy.getDouble("pixel_y_size"); if (pixelX2 != null && pixelY2 != null) { Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not increase while " + "the zoom level decrease. Invalid pixel_x_size %s. Invalid pixel_y_size: %s.", pixelX.toString(), pixelY.toString()), pixelX2 > pixelX && pixelY2 > pixelY); pixelX2 = pixelX; pixelY2 = pixelY; } else if (zoomPixxPixy.next()) { pixelX2 = zoomPixxPixy.getDouble("pixel_x_size"); pixelY2 = zoomPixxPixy.getDouble("pixel_y_size"); Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not increase while " + "the zoom level decrease. Invalid pixel_x_size %s. Invalid pixel_y_size: %s.", pixelX2.toString(), pixelY2.toString()), pixelX > pixelX2 && pixelY > pixelY2); } } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } } @Requirement (number = 52, text = "Each tile matrix set in a GeoPackage SHALL " + "be stored in a different tile pyramid user " + "data table or updateable view with a unique " + "name that SHALL have a column named \"id\" with" + " column type INTEGER and PRIMARY KEY AUTOINCREMENT" + " column constraints per Clause 2.2.8.1.1 Table Definition," + " Tiles Table or View Definition and EXAMPLE: tiles table " + "Insert Statement (Informative). ", severity = Severity.Error) public void Requirement52() throws AssertionError, SQLException { //verify the tables are defined correctly for(final String table: this.pyramidTablesInContents) { if(DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), table)) { this.verifyTable(new TilePyramidUserDataTableDefinition(table)); } else { throw new AssertionError(String.format("The tiles table %s does not exist even though it is defined in the gpkg_contents table. " + "Either create the table %s or delete the record in gpkg_contents table referring to table %s.", table, table, table)); } } //Ensure that the pyramid tables are referenced in tile matrix set if(this.hasTileMatrixSetTable) { final String query2 = "SELECT DISTINCT table_name " + "FROM gpkg_contents WHERE data_type = 'tiles' " + "AND table_name NOT IN" + " (SELECT DISTINCT table_name " + " FROM gpkg_tile_matrix_set);"; try(Statement stmt2 = this.getSqliteConnection().createStatement(); ResultSet unreferencedPyramidTableInTMS = stmt2.executeQuery(query2)) { //verify that all the pyramid user data tables are referenced in the Tile Matrix Set table if(unreferencedPyramidTableInTMS.next()) { Assert.fail(String.format("There are Pyramid User Data Tables that do not contain a record in the gpkg_tile_matrix_set." + " Unreferenced Pyramid table: %s", unreferencedPyramidTableInTMS.getString("table_name"))); } } catch(final SQLException ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 53</div> * <blockquote> * For each distinct <code>table_name</code> from the <code>gpkg_tile_matrix</code> * (tm) table, the tile pyramid (tp) user data table <code>zoom_level</code> * column value in a GeoPackage SHALL be in the range min(tm.zoom_level) <= tp.zoom_level <= max(tm.zoom_level). * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 53, text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, " + "the tile pyramid (tp) user data table zoom_level column value in a " + "GeoPackage SHALL be in the range min(tm.zoom_level) less than or equal " + "to tp.zoom_level less than or equal to max(tm.zoom_level).", severity = Severity.Error) public void Requirement53() throws AssertionError { if(this.hasTileMatrixTable) { final String query = "SELECT DISTINCT table_name FROM gpkg_tile_matrix;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet pyramidTableNameInTM = stmt.executeQuery(query)) { while (pyramidTableNameInTM.next()) { final String pyramidName = pyramidTableNameInTM.getString("table_name"); final String query2 = String.format("SELECT MIN(zoom_level) AS min_gtm_zoom, MAX(zoom_level) " + "AS max_gtm_zoom FROM gpkg_tile_matrix WHERE table_name = '%s'", pyramidName); //ensure the pyramid table exists prior to testing if(DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), pyramidName)) { try (Statement stmt2 = this.getSqliteConnection().createStatement(); ResultSet minMaxZoom = stmt2.executeQuery(query2)) { final int minZoom = minMaxZoom.getInt("min_gtm_zoom"); final int maxZoom = minMaxZoom.getInt("max_gtm_zoom"); if (!minMaxZoom.wasNull()) { final String query3 = String.format("SELECT id FROM %s WHERE zoom_level < %d OR zoom_level > %d", pyramidName, minZoom, maxZoom); try (Statement stmt3 = this.getSqliteConnection().createStatement(); ResultSet invalidZooms = stmt3.executeQuery(query3)) { if (invalidZooms.next()) { Assert.fail(String.format("There are zoom_levels in the Pyramid User Data Table: %s such that the zoom level is bigger than the maximum zoom level: %d or smaller than the minimum zoom_level: %d" + " that was determined by the gpkg_tile_matrix Table. Invalid tile with an id of %d from table %s", pyramidName, maxZoom, minZoom, invalidZooms.getInt("id"), pyramidName)); } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } } } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } /** * <div class="title">Requirement 54</div> * <blockquote> * For each distinct <code>table_name</code> from the <code>gpkg_tile_matrix</code> * (tm) table, the tile pyramid (tp) user data table <code>tile_column</code> column * value in a GeoPackage SHALL be in the range 0 <= tp.tile_column <= tm.matrix_width 1 * where the tm and tp <code>zoom_level</code> column values are equal. * </blockquote> * </div> * @throws AssertionError * @throws SQLException */ @Requirement (number = 54, text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, " + "the tile pyramid (tp) user data table tile_column column value in a " + "GeoPackage SHALL be in the range 0 <= tp.tile_column <= tm.matrix_width - 1 " + "where the tm and tp zoom_level column values are equal. ", severity = Severity.Warning) public void Requirement54() throws AssertionError, SQLException { class TileData { int id; int matrixWidth; int column; int zoomLevel; }; if (this.hasTileMatrixTable) { for(String pyramidName : this.pyramidTablesInTileMatrix) { // this query will only pull the incorrect values for the // pyramid user data table's column width, the value // of the tile_column value for the pyramid user data table // SHOULD be null otherwise those fields are in violation // of the range final String query2 = String.format("SELECT DISTINCT udt.id, " + "gtmm.matrix_width AS gtmm_width," + "gtmm.zoom_level, " + "udt.tile_column AS udt_column" + " FROM gpkg_tile_matrix AS gtmm " + "LEFT OUTER JOIN %s AS udt ON" + " udt.zoom_level = gtmm.zoom_level AND" + " gtmm.table_name = '%s' AND" + " (udt_column < 0 OR udt_column > (gtmm_width - 1));", pyramidName, pyramidName); // TODO use format parameter indices try (Statement stmt2 = this.getSqliteConnection().createStatement(); ResultSet incorrectColumns = stmt2.executeQuery(query2)) { final Map<String, TileData> allTileData = ResultSetStream.getStream(incorrectColumns) .map(resultSet -> { try { TileData tileData = new TileData(); tileData.column = incorrectColumns.getInt("udt_column"); //if this value is null //column is in valid range if(resultSet.wasNull()) { return null; } tileData.id = incorrectColumns.getInt("id"); tileData.matrixWidth = incorrectColumns.getInt("gtmm_width"); tileData.zoomLevel = incorrectColumns.getInt("zoom_level"); return new AbstractMap.SimpleImmutableEntry<>(pyramidName, tileData); } catch (final Exception ex1) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); // TODO this will cause the function to fail after the first incorrect assertion. we want all tiles in violation // Assert.assertTrue(String.format("The Pyramid User Data table tile_column value must be greater than zero" // + " and less than or equal to the Tile Matrix's table's width (in this case is %d) minus 1," // + " when the zoom_level in the Tile Matrix Table equals the zoom_level " // + "in the Pyramid User Data Table. Invalid tile id: %d with tile_column value: %d at zoom_level: %d Pyramid Table: %s", // matrixWidth, // pyramidTileId, // pyramidTileColumn, // tileMatrixZoomLevel, // pyramidName), // incorrectColumns.wasNull()); } } } } /** * <div class="title">Requirement 55</div> * <blockquote> * For each distinct <code>table_name</code> from the <code>gpkg_tile_matrix</code> * (tm) table, the tile pyramid (tp) user data table <code>tile_row</code> column * value in a GeoPackage SHALL be in the range 0 <= tp.tile_row <= tm.matrix_height 1 * where the tm and tp <code>zoom_level</code> column values are equal. * </blockquote> * </div> * @throws AssertionError */ @Requirement (number = 55, text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, the tile pyramid (tp) " + "user data table tile_row column value in a GeoPackage SHALL be in the range 0 <= tp.tile_row <= tm.matrix_height - 1 " + "where the tm and tp zoom_level column values are equal. ", severity = Severity.Warning) public void Requirement55() throws AssertionError { // TODO this is a lot of code, and it's very similar to the above function. consider abstracting if (this.hasTileMatrixTable) { final String query = "SELECT DISTINCT table_name FROM gpkg_tile_matrix;"; try (Statement stmt = this.getSqliteConnection().createStatement(); ResultSet pyramidTableName = stmt.executeQuery(query)) { while (pyramidTableName.next()) { final String pyramidName = pyramidTableName.getString("table_name"); // this query will only pull the incorrect values for the // pyramid user data table's column height, the value // of the tile_row value for the pyramid user data table // SHOULD be null otherwise those fields are in violation // of the range final String query2 = String.format("SELECT DISTINCT gtmm.zoom_level AS gtmm_zoom, gtmm.matrix_height AS gtmm_height," + "udt.zoom_level AS udt_zoom, udt.tile_row AS udt_row, udt.id AS udt_id FROM gpkg_tile_matrix AS gtmm " + "LEFT OUTER JOIN %s AS udt ON " + "udt.zoom_level = gtmm.zoom_level AND gtmm.table_name = '%s' AND (udt_row < 0 OR udt_row > (gtmm_height- 1));", pyramidName, pyramidName); if (DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), pyramidName)) { try (Statement stmt2 = this.getSqliteConnection().createStatement(); ResultSet incorrectTileRow = stmt2.executeQuery(query2)) { while(incorrectTileRow.next()) { final int matrixHeight = incorrectTileRow.getInt("gtmm_height"); final int pyramidTileID = incorrectTileRow.getInt("udt_id"); final int tileMatrixZoom = incorrectTileRow.getInt("gtmm_zoom"); final int pyramidTileRow = incorrectTileRow.getInt("udt_row"); Assert.assertTrue(String.format("The Pyramid User Data table tile_row value must be greater than zero and less " + "than or equal to the Tile Matrix's table's height (in this case is %d) minus 1," + " only when the zoom_level in the Tile Matrix Table equals the zoom_level" + " in the Pyramid User Data Table. Invalid tile_row: %d with an id of: %d at zoom_level: %d in the Pyramid Table: %s", matrixHeight, pyramidTileRow, pyramidTileID, tileMatrixZoom, pyramidName), incorrectTileRow.wasNull()); } } } } } catch (final Exception ex) { Assert.fail(ex.getMessage()); } } } /** * This method determines if the two doubles are * equal based upon the maximum level of allowable * differenced determined by the Epsilon value 0.001 * @param first * @param second * @return */ private static boolean isEqual(final double first, final double second) { return Math.abs(first - second) < TilesVerifier.EPSILON; } private static <T> Collection<T> iteratorToCollection(final Iterator<T> iterator) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false) .collect(Collectors.toCollection(ArrayList::new)); } /** * This Verifies if the Tile Matrix Table exists. * @return true if the gpkg_tile_matrix table exists * @throws AssertionError throws an assertion error if the gpkg_tile_matrix table * doesn't exist and the GeoPackage contains a tiles table */ private boolean tileMatrixTableExists() throws SQLException { return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), GeoPackageTiles.MatrixTableName); } /** * This Verifies if the Tile Matrix Set Table exists in the * GeoPackage. * @return true if the gpkg_tile_matrix Set table exists * @throws AssertionError throws an assertion error if the gpkg_tile_matrix_set table * doesn't exist and the GeoPackage contains a tiles table * @throws SQLException */ private boolean tileMatrixSetTableExists() throws SQLException { return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), GeoPackageTiles.MatrixSetTableName); } private static boolean canReadImage(final Collection<ImageReader> imageReaders, final ImageInputStream image) { return imageReaders.stream() .anyMatch(imageReader -> { try { image.mark(); final boolean canDecode = imageReader.getOriginatingProvider().canDecodeInput(image); return canDecode; } catch(final Exception ex) { return false; } finally { try { image.reset(); } catch (final Exception e) { e.printStackTrace(); } } }); } private static final TableDefinition TileMatrixSetTableDefinition; private static final TableDefinition TileMatrixTableDefinition; static { final Map<String, ColumnDefinition> tileMatrixSetColumns = new HashMap<>(); tileMatrixSetColumns.put("table_name", new ColumnDefinition("TEXT", true, true, true, null)); tileMatrixSetColumns.put("srs_id", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixSetColumns.put("min_x", new ColumnDefinition("DOUBLE", true, false, false, null)); tileMatrixSetColumns.put("min_y", new ColumnDefinition("DOUBLE", true, false, false, null)); tileMatrixSetColumns.put("max_x", new ColumnDefinition("DOUBLE", true, false, false, null)); tileMatrixSetColumns.put("max_y", new ColumnDefinition("DOUBLE", true, false, false, null)); TileMatrixSetTableDefinition = new TableDefinition("gpkg_tile_matrix_set", tileMatrixSetColumns, new HashSet<>(Arrays.asList(new ForeignKeyDefinition("gpkg_spatial_ref_sys", "srs_id", "srs_id"), new ForeignKeyDefinition("gpkg_contents", "table_name", "table_name")))); final Map<String, ColumnDefinition> tileMatrixColumns = new HashMap<>(); tileMatrixColumns.put("table_name", new ColumnDefinition("TEXT", true, true, true, null)); tileMatrixColumns.put("zoom_level", new ColumnDefinition("INTEGER", true, true, true, null)); tileMatrixColumns.put("matrix_width", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixColumns.put("matrix_height", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixColumns.put("tile_width", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixColumns.put("tile_height", new ColumnDefinition("INTEGER", true, false, false, null)); tileMatrixColumns.put("pixel_x_size", new ColumnDefinition("DOUBLE", true, false, false, null)); tileMatrixColumns.put("pixel_y_size", new ColumnDefinition("DOUBLE", true, false, false, null)); TileMatrixTableDefinition = new TableDefinition("gpkg_tile_matrix", tileMatrixColumns, new HashSet<>(Arrays.asList(new ForeignKeyDefinition("gpkg_contents", "table_name", "table_name")))); } }
package se.sics.contiki.collect; public class SensorDataAggregator implements SensorInfo { private final Node node; private long[] values; private int minSeqno = Integer.MAX_VALUE; private int maxSeqno = Integer.MIN_VALUE; private int seqnoDelta = 0; private int dataCount; private int duplicates = 0; private int lost = 0; private int nodeRestartCount = 0; private int nextHopChangeCount = 0; private int lastNextHop = 0; private long shortestPeriod = Long.MAX_VALUE; private long longestPeriod = 0; public SensorDataAggregator(Node node) { this.node = node; this.values = new long[VALUES_COUNT]; } public Node getNode() { return node; } public String getNodeID() { return node.getID(); } public long getValue(int index) { return values[index]; } public double getAverageValue(int index) { return dataCount > 0 ? (double)values[index] / (double)dataCount : 0; } public int getValueCount() { return values.length; } public int getDataCount() { return dataCount; } public void addSensorData(SensorData data) { int seqn = data.getValue(SEQNO); int s = seqn + seqnoDelta; int bestNeighbor = data.getValue(BEST_NEIGHBOR); if (lastNextHop != bestNeighbor && lastNextHop != 0) { nextHopChangeCount++; } lastNextHop = bestNeighbor; if (s <= maxSeqno) { // Check for duplicates among the last 5 packets for(int n = node.getSensorDataCount() - 1, i = n > 5 ? n - 5 : 0; i < n; i++) { SensorData sd = node.getSensorData(i); if (sd.getValue(SEQNO) != seqn || sd == data || sd.getValueCount() != data.getValueCount()) { // Not a duplicate } else if (Math.abs(data.getNodeTime() - sd.getNodeTime()) > 180000) { // Too long time between packets. Not a duplicate. // System.err.println("Too long time between packets with same seqno from " // + data.getNode() + ": " // + (Math.abs(data.getNodeTime() - sd.getNodeTime()) / 1000) // + " sec, " + (n - i) + " packets ago"); } else { data.setDuplicate(true); // Verify that the packet is a duplicate for(int j = DATA_LEN2, m = data.getValueCount(); j < m; j++) { if (sd.getValue(j) != data.getValue(j)) { data.setDuplicate(false); // System.out.println("NOT Duplicate: " + data.getNode() + " (" // + (n - i) + ": " // + ((data.getNodeTime() - sd.getNodeTime()) / 1000) + "sek): " // + seqn + " value[" + j + "]: " + sd.getValue(j) + " != " // + data.getValue(j)); break; } } if (data.isDuplicate()) { // System.out.println("Duplicate: " + data.getNode() + ": " + seqn // + (Math.abs(data.getNodeTime() - sd.getNodeTime()) / 1000) // + " sec, " + (n - i) + " packets ago"); duplicates++; break; } } } } if (!data.isDuplicate()) { for (int i = 0, n = Math.min(VALUES_COUNT, data.getValueCount()); i < n; i++) { values[i] += data.getValue(i); } if (node.getSensorDataCount() > 1) { long timeDiff = data.getNodeTime() - node.getSensorData(node.getSensorDataCount() - 2).getNodeTime(); if (timeDiff > longestPeriod) { longestPeriod = timeDiff; } if (timeDiff < shortestPeriod) { shortestPeriod = timeDiff; } } if (dataCount == 0) { // First packet from node. } else if (maxSeqno - s > 2) { // Handle sequence number overflow. seqnoDelta = maxSeqno + 1; s = seqnoDelta + seqn; if (seqn > 127) { // Sequence number restarted at 128 (to separate node restarts // from sequence number overflow). seqn -= 128; seqnoDelta -= 128; s -= 128; } else { // Sequence number restarted at 0. This is usually an indication that // the node restarted. nodeRestartCount++; } if (seqn > 0) { lost += seqn; } } else if (s > maxSeqno + 1){ lost += s - (maxSeqno + 1); } if (s < minSeqno) minSeqno = s; if (s > maxSeqno) maxSeqno = s; dataCount++; } data.setSeqno(s); } public void clear() { for (int i = 0, n = values.length; i < n; i++) { values[i] = 0L; } dataCount = 0; duplicates = 0; lost = 0; nodeRestartCount = 0; nextHopChangeCount = 0; lastNextHop = 0; minSeqno = Integer.MAX_VALUE; maxSeqno = Integer.MIN_VALUE; seqnoDelta = 0; shortestPeriod = Long.MAX_VALUE; longestPeriod = 0; } public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0, n = values.length; i < n; i++) { if (i > 0) sb.append(' '); sb.append(values[i]); } return sb.toString(); } public double getCPUPower() { return (values[TIME_CPU] * POWER_CPU) / (values[TIME_CPU] + values[TIME_LPM]); } public double getLPMPower() { return (values[TIME_LPM] * POWER_LPM) / (values[TIME_CPU] + values[TIME_LPM]); } public double getListenPower() { return (values[TIME_LISTEN] * POWER_LISTEN) / (values[TIME_CPU] + values[TIME_LPM]); } public double getTransmitPower() { return (values[TIME_TRANSMIT] * POWER_TRANSMIT) / (values[TIME_CPU] + values[TIME_LPM]); } public double getAveragePower() { return (values[TIME_CPU] * POWER_CPU + values[TIME_LPM] * POWER_LPM + values[TIME_LISTEN] * POWER_LISTEN + values[TIME_TRANSMIT] * POWER_TRANSMIT) / (values[TIME_CPU] + values[TIME_LPM]); } public double getAverageDutyCycle(int index) { return (double)(values[index]) / (double)(values[TIME_CPU] + values[TIME_LPM]); } public long getPowerMeasureTime() { return (1000L * (values[TIME_CPU] + values[TIME_LPM])) / TICKS_PER_SECOND; } public double getAverageTemperature() { return dataCount > 0 ? (-39.6 + 0.01 * (values[TEMPERATURE] / dataCount)) : 0.0; } public double getAverageRadioIntensity() { return getAverageValue(RSSI); } public double getAverageLatency() { return getAverageValue(LATENCY) / 4096.0; } public double getAverageHumidity() { double v = 0.0; if (dataCount > 0) { v = -4.0 + 405.0 * (values[HUMIDITY] / dataCount) / 10000.0; } return v > 100 ? 100 : v; } public double getAverageLight1() { return 10.0 * getAverageValue(LIGHT1) / 7.0; } public double getAverageLight2() { return 46.0 * getAverageValue(LIGHT2) / 10.0; } public double getAverageBestNeighborETX() { return getAverageValue(BEST_NEIGHBOR_ETX) / 16.0; } public int getPacketCount() { return node.getSensorDataCount(); } public int getNextHopChangeCount() { return nextHopChangeCount; } public int getEstimatedRestarts() { return nodeRestartCount; } public int getEstimatedLostCount() { return lost; } public int getDuplicateCount() { return duplicates; } public int getMinSeqno() { return minSeqno; } public int getMaxSeqno() { return maxSeqno; } public long getAveragePeriod() { if (dataCount > 1) { long first = node.getSensorData(0).getNodeTime(); long last = node.getSensorData(node.getSensorDataCount() - 1).getNodeTime(); return (last - first) / dataCount; } return 0; } public long getShortestPeriod() { return shortestPeriod < Long.MAX_VALUE ? shortestPeriod : 0; } public long getLongestPeriod() { return longestPeriod; } }
package org.exist.test.runner; import org.exist.xquery.Annotation; import org.exist.xquery.ErrorCodes; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.functions.map.MapType; import org.exist.xquery.value.*; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import javax.annotation.Nullable; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.exist.xquery.FunctionDSL.optParam; import static org.exist.xquery.FunctionDSL.param; import static org.exist.xquery.FunctionDSL.params; public class ExtTestErrorFunction extends JUnitIntegrationFunction { public ExtTestErrorFunction(final XQueryContext context, final String parentName, final RunNotifier notifier) { super("ext-test-error-function", params( param("name", Type.STRING, "name of the test"), optParam("error", Type.MAP, "error detail of the test. e.g. map { \"code\": $err:code, \"description\": $err:description, \"value\": $err:value, \"module\": $err:module, \"line-number\": $err:line-number, \"column-number\": $err:column-number, \"additional\": $err:additional, \"xquery-stack-trace\": $exerr:xquery-stack-trace, \"java-stack-trace\": $exerr:java-stack-trace}") ), context, parentName, notifier); } @Override public Sequence eval(final Sequence contextSequence, final Item contextItem) throws XPathException { final Sequence arg1 = getCurrentArguments()[0]; final String name = arg1.itemAt(0).getStringValue(); final Sequence arg2 = getCurrentArguments().length == 2 ? getCurrentArguments()[1] : null; final MapType error = arg2 != null ? (MapType)arg2.itemAt(0) : null; final Description description = Description.createTestDescription(suiteName, name, new Annotation[0]); // notify JUnit try { final XPathException errorReason = errorMapAsXPathException(error); notifier.fireTestFailure(new Failure(description, errorReason)); } catch (final XPathException e) { //signal internal failure notifier.fireTestFailure(new Failure(description, e)); } return Sequence.EMPTY_SEQUENCE; } private XPathException errorMapAsXPathException(final MapType errorMap) throws XPathException { final Sequence seqDescription = errorMap.get(new StringValue("description")); final String description; if(seqDescription != null && !seqDescription.isEmpty()) { description = seqDescription.itemAt(0).getStringValue(); } else { description = ""; } final Sequence seqErrorCode = errorMap.get(new StringValue("code")); final ErrorCodes.ErrorCode errorCode; if(seqErrorCode != null && !seqErrorCode.isEmpty()) { errorCode = new ErrorCodes.ErrorCode(((QNameValue)seqErrorCode.itemAt(0)).getQName(), description); } else { errorCode = ErrorCodes.ERROR; } final Sequence seqLineNumber = errorMap.get(new StringValue("line-number")); final int lineNumber; if(seqLineNumber != null && !seqLineNumber.isEmpty()) { lineNumber = seqLineNumber.itemAt(0).toJavaObject(int.class); } else { lineNumber = -1; } final Sequence seqColumnNumber = errorMap.get(new StringValue("column-number")); final int columnNumber; if(seqColumnNumber != null && !seqColumnNumber.isEmpty()) { columnNumber = seqColumnNumber.itemAt(0).toJavaObject(int.class); } else { columnNumber = -1; } final XPathException xpe = new XPathException(lineNumber, columnNumber, errorCode, description); final Sequence seqJavaStackTrace = errorMap.get(new StringValue("java-stack-trace")); if (seqJavaStackTrace != null && !seqJavaStackTrace.isEmpty()) { try { xpe.setStackTrace(convertStackTraceElements(seqJavaStackTrace)); } catch (final NullPointerException e) { e.printStackTrace(); } } return xpe; } private static final Pattern PTN_CAUSED_BY = Pattern.compile("Caused by:\\s([a-zA-Z0-9_$\\.]+)(?::\\s(.+))?"); private static final Pattern PTN_AT = Pattern.compile("at\\s((?:[a-zA-Z0-9_$]+)(?:\\.[a-zA-Z0-9_$]+)*)\\.([a-zA-Z0-9_$-]+)\\(([a-zA-Z0-9_]+\\.java):([0-9]+)\\)"); protected StackTraceElement[] convertStackTraceElements(final Sequence seqJavaStackTrace) throws XPathException { StackTraceElement[] traceElements = new StackTraceElement[seqJavaStackTrace.getItemCount() - 1]; final Matcher matcherAt = PTN_AT.matcher(""); // index 0 is the first `Caused by: ...` int i = 1; for ( ; i < seqJavaStackTrace.getItemCount(); i++) { final String item = seqJavaStackTrace.itemAt(i).getStringValue(); final StackTraceElement stackTraceElement = convertStackTraceElement(matcherAt, item); if (stackTraceElement == null) { break; } traceElements[i - 1] = stackTraceElement; } if (i + 1 < seqJavaStackTrace.getItemCount()) { traceElements = Arrays.copyOf(traceElements, i); } return traceElements; } private @Nullable StackTraceElement convertStackTraceElement(final Matcher matcherAt, final String s) { matcherAt.reset(s); if (matcherAt.matches()) { final String declaringClass = matcherAt.group(1); final String methodName = matcherAt.group(2); final String fileName = matcherAt.group(3); final String lineNumber = matcherAt.group(4); return new StackTraceElement(declaringClass, methodName, fileName, Integer.valueOf(lineNumber)); } else { return null; } } }
package org.exist.xquery.modules.lucene; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; import org.apache.lucene.queryParser.ParseException; import org.exist.dom.DocumentSet; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.indexing.lucene.LuceneIndex; import org.exist.indexing.lucene.LuceneIndexWorker; import org.exist.storage.ElementValue; import org.exist.xquery.*; import org.exist.xquery.modules.lucene.LuceneModule; import org.exist.xquery.value.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; public class Query extends Function implements Optimizable { protected static final Logger logger = Logger.getLogger(Query.class); public final static FunctionSignature[] signatures = { new FunctionSignature( new QName("query", LuceneModule.NAMESPACE_URI, LuceneModule.PREFIX), "Queries a node set using a Lucene full text index; a lucene index " + "must already be defined on the nodes, because if no index is available " + "on a node, nothing will be found. Indexes on descendant nodes are not " + "used. The context of the Lucene query is determined by the given input " + "node set. The query is specified either as a query string based on " + "Lucene's default query syntax or as an XML fragment. " + "See http://exist-db.org/lucene.html#N1029E for complete documentation.", new SequenceType[] { new FunctionParameterSequenceType("nodes", Type.NODE, Cardinality.ZERO_OR_MORE, "The node set to search using a Lucene full text index which is defined on those nodes"), new FunctionParameterSequenceType("query", Type.ITEM, Cardinality.EXACTLY_ONE, "The query to search for, provided either as a string or text in Lucene's default query " + "syntax or as an XML fragment to bypass Lucene's default query parser") }, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set matching the query. match highlighting information " + "will be available for all returned nodes. Lucene's match score can be retrieved via " + "the ft:score function.") ), new FunctionSignature( new QName("query", LuceneModule.NAMESPACE_URI, LuceneModule.PREFIX), "Queries a node set using a Lucene full text index; a lucene index " + "must already be defined on the nodes, because if no index is available " + "on a node, nothing will be found. Indexes on descendant nodes are not " + "used. The context of the Lucene query is determined by the given input " + "node set. The query is specified either as a query string based on " + "Lucene's default query syntax or as an XML fragment. " + "See http://exist-db.org/lucene.html#N1029E for complete documentation.", new SequenceType[] { new FunctionParameterSequenceType("nodes", Type.NODE, Cardinality.ZERO_OR_MORE, "The node set to search using a Lucene full text index which is defined on those nodes"), new FunctionParameterSequenceType("query", Type.ITEM, Cardinality.EXACTLY_ONE, "The query to search for, provided either as a string or text in Lucene's default query " + "syntax or as an XML fragment to bypass Lucene's default query parser"), new FunctionParameterSequenceType("options", Type.NODE, Cardinality.ZERO_OR_ONE, "An XML fragment containing options to be passed to Lucene's query parser. The following " + "options are supported (a description can be found in the docs):\n" + "<options>\n" + " <default-operator>and|or</default-operator>\n" + " <phrase-slop>number</phrase-slop>\n" + " <leading-wildcard>yes|no</leading-wildcard>\n" + " <filter-rewrite>yes|no</filter-rewrite>\n" + "</options>") }, new FunctionReturnSequenceType(Type.NODE, Cardinality.ZERO_OR_MORE, "all nodes from the input node set matching the query. match highlighting information " + "will be available for all returned nodes. Lucene's match score can be retrieved via " + "the ft:score function.") ) }; private LocationStep contextStep = null; protected QName contextQName = null; protected int axis = Constants.UNKNOWN_AXIS; private NodeSet preselectResult = null; protected boolean optimizeSelf = false; public Query(XQueryContext context, FunctionSignature signature) { super(context, signature); } public void setArguments(List arguments) throws XPathException { Expression path = (Expression) arguments.get(0); steps.add(path); Expression arg = (Expression) arguments.get(1); arg = new DynamicCardinalityCheck(context, Cardinality.EXACTLY_ONE, arg, new org.exist.xquery.util.Error(org.exist.xquery.util.Error.FUNC_PARAM_CARDINALITY, "2", mySignature)); steps.add(arg); if (arguments.size() == 3) { arg = (Expression) arguments.get(2); arg = new DynamicCardinalityCheck(context, Cardinality.EXACTLY_ONE, arg, new org.exist.xquery.util.Error(org.exist.xquery.util.Error.FUNC_PARAM_CARDINALITY, "2", mySignature)); arg = new DynamicTypeCheck(context, Type.ELEMENT, arg); steps.add(arg); } } /* (non-Javadoc) * @see org.exist.xquery.PathExpr#analyze(org.exist.xquery.Expression) */ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { super.analyze(new AnalyzeContextInfo(contextInfo)); List steps = BasicExpressionVisitor.findLocationSteps(getArgument(0)); if (!steps.isEmpty()) { LocationStep firstStep = (LocationStep) steps.get(0); LocationStep lastStep = (LocationStep) steps.get(steps.size() - 1); if (steps.size() == 1 && firstStep.getAxis() == Constants.SELF_AXIS) { Expression outerExpr = contextInfo.getContextStep(); if (outerExpr != null && outerExpr instanceof LocationStep) { LocationStep outerStep = (LocationStep) outerExpr; NodeTest test = outerStep.getTest(); if (!test.isWildcardTest() && test.getName() != null) { contextQName = new QName(test.getName()); if (outerStep.getAxis() == Constants.ATTRIBUTE_AXIS || outerStep.getAxis() == Constants.DESCENDANT_ATTRIBUTE_AXIS) contextQName.setNameType(ElementValue.ATTRIBUTE); contextStep = firstStep; axis = outerStep.getAxis(); optimizeSelf = true; } } } else { NodeTest test = lastStep.getTest(); if (!test.isWildcardTest() && test.getName() != null) { contextQName = new QName(test.getName()); if (lastStep.getAxis() == Constants.ATTRIBUTE_AXIS || lastStep.getAxis() == Constants.DESCENDANT_ATTRIBUTE_AXIS) contextQName.setNameType(ElementValue.ATTRIBUTE); axis = firstStep.getAxis(); contextStep = lastStep; } } } } public boolean canOptimize(Sequence contextSequence) { return contextQName != null; } public boolean optimizeOnSelf() { return optimizeSelf; } public int getOptimizeAxis() { return axis; } public NodeSet preSelect(Sequence contextSequence, boolean useContext) throws XPathException { if (contextSequence != null && !contextSequence.isPersistentSet()) // in-memory docs won't have an index return NodeSet.EMPTY_SET; long start = System.currentTimeMillis(); // the expression can be called multiple times, so we need to clear the previous preselectResult preselectResult = null; LuceneIndexWorker index = (LuceneIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(LuceneIndex.ID); DocumentSet docs = contextSequence.getDocumentSet(); Item key = getKey(contextSequence, null); List qnames = new ArrayList(1); qnames.add(contextQName); Properties options = parseOptions(contextSequence, null); try { if (Type.subTypeOf(key.getType(), Type.ELEMENT)) preselectResult = index.query(context, getExpressionId(), docs, useContext ? contextSequence.toNodeSet() : null, qnames, (Element) ((NodeValue)key).getNode(), NodeSet.DESCENDANT, options); else preselectResult = index.query(context, getExpressionId(), docs, useContext ? contextSequence.toNodeSet() : null, qnames, key.getStringValue(), NodeSet.DESCENDANT, options); } catch (IOException e) { throw new XPathException(this, "Error while querying full text index: " + e.getMessage(), e); } catch (ParseException e) { throw new XPathException(this, "Error while querying full text index: " + e.getMessage(), e); } LOG.debug("Lucene query took " + (System.currentTimeMillis() - start)); return preselectResult; } public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException { if (contextItem != null) contextSequence = contextItem.toSequence(); if (contextSequence != null && !contextSequence.isPersistentSet()) // in-memory docs won't have an index return Sequence.EMPTY_SEQUENCE; NodeSet result; if (preselectResult == null) { Sequence input = getArgument(0).eval(contextSequence); if (input.isEmpty()) result = NodeSet.EMPTY_SET; else { NodeSet inNodes = input.toNodeSet(); DocumentSet docs = inNodes.getDocumentSet(); LuceneIndexWorker index = (LuceneIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(LuceneIndex.ID); Item key = getKey(contextSequence, contextItem); List qnames = null; if (contextQName != null) { qnames = new ArrayList(1); qnames.add(contextQName); } Properties options = parseOptions(contextSequence, contextItem); try { if (Type.subTypeOf(key.getType(), Type.ELEMENT)) result = index.query(context, getExpressionId(), docs, inNodes, qnames, (Element)((NodeValue)key).getNode(), NodeSet.ANCESTOR, options); else result = index.query(context, getExpressionId(), docs, inNodes, qnames, key.getStringValue(), NodeSet.ANCESTOR, options); } catch (IOException e) { throw new XPathException(this, e.getMessage()); } catch (ParseException e) { throw new XPathException(this, e.getMessage()); } } } else { contextStep.setPreloadedData(contextSequence.getDocumentSet(), preselectResult); result = getArgument(0).eval(contextSequence).toNodeSet(); } return result; } private Item getKey(Sequence contextSequence, Item contextItem) throws XPathException { Sequence keySeq = getArgument(1).eval(contextSequence, contextItem); Item key = keySeq.itemAt(0); if (!(Type.subTypeOf(key.getType(), Type.STRING) || Type.subTypeOf(key.getType(), Type.NODE))) throw new XPathException(this, "Second argument to ft:query should either be a query string or " + "an XML element describing the query. Found: " + Type.getTypeName(key.getType())); return key; } public int getDependencies() { final Expression stringArg = getArgument(0); if (Type.subTypeOf(stringArg.returnsType(), Type.NODE) && !Dependency.dependsOn(stringArg, Dependency.CONTEXT_ITEM)) { return Dependency.CONTEXT_SET; } else { return Dependency.CONTEXT_SET + Dependency.CONTEXT_ITEM; } } public int returnsType() { return Type.NODE; } private Properties parseOptions(Sequence contextSequence, Item contextItem) throws XPathException { if (getArgumentCount() < 3) return null; Properties options = new Properties(); Sequence optSeq = getArgument(2).eval(contextSequence, contextItem); NodeValue optRoot = (NodeValue) optSeq.itemAt(0); try { XMLStreamReader reader = context.getXMLStreamReader(optRoot); reader.next(); reader.next(); while (reader.hasNext()) { int status = reader.next(); if (status == XMLStreamReader.START_ELEMENT) { options.put(reader.getLocalName(), reader.getElementText()); } } return options; } catch (XMLStreamException e) { throw new XPathException(this, "Error while parsing options to ft:query: " + e.getMessage(), e); } catch (IOException e) { throw new XPathException(this, "Error while parsing options to ft:query: " + e.getMessage(), e); } } }
package org.opennms.poller.remote; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.JOptionPane; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.opennms.netmgt.icmp.NullPinger; import org.opennms.netmgt.icmp.Pinger; import org.opennms.netmgt.icmp.PingerFactory; import org.opennms.netmgt.poller.remote.PollerFrontEnd; import org.opennms.netmgt.poller.remote.support.DefaultPollerFrontEnd.PollerFrontEndStates; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; /** * <p>Main class.</p> * * @author <a href="mailto:ranger@opennms.org">Benjamin Reed</a> * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> */ public class Main implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Main.class); protected final String[] m_args; protected URI m_uri = null; protected String m_locationName; protected String m_username = null; protected String m_password = null; protected boolean m_gui = false; protected boolean m_disableIcmp = false; private Main(String[] args) { // Give us some time to attach a debugger if necessary //try { Thread.sleep(20000); } catch (InterruptedException e) {} m_args = Arrays.copyOf(args, args.length); } public void initializePinger() { if (m_disableIcmp) { LOG.info("Disabling ICMP by user request."); System.setProperty("org.opennms.netmgt.icmp.pingerClass", "org.opennms.netmgt.icmp.NullPinger"); PingerFactory.setInstance(new NullPinger()); return; } final String pingerClass = System.getProperty("org.opennms.netmgt.icmp.pingerClass"); if (pingerClass == null) { LOG.info("System property org.opennms.netmgt.icmp.pingerClass is not set; using JnaPinger by default"); System.setProperty("org.opennms.netmgt.icmp.pingerClass", "org.opennms.netmgt.icmp.jna.JnaPinger"); } LOG.info("Pinger class: {}", System.getProperty("org.opennms.netmgt.icmp.pingerClass")); try { final Pinger pinger = PingerFactory.getInstance(); pinger.ping(InetAddress.getLoopbackAddress()); } catch (final Throwable t) { LOG.warn("Unable to get pinger instance. Setting pingerClass to NullPinger. For details, see: http: System.setProperty("org.opennms.netmgt.icmp.pingerClass", "org.opennms.netmgt.icmp.NullPinger"); PingerFactory.setInstance(new NullPinger()); if (m_gui) { final String message = "ICMP (ping) could not be initialized: " + t.getMessage() + "\nDisabling ICMP and using the NullPinger instead." + "\nFor details, see: http: JOptionPane.showMessageDialog(null, message, "ICMP Not Available", JOptionPane.WARNING_MESSAGE); } } } private void getAuthenticationInfo() { if (m_uri == null || m_uri.getScheme() == null) { throw new RuntimeException("no URI specified!"); } if (m_uri.getScheme().equals("rmi")) { // RMI doesn't have authentication return; } if (m_username == null) { GroovyGui gui = createGui(); gui.createAndShowGui(); AuthenticationBean auth = gui.getAuthenticationBean(); m_username = auth.getUsername(); m_password = auth.getPassword(); } if (m_username != null) { SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(m_username, m_password)); } } private static GroovyGui createGui() { try { return (GroovyGui)Class.forName("org.opennms.groovy.poller.remote.ConfigurationGui").newInstance(); } catch (Throwable e) { throw new RuntimeException("Unable to find Configuration GUI!", e); } } @Override public void run() { try { // Parse arguments to initialize the configuration fields. parseArguments(m_args); // Test to make sure that we can use ICMP. If not, replace the ICMP // implementation with NullPinger. initializePinger(); // If we didn't get authentication information from the command line or // system properties, then use an AWT window to prompt the user. // Initialize a Spring {@link SecurityContext} that contains the // credentials. getAuthenticationInfo(); AbstractApplicationContext context = createAppContext(); PollerFrontEnd frontEnd = getPollerFrontEnd(context); if (!m_gui) { if (!frontEnd.isRegistered()) { if (m_locationName == null) { LOG.error("No location name provided. You must pass a location name the first time you start the remote poller!"); System.exit(27); } else { frontEnd.register(m_locationName); } } } } catch(Throwable e) { // a fatal exception occurred LOG.error("Exception occurred during registration!", e); System.exit(27); } } private void parseArguments(String[] args) throws ParseException { Options options = new Options(); options.addOption("h", "help", false, "this help"); options.addOption("d", "debug", false, "write debug messages to the log"); options.addOption("g", "gui", false, "start a GUI (default: false)"); options.addOption("i", "disable-icmp", false, "disable ICMP/ping (overrides -Dorg.opennms.netmgt.icmp.pingerClass=)"); options.addOption("l", "location", true, "the location name of this remote poller"); options.addOption("u", "url", true, "the URL for OpenNMS (example: https://server-name/opennms-remoting)"); options.addOption("n", "name", true, "the name of the user to connect as"); options.addOption("p", "password", true, "the password to use when connecting"); CommandLineParser parser = new PosixParser(); CommandLine cl = parser.parse(options, args); if (cl.hasOption("h")) { usage(options); System.exit(1); } if (cl.hasOption("d")) { } if (cl.hasOption("i")) { m_disableIcmp = true; } if (cl.hasOption("l")) { m_locationName = cl.getOptionValue("l"); } if (cl.hasOption("u")) { String arg = cl.getOptionValue("u").toLowerCase(); try { m_uri = new URI(arg); } catch (URISyntaxException e) { usage(options); e.printStackTrace(); System.exit(2); } } else { usage(options); System.exit(3); } if (cl.hasOption("g")) { m_gui = true; } if (cl.hasOption("n")) { m_username = cl.getOptionValue("n"); m_password = cl.getOptionValue("p"); if (m_password == null) { m_password = ""; } } // If we cannot obtain the username/password from the command line, attempt // to optionally get it from system properties if (m_username == null) { m_username = System.getProperty("opennms.poller.server.username"); if (m_username != null) { m_password = System.getProperty("opennms.poller.server.password"); if (m_password == null) { m_password = ""; } } } } private static void usage(Options o) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Main.class.getName() + " -u [URL] [options]", o); } private AbstractApplicationContext createAppContext() { /* * Set a system property called user.home.url so that the * Spring contexts can reference resources that are stored * in the user's home directory. */ File homeDir = new File(System.getProperty("user.home")); String homeUrl = homeDir.toURI().toString(); // Trim the trailing file separator off of the end of the URI if (homeUrl.endsWith("/")) { homeUrl = homeUrl.substring(0, homeUrl.length()-1); } LOG.info("user.home.url = {}", homeUrl); System.setProperty("user.home.url", homeUrl); /** * <p>main</p> * * @param args an array of {@link java.lang.String} objects. * @throws java.lang.Exception if any. */ public static void main(String[] args) { try { String killSwitchFileName = System.getProperty("opennms.poller.killSwitch.resource"); File killSwitch = null; if (! "".equals(killSwitchFileName) && killSwitchFileName != null) { killSwitch = new File(System.getProperty("opennms.poller.killSwitch.resource")); if (!killSwitch.exists()) { try { killSwitch.createNewFile(); } catch (IOException ioe) { // We'll just do without one } } } new Main(args).run(); } catch (Throwable e) { e.printStackTrace(); } } }
package wraith.library.WindowUtil; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.Random; import javax.swing.JPanel; public class LineGraph extends JPanel{ private String[] rowNames = new String[0]; private String[] colNames = new String[0]; private double[][] values = new double[0][]; private String[][] valueNames = new String[0][]; private String[] key = new String[0]; private static Color[] PRIME_COLORS = { Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.YELLOW, Color.CYAN, Color.MAGENTA, Color.PINK, new Color(151, 35, 201), new Color(152, 235, 29), new Color(75, 81, 255) }; private static final int COLOR_GENERATOR = 2; private static final int PIXEL_TEXT_BUFFER = 10; public void setValues(double[][] values, String[][] valueNames){ this.values=values; this.valueNames=valueNames; repaint(); } @Override public void paint(Graphics g1){ Graphics2D g = (Graphics2D)g1; g.setColor(Color.gray); g.fillRect(0, 0, getWidth(), getHeight()); if(values.length==0)return; FontMetrics fm = g.getFontMetrics(); int rowNameBuffer = calculateRowNameBuffer(fm)+PIXEL_TEXT_BUFFER; int colNameBuffer = fm.getHeight()+PIXEL_TEXT_BUFFER; int keyBuffer = calculateKeyBuffer(fm)+PIXEL_TEXT_BUFFER; int width = getWidth()-rowNameBuffer-keyBuffer; int height = getHeight()-colNameBuffer; g.setColor(Color.black); for(int i = 0; i<rowNames.length; i++)g.drawString(rowNames[i], (rowNameBuffer-fm.stringWidth(rowNames[i]))/2, (int)(height/(double)rowNames.length*((rowNames.length-i)))); for(int i = 0; i<colNames.length; i++)g.drawString(colNames[i], (int)(width/(double)colNames.length*(i+0.5)-fm.stringWidth(colNames[i])/2), getHeight()-colNameBuffer/2+fm.getAscent()/2); g.setColor(Color.darkGray); for(int i = 0; i<=rowNames.length; i++)g.drawLine(rowNameBuffer, (int)(height/(double)rowNames.length*i), getWidth()-keyBuffer, (int)(height/(double)rowNames.length*i)); for(int i = 0; i<colNames.length; i++)g.drawLine((int)(width/(double)colNames.length*(i+0.5)), 0, (int)(width/(double)colNames.length*(i+0.5)), height); Color c; Random colorGen = new Random(COLOR_GENERATOR); for(int a = 0; a<values.length; a++){ c=(values.length<PRIME_COLORS.length?PRIME_COLORS[a]:new Color(colorGen.nextFloat(), colorGen.nextFloat(), colorGen.nextFloat())); g.setColor(c); if(values[a].length==1){ g.drawLine(rowNameBuffer, (int)(height*(1-values[a][0])), getWidth()-keyBuffer, (int)(height*(1-values[a][0]))); g.setColor(Color.white); g.drawString(valueNames[a][0], (width-fm.stringWidth(valueNames[a][0]))/2, (int)(height*(1-values[a][0]))); g.setColor(c); }else{ for(int b = 0; b<values[a].length; b++){ if(b==0){ g.setColor(Color.white); g.drawString(valueNames[a][b], (int)(width/(double)colNames.length*(b+0.5))-fm.stringWidth(valueNames[a][b])/2, (int)(height*(1-values[a][b]))-2); g.setColor(c); continue; } g.drawLine((int)(width/(double)colNames.length*(b-0.5)), (int)(height*(1-values[a][b-1])), (int)(width/(double)colNames.length*(b+0.5)), (int)(height*(1-values[a][b]))); g.setColor(Color.white); g.drawString(valueNames[a][b], (int)(width/(double)colNames.length*(b+0.5))-fm.stringWidth(valueNames[a][b])/2, (int)(height*(1-values[a][b]))-2); g.setColor(c); } } } Random keyGen = new Random(COLOR_GENERATOR); int sampleX = getWidth()-keyBuffer+PIXEL_TEXT_BUFFER/2; for(int i = 0; i<key.length; i++){ c=(values.length<PRIME_COLORS.length?PRIME_COLORS[i]:new Color(keyGen.nextFloat(), keyGen.nextFloat(), keyGen.nextFloat())); g.setColor(c); g.fillRect(sampleX, i*(fm.getHeight()+5)+PIXEL_TEXT_BUFFER/2, 10, 10); g.setColor(Color.black); g.drawRect(sampleX, i*(fm.getHeight()+5)+PIXEL_TEXT_BUFFER/2, 10, 10); g.setColor(Color.white); g.drawString(key[i], sampleX+10+PIXEL_TEXT_BUFFER/2, i*(fm.getHeight()+5)+PIXEL_TEXT_BUFFER/2+10); } g.dispose(); } private int calculateRowNameBuffer(FontMetrics fm){ int l = 0; int c; for(String s : rowNames)if((c=fm.stringWidth(s))>l)l=c; return l; } public void setRowNames(String[] rowNames){ this.rowNames=rowNames; repaint(); } public void setColNames(String[] colNames){ this.colNames=colNames; repaint(); } public void setKey(String[] key){ this.key=key; repaint(); } private int calculateKeyBuffer(FontMetrics fm){ int l = 0; int c; for(String s : key)if((c=fm.stringWidth(s))>l)l=c; return l+10+PIXEL_TEXT_BUFFER/2; } }
package com.ppproductions.yankenpon.logic; import java.util.Scanner; /** * * @author pki */ public class duel { Scanner Puffer = new Scanner(System.in); final Integer NUMBER_OF_WINS = 3; final Integer WIN_PLAYER = 0; final Integer WIN_OPPONENT = 1; final Integer TIE = 2; private String opponent; private Integer oWinCount; private Integer pWinCount; duel (String opponent){ this.opponent=opponent; } public Boolean fight() { opponent Opponent = new opponent(); Boolean Win=true; String PlayerMove; String OpponentMove; Integer Comparisation; do { //get Opponent & Player choices: OpponentMove = Opponent.getPon(); do { PlayerMove = Puffer.nextLine(); } while (!"Rock".equals(PlayerMove) || !"Paper".equals(PlayerMove) || !"Scissors".equals(PlayerMove)); Comparisation = compareMoves(PlayerMove, OpponentMove); if (Comparisation == WIN_PLAYER) pWinCount++; else if (Comparisation == WIN_OPPONENT) oWinCount++; } while (oWinCount < NUMBER_OF_WINS && pWinCount < NUMBER_OF_WINS); if (pWinCount < oWinCount) Win = false; return Win; } private Integer compareMoves(String PlayerMove, String OpponentMove) { Integer result = null; switch (PlayerMove) { case "Rock": if ("Rock".equals(OpponentMove)) result = TIE; if ("Paper".equals(OpponentMove)) result = WIN_OPPONENT; if ("Scissors".equals(OpponentMove)) result = WIN_PLAYER; break; case "Paper": if ("Paper".equals(OpponentMove)) result = TIE; if ("Scissors".equals(OpponentMove)) result = WIN_OPPONENT; if ("Rock".equals(OpponentMove)) result = WIN_PLAYER; break; case "Scissors": if ("Scissors".equals(OpponentMove)) result = TIE; if ("Rock".equals(OpponentMove)) result = WIN_OPPONENT; if ("Paper".equals(OpponentMove)) result = WIN_PLAYER; break; default: result = WIN_OPPONENT; break; } return result; } }
package net.yuanmomo.dwz.test.mock; import net.yuanmomo.dwz.business.mybatis.TestBusiness; import net.yuanmomo.dwz.controller.mybatis.TestController; import net.yuanmomo.dwz.mybatis.mapper.TestMapper; import net.yuanmomo.dwz.test.BaseTest; import org.easymock.EasyMock; import org.easymock.IMocksControl; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.util.AopTestUtils; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.List; public class DemoMockTest extends BaseTest { @Autowired protected TestBusiness testBusiness = null; @Autowired protected TestController testController = null; private TestMapper mockTestMapper; private TestBusiness mockTestBusiness; private IMocksControl control = null; /** * , mock */ @Before public void before() throws Exception { control = EasyMock.createControl(); mockTestMapper = control.createMock(TestMapper.class); mockTestBusiness = control.createMock(TestBusiness.class); ReflectionTestUtils.setField(AopTestUtils.getTargetObject(testBusiness), "testMapper", mockTestMapper); ReflectionTestUtils.setField(AopTestUtils.getTargetObject(testController), "testBusiness", mockTestBusiness); } /** * 1. mock mapper , business , */ @Test public void testInsertSelective() { try { // net.yuanmomo.dwz.bean.Test test = null; // mapper , int count = testBusiness.insertSelective(test); Assert.assertEquals(", 0", 0, count); count = 0; test = new net.yuanmomo.dwz.bean.Test(); // 2. , business , mapper.insertSelective EasyMock.expect(mockTestMapper.insertSelective(EasyMock.anyObject(net.yuanmomo.dwz.bean.Test.class))).andThrow(new RuntimeException()); control.replay(); // 4. , business try { count = testBusiness.insertSelective(test); Assert.fail(); } catch (Exception e) { Assert.assertTrue(true); } Assert.assertEquals("", 0, count); // 6. mock control.verify(); control.reset(); // i = 0 , // i = 1 , for (int i = 0; i <= 1; i++) { count = 0; test = new net.yuanmomo.dwz.bean.Test(); // 2. , business , mapper.insertSelective 0 , EasyMock.expect(mockTestMapper.insertSelective(EasyMock.anyObject(net.yuanmomo.dwz.bean.Test.class))).andReturn(i); control.replay(); // 4. , business count = testBusiness.insertSelective(test); Assert.assertEquals("", i, count); // 6. mock control.verify(); control.reset(); } // List<net.yuanmomo.dwz.bean.Test> testList = null; // mapper , count = testBusiness.insertSelective(testList); Assert.assertEquals(" , 0", 0, count); count = 0; testList = new ArrayList<>(); for (int i1 = 0; i1 < 10; i1++) { testList.add(new net.yuanmomo.dwz.bean.Test()); } // 2. , business , mapper.insertSelective EasyMock.expect(mockTestMapper.insertSelective(EasyMock.anyObject(net.yuanmomo.dwz.bean.Test.class))).andThrow(new RuntimeException()); control.replay(); // 4. , business try { count = testBusiness.insertSelective(testList); Assert.fail(); } catch (Exception e) { Assert.assertTrue(true); } Assert.assertEquals(0, count); // 6. mock control.verify(); control.reset(); /** * i = 0 , 10 * i = 1 , 10 */ for (int i = 0; i <= 1; i++) { count = 0; testList = new ArrayList<>(); for (int i1 = 0; i1 < 10; i1++) { testList.add(new net.yuanmomo.dwz.bean.Test()); } // 2. , business , mapper.insertSelective 0 , EasyMock.expect(mockTestMapper.insertSelective(EasyMock.anyObject(net.yuanmomo.dwz.bean.Test.class))).andReturn(i).times(10); control.replay(); // 4. , business count = testBusiness.insertSelective(testList); Assert.assertEquals(i == 0 ? 0 : 10, count); // 6. mock control.verify(); control.reset(); } /** * 10 , 5, 5 */ count = 0; testList = new ArrayList<>(); for (int i1 = 0; i1 < 5; i1++) { testList.add(new net.yuanmomo.dwz.bean.Test()); } // 2. , business , mapper.insertSelective 0 , EasyMock.expect(mockTestMapper.insertSelective(EasyMock.anyObject(net.yuanmomo.dwz.bean.Test.class))).andReturn(1).times(5); control.replay(); // 4. , business count = testBusiness.insertSelective(testList); Assert.assertEquals(5, count); // 6. mock control.verify(); control.reset(); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void testSelectGetTestByKey() { try { /** * key */ // 2. , business , mapper.selectByPrimaryKey net.yuanmomo.dwz.bean.Test test = null; EasyMock.expect(mockTestMapper.selectByPrimaryKey(null)).andReturn(null); control.replay(); // 4. , business test = testBusiness.getTestByKey(null); Assert.assertNull(test); // 6. mock control.verify(); control.reset(); // 2. , business , mapper.selectByPrimaryKey EasyMock.expect(mockTestMapper.selectByPrimaryKey(EasyMock.anyLong())).andThrow(new RuntimeException()); control.replay(); // 4. , business try { test = testBusiness.getTestByKey(EasyMock.anyLong()); Assert.fail(); } catch (Exception e) { Assert.assertTrue(true); } Assert.assertNull(test); // 6. mock control.verify(); control.reset(); // 2. , business , mapper.selectByPrimaryKey EasyMock.expect(mockTestMapper.selectByPrimaryKey(0L)).andReturn(null); control.replay(); // 4. , business test = testBusiness.getTestByKey(EasyMock.anyLong()); Assert.assertNull(test); // 6. mock control.verify(); control.reset(); // 2. , business , mapper.selectByPrimaryKey EasyMock.expect(mockTestMapper.selectByPrimaryKey(0L)).andReturn(new net.yuanmomo.dwz.bean.Test()); control.replay(); // 4. , business test = testBusiness.getTestByKey(EasyMock.anyLong()); Assert.assertNotNull(test); // 6. mock control.verify(); control.reset(); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } }
import java.util.regex.Matcher; import java.util.regex.Pattern; public class HeaderEditor { public static int parseLength(String header){ int returnVar = 0; Pattern pattern = Pattern.compile("Content-Length:(.)*"); Matcher matcher = pattern.matcher(header); if(!matcher.find()){ //it was a GET, or non-payload HTTP packet return -1; } String length = matcher.group(); length = length.replaceFirst("Content-Length: ",""); length = length.trim(); try { returnVar = Integer.parseInt(length); } catch(NumberFormatException e){ System.err.println("Error while parsing '"+length+"' to an integer!"); } return returnVar; } public static int parseLength(byte[] request){ String strRequest = new String(request); return parseLength(strRequest); } public static int parseLength(String[] header){ StringBuilder sb = new StringBuilder(); for(String s: header)sb.append(s); return parseLength(sb.toString()); } /** * Grabs the host from the HTTP request * @param request HTTP request as a string * @return the hostname as a string * * Complexity: 2 */ public static String parseHost(byte[] request){ String httpHeader = new String(request); Pattern pattern = Pattern.compile("Host:(.)*"); Matcher matcher = pattern.matcher(httpHeader); if(!matcher.find()){ System.err.println("Malformed HTTP request! No Host specified!"); return null; } String returnVar = matcher.group(); returnVar = returnVar.trim(); returnVar = returnVar.replaceFirst("Host: ",""); returnVar = returnVar.replaceFirst(":(.)*", "");//get rid of the explicit port. returnVar = returnVar.trim(); return returnVar; } public static byte[] convertConnection(byte[] request){ String returnVar = new String(request); returnVar = returnVar.replaceFirst("Connection: keep-alive","Connection: close"); return returnVar.getBytes(); } }
package lu.ing.gameofcode.services; import com.google.android.gms.maps.model.LatLng; import java.util.List; import lu.ing.gameofcode.model.BusStop; public interface BusService { List<BusStop> getBusStops(final int busLineNumber, LatLng start, LatLng stop); }
package mil.nga.geopackage.user; import android.database.Cursor; import mil.nga.geopackage.db.GeoPackageConnection; import mil.nga.geopackage.db.GeoPackageDatabase; import mil.nga.geopackage.db.SQLiteQueryBuilder; /** * GeoPackage Connection used to define common functionality within different * connection types * * @param <TColumn> column type * @param <TTable> table type * @param <TRow> row type * @param <TResult> result type * @author osbornb */ public abstract class UserConnection<TColumn extends UserColumn, TTable extends UserTable<TColumn>, TRow extends UserRow<TColumn, TTable>, TResult extends UserCursor<TColumn, TTable, TRow>> extends UserCoreConnection<TColumn, TTable, TRow, TResult> { /** * Database connection */ protected final GeoPackageDatabase database; /** * Table */ protected TTable table; /** * Constructor * * @param database GeoPackage connection */ protected UserConnection(GeoPackageConnection database) { this.database = database.getDb(); } /** * Get the table * * @return table * @since 3.2.0 */ public TTable getTable() { return table; } /** * Set the table * * @param table table * @since 3.2.0 */ public void setTable(TTable table) { this.table = table; } /** * {@inheritDoc} */ @Override public TResult rawQuery(String sql, String[] selectionArgs) { UserQuery query = new UserQuery(sql, selectionArgs); TResult result = query(query); return result; } /** * {@inheritDoc} */ @Override public TResult query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) { UserQuery query = new UserQuery(table, columns, selection, selectionArgs, groupBy, having, orderBy); TResult result = query(query); return result; } /** * {@inheritDoc} */ @Override public TResult query(String table, String[] columns, String[] columnsAs, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) { UserQuery query = new UserQuery(table, columns, columnsAs, selection, selectionArgs, groupBy, having, orderBy); TResult result = query(query); return result; } /** * {@inheritDoc} */ @Override public TResult query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { UserQuery query = new UserQuery(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); TResult result = query(query); return result; } /** * {@inheritDoc} */ @Override public TResult query(String table, String[] columns, String[] columnsAs, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { UserQuery query = new UserQuery(table, columns, columnsAs, selection, selectionArgs, groupBy, having, orderBy, limit); TResult result = query(query); return result; } /** * {@inheritDoc} */ @Override public String querySQL(String table, String[] columns, String selection, String groupBy, String having, String orderBy) { return querySQL(table, columns, null, selection, groupBy, having, orderBy, null); } /** * {@inheritDoc} */ @Override public String querySQL(String table, String[] columns, String[] columnsAs, String selection, String groupBy, String having, String orderBy) { return querySQL(table, columns, columnsAs, selection, groupBy, having, orderBy, null); } /** * {@inheritDoc} */ @Override public String querySQL(String table, String[] columns, String selection, String groupBy, String having, String orderBy, String limit) { return querySQL(table, columns, null, selection, groupBy, having, orderBy, limit); } /** * {@inheritDoc} */ @Override public String querySQL(String table, String[] columns, String[] columnsAs, String selection, String groupBy, String having, String orderBy, String limit) { return SQLiteQueryBuilder.buildQueryString(false, table, columns, columnsAs, selection, groupBy, having, orderBy, limit); } /** * Query using the query from a previous query result * * @param previousResult previous result * @return result * @since 2.0.0 */ public TResult query(TResult previousResult) { UserQuery query = previousResult.getQuery(); TResult result = query(query); return result; } /** * Query using the user query arguments * * @param query user query * @return result * @since 2.0.0 */ public TResult query(UserQuery query) { Cursor cursor = null; String[] selectionArgs = query.getSelectionArgs(); String sql = query.getSql(); if (sql != null) { cursor = database.rawQuery(sql, selectionArgs); } else { String table = query.getTable(); String[] columns = query.getColumns(); String selection = query.getSelection(); String groupBy = query.getGroupBy(); String having = query.getHaving(); String orderBy = query.getOrderBy(); String[] columnsAs = query.getColumnsAs(); String limit = query.getLimit(); if (columnsAs != null && limit != null) { cursor = database.query(table, columns, columnsAs, selection, selectionArgs, groupBy, having, orderBy, limit); } else if (columnsAs != null) { cursor = database.query(table, columns, columnsAs, selection, selectionArgs, groupBy, having, orderBy); } else if (limit != null) { cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); } else { cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); } } TResult result = handleCursor(cursor, query); return result; } /** * Convert the cursor to the result type cursor * * @param cursor cursor * @param query user query * @return result cursor */ private TResult handleCursor(Cursor cursor, UserQuery query) { TResult result = convertCursor(cursor); result.setQuery(query); if (table != null) { result.setTable(table); } return result; } /** * Convert the cursor to the result type cursor * * @param cursor cursor * @return result cursor * @since 2.0.0 */ protected TResult convertCursor(Cursor cursor) { return (TResult) cursor; } }
package com.util; import java.io.IOException; import javax.microedition.lcdui.Image; /** * @author nick * */ /** * @author nick * */ /** * @author nick * */ public class Cards { private String[] name = null; private int[] expansion = null; private int[] playing = null; /* * #0 = Is Selected for availability * #1 = Is Black Market available */ private boolean[][] isGamingRelated = null; private int[] cost = null; /* * #0 = Action * #1 = Victory * #2 = Treasury * #3 = Attack * #4 = Reaction * #5 = Duration */ private boolean[][] isSpecific = null; /* * #0 = Adds # Cards * #1 = Adds # Actions * #2 = Adds # Buys * #3 = Adds # Coins * #4 = Adds # Trash * #5 = Adds # Curse * #6 = Adds # Potions */ private int[][] addsInfo = null; private int[] percentage = null; private static int i, k; public Cards(int size, int isSet) { if ( size > 0 ) { name = new String[size]; playing = new int[size]; isGamingRelated = new boolean[size][2]; cost = new int[size]; isSpecific = new boolean[size][6]; addsInfo = new int[size][8]; if ( isSet == IS_SET ) expansion = new int[1]; else expansion = new int[size]; expansion[0] = -1; percentage = new int[size]; for ( i = 0 ; i < size ; i++ ) { name[i] = null; cost[i] = 0; playing[i] = 0; isGamingRelated[i][0] = true; isGamingRelated[i][1] = true; for ( k = 0 ; k < addsInfo[i].length ; k++ ) addsInfo[i][k] = 0; if ( isSet == IS_NOT_SET ) expansion[i] = -1; percentage[i] = 0; } } } /** * @param index the index of the card in the list * @return the name of the card */ public String getName(int index) { return name[index]; } /** * @param index the index of the card in the list * @param name the name that should be given to the card */ public void setName(int index, String name) { this.name[index] = name; } /** * @return the expansion number of the list determined from the first card */ public int getExpansion() { if ( expansion != null) return expansion[0]; return -1; } /** * @param index the index of the card in the list * @return the expansion number of the card */ public int getExpansion(int index) { if ( expansion.length == 1 ) return expansion[0]; return expansion[index]; } /** * @param index the index of the card in the list * @param expansion the expansion which should be assigned with the card */ public void setExpansion(int index, int expansion) { this.expansion[index] = expansion; } /** * @param index the index of the card in the list * @return the percentage set on the card */ public int getPercentage(int index) { return percentage[index]; } /** * @param index the index of the card in the list * @param percentage the percentage which is to be assigned with the card */ public void setPercentage(int index, int percentage) { this.percentage[index] = percentage; } /** * @param expansion sets the default expansion number */ public void setExpansion(int expansion) { this.expansion[0] = expansion; } /** * @param index the index of the card in the list * @return an integer which determines the state of the card */ public int isPlaying(int index) { return playing[index]; } /** * @param index the index of the card in the list * @param playingSet the playingset which needs to be checked * @return true if the card is playing in the playingset, otherwise false */ public boolean isPlayingSet(int index, int playingSet) { if ( playing[index] > 100 ) return playing[index] - 100 == playingSet; return playing[index] == playingSet; } /** * @param index the index of the card in the list * @param playing the playing state of the card */ public void setPlaying(int index, int playing) { this.playing[index] = playing; } /** * @param index the index of the card in the list * @return how much the card costs in potions */ public int getPotionCost(int index) { return (cost[index] - cost[index] % 100) / 100; } /** * @param index the index of the card in the list * @return the actual playing set */ @Deprecated public int getPlaying(int index) { if ( playing[index] > 100 ) return playing[index] - 100; return playing[index]; } /** * @param index the index of the card in the list * @param playingSet the playing set to be checked * @return true if the card is holded on the playingset, false otherwise */ public boolean isHold(int index, int playingSet) { return playing[index] == playingSet + 100; } /** * @param index the index of the card in the list * @return true if the card is holded on any playingset, false otherwise */ public boolean isHold(int index) { return playing[index] > 100; } /** * @param name the name of the card * @param the new hold state of the card */ public void setHoldCard(String name, boolean hold) { for ( i = 0 ; i < playing.length ; i++ ) if ( this.name[i].equals(name) ) { setHoldCard(i, hold); return; } } /** * @param index the index of the card in the list * @param the new hold state of the card */ public void setHoldCard(int index, boolean hold) { if ( hold ) { if ( 0 < playing[index] & playing[index] < 100 ) playing[index] = playing[index] + 100; } else { if ( playing[index] > 100 ) playing[index] = playing[index] - 100; } } /** * @param index the index of the card in the list * @return the availability of the card */ public boolean isAvailable(int index) { return isGamingRelated[index][0]; } /** * @param index the index of the card in the list * @param available the available state of the card */ public void setAvailable(int index, boolean available) { isGamingRelated[index][0] = available; } /** * @param index the index of the card in the list * @return true if the card is available for the Black Market */ public boolean isBlackMarketAvailable(int index) { return isGamingRelated[index][1]; } /** * @param index the index of the card in the list * @param bmAvailable the state of the Black Market availability */ public void setBlackMarketAvailable(int index, boolean bmAvailable) { isGamingRelated[index][1] = bmAvailable; } /** * @param index the index of the card in the list * @return the cobber cost of the card */ public int getCost(int index) { return cost[index] % 100; } /** * @param index the index of the card in the list * @param cost the cost in cobber of the card * @param potions the cost in potions of the card */ public void setCost(int index, int cost, int potions) { this.cost[index] = cost + 100 * potions; } /** * @param index the index of the card in the list * @param whichType which type is the card * @param state sets if it is the type of card or not */ public void setType(int index, int whichType, boolean state) { isSpecific[index][whichType] = state; } /** * @param index the index of the card in the list * @param whichType the type to check for * @return true if it is the type, false otherwise */ public boolean isType(int index, int whichType) { return isSpecific[index][whichType]; } /** * @param index the index of the card in the list * @param whichType the type to check for * @return true if the card is only that one type, false otherwise */ public boolean isOnlyType(int index, int whichType) { boolean tmp = false; for (int i = 0 ; i < isSpecific[index].length ; i++ ) tmp = (i == whichType ? tmp : tmp | isSpecific[index][i]); return !(isSpecific[index][whichType] & tmp); } /** * @param index * @return */ public int getCardType(int index) { if ( isType(index, TYPE_ACTION) ) { if ( isType(index, TYPE_VICTORY) ) return TYPE_ACTION_VICTORY; if ( isType(index, TYPE_TREASURY) ) return TYPE_ACTION_TREASURY; if ( isType(index, TYPE_ATTACK) ) return TYPE_ACTION_ATTACK; if ( isType(index, TYPE_DURATION) ) return TYPE_ACTION_DURATION; if ( isType(index, TYPE_REACTION) ) // last because of Lighthouse return TYPE_ACTION_REACTION; // Default is action anyway! } else if ( isOnlyType(index, TYPE_VICTORY) ) { return TYPE_VICTORY; } else if ( isType(index, TYPE_TREASURY) ) { if ( isType(index, TYPE_VICTORY) ) return TYPE_TREASURY_VICTORY; return TYPE_TREASURY; } else if ( isType(index, TYPE_ATTACK) ) { if ( isType(index, TYPE_VICTORY) ) return TYPE_ATTACK_VICTORY; if ( isType(index, TYPE_TREASURY) ) return TYPE_ATTACK_TREASURY; if ( isType(index, TYPE_REACTION) ) return TYPE_ATTACK_REACTION; if ( isType(index, TYPE_DURATION) ) return TYPE_ATTACK_DURATION; // TODO : what if it is only a ATTACK } else if ( isType(index, TYPE_REACTION) ) { if ( isType(index, TYPE_VICTORY) ) return TYPE_REACTION_VICTORY; if ( isType(index, TYPE_TREASURY) ) return TYPE_REACTION_TREASURY; if ( isType(index, TYPE_DURATION) ) return TYPE_REACTION_DURATION; // TODO : what if it is only a REACTION } else if ( isType(index, TYPE_DURATION) ) { if ( isType(index, TYPE_VICTORY) ) return TYPE_DURATION_VICTORY; if ( isType(index, TYPE_TREASURY) ) return TYPE_DURATION_TREASURY; // TODO : what if it is only a DURATION } return TYPE_ACTION; } public void setAddInfo(int index, int whichAddInfo, int info) { addsInfo[index][whichAddInfo] = info; } public int getAddInfo(int index, int whichAddInfo) { return addsInfo[index][whichAddInfo]; } public Object[] getCard(int index) { Object[] tmp = new Object[20]; tmp[0] = getName(index); tmp[1] = new Integer(getExpansion(index)); tmp[2] = new Integer(getCost(index)+getPotionCost(index)*100); tmp[3] = new Boolean(isType(index, TYPE_ACTION)); tmp[4] = new Boolean(isType(index, TYPE_VICTORY)); tmp[5] = new Boolean(isType(index, TYPE_ATTACK)); tmp[6] = new Boolean(isType(index, TYPE_TREASURY)); tmp[7] = new Boolean(isType(index, TYPE_REACTION)); tmp[8] = new Boolean(isType(index, TYPE_DURATION)); tmp[9] = new Integer(isPlaying(index)); tmp[10] = new Boolean(isAvailable(index)); tmp[11] = new Boolean(isBlackMarketAvailable(index)); tmp[12] = new Integer(getAddInfo(index, ADDS_CARDS)); tmp[13] = new Integer(getAddInfo(index, ADDS_ACTIONS)); tmp[14] = new Integer(getAddInfo(index, ADDS_BUYS)); tmp[15] = new Integer(getAddInfo(index, ADDS_COINS)); tmp[16] = new Integer(getAddInfo(index, ADDS_TRASH)); tmp[17] = new Integer(getAddInfo(index, ADDS_CURSE)); tmp[18] = new Integer(getAddInfo(index, ADDS_POTIONS)); tmp[19] = new Integer(getAddInfo(index, ADDS_VICTORY_POINTS)); return tmp; } public int fromExpansion(int exp) { int tmp = 0; for ( i = 0 ; i < size() ; i++ ) { if ( getExpansion(i) > -1 && getExpansion(i) == exp ) tmp++; } return tmp; } public void setCard(int index, Object[] cardInfo) { if ( cardInfo.length == 0 ) return; for ( i = 0 ; i < cardInfo.length ; i++ ) { if ( cardInfo[i] == null ) { //#debug dominizer System.out.println("cardinfo " + i + " is null "); } } if ( cardInfo[0] == null ) { //#debug dominizer System.out.println("cardinfo 0 is null "); } setName(index, cardInfo[0].toString()); setExpansion(index, ((Integer)cardInfo[1]).intValue()); this.cost[index] = ((Integer)cardInfo[2]).intValue(); // simply to bypass the potion cost. setType(index, TYPE_ACTION, ((Boolean)cardInfo[3]).booleanValue()); setType(index, TYPE_VICTORY, ((Boolean)cardInfo[4]).booleanValue()); setType(index, TYPE_ATTACK, ((Boolean)cardInfo[5]).booleanValue()); setType(index, TYPE_TREASURY, ((Boolean)cardInfo[6]).booleanValue()); setType(index, TYPE_REACTION, ((Boolean)cardInfo[7]).booleanValue()); setType(index, TYPE_DURATION, ((Boolean)cardInfo[8]).booleanValue()); setPlaying(index, ((Integer)cardInfo[9]).intValue()); setAvailable(index, ((Boolean)cardInfo[10]).booleanValue()); setBlackMarketAvailable(index, ((Boolean)cardInfo[11]).booleanValue()); setAddInfo(index, ADDS_CARDS, ((Integer)cardInfo[12]).intValue()); setAddInfo(index, ADDS_ACTIONS, ((Integer)cardInfo[13]).intValue()); setAddInfo(index, ADDS_BUYS, ((Integer)cardInfo[14]).intValue()); setAddInfo(index, ADDS_COINS, ((Integer)cardInfo[15]).intValue()); setAddInfo(index, ADDS_TRASH, ((Integer)cardInfo[16]).intValue()); setAddInfo(index, ADDS_CURSE, ((Integer)cardInfo[17]).intValue()); setAddInfo(index, ADDS_POTIONS, ((Integer)cardInfo[18]).intValue()); setAddInfo(index, ADDS_VICTORY_POINTS, ((Integer)cardInfo[19]).intValue()); } public static int compare(Object[] first, Object[] compareTo, int method) { switch ( method ) { case COMPARE_EXPANSION_NAME: if ( compare(first, compareTo, COMPARE_EXPANSION) == 0 ) return compare(first, compareTo, COMPARE_NAME); else return compare(first, compareTo, COMPARE_EXPANSION); case COMPARE_EXPANSION_COST: if ( compare(first, compareTo, COMPARE_EXPANSION) != 0 ) return compare(first, compareTo, COMPARE_EXPANSION); if ( compare(first, compareTo, COMPARE_COST) != 0 ) return compare(first, compareTo, COMPARE_COST); return compare(first, compareTo, COMPARE_NAME); case COMPARE_COST_EXPANSION: if ( compare(first, compareTo, COMPARE_COST) != 0 ) return compare(first, compareTo, COMPARE_COST); if ( compare(first, compareTo, COMPARE_EXPANSION) != 0 ) return compare(first, compareTo, COMPARE_EXPANSION); return compare(first, compareTo, COMPARE_NAME); case COMPARE_COST_NAME: if ( compare(first, compareTo, COMPARE_COST) != 0 ) return compare(first, compareTo, COMPARE_COST); return compare(first, compareTo, COMPARE_NAME); case COMPARE_EXPANSION: if ( ((Integer) first[1]).intValue() > ((Integer) compareTo[1]).intValue() ) return 1; else if ( ((Integer) first[1]).intValue() < ((Integer) compareTo[1]).intValue() ) return -1; else return 0; case COMPARE_COST: if ( ((Integer) first[2]).intValue() > ((Integer) compareTo[2]).intValue() ) return 1; else if ( ((Integer) first[2]).intValue() < ((Integer) compareTo[2]).intValue() ) return -1; else return 0; case COMPARE_NAME: return first[0].toString().compareTo(compareTo[0].toString()); default: return compare(first, compareTo, COMPARE_EXPANSION_NAME); } } public boolean contains(String cardName) { for ( i = 0 ; i < size() ; i++ ) if ( getName(i) != null ) if ( getName(i).equals(cardName) ) return true; return false; } public String toString(int index) { return getName(index); } public int size() { if ( name == null ) return 0; for ( int i = 0 ; i < name.length ; i++ ) if ( name[i] == null ) return i + 1; return name.length; } public Image getCostImage(int card) { try { /* Image source = Image.createImage("/trea" + getCost(card) + ".png"); Image copy = Image.createImage(source.getWidth(), source.getHeight()); Graphics g = copy.getGraphics(); g.drawImage(source, 0, 0, Graphics.TOP | Graphics.LEFT); if ( copy.isMutable() ) { //#debug dominizer System.out.println("image is mutable"); g.drawString(""+getCost(card), source.getWidth() / 2, source.getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER); }*/ if ( getPotionCost(card) > 0 ) { return Image.createImage("/t" + getCost(card) + "P.png"); } else { return Image.createImage("/t" + getCost(card) + ".png"); } } catch (IOException exp) { return null; } } public Image getCardTypeImage(int card) { try { if ( getExpansion(card) == Dominion.PROMO ) { if ( getName(card).equals(Dominion.expansions[Dominion.PROMO].getName(0)) ) return Image.createImage("/" + Dominion.getExpansionImageName(Dominion.PROMO) + "0.png"); else if ( getName(card).equals(Dominion.expansions[Dominion.PROMO].getName(1)) ) return Image.createImage("/" + Dominion.getExpansionImageName(Dominion.PROMO) + "1.png"); else if ( getName(card).equals(Dominion.expansions[Dominion.PROMO].getName(2)) ) return Image.createImage("/" + Dominion.getExpansionImageName(Dominion.PROMO) + "2.png"); return null; } else { return Image.createImage("/" + Dominion.getExpansionImageName(getExpansion(card)) + getCardType(card) + ".png"); } } catch (IOException expc) { return Dominion.getExpansionImage(getExpansion(card)); } } public int getTypes(int type) { int sum = 0; for ( int i = 0 ; i < size() ; i++ ) if ( isType(i, type) ) sum++; return sum; } public int getAdds(int addInfo) { int sum = 0; for ( int i = 0 ; i < size() ; i++ ) sum += getAddInfo(i, addInfo); return sum; } public static final int COMPARE_EXPANSION_NAME = 0; public static final int COMPARE_EXPANSION_COST = 1; public static final int COMPARE_NAME = 2; public static final int COMPARE_COST_NAME = 3; public static final int COMPARE_COST_EXPANSION = 4; public static final int COMPARE_COST = 10; public static final int COMPARE_EXPANSION = 11; public static int COMPARE_PREFERRED = COMPARE_EXPANSION_NAME; public static final int IS_SET = 1; public static final int IS_NOT_SET = 0; // TODO : When changing the below to non-consecutive numbers please update method "parseCondition" in Dominion public static final int TYPE_ACTION = 0; public static final int TYPE_VICTORY = 1; public static final int TYPE_TREASURY = 2; public static final int TYPE_ATTACK = 3; public static final int TYPE_REACTION = 4; public static final int TYPE_DURATION = 5; public static final int TYPE_ACTION_VICTORY = 21; public static final int TYPE_ACTION_TREASURY = 22; public static final int TYPE_ACTION_ATTACK = 23; public static final int TYPE_ACTION_REACTION = 24; public static final int TYPE_ACTION_DURATION = 25; public static final int TYPE_TREASURY_VICTORY = 31; public static final int TYPE_ATTACK_VICTORY = 41; public static final int TYPE_ATTACK_TREASURY = 42; public static final int TYPE_ATTACK_REACTION = 44; public static final int TYPE_ATTACK_DURATION = 45; public static final int TYPE_REACTION_VICTORY = 51; public static final int TYPE_REACTION_TREASURY = 52; public static final int TYPE_REACTION_DURATION = 55; public static final int TYPE_DURATION_VICTORY = 61; public static final int TYPE_DURATION_TREASURY = 62; // TODO : When changing the below to non-consecutive numbers please update method "parseCondition" in Dominion public static final int ADDS_CARDS = 0; public static final int ADDS_ACTIONS = 1; public static final int ADDS_BUYS = 2; public static final int ADDS_COINS = 3; public static final int ADDS_TRASH = 4; public static final int ADDS_CURSE = 5; public static final int ADDS_VICTORY_POINTS = 6; public static final int ADDS_POTIONS = 7; public static final int COST_POTIONS = 100; }
package st.gaw.db; import java.lang.ref.WeakReference; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; /** * the main helper class that saves/restore item in memory using a DB storage * <p> * the storage handling is done in a separate thread * @author Steve Lhomme * * @param <E> the type of items stored in memory */ public abstract class AsynchronousDbHelper<E> extends SQLiteOpenHelper { protected final static String TAG = "MemoryDb"; protected final static String STARTUP_TAG = "Startup"; protected final static boolean DEBUG_DB = false; private final Handler saveStoreHandler; private static final int MSG_LOAD_IN_MEMORY = 100; private static final int MSG_STORE_ITEM = 101; private static final int MSG_REMOVE_ITEM = 102; private static final int MSG_UPDATE_ITEM = 103; private static final int MSG_CLEAR_DATABASE = 104; private static final int MSG_SWAP_ITEMS = 106; private static final int MSG_REPLACE_ITEMS = 107; private static final int MSG_CUSTOM_OPERATION = 108; private WeakReference<InMemoryDbErrorHandler<E>> mErrorHandler; // not protected for now private final CopyOnWriteArrayList<WeakReference<InMemoryDbListener<E>>> mDbListeners = new CopyOnWriteArrayList<WeakReference<InMemoryDbListener<E>>>(); private AtomicBoolean mDataLoaded = new AtomicBoolean(); private final AtomicInteger modifyingTransactionLevel = new AtomicInteger(0); /** * @param context to use to open or create the database * @param name of the database file, or null for an in-memory database * @param version number of the database (starting at 1); if the database is older, * {@link #onUpgrade} will be used to upgrade the database; if the database is * newer, {@link #onDowngrade} will be used to downgrade the database * @param logger the {@link Logger} to use for all logs (can be null for the default Android logs) */ @SuppressLint("HandlerLeak") protected AsynchronousDbHelper(Context context, String name, int version, Logger logger) { super(context, name, null, version); if (logger!=null) LogManager.setLogger(logger); preloadInit(); HandlerThread handlerThread = new HandlerThread(getClass().getSimpleName(), android.os.Process.THREAD_PRIORITY_BACKGROUND); handlerThread.start(); saveStoreHandler = new Handler(handlerThread.getLooper()) { public void handleMessage(Message msg) { SQLiteDatabase db; switch (msg.what) { case MSG_LOAD_IN_MEMORY: db = getWritableDatabase(); startLoadingInMemory(); try { Cursor c = db.query(getMainTableName(), null, null, null, null, null, null); if (c!=null) try { if (c.moveToFirst()) { startLoadingFromCursor(c); do { addCursorInMemory(c); } while (c.moveToNext()); } } finally { c.close(); } } catch (SQLException e) { LogManager.logger.w(STARTUP_TAG,"Can't query table "+getMainTableName()+" in "+AsynchronousDbHelper.this, e); } finally { finishLoadingInMemory(); } break; case MSG_CLEAR_DATABASE: try { db = getWritableDatabase(); db.delete(getMainTableName(), "1", null); } catch (Throwable e) { LogManager.logger.w(TAG,"Failed to empty table "+getMainTableName()+" in "+AsynchronousDbHelper.this, e); sendEmptyMessage(MSG_LOAD_IN_MEMORY); // reload the DB into memory } SQLiteDatabase.releaseMemory(); break; case MSG_STORE_ITEM: @SuppressWarnings("unchecked") E itemToAdd = (E) msg.obj; ContentValues addValues = null; try { db = getWritableDatabase(); addValues = getValuesFromData(itemToAdd, db); if (addValues!=null) { long id = db.insertOrThrow(getMainTableName(), null, addValues); if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" insert "+addValues+" = "+id); if (id==-1) throw new RuntimeException("failed to add values "+addValues+" in "+AsynchronousDbHelper.this.getClass().getSimpleName()); } } catch (Throwable e) { notifyAddItemFailed(itemToAdd, addValues, e); } break; case MSG_REMOVE_ITEM: @SuppressWarnings("unchecked") E itemToDelete = (E) msg.obj; try { db = getWritableDatabase(); if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" remove "+itemToDelete); if (db.delete(getMainTableName(), getItemSelectClause(itemToDelete), getItemSelectArgs(itemToDelete))==0) notifyRemoveItemFailed(itemToDelete, new RuntimeException("No item "+itemToDelete+" in "+AsynchronousDbHelper.this.getClass().getSimpleName())); } catch (Throwable e) { notifyRemoveItemFailed(itemToDelete, e); } break; case MSG_UPDATE_ITEM: @SuppressWarnings("unchecked") E itemToUpdate = (E) msg.obj; ContentValues updateValues = null; try { db = getWritableDatabase(); updateValues = getValuesFromData(itemToUpdate, db); if (updateValues!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+updateValues+" for "+itemToUpdate); if (db.update(getMainTableName(), updateValues, getItemSelectClause(itemToUpdate), getItemSelectArgs(itemToUpdate)/*, SQLiteDatabase.CONFLICT_NONE*/)==0) { notifyUpdateItemFailed(itemToUpdate, updateValues, new RuntimeException("Can't update "+updateValues+" in "+AsynchronousDbHelper.this.getClass().getSimpleName())); } } } catch (Throwable e) { notifyUpdateItemFailed(itemToUpdate, updateValues, e); } break; case MSG_REPLACE_ITEMS: @SuppressWarnings("unchecked") DoubleItems itemsToReplace = (DoubleItems) msg.obj; try { db = getWritableDatabase(); ContentValues newValues = getValuesFromData(itemsToReplace.itemA, db); if (newValues!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" replace "+itemsToReplace+" with "+newValues); db.update(getMainTableName(), newValues, getItemSelectClause(itemsToReplace.itemB), getItemSelectArgs(itemsToReplace.itemB)); } } catch (Throwable e) { notifyReplaceItemFailed(itemsToReplace.itemA, itemsToReplace.itemB, e); } break; case MSG_SWAP_ITEMS: @SuppressWarnings("unchecked") DoubleItems itemsToSwap = (DoubleItems) msg.obj; ContentValues newValuesA = null; try { db = getWritableDatabase(); newValuesA = getValuesFromData(itemsToSwap.itemB, db); if (newValuesA!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+itemsToSwap.itemB+" with "+newValuesA); db.update(getMainTableName(), newValuesA, getItemSelectClause(itemsToSwap.itemA), getItemSelectArgs(itemsToSwap.itemA)); } } catch (Throwable e) { notifyUpdateItemFailed(itemsToSwap.itemA, newValuesA, e); } ContentValues newValuesB = null; try { db = getWritableDatabase(); newValuesB = getValuesFromData(itemsToSwap.itemA, db); if (newValuesB!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+itemsToSwap.itemA+" with "+newValuesB); db.update(getMainTableName(), newValuesB, getItemSelectClause(itemsToSwap.itemB), getItemSelectArgs(itemsToSwap.itemB)); } } catch (Throwable e) { notifyUpdateItemFailed(itemsToSwap.itemB, newValuesB, e); } break; case MSG_CUSTOM_OPERATION: try { @SuppressWarnings("unchecked") AsynchronousDbOperation<E> operation = (AsynchronousDbOperation<E>) msg.obj; operation.runInMemoryDbOperation(AsynchronousDbHelper.this); } catch (Throwable e) { LogManager.logger.w(TAG, AsynchronousDbHelper.this+" failed to run operation "+msg.obj,e); } break; } super.handleMessage(msg); } }; saveStoreHandler.sendEmptyMessage(MSG_LOAD_IN_MEMORY); } /** * Method called at the end of constructor, just before the data start loading */ protected void preloadInit() {} /** * tell the InMemory database that we are about to modify its data * <p> see also {@link #popModifyingTransaction()} */ protected void pushModifyingTransaction() { modifyingTransactionLevel.incrementAndGet(); } /** * tell the InMemory database we have finish modifying the data at this level. * Once the pop matches all the push {@link #notifyDatabaseChanged()} is called * <p> this is useful to avoid multiple calls to {@link #notifyDatabaseChanged()} during a batch of changes * <p> see also {@link #pushModifyingTransaction()} */ protected void popModifyingTransaction() { if (modifyingTransactionLevel.decrementAndGet()==0) { notifyDatabaseChanged(); } } protected void clearDataInMemory() {} @Override @Deprecated public SQLiteDatabase getReadableDatabase() { return super.getReadableDatabase(); } /** * set the listener that will receive error events * @param listener null to remove the listener */ public void setDbErrorHandler(InMemoryDbErrorHandler<E> listener) { if (listener==null) mErrorHandler = null; else mErrorHandler = new WeakReference<InMemoryDbErrorHandler<E>>(listener); } public void addListener(InMemoryDbListener<E> listener) { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { if (l.get()==null) mDbListeners.remove(l); else if (l.get()==listener) return; } if (mDataLoaded.get()) listener.onMemoryDbChanged(this); mDbListeners.add(new WeakReference<InMemoryDbListener<E>>(listener)); } public void removeListener(InMemoryDbListener<E> listener) { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { if (l.get()==null) mDbListeners.remove(l); else if (l.get()==listener) mDbListeners.remove(l); } } /** * delete all the data in memory and in the database */ public final void clear() { pushModifyingTransaction(); clearDataInMemory(); popModifyingTransaction(); saveStoreHandler.sendEmptyMessage(MSG_CLEAR_DATABASE); } private void notifyAddItemFailed(E item, ContentValues values, Throwable cause) { LogManager.logger.i(TAG, this+" failed to add item "+item+(DEBUG_DB ? (" values"+values) : ""), cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onAddItemFailed(this, item, values, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyReplaceItemFailed(E srcItem, E replacement, Throwable cause) { LogManager.logger.i(TAG, this+" failed to replace item "+srcItem+" with "+replacement, cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onReplaceItemFailed(this, srcItem, replacement, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyUpdateItemFailed(E item, ContentValues values, Throwable cause) { LogManager.logger.i(TAG, this+" failed to update item "+item+(DEBUG_DB ? (" values"+values) : ""), cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onAddItemFailed(this, item, values, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyRemoveItemFailed(E item, Throwable cause) { LogManager.logger.i(TAG, this+" failed to remove item "+item, cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onRemoveItemFailed(this, item, cause); } pushModifyingTransaction(); popModifyingTransaction(); } /** * the name of the main table corresponding to the inMemory elements * @return the name of the main table */ protected abstract String getMainTableName(); /** * use the data in the {@link Cursor} to store them in the memory storage * @param c the Cursor to use * @see #getValuesFromData(Object, SQLiteDatabase) */ protected abstract void addCursorInMemory(Cursor c); /** * transform the element in memory into {@link ContentValues} that can be saved in the database * <p> you can return null and fill the database yourself if you need to * @param data the data to transform * @param dbToFill the database that will receive new items * @return a ContentValues element with all data that can be used to restore the data later from the database * @see #addCursorInMemory(Cursor) */ protected abstract ContentValues getValuesFromData(E data, SQLiteDatabase dbToFill) throws RuntimeException; /** * the where clause that should be used to update/delete the item * <p> see {@link #getItemSelectArgs(Object)} * @param itemToSelect the item about to be selected in the database * @return a string for the whereClause in {@link SQLiteDatabase#update(String, ContentValues, String, String[])} or {@link SQLiteDatabase#delete(String, String, String[])} */ protected abstract String getItemSelectClause(E itemToSelect); /** * the where arguments that should be used to update/delete the item * <p> see {@link #getItemSelectClause(Object)} * @param itemToSelect the item about to be selected in the database * @return a string array for the whereArgs in {@link SQLiteDatabase#update(String, ContentValues, String, String[])} or {@link SQLiteDatabase#delete(String, String, String[])} */ protected abstract String[] getItemSelectArgs(E itemToSelect); /** * request to store the item in the database, it should be kept in synch with the in memory storage * <p> * will call the {@link InMemoryDbErrorHandler} in case of error * @param item */ protected final void scheduleAddOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_STORE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleUpdateOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_UPDATE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } private class DoubleItems { final E itemA; final E itemB; public DoubleItems(E itemA, E itemB) { this.itemA = itemA; this.itemB = itemB; } } protected final void scheduleReplaceOperation(E original, E replacement) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_REPLACE_ITEMS, new DoubleItems(original, replacement))); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleSwapOperation(E itemA, E itemB) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_SWAP_ITEMS, new DoubleItems(itemA, itemB))); pushModifyingTransaction(); popModifyingTransaction(); } /** * request to delete the item from the database, it should be kept in synch with the in memory storage * <p> * will call the {@link InMemoryDbErrorHandler} in case of error * @param item */ protected final void scheduleRemoveOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_REMOVE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } /** * run the operation in the internal thread * @param operation */ protected final void scheduleCustomOperation(AsynchronousDbOperation<E> operation) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_CUSTOM_OPERATION, operation)); } /** * called when we are about to read all items from the disk */ protected void startLoadingInMemory() { pushModifyingTransaction(); mDataLoaded.set(false); } /** * called when we have the cursor to read the data from * <p> * useful to prepare the amount of data needed or get the index of the column we need * @param c the {@link Cursor} that will be used to read the data */ protected void startLoadingFromCursor(Cursor c) {} /** * called after all items have been read from the disk */ protected void finishLoadingInMemory() { mDataLoaded.set(true); popModifyingTransaction(); } protected void notifyDatabaseChanged() { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { final InMemoryDbListener<E> listener = l.get(); if (listener==null) mDbListeners.remove(l); else listener.onMemoryDbChanged(this); } } public boolean isDataLoaded() { return mDataLoaded.get(); } /** Wait until the data are loaded */ public void waitForDataLoaded() {} @Override public String toString() { StringBuilder sb = new StringBuilder(48); sb.append('{'); sb.append(getClass().getSimpleName()); sb.append(' '); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append('}'); return sb.toString(); } }
package com.messenger; import com.facebook.react.ReactActivity; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.rt2zz.reactnativecontacts.ReactNativeContacts; import android.os.Bundle; import android.os.Environment; import com.github.ethereum.go_ethereum.cmd.Geth; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.io.File; import com.i18n.reactnativei18n.ReactNativeI18n; public class MainActivity extends ReactActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Required for android-16 (???) System.loadLibrary("gethraw"); System.loadLibrary("geth"); // Required because of crazy APN settings redirecting localhost Properties properties = System.getProperties(); properties.setProperty("http.nonProxyHosts", "localhost|127.0.0.1"); properties.setProperty("https.nonProxyHosts", "localhost|127.0.0.1"); File extStore = Environment.getExternalStorageDirectory(); final String dataFolder = extStore.exists() ? extStore.getAbsolutePath() : getApplicationInfo().dataDir; // Launch! new Thread(new Runnable() { public void run() { Geth.run("--bootnodes enode://e2f28126720452aa82f7d3083e49e6b3945502cb94d9750a15e27ee310eed6991618199f878e5fbc7dfa0e20f0af9554b41f491dc8f1dbae8f0f2d37a3a613aa@139.162.13.89:30303 --shh --ipcdisable --nodiscover --rpc --rpcapi db,eth,net,web3,shh --fast --datadir=" + dataFolder); } }).start(); } /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "Messenger"; } /** * Returns whether dev mode should be enabled. * This enables e.g. the dev menu. */ @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new ReactNativeContacts(), new ReactNativeI18n() ); } }
package com.sometrik.framework; import android.app.Dialog; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.text.TextUtils.TruncateAt; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; class ViewStyleManager { private enum WhiteSpace { NORMAL, NOWRAP }; private enum HorizontalAlignment { LEFT, CENTER, RIGHT }; private enum TextOverflow { CLIP, ELLIPSIS }; private enum FontStyle { NORMAL, ITALIC, OBLIQUE }; private BitmapCache bitmapCache; private float displayScale = 1.0f; private float[] padding = null; private float[] margin = null; private Integer width = null, height = null; private Float opacity = null; private Integer leftPosition = null, topPosition = null; private Integer rightPosition = null, bottomPosition = null; private int minWidth = 0, minHeight = 0; private String title = null; private Integer weight = null; private Integer backgroundColor = null; private Integer color = null; private Integer gravity = null; private Float zoom = null; private Integer shadow = null; private float[] borderRadius = null; private Integer borderWidth = null, borderColor = null; private Integer fontSize = null; private WhiteSpace whiteSpace = null; private HorizontalAlignment textAlign = null; private TextOverflow textOverflow = null; private Integer fontWeight = null; private FontStyle fontStyle = null; private String fontFamily = null; private String hint = null; private String iconFile = null; private String iconAttachment = null; public ViewStyleManager(BitmapCache bitmapCache, float displayScale, boolean isDefault) { this.bitmapCache = bitmapCache; this.displayScale = displayScale; if (isDefault) setDefaults(); } private void initPadding() { padding = new float[4]; padding[0] = padding[1] = padding[2] = padding[3] = 0.0f; } private void initMargin() { margin = new float[4]; margin[0] = margin[1] = margin[2] = margin[3] = 0.0f; } public void setDefaults() { zoom = new Float(1.0); opacity = new Float(1.0); shadow = new Integer(0); color = new Integer(Color.parseColor("#000000")); backgroundColor = new Integer(0); fontWeight = new Integer(400); iconFile = ""; initPadding(); initMargin(); } public void setStyle(String key, String value) { if (key.equals("padding")) { padding = parseFloatArray(value, 4); } else if (key.equals("padding-top")) { if (padding == null) initPadding(); padding[0] = Float.parseFloat(value); } else if (key.equals("padding-right")) { if (padding == null) initPadding(); padding[1] = Float.parseFloat(value); } else if (key.equals("padding-bottom")) { if (padding == null) initPadding(); padding[2] = Float.parseFloat(value); } else if (key.equals("padding-left")) { if (padding == null) initPadding(); padding[3] = Float.parseFloat(value); } else if (key.equals("margin")) { margin = parseFloatArray(value, 4); } else if (key.equals("margin-top")) { if (margin == null) initMargin(); margin[0] = Float.parseFloat(value); } else if (key.equals("margin-right")) { if (margin == null) initMargin(); margin[1] = Float.parseFloat(value); } else if (key.equals("margin-bottom")) { if (margin == null) initMargin(); margin[2] = Float.parseFloat(value); } else if (key.equals("margin-left")) { if (margin == null) initMargin(); margin[3] = Float.parseFloat(value); } else if (key.equals("weight")) { weight = new Integer(value); } else if (key.equals("opacity")) { opacity = new Float(value); } else if (key.equals("text-shadow")) { } else if (key.equals("box-shadow")) { } else if (key.equals("shadow")) { shadow = new Integer(value); } else if (key.equals("left")) { leftPosition = new Integer(value); } else if (key.equals("top")) { topPosition = new Integer(value); } else if (key.equals("right")) { rightPosition = new Integer(value); } else if (key.equals("bottom")) { bottomPosition = new Integer(value); } else if (key.equals("min-width")) { minWidth = Integer.parseInt(value); } else if (key.equals("min-height")) { minHeight = Integer.parseInt(value); } else if (key.equals("title")) { title = value; } else if (key.equals("width")) { if (value.equals("wrap-content")) { width = new Integer(LayoutParams.WRAP_CONTENT); } else if (value.equals("match-parent")) { width = new Integer(LayoutParams.MATCH_PARENT); } else { width = new Integer(value); } } else if (key.equals("height")) { if (value.equals("wrap-content")) { height = new Integer(LayoutParams.WRAP_CONTENT); } else if (value.equals("match-parent")) { height = new Integer(LayoutParams.MATCH_PARENT); } else { height = new Integer(value); } } else if (key.equals("background-color")) { backgroundColor = new Integer(Color.parseColor(value)); } else if (key.equals("color")) { color = new Integer(Color.parseColor(value)); } else if (key.equals("gravity")) { if (value.equals("bottom")) { gravity = new Integer(Gravity.BOTTOM); } else if (value.equals("top")) { gravity = new Integer(Gravity.TOP); } else if (value.equals("left")) { gravity = new Integer(Gravity.LEFT); } else if (value.equals("right")) { gravity = new Integer(Gravity.RIGHT); } else if (value.equals("center")) { gravity = new Integer(Gravity.CENTER); } else if (value.equals("center-vertical")) { gravity = new Integer(Gravity.CENTER_VERTICAL); } else if (value.equals("center-horizontal")) { gravity = new Integer(Gravity.CENTER_HORIZONTAL); } } else if (key.equals("zoom")) { if (value.equals("inherit")) { zoom = null; } else { zoom = new Float(value); } } else if (key.equals("border")) { if (value.equals("none")) { borderWidth = new Integer(0); } else { borderWidth = new Integer(1); borderColor = new Integer(Color.parseColor(value)); } } else if (key.equals("border-radius")) { borderRadius = parseFloatArray(value, 4); } else if (key.equals("font-size")) { if (value.equals("small")){ fontSize = new Integer(9); } else if (value.equals("medium")){ fontSize = new Integer(12); } else if (value.equals("large")){ fontSize = new Integer(15); } else { fontSize = new Integer(value); } } else if (key.equals("white-space")) { if (value.equals("normal")) whiteSpace = WhiteSpace.NORMAL; else if (value.equals("nowrap")) whiteSpace = WhiteSpace.NOWRAP; } else if (key.equals("text-overflow")) { if (value.equals("ellipsis")) { textOverflow = TextOverflow.ELLIPSIS; } } else if (key.equals("font-weight")) { if (value.equals("normal")) { fontWeight = new Integer(400); } else if (value.equals("bold")) { fontWeight = new Integer(700); } else { fontWeight = new Integer(value); } } else if (key.equals("font-style")) { if (value.equals("italic")) { fontStyle = FontStyle.ITALIC; } else if (value.equals("oblique")) { fontStyle = FontStyle.OBLIQUE; } else { fontStyle = FontStyle.NORMAL; } } else if (key.equals("text-align")) { if (value.equals("left")) { textAlign = HorizontalAlignment.LEFT; } else if (value.equals("center")) { textAlign = HorizontalAlignment.CENTER; } else if (value.equals("right")) { textAlign = HorizontalAlignment.RIGHT; } } else if (key.equals("font-family")) { fontFamily = value; } else if (key.equals("hint")) { hint = value; } else if (key.equals("icon-attachment")) { iconAttachment = value; // right, top, bottom, left } else if (key.equals("icon")) { if (value.equals("none")) { iconFile = ""; } else { iconFile = value; } } } public void apply(Dialog dialog) { if (width != null || height != null) { ViewGroup.LayoutParams params = dialog.getWindow().getAttributes(); if (width != null) params.width = applyScale(width); if (height != null) params.height = applyScale(height); dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); } } public void apply(View view) { if (opacity != null) view.setAlpha(opacity); if (zoom != null) { view.setScaleX(zoom); view.setScaleY(zoom); } if (shadow != null) view.setElevation(shadow); // if (title != null) view.setTooltipText(title); // Scaled parameters if (padding != null) { view.setPadding((int)applyScale(padding[3]), (int)applyScale(padding[0]), (int)applyScale(padding[1]), (int)applyScale(padding[2])); } if (leftPosition != null) view.setLeft(applyScale(leftPosition)); if (rightPosition != null) view.setRight(applyScale(rightPosition)); if (topPosition != null) view.setTop(applyScale(topPosition)); if (bottomPosition != null) view.setBottom(applyScale(bottomPosition)); if (minWidth > 0) view.setMinimumWidth(applyScale(minWidth)); if (minHeight > 0) view.setMinimumHeight(applyScale(minHeight)); if ((borderColor != null && borderWidth != null) || borderRadius != null) { view.setBackgroundResource(0); if (borderRadius != null && (backgroundColor == null || backgroundColor == 0) && (borderWidth == null || borderWidth == 0)) { if (backgroundColor != null) view.setBackgroundColor(backgroundColor); RoundRectShape shape = new RoundRectShape(expandRadii(borderRadius), null, null); ShapeDrawable sd = new ShapeDrawable(shape); view.setBackground(sd); } else { GradientDrawable gd = new GradientDrawable(); if (backgroundColor != null) gd.setColor(backgroundColor); if (borderRadius != null) { gd.setCornerRadius(2); // Might be necessary for zero radiuses to work gd.setCornerRadii(expandRadii(borderRadius)); } if (borderColor != null && borderWidth != null) { gd.setStroke(borderWidth, borderColor); } view.setBackground(gd); } } else if (backgroundColor != null) { view.setBackgroundColor(backgroundColor); } // Layout parameters if (weight != null || width != null || height != null || margin != null || gravity != null) { if (view.getParent() instanceof ScrollView) { // stupid hack FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); view.setLayoutParams(params); } else if (view.getParent() instanceof LinearLayout) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams(); if (weight != null) params.weight = weight; if (margin != null) { params.topMargin = (int)applyScale(margin[0]); params.rightMargin = (int)applyScale(margin[1]); params.bottomMargin = (int)applyScale(margin[2]); params.leftMargin = (int)applyScale(margin[3]); } if (width != null) params.width = applyScale(width); if (height != null) params.height = applyScale(height); if (gravity != null) params.gravity = gravity; view.setLayoutParams(params); } else if (view.getParent() instanceof FrameLayout) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams(); if (margin != null) { params.topMargin = (int)applyScale(margin[0]); params.rightMargin = (int)applyScale(margin[1]); params.bottomMargin = (int)applyScale(margin[2]); params.leftMargin = (int)applyScale(margin[3]); } if (width != null) params.width = applyScale(width); if (height != null) params.height = applyScale(height); if (gravity != null) params.gravity = gravity; view.setLayoutParams(params); } else if (view.getParent() instanceof RelativeLayout) { RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)view.getLayoutParams(); if (margin != null) { params.topMargin = (int)applyScale(margin[0]); params.rightMargin = (int)applyScale(margin[1]); params.bottomMargin = (int)applyScale(margin[2]); params.leftMargin = (int)applyScale(margin[3]); } if (width != null) params.width = applyScale(width); if (height != null) params.height = applyScale(height); view.setLayoutParams(params); } else { System.out.println("this style cannot be applied to view that doesn't have valid layout as parent"); } } if (view instanceof EditText) { EditText editText = (EditText) view; if (whiteSpace != null) { switch (whiteSpace) { case NORMAL: editText.setSingleLine(false); // editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE); break; case NOWRAP: editText.setSingleLine(true); break; } } } if (view instanceof TextView) { // also Buttons TextView textView = (TextView)view; if (color != null) textView.setTextColor(color); if (fontSize != null) textView.setTextSize(fontSize); if (whiteSpace != null) { switch (whiteSpace) { case NORMAL: textView.setSingleLine(false); break; case NOWRAP: textView.setSingleLine(true); break; } } if (textAlign != null) { switch (textAlign) { case LEFT: textView.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_START); break; case CENTER: textView.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER); break; case RIGHT: textView.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_END); break; } } if (textOverflow != null) { switch (textOverflow) { case CLIP: textView.setEllipsize(null); break; case ELLIPSIS: textView.setEllipsize(TruncateAt.END); break; } } if (fontFamily != null || fontWeight != null || fontStyle != null) { int flags = 0; if (fontWeight != null && fontWeight > 550) flags |= Typeface.BOLD; if (fontStyle != null && (fontStyle == FontStyle.ITALIC || fontStyle == FontStyle.OBLIQUE)) flags |= Typeface.ITALIC; if (fontFamily != null) { textView.setTypeface(Typeface.create(fontFamily, flags), flags); } else { textView.setTypeface(null, flags); } } if (hint != null) textView.setHint(hint); if (iconFile != null) { BitmapDrawable drawable = null; if (!iconFile.isEmpty()) { Bitmap bitmap = bitmapCache.loadBitmap(iconFile); if (bitmap != null) drawable = new BitmapDrawable(bitmap); } if (iconAttachment == null || iconAttachment.equals("top")) { textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); } else if (iconAttachment.equals("left")) { textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null); } else if (iconAttachment.equals("right")) { textView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); } else if (iconAttachment.equals("bottom")) { textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable); } } } if (view instanceof Button) { Button button = (Button)view; if (color != null) button.setTextColor(color); if (fontSize != null) button.setTextSize(fontSize); if (whiteSpace != null) { switch (whiteSpace) { case NORMAL: button.setSingleLine(false); break; case NOWRAP: button.setSingleLine(true); break; } } if (textAlign != null) { switch (textAlign) { case LEFT: button.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_START); break; case CENTER: button.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER); break; case RIGHT: button.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_END); break; } } if (textOverflow != null) { switch (textOverflow) { case CLIP: button.setEllipsize(null); break; case ELLIPSIS: button.setEllipsize(TruncateAt.END); break; } } if (fontFamily != null || fontWeight != null || fontStyle != null) { int flags = 0; if (fontWeight != null && fontWeight > 550) flags |= Typeface.BOLD; if (fontStyle != null && (fontStyle == FontStyle.ITALIC || fontStyle == FontStyle.OBLIQUE)) flags |= Typeface.ITALIC; if (fontFamily != null) { button.setTypeface(Typeface.create(fontFamily, flags), flags); } else { button.setTypeface(null, flags); } } if (hint != null) button.setHint(hint); if (iconFile != null) { BitmapDrawable drawable = null; if (!iconFile.isEmpty()) { Bitmap bitmap = bitmapCache.loadBitmap(iconFile); if (bitmap != null) drawable = new BitmapDrawable(bitmap); } if (iconAttachment == null || iconAttachment.equals("top")) { button.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); } else if (iconAttachment.equals("left")) { button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null); } else if (iconAttachment.equals("right")) { button.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); } else if (iconAttachment.equals("bottom")) { button.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable); } } } } public void applyLinkColor(View view) { if (view instanceof TextView) { // also Buttons TextView textView = (TextView)view; if (color != null) textView.setLinkTextColor(color); } } protected int applyScale(int v) { return (int)(v * displayScale + 0.5f); } protected float applyScale(float v) { return v * displayScale; } protected float[] expandRadii(float[] input) { float[] r = new float[8]; for (int i = 0; i < 4; i++) { r[2 * i] = r[2 * i + 1] = applyScale(borderRadius[i]); } return r; } protected float[] parseFloatArray(String value, int size) { String[] values = value.split(" "); float[] r = new float[size]; float prev = 0.0f; for (int i = 0; i < size; i++) { if (i < values.length) prev = Float.valueOf(values[i].trim()); r[i] = prev; } return r; } }
package controllers.acentera; import models.db.User; import models.db.acentera.impl.UserImpl; import models.web.AppObj; import models.web.AppObj$; import models.web.DesktopObject; import models.web.WebSession; import net.sf.json.JSONObject; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.session.ExpiredSessionException; import org.apache.shiro.session.UnknownSessionException; import org.apache.shiro.subject.Subject; import play.Logger; import play.api.libs.Crypto; import play.cache.Cache; import play.i18n.Messages; import play.libs.F; import play.mvc.Action; import play.mvc.Http; import play.mvc.Result; import play.mvc.SimpleResult; import utils.DatabaseManager; import utils.HibernateSessionFactory; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.security.MessageDigest; public class AnonymousSecurityController extends Action.Simple { //public final static String AUTH_TOKEN_HEADER = "X-AUTH-TOKEN"; public static final String AUTH_TOKEN = "token"; public static final String AUTHSECRET_TOKEN = "token"; public static final String DESKTOP_TOKEN = "dtid"; String uuid(Http.Context ctx) { Http.Cookie res = ctx.request().cookie(AUTH_TOKEN); if (res == null) { return ""; } return res.value(); } String getEmailFromSession(Http.Context ctx) { Http.Cookie res = ctx.request().cookie("email"); if (res == null) { return ""; } return res.value(); } String getCookieKeyInfo(Http.Context ctx, String key ) { try { return (String)ctx.request().cookie(key).value(); } catch (Exception ee) { ee.printStackTrace(); return null; } } String getStringCacheValue ( Http.Context ctx, String key ) { try { String keyCache = uuid(ctx) + "." + key; Logger.debug("CACHE KEY IS : " + keyCache); Object data = Cache.get(keyCache); if (data == null) { return ""; } else { return data.toString(); } } catch (Exception ee) { //No cache } return null; } Object getCacheObject ( Http.Context ctx, String key ) { try { String keyCache = uuid(ctx) + "." + key; Object data = Cache.get(keyCache); if (data == null) { return null; } else { return data; } } catch (Exception ee) { //No cache } return null; } void setCacheObject ( Http.Context ctx, String key, String value ) { String keyCache = uuid(ctx) + "." + key; Cache.set(uuid(ctx) + "." + key, value); } public static Result FailedMessage(String message) { JSONObject jsoUnauthorzed = new JSONObject(); jsoUnauthorzed.put("status", "failed"); jsoUnauthorzed.put("message", Messages.get(message)); return notFound(jsoUnauthorzed.toString()).as("application/json"); } public static Result InternalServerError(String message) { return internalServerError().as("application/json"); } public F.Promise<Result> NotAuthorized() { //return play.libs.F.Promise.pure((SimpleResult) controllers.Auth.logout()); return F.Promise.pure((Result) FailedMessage("UNAUTHORIZED")); } public static F.Promise<Result> logout(final play.mvc.Http.Context ctx) { try { ctx.session().remove(SecurityController.AUTH_TOKEN); ctx.session().remove(SecurityController.DESKTOP_TOKEN); ctx.response().discardCookie(SecurityController.AUTH_TOKEN); ctx.response().discardCookie(SecurityController.DESKTOP_TOKEN); }catch (Exception ee) { } try { WebSession websession = null; websession = SecurityController.getWebSession(); if (websession != null) { websession.removeAllDesktop(); websession.removeSession(); } } catch (Exception ee){ } try { SecurityController.getSubject().logout(); } catch (Exception ee) { } return play.libs.F.Promise.pure((Result) redirect("/")); } public static Subject getSubject() throws org.apache.shiro.session.ExpiredSessionException { try { Http.Context context = Http.Context.current(); Subject s = (Subject)context.args.get("subject"); //Logger.debug("S IS : " + s); if (s == null) { //Logger.debug("S WAS NULLLLL??"); s = SecurityUtils.getSubject(); if ((s == null) || (s.getSession() == null)) { s = new Subject.Builder().buildSubject(); } } else { if (s.getPrincipal() != null) { //Logger.debug("A SUBJECT SHIRO SESSIONID USER IS : " + ((User)s.getPrincipal()).getEmail()); } } //Logger.debug("A SUBJECT SHIRO SESSIONID IS : " + s.getSession().getId()); return s; } catch (org.apache.shiro.session.UnknownSessionException e) { /*Subject s = new Subject.Builder().buildSubject(); if (s.getSession(true) == null) { s = new Subject.Builder().buildSubject(); } return s;*/ //Logger.debug("SHIRO SESSION IS NOW EXPIRED"); e.printStackTrace(); Subject s = new Subject.Builder().buildSubject(); return s; } catch (UnknownAccountException ue) { ue.printStackTrace(); try { Subject s = new Subject.Builder().buildSubject(); return s; } catch (UnknownSessionException ss) { ss.printStackTrace(); } catch (ExpiredSessionException ss) { ss.printStackTrace(); } catch (Exception eee) { eee.printStackTrace();; throw eee; } } catch (org.apache.shiro.session.ExpiredSessionException ee) { Logger.debug("SHIRO SESSION IS NOW EXPIRED"); throw ee; } catch (Exception e) { try { Subject s = new Subject.Builder().buildSubject(); return s; } catch (UnknownSessionException ss) { ss.printStackTrace(); } catch (ExpiredSessionException ss) { ss.printStackTrace(); } catch (Exception eee) { eee.printStackTrace();; throw eee; } } //Subject s = new Subject.Builder().buildSubject(); //return s; return null; }; public F.Promise<Result> call(final Http.Context ctx) throws Throwable { try { Subject s = getSubject(); User user= null; //Get the Session //HibernateSessionFactory.getSession(); String cacheValue = getStringCacheValue(ctx, AUTH_TOKEN); String email = getEmailFromSession(ctx); Logger.debug("GOT EMAIL OF : " + email + " and cache avlue of : " + cacheValue); if (email != null && cacheValue != null) { if (cacheValue.compareTo(email) == 0) { ctx.args.put("email", email); user = UserImpl.getUserByEmail(email); } else { //Stay logged in if hit another server (or in dev by using token secret...) user = UserImpl.getUserByEmail(email); if (user == null) { return NotAuthorized(); } else { String k = Crypto.sign(user.getEmail() + "-" + user.getSalt() + "-" + user.getPassword()); Logger.debug("the crypto sign was : " + k); Http.Cookie c = ctx.request().cookie("tokensecret"); String custom = ""; if (c != null) { custom = c.value(); } if (k.compareTo(custom) == 0) { //Its all good if (custom.compareTo("") != 0) { } } else { } } } } else { //Stay logged in if hit another server (or in dev by using token secret...) if (email != null) { user = UserImpl.getUserByEmail(email); if (user == null) { } else { String k = Crypto.sign(user.getEmail() + "-" + user.getSalt() + "-" + user.getPassword()); Logger.debug("WILL CHECK CRYPTO VALUE OF... k " + k + " vs " + ctx.request().cookie("tokensecret").value()); if (k.compareTo(ctx.request().cookie("tokensecret").value()) == 0) { //Its all good Logger.debug("ITS GOOD....."); ctx.args.put("email", email); user = UserImpl.getUserByEmail(email); } else { //Invalid user... signature recevied not match email.. user = null; } } } } Subject currentUser = null; Logger.debug("USER IS... " + user); if (user != null) { //set the subject principals... String passphrase = play.Play.application().configuration().getString("privatekey"); MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(passphrase.getBytes()); SecretKeySpec key = new SecretKeySpec(digest.digest(), 0, 16, "AES"); Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding"); aes.init(Cipher.DECRYPT_MODE, key); String pw = null; try { //String k = Crypto.sign(wu.getUser().getEmail() + "-" + wu.getUser().getSalt() + "-" + wu.getUser().getPassword()); Logger.debug("WILL CHECK SECRET KEY ?"); byte[] pwHashed = java.util.Base64.getDecoder().decode(getCookieKeyInfo(ctx, "secret_key")); pw = new String(aes.doFinal(pwHashed)); Logger.debug("GOT PW OF : " + pw); //pw = new String(aes.doFinal(((byte[]) Cache.get(user.getEmail() + "_pass")))); } catch (Exception ee) { ee.printStackTrace(); if (play.Play.isDev()) { pw = play.Play.application().configuration().getString("dev_default_user_password"); } } //Because we are stateless we must login each time... //TODO: If we impersonnate user (from an admin portal) to simulate we are someone else.. //we should override the login / user here.. UsernamePasswordToken tk = new UsernamePasswordToken(user.getEmail(), pw); try { currentUser = getSubject(); tk.setRememberMe(true); currentUser.login(tk); } catch (org.apache.shiro.session.UnknownSessionException usession) { currentUser = new Subject.Builder().buildSubject(); currentUser.login(tk); } catch (Exception ee) { currentUser = new Subject.Builder().buildSubject(); currentUser.login(tk); } //setCacheObject(ctx, "email", user.getEmail()); } ctx.args.put("subject", currentUser); return processRequest(ctx); } catch (ExpiredSessionException e) { e.printStackTrace(); //Rollback any changes try { DatabaseManager.getInstance().rollback(); } catch (Exception ew) { } HibernateSessionFactory.rollback(); Logger.debug(this + " - REDIRECTING TO /login"); return F.Promise.pure(redirect("/login")); } catch (Exception e) { //e.printStackTrace(); //Rollback any changes try { DatabaseManager.getInstance().rollback(); } catch (Exception ew) { } HibernateSessionFactory.rollback(); } finally { //Commit or close the active session try { DatabaseManager.getInstance().closeIfConnectionOpen(); } catch (Exception ew) { } HibernateSessionFactory.closeSession(); } return NotAuthorized(); } protected F.Promise<Result> processRequest(Http.Context ctx) throws Throwable { Logger.debug(" [ AnonymousProcessRequest ] - Start "); try { F.Promise<Result> z = delegate.call(ctx); return z; } finally { try { DatabaseManager.getInstance().rollback(); } catch (Exception z){ } try { HibernateSessionFactory.rollback(); } catch (Exception z){ } Logger.debug(" [ AnonymousProcessRequest ] - Completed "); } } public static String getEmail() { try { return (String) Http.Context.current().args.get("email"); } catch (Exception ee) { try { return (String)((User)getSubject().getPrincipal()).getEmail(); } catch (Exception expired) { return ""; } } } public static User getUser() { //TODO: Try to get it from cache ??? try { return (User) Http.Context.current().args.get("user"); } catch (Exception ee) { try { return (User) getSubject().getSession().getAttribute("user"); } catch (Exception expired) { return null; } } } public static WebSession getWebSession() { return (WebSession)Http.Context.current().args.get("websession"); } public static DesktopObject getDesktop() { try { return (DesktopObject) Http.Context.current().args.get("desktop"); } catch (Exception ee) { try { return (DesktopObject) getSubject().getSession().getAttribute("desktop"); } catch (Exception expired) { return null; } } } public static DesktopObject getDesktop(String desktopId) { DesktopObject desktop = AppObj$.MODULE$.getDesktop(desktopId); //TODO: Should we validate that the desktop belongs to that user ? (desktop user... vs current logged in user?? bu we want to support impersonating a user too.. so lets ignore for now) return desktop; } }
package com.andela.webservice; import android.app.ListActivity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.andela.webservice.model.Flower; import com.andela.webservice.parser.FlowerJsonParser; import java.util.ArrayList; import java.util.List; public class MainActivity extends ListActivity { private TextView output; private ProgressBar progressBar; private List<MyTask> tasks; private List<Flower> flowerList; private static final String PHOTO_BASE_URL = "http://services.hanselandpetal.com/photos/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = (ProgressBar) findViewById(R.id.progressBar1); progressBar.setVisibility(View.INVISIBLE); tasks = new ArrayList<>(); //output = (TextView) findViewById(R.id.textView); //output.setMovementMethod(new ScrollingMovementMethod()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_do_task) { if(isOnline()) { requestData("http://services.hanselandpetal.com/secure/flowers.json"); } else { Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show(); } } return true; } private void requestData(String uri) { MyTask task = new MyTask(); //This makes serial request task.execute(uri); //For parrallel processing //task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "param1", "param2", "param3"); } private void updateDisplay() { /*if(flowerList != null) { for (Flower flower : flowerList) { output.append(flower.getName() + "\n"); } }*/ FlowerAdapter adapter = new FlowerAdapter(this, R.layout.item_flower, flowerList); setListAdapter(adapter); } protected boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if(netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } else { return false; } } private class MyTask extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { //updateDisplay("Starting task"); if(tasks.size() == 0) { progressBar.setVisibility(View.VISIBLE); } tasks.add(this); } @Override protected String doInBackground(String... params) { String content = HttpManager.getData(params[0],"feeduser","feedpassword"); return content; } @Override protected void onPostExecute(String result) { tasks.remove(this); if(tasks.size() == 0) { progressBar.setVisibility(View.INVISIBLE); } //flowerList = FlowerXmlParser.parseFeed(result); if(result == null) { Toast.makeText(MainActivity.this, "Can't connect to webservice", Toast.LENGTH_LONG).show(); return; } flowerList = FlowerJsonParser.parseFeed(result); updateDisplay(); } @Override protected void onProgressUpdate(String... values) { //updateDisplay(values[0]); } } }
package com.malmstein.yahnac.data; import android.content.ContentValues; import android.util.Pair; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.malmstein.yahnac.inject.Inject; import com.malmstein.yahnac.model.StoriesJsoup; import com.malmstein.yahnac.model.Story; import com.malmstein.yahnac.tasks.FetchCommentsTask; import com.malmstein.yahnac.tasks.FetchStoriesTask; import com.novoda.notils.logger.simple.Log; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Vector; import rx.Observable; import rx.Subscriber; import rx.functions.Func1; import rx.schedulers.Schedulers; public class HNewsApi { public Observable<List<ContentValues>> getStories(final Story.TYPE type) { return Observable.create(new Observable.OnSubscribe<DataSnapshot>() { @Override public void call(final Subscriber<? super DataSnapshot> subscriber) { Firebase topStories = getStoryFirebase(type); topStories.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot != null) { subscriber.onNext(dataSnapshot); } else { Inject.crashAnalytics().logSomethingWentWrong("HNewsApi: getStories is empty for " + type.name()); } subscriber.onCompleted(); } @Override public void onCancelled(FirebaseError firebaseError) { Log.d(firebaseError.getCode()); } }); } }).flatMap(new Func1<DataSnapshot, Observable<Pair<Integer, Long>>>() { @Override public Observable<Pair<Integer, Long>> call(final DataSnapshot dataSnapshot) { return Observable.create(new Observable.OnSubscribe<Pair<Integer, Long>>() { @Override public void call(Subscriber<? super Pair<Integer, Long>> subscriber) { for (int i = 0; i < dataSnapshot.getChildrenCount(); i++) { Long id = (Long) dataSnapshot.child(String.valueOf(i)).getValue(); Integer rank = Integer.valueOf(dataSnapshot.child(String.valueOf(i)).getKey()); Pair<Integer, Long> storyRoot = new Pair<>(rank, id); subscriber.onNext(storyRoot); } subscriber.onCompleted(); } }); } }).flatMap(new Func1<Pair<Integer, Long>, Observable<ContentValues>>() { @Override public Observable<ContentValues> call(final Pair<Integer, Long> storyRoot) { return Observable.create(new Observable.OnSubscribe<ContentValues>() { @Override public void call(final Subscriber<? super ContentValues> subscriber) { final Firebase story = new Firebase("https://hacker-news.firebaseio.com/v0/item/" + storyRoot.second); story.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Map<String, Object> newItem = (Map<String, Object>) dataSnapshot.getValue(); if (newItem != null) { subscriber.onNext(mapStory(newItem, type, storyRoot.first)); } else { Inject.crashAnalytics().logSomethingWentWrong("HNewsApi: onDataChange is empty in " + storyRoot.second ); } subscriber.onCompleted(); } @Override public void onCancelled(FirebaseError firebaseError) { Log.d(firebaseError.getCode()); } }); } }); } }).toList(); } private ContentValues mapStory(Map<String, Object> map, Story.TYPE rootType, Integer rank) { String by = (String) map.get("by"); Long id = (Long) map.get("id"); String type; if (rootType == Story.TYPE.best_story || rootType == Story.TYPE.new_story){ type = Story.TYPE.top_story.name(); } else { type = rootType.name(); } Long time = (Long) map.get("time"); Long score = (Long) map.get("score"); String title = (String) map.get("title"); String url = (String) map.get("url"); Long descendants = (Long) map.get("descendants"); ContentValues storyValues = new ContentValues(); storyValues.put(HNewsContract.StoryEntry.ITEM_ID, id); storyValues.put(HNewsContract.StoryEntry.BY, by); storyValues.put(HNewsContract.StoryEntry.TYPE, type); storyValues.put(HNewsContract.StoryEntry.TIME_AGO, time * 1000); storyValues.put(HNewsContract.StoryEntry.SCORE, score); storyValues.put(HNewsContract.StoryEntry.TITLE, title); storyValues.put(HNewsContract.StoryEntry.COMMENTS, descendants); storyValues.put(HNewsContract.StoryEntry.URL, url); storyValues.put(HNewsContract.StoryEntry.RANK, rank); storyValues.put(HNewsContract.StoryEntry.TIMESTAMP, System.currentTimeMillis()); return storyValues; } private Firebase getStoryFirebase(Story.TYPE type){ switch (type){ case top_story: return new Firebase("https://hacker-news.firebaseio.com/v0/topstories"); case new_story: return new Firebase("https://hacker-news.firebaseio.com/v0/topstories"); case best_story: return new Firebase("https://hacker-news.firebaseio.com/v0/topstories"); case show: return new Firebase("https://hacker-news.firebaseio.com/v0/showstories"); case ask: return new Firebase("https://hacker-news.firebaseio.com/v0/askstories"); case jobs: return new Firebase("https://hacker-news.firebaseio.com/v0/jobstories"); default: return new Firebase("https://hacker-news.firebaseio.com/v0/topstories"); } } Observable<StoriesJsoup> getStories(Story.TYPE storyType, String nextUrl) { return Observable.create( new StoriesUpdateOnSubscribe(storyType, nextUrl)) .subscribeOn(Schedulers.io()); } private static class StoriesUpdateOnSubscribe implements Observable.OnSubscribe<StoriesJsoup> { private final Story.TYPE type; private final String nextUrl; private Subscriber<? super StoriesJsoup> subscriber; private StoriesUpdateOnSubscribe(Story.TYPE type, String nextUrl) { this.type = type; this.nextUrl = nextUrl; } @Override public void call(Subscriber<? super StoriesJsoup> subscriber) { this.subscriber = subscriber; startFetchingStories(); subscriber.onCompleted(); } private void startFetchingStories() { StoriesJsoup stories = StoriesJsoup.empty(); try { stories = new FetchStoriesTask(type, nextUrl).execute(); } catch (IOException e) { subscriber.onError(e); } if (stories.getStories().size() == 0) { subscriber.onError(new RuntimeException("API is not returning any data")); } else { subscriber.onNext(stories); } } } Observable<Vector<ContentValues>> getCommentsFromStory(Long storyId) { return Observable.create( new CommentsUpdateOnSubscribe(storyId)) .subscribeOn(Schedulers.io()); } private static class CommentsUpdateOnSubscribe implements Observable.OnSubscribe<Vector<ContentValues>> { private final Long storyId; private Subscriber<? super Vector<ContentValues>> subscriber; private CommentsUpdateOnSubscribe(Long storyId) { this.storyId = storyId; } @Override public void call(Subscriber<? super Vector<ContentValues>> subscriber) { this.subscriber = subscriber; startFetchingComments(); subscriber.onCompleted(); } private void startFetchingComments() { Vector<ContentValues> commentsList = new Vector<>(); try { commentsList = new FetchCommentsTask(storyId).execute(); } catch (IOException e) { subscriber.onError(e); } subscriber.onNext(commentsList); } } }
package com.nokia.mid.ui; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import javax.microedition.lcdui.game.Sprite; public class DirectGraphicsImp implements DirectGraphics { private Graphics graphics; private int alphaComponent; /** * @param g */ public DirectGraphicsImp(Graphics g) { graphics = g; } /** * @param img * @param x * @param y * @param anchor * @param manipulation ignored, since manipulations are not supported at the moment */ public void drawImage(Image img, int x, int y, int anchor, int manipulation) { if (img == null) { throw new NullPointerException(); } int transform; switch (manipulation) { case FLIP_HORIZONTAL: transform = Sprite.TRANS_MIRROR_ROT180; break; case FLIP_VERTICAL: transform = Sprite.TRANS_MIRROR; break; case ROTATE_90: transform = Sprite.TRANS_ROT90; break; case ROTATE_180: transform = Sprite.TRANS_ROT180; break; case ROTATE_270: transform = Sprite.TRANS_ROT270; break; default: transform = -1; } if (anchor >= 64 || transform == -1) { throw new IllegalArgumentException(); } else { graphics.drawRegion( img, x + graphics.getTranslateX(), y + graphics.getTranslateY(), img.getWidth(), img.getHeight(), transform, x + graphics.getTranslateX(), y + graphics.getTranslateY(), anchor); return; } } /** * @param argb */ public void setARGBColor(int argb) { alphaComponent = (argb >> 24 & 0xff); graphics.setColorAlpha(argb); } /** * @return */ public int getAlphaComponent() { return alphaComponent; } /** * @return */ public int getNativePixelFormat() { return TYPE_BYTE_1_GRAY; } /** * @param xPoints * @param xOffset * @param yPoints * @param yOffset * @param nPoints * @param argbColor */ public void drawPolygon(int xPoints[], int xOffset, int yPoints[], int yOffset, int nPoints, int argbColor) { setARGBColor(argbColor); graphics.drawPolygon(xPoints, xOffset, yPoints, yOffset, nPoints); } /** * @param x1 * @param y1 * @param x2 * @param y2 * @param x3 * @param y3 * @param argbColor */ public void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3, int argbColor) { drawPolygon(new int[]{x1, x2, x3}, 0, new int[]{y1, y2, y3}, 0, 3, argbColor); } /** * @param xPoints * @param xOffset * @param yPoints * @param yOffset * @param nPoints * @param argbColor */ public void fillPolygon(int xPoints[], int xOffset, int yPoints[], int yOffset, int nPoints, int argbColor) { setARGBColor(argbColor); graphics.fillPolygon(xPoints, xOffset, yPoints, yOffset, nPoints); } /** * @param x1 * @param y1 * @param x2 * @param y2 * @param x3 * @param y3 * @param argbColor */ public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3, int argbColor) { fillPolygon(new int[]{x1, x2, x3}, 0, new int[]{y1, y2, y3}, 0, 3, argbColor); } //manipulations are not supported! /** * @param pix * @param alpha * @param off * @param scanlen * @param x * @param y * @param width * @param height * @param manipulation ignored, since manipulations are not supported at the moment * @param format */ public void drawPixels(byte[] pix, byte[] alpha, int off, int scanlen, int x, int y, int width, int height, int manipulation, int format) { System.out.println("public void drawPixels(byte[] pix, byte[] alpha, int off, int scanlen, int x, int y, int width, int height, int manipulation, int format)"); if (pix == null) { throw new NullPointerException(); } if (width < 0 || height < 0) { throw new IllegalArgumentException(); } Graphics g = graphics; int c; if (format == TYPE_BYTE_1_GRAY) { int b = 7; for (int yj = 0; yj < height; yj++) { int line = off + yj * scanlen; int ypos = yj * width; for (int xj = 0; xj < width; xj++) { c = doAlpha(pix, alpha, (line + xj) / 8, b); if ((c >> 24 & 0xff) != 0)//alpha { if (g.getColor() != c) g.setColor(c); g.drawLine(xj + x, yj + y, xj + x, yj + y); } b if (b < 0) b = 7; } } } else if (format == TYPE_BYTE_1_GRAY_VERTICAL) { int ods = off / scanlen; int oms = off % scanlen; int b = 0; for (int yj = 0; yj < height; yj++) { int ypos = yj * width; int tmp = (ods + yj) / 8 * scanlen + oms; for (int xj = 0; xj < width; xj++) { c = doAlpha(pix, alpha, tmp + xj, b); if (g.getColor() != c) g.setColor(c); if ((c >> 24 & 0xff) != 0) //alpha g.drawLine(xj + x, yj + y, xj + x, yj + y); } b++; if (b > 7) b = 0; } } else throw new IllegalArgumentException(); } /** * Only TYPE_USHORT_4444_ARGB format supported * * @param pix * @param trans * @param off * @param scanlen * @param x * @param y * @param width * @param height * @param manipulation * @param format */ public void drawPixels(short pix[], boolean trans, int off, int scanlen, int x, int y, int width, int height, int manipulation, int format) { if (format != TYPE_USHORT_4444_ARGB) { throw new IllegalArgumentException("Illegal format: " + format); } Graphics g = graphics; for (int iy = 0; iy < height; iy++) { for (int ix = 0; ix < width; ix++) { int c = toARGB(pix[off + ix + iy * scanlen], TYPE_USHORT_4444_ARGB); if (!isTransparent(c)) { g.setColor(c); g.drawLine(x + ix, y + iy, x + ix, y + iy); } } } } /** * Not supported * * @param pix * @param trans * @param off * @param scanlen * @param x * @param y * @param width * @param height * @param manipulation * @param format */ public void drawPixels(int pix[], boolean trans, int off, int scanlen, int x, int y, int width, int height, int manipulation, int format) { System.out.println("public void drawPixels(int pix[], boolean trans, int off, int scanlen, int x, int y, int width, int height, int manipulation, int format)"); throw new IllegalArgumentException(); } /** * Not supported * * @param pix * @param alpha * @param offset * @param scanlen * @param x * @param y * @param width * @param height * @param format */ public void getPixels(byte pix[], byte alpha[], int offset, int scanlen, int x, int y, int width, int height, int format) { System.out.println("public void getPixels(byte pix[], byte alpha[], int offset, int scanlen, int x, int y, int width, int height, int format)"); throw new IllegalArgumentException(); } /** * Only TYPE_USHORT_4444_ARGB format supported * * @param pix * @param offset * @param scanlen * @param x * @param y * @param width * @param height * @param format */ public void getPixels(short pix[], int offset, int scanlen, int x, int y, int width, int height, int format) { System.out.println("public void getPixels(short pix[], int offset, int scanlen, int x, int y, int width, int height, int format)"); throw new IllegalArgumentException(); } /** * Not supported * * @param pix * @param offset * @param scanlen * @param x * @param y * @param width * @param height * @param format */ public void getPixels(int pix[], int offset, int scanlen, int x, int y, int width, int height, int format) { System.out.println("public void getPixels(int pix[], int offset, int scanlen, int x, int y, int width, int height, int format"); throw new IllegalArgumentException(); } private static int doAlpha(byte[] pix, byte[] alpha, int pos, int shift) { int p; int a; if (isBitSet(pix[pos], shift)) p = 0; else p = 0x00FFFFFF; if (alpha == null || isBitSet(alpha[pos], shift)) a = 0xFF000000; else a = 0; return p | a; } private static boolean isBitSet(byte b, int pos) { return ((b & (byte) (1 << pos)) != 0); } private static int toARGB(int s, int type) { switch (type) { case TYPE_USHORT_4444_ARGB: { int a = ((s) & 0xF000) >>> 12; int r = ((s) & 0x0F00) >>> 8; int g = ((s) & 0x00F0) >>> 4; int b = ((s) & 0x000F); s = ((a * 15) << 24) | ((r * 15) << 16) | ((g * 15) << 8) | (b * 15); break; } case TYPE_USHORT_444_RGB: { int r = ((s) & 0x0F00) >>> 8; int g = ((s) & 0x00F0) >>> 4; int b = ((s) & 0x000F); s = ((r * 15) << 16) | ((g * 15) << 8) | (b * 15); break; } } return s; } private static boolean isTransparent(int s) { return (s & 0xFF000000) == 0; } }
package com.procleus.brime; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.Toast; public class CustomDialogBox extends Dialog implements View.OnClickListener{ Spinner spinner; public Activity c; public Dialog d; public Button yes, no; Boolean isLoggedIn; public CustomDialogBox(Activity context, Boolean isLoggedIn) { super(context); c=context; this.isLoggedIn = isLoggedIn; } @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dialog); RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1); yes = (Button) findViewById(R.id.btn_yes); no = (Button) findViewById(R.id.btn_no); yes.setOnClickListener(this); no.setOnClickListener(this); if (!isLoggedIn) { for (int i = 0; i < radioGroup.getChildCount(); i++) { radioGroup.getChildAt(i).setEnabled(false); } } else { for (int i = 0; i < radioGroup.getChildCount(); i++) { radioGroup.getChildAt(i).setEnabled(true); } } spinner = (Spinner) findViewById(R.id.spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.lables_array, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_yes: RadioGroup rg = (RadioGroup)findViewById(R.id.radioGroup1); int id = rg.getCheckedRadioButtonId(); if(id==R.id.radioPublic) { ///**/Public segement Toast.makeText(getContext(), "Public segment", Toast.LENGTH_SHORT).show(); ((CreateNotes)c).check(); c.finish(); } else if(id==R.id.radioPrivate){ /**/ PRivate Segment Toast.makeText(getContext(), "Private segment", Toast.LENGTH_SHORT).show(); ((CreateNotes)c).check2(); c.finish(); } else {